Compare commits
12
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
897dc478be | ||
|
|
bb972dde65 | ||
|
|
f14f61e47c | ||
|
|
06ea8746d3 | ||
|
|
9318e1b7a7 | ||
|
|
4dab718e87 | ||
|
|
4c955aba31 | ||
|
|
5f0b4dcf4b | ||
|
|
b9e090f48a | ||
|
|
dbd79a6da1 | ||
|
|
4c2d094a4a | ||
|
|
860e03059a |
@@ -0,0 +1,3 @@
|
||||
.git
|
||||
.gitea
|
||||
out
|
||||
@@ -0,0 +1,221 @@
|
||||
name: release
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: ['**']
|
||||
workflow_dispatch:
|
||||
|
||||
concurrency:
|
||||
group: release-${{ github.ref }}
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
release:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 45
|
||||
permissions:
|
||||
contents: read
|
||||
env:
|
||||
KIND: mc
|
||||
BIN: mc
|
||||
PKG: minio-mc
|
||||
REGISTRY: git.vezha.io
|
||||
steps:
|
||||
- name: AC1 checkout the recipe
|
||||
uses: https://git.vezha.io/actions/checkout@v4
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- name: AC2 pins are complete and well formed
|
||||
id: pins
|
||||
run: sh vezha/gates.sh pins "$KIND" | tee -a "$GITHUB_ENV" | tee -a "$GITHUB_OUTPUT"
|
||||
|
||||
- name: AC3 no unpinned reference and workflow lint
|
||||
run: sh vezha/gates.sh refs "$KIND"
|
||||
|
||||
- name: tools docker cli and jq
|
||||
run: |
|
||||
command -v docker >/dev/null 2>&1 || { apt-get update -qq; DEBIAN_FRONTEND=noninteractive apt-get install -y -qq docker.io >/dev/null; }
|
||||
command -v jq >/dev/null 2>&1 || { apt-get update -qq; DEBIAN_FRONTEND=noninteractive apt-get install -y -qq jq >/dev/null; }
|
||||
docker version --format 'client {{.Client.Version}} server {{.Server.Version}}'
|
||||
jq --version
|
||||
|
||||
- name: AC1 provenance of the import, anonymous
|
||||
run: sh vezha/gates.sh provenance-remote
|
||||
|
||||
- name: AC1 checkout the pinned upstream source
|
||||
uses: https://git.vezha.io/actions/checkout@v4
|
||||
with:
|
||||
ref: ${{ steps.pins.outputs.UPSTREAM_COMMIT }}
|
||||
path: src
|
||||
fetch-depth: 1
|
||||
persist-credentials: false
|
||||
|
||||
- name: AC1 source tree is at the pinned commit
|
||||
run: sh vezha/gates.sh provenance-src
|
||||
|
||||
- name: AC7 source offer URLs answer anonymously
|
||||
run: sh vezha/gates.sh source-urls
|
||||
|
||||
- name: negative controls, every gate must refuse its planted input
|
||||
run: sh vezha/gates.sh self-test
|
||||
|
||||
- name: names and build arguments
|
||||
run: |
|
||||
TAG=$(sh vezha/gates.sh make-tag)
|
||||
{ echo "TAG=$TAG"; echo "IMG=$REGISTRY/para/$PKG:$TAG"; echo "LOCAL=vezha-build-$KIND:$GITHUB_RUN_ID"; } >> "$GITHUB_ENV"
|
||||
mkdir -p out
|
||||
sh vezha/gates.sh pins "$KIND" | sed 's/^/--build-arg=/' > out/build-args
|
||||
echo "tag $TAG"
|
||||
|
||||
- name: AC2 pins stage proves the source tree and the module
|
||||
run: |
|
||||
mapfile -t ARGS < out/build-args
|
||||
docker build --target pins -f vezha/Dockerfile "${ARGS[@]}" -t "$LOCAL-pins" .
|
||||
|
||||
- name: AC4 build stage and binary hash A
|
||||
run: |
|
||||
mapfile -t ARGS < out/build-args
|
||||
docker build --target build -f vezha/Dockerfile "${ARGS[@]}" -t "$LOCAL-build" .
|
||||
cid=$(docker create "$LOCAL-build")
|
||||
docker cp "$cid:/out/$BIN" "out/$BIN.a"
|
||||
docker cp "$cid:/out/$BIN.sha256" out/sha.a
|
||||
docker rm "$cid" > /dev/null
|
||||
A=$(sha256sum "out/$BIN.a" | cut -d' ' -f1)
|
||||
if [ "$A" != "$(cat out/sha.a)" ]; then
|
||||
echo "REFUSED build: the extracted binary does not match the build stage's sha file"
|
||||
exit 1
|
||||
fi
|
||||
echo "BINARY_SHA256=$A" >> "$GITHUB_ENV"
|
||||
echo "binary sha256 A: $A"
|
||||
|
||||
- name: AC6 final image and content check
|
||||
run: |
|
||||
mapfile -t ARGS < out/build-args
|
||||
sh vezha/gates.sh render-source vezha/SOURCE.tmpl vezha/SOURCE
|
||||
docker build -f vezha/Dockerfile "${ARGS[@]}" "--build-arg=RECIPE_COMMIT=$GITHUB_SHA" "--build-arg=BINARY_SHA256=$BINARY_SHA256" -t "$IMG" .
|
||||
RECIPE_COMMIT="$GITHUB_SHA" sh vezha/check-image.sh "$KIND" "$IMG"
|
||||
|
||||
- name: AC4 version output carries the pinned release and commit
|
||||
run: |
|
||||
out=$(docker run --rm --label "io.vezha.smoke=$GITHUB_RUN_ID" "$IMG" --version)
|
||||
echo "$out"
|
||||
case "$out" in
|
||||
*"$UPSTREAM_RELEASE"*"commit-id=$UPSTREAM_COMMIT"*) echo "version output names $UPSTREAM_RELEASE and $UPSTREAM_COMMIT" ;;
|
||||
*) echo "REFUSED version: --version does not name $UPSTREAM_RELEASE and commit-id=$UPSTREAM_COMMIT"; exit 1 ;;
|
||||
esac
|
||||
|
||||
- name: AC5 reproducible, second no-cache build of the build stage
|
||||
run: |
|
||||
mapfile -t ARGS < out/build-args
|
||||
docker build --no-cache --target build -f vezha/Dockerfile "${ARGS[@]}" -t "$LOCAL-build2" .
|
||||
cid=$(docker create "$LOCAL-build2")
|
||||
docker cp "$cid:/out/$BIN" "out/$BIN.b"
|
||||
docker rm "$cid" > /dev/null
|
||||
B=$(sha256sum "out/$BIN.b" | cut -d' ' -f1)
|
||||
if [ "$B" != "$BINARY_SHA256" ]; then
|
||||
echo "REFUSED reproducible: second build has sha256 $B, first has $BINARY_SHA256"
|
||||
exit 1
|
||||
fi
|
||||
echo "both builds have sha256 $B"
|
||||
|
||||
- name: AC7 source offer in the image resolves anonymously
|
||||
run: sh vezha/gates.sh source-offer "$IMG" "$KIND" "$UPSTREAM_RELEASE"
|
||||
|
||||
- name: AC8 smoke against the stopgap server
|
||||
run: sh vezha/smoke.sh smoke git.vezha.io/para/minio@sha256:a1a8bd4ac40ad7881a245bab97323e18f971e4d4cba2c2007ec1bedd21cbaba2 "$IMG"
|
||||
|
||||
- name: AC10 preflight, write-once tag and the stopgap tags before
|
||||
run: |
|
||||
sh vezha/gates.sh preflight "$KIND" "$GITHUB_REF" "${MC_IMAGE:-}"
|
||||
sh vezha/gates.sh tag "$PKG" "$TAG"
|
||||
sh vezha/gates.sh stopgap | tee out/stopgap.before
|
||||
|
||||
- name: publish tools, pinned syft and oras installed before any login
|
||||
if: github.ref == 'refs/heads/vezha'
|
||||
run: |
|
||||
curl -fsSLO https://github.com/anchore/syft/releases/download/v1.50.0/syft_1.50.0_linux_amd64.tar.gz
|
||||
echo "bf7b29ff57f06da30918266a0e1c2885a8f99784798d1bdb1628886aa015d788 syft_1.50.0_linux_amd64.tar.gz" | sha256sum -c -
|
||||
tar -xzf syft_1.50.0_linux_amd64.tar.gz syft
|
||||
install -m 0755 syft /usr/local/bin/syft
|
||||
curl -fsSLO https://github.com/oras-project/oras/releases/download/v1.3.3/oras_1.3.3_linux_amd64.tar.gz
|
||||
echo "9ce999f8d2de03fc03968b29d743077a58783e545e5eaa53917ca177352d0e59 oras_1.3.3_linux_amd64.tar.gz" | sha256sum -c -
|
||||
tar -xzf oras_1.3.3_linux_amd64.tar.gz oras
|
||||
install -m 0755 oras /usr/local/bin/oras
|
||||
syft version
|
||||
oras version
|
||||
|
||||
- name: publish SBOM generated before the image
|
||||
if: github.ref == 'refs/heads/vezha'
|
||||
run: |
|
||||
syft "docker:$IMG" -o "spdx-json=out/sbom.spdx.json"
|
||||
test -s out/sbom.spdx.json
|
||||
|
||||
- name: publish login to the registry
|
||||
if: github.ref == 'refs/heads/vezha'
|
||||
env:
|
||||
REGISTRY_USER: ${{ secrets.REGISTRY_USER || github.actor }}
|
||||
REGISTRY_TOKEN: ${{ secrets.REGISTRY_TOKEN }}
|
||||
run: |
|
||||
sh vezha/gates.sh login-guard
|
||||
echo "$REGISTRY_TOKEN" | docker login "$REGISTRY" -u "$REGISTRY_USER" --password-stdin
|
||||
|
||||
- name: publish SBOM artifact pushed before the image
|
||||
if: github.ref == 'refs/heads/vezha'
|
||||
run: cd out && oras push "$REGISTRY/para/$PKG-sbom:$TAG" --artifact-type application/spdx+json sbom.spdx.json:application/spdx+json
|
||||
|
||||
- name: publish the image and cross-check its digest
|
||||
if: github.ref == 'refs/heads/vezha'
|
||||
run: |
|
||||
docker push "$IMG" | tee out/push.log
|
||||
D=$(sed -n 's/.*digest: \(sha256:[0-9a-f]\{64\}\).*/\1/p' out/push.log | tail -1)
|
||||
if [ -z "$D" ]; then
|
||||
echo "REFUSED push: no digest in the push output"
|
||||
exit 1
|
||||
fi
|
||||
R=$(sh vezha/gates.sh digest "$PKG" "$TAG")
|
||||
if [ "$R" != "$D" ]; then
|
||||
echo "REFUSED push: docker push printed $D but the registry serves $R for $TAG"
|
||||
exit 1
|
||||
fi
|
||||
echo "DIGEST=$D" >> "$GITHUB_ENV"
|
||||
|
||||
- name: publish AC11 digest proof, pull by digest and compare the binary
|
||||
if: github.ref == 'refs/heads/vezha'
|
||||
run: |
|
||||
REF="$REGISTRY/para/$PKG@$DIGEST"
|
||||
docker rmi "$IMG" > /dev/null
|
||||
sh vezha/gates.sh prove "$REF" "$BIN" "$BINARY_SHA256"
|
||||
docker run --rm --label "io.vezha.smoke=$GITHUB_RUN_ID" "$REF" --version
|
||||
oras pull "$REGISTRY/para/$PKG-sbom:$TAG" -o out/sbom-back
|
||||
grep -q '"spdxVersion"' out/sbom-back/sbom.spdx.json
|
||||
echo "the SBOM was pulled back and is SPDX JSON"
|
||||
|
||||
- name: publish AC11 the PUBLISHED line
|
||||
if: github.ref == 'refs/heads/vezha'
|
||||
run: |
|
||||
LINE="PUBLISHED $REGISTRY/para/$PKG@$DIGEST tag=$TAG binary-sha256=$BINARY_SHA256"
|
||||
echo "$LINE" | grep -Eq '^PUBLISHED git\.vezha\.io/para/(minio|minio-mc)@sha256:[0-9a-f]{64} tag=[a-z0-9._-]+ binary-sha256=[0-9a-f]{64}$' || { echo "REFUSED published: malformed line"; exit 1; }
|
||||
echo "$LINE"
|
||||
echo "$LINE" > out/published.txt
|
||||
cd out && oras push "$REGISTRY/para/$PKG-published:$TAG" published.txt:text/plain
|
||||
|
||||
- name: publish AC10 stopgap tags unchanged after the run
|
||||
if: github.ref == 'refs/heads/vezha'
|
||||
run: |
|
||||
sh vezha/gates.sh stopgap > out/stopgap.after
|
||||
diff out/stopgap.before out/stopgap.after
|
||||
echo "the stopgap tags resolve to the same digests as before the run"
|
||||
|
||||
- name: publish AC7 source offer of the pulled digest resolves anonymously
|
||||
if: github.ref == 'refs/heads/vezha'
|
||||
run: sh vezha/gates.sh source-offer "$REGISTRY/para/$PKG@$DIGEST" "$KIND" "$UPSTREAM_RELEASE"
|
||||
|
||||
- name: cleanup of this run's containers, networks, volumes and images
|
||||
if: always()
|
||||
run: |
|
||||
for c in $(docker ps -aq --filter "label=io.vezha.smoke=$GITHUB_RUN_ID"); do docker rm -f "$c" > /dev/null 2>&1 || true; done
|
||||
for n in $(docker network ls -q --filter "label=io.vezha.smoke=$GITHUB_RUN_ID"); do docker network rm "$n" > /dev/null 2>&1 || true; done
|
||||
for v in $(docker volume ls -q --filter "label=io.vezha.smoke=$GITHUB_RUN_ID"); do docker volume rm "$v" > /dev/null 2>&1 || true; done
|
||||
for i in "${LOCAL:-none}-pins" "${LOCAL:-none}-build" "${LOCAL:-none}-build2" "${IMG:-none}" "${REGISTRY}/para/${PKG}@${DIGEST:-none}"; do docker rmi "$i" > /dev/null 2>&1 || true; done
|
||||
docker logout "$REGISTRY" > /dev/null 2>&1 || true
|
||||
@@ -1,12 +0,0 @@
|
||||
## Expected behavior
|
||||
|
||||
## Actual behavior
|
||||
|
||||
## Steps to reproduce the behavior
|
||||
|
||||
## mc --version
|
||||
- (paste output of `mc --version`)
|
||||
|
||||
## System information
|
||||
|
||||
|
||||
@@ -1,19 +0,0 @@
|
||||
---
|
||||
name: Bug report
|
||||
about: Bug report template
|
||||
title: ''
|
||||
labels: community, triage
|
||||
assignees: ''
|
||||
|
||||
---
|
||||
|
||||
## Expected behavior
|
||||
|
||||
## Actual behavior
|
||||
|
||||
## Steps to reproduce the behavior
|
||||
|
||||
## mc --version
|
||||
- (paste output of `mc --version`)
|
||||
|
||||
## System information
|
||||
@@ -1,5 +0,0 @@
|
||||
blank_issues_enabled: false
|
||||
contact_links:
|
||||
- name: MinIO Community Support
|
||||
url: https://slack.min.io
|
||||
about: Please ask and answer questions here.
|
||||
@@ -1,26 +0,0 @@
|
||||
## Community Contribution License
|
||||
All community contributions in this pull request are licensed to the project maintainers
|
||||
under the terms of the [Apache 2 license](https://www.apache.org/licenses/LICENSE-2.0).
|
||||
By creating this pull request I represent that I have the right to license the
|
||||
contributions to the project maintainers under the Apache 2 license.
|
||||
|
||||
## Description
|
||||
|
||||
|
||||
## Motivation and Context
|
||||
|
||||
|
||||
## How to test this PR?
|
||||
|
||||
|
||||
## Types of changes
|
||||
- [ ] Bug fix (non-breaking change which fixes an issue)
|
||||
- [ ] New feature (non-breaking change which adds functionality)
|
||||
- [ ] Optimization (provides speedup with no functional changes)
|
||||
- [ ] Breaking change (fix or feature that would cause existing functionality to change)
|
||||
|
||||
## Checklist:
|
||||
- [ ] Fixes a regression (If yes, please add `commit-id` or `PR #` here)
|
||||
- [ ] Unit tests added/updated
|
||||
- [ ] Internal documentation updated
|
||||
- [ ] Create a documentation update request [here](https://github.com/minio/docs/issues/new?label=doc-change,title=Doc+Updated+Needed+For+PR+github.com%2fminio%2fmc%2fpull%2fNNNNN)
|
||||
@@ -1,39 +0,0 @@
|
||||
# Configuration for Lock Threads - https://github.com/dessant/lock-threads-app
|
||||
|
||||
# Number of days of inactivity before a closed issue or pull request is locked
|
||||
daysUntilLock: 365
|
||||
|
||||
# Skip issues and pull requests created before a given timestamp. Timestamp must
|
||||
# follow ISO 8601 (`YYYY-MM-DD`). Set to `false` to disable
|
||||
skipCreatedBefore: false
|
||||
|
||||
# Issues and pull requests with these labels will be ignored. Set to `[]` to disable
|
||||
exemptLabels: []
|
||||
|
||||
# Label to add before locking, such as `outdated`. Set to `false` to disable
|
||||
lockLabel: false
|
||||
|
||||
# Comment to post before locking. Set to `false` to disable
|
||||
lockComment: >-
|
||||
|
||||
This thread has been automatically locked since there has not been
|
||||
any recent activity after it was closed. Please open a new issue for
|
||||
related bugs.
|
||||
|
||||
# Assign `resolved` as the reason for locking. Set to `false` to disable
|
||||
setLockReason: true
|
||||
|
||||
# Limit to only `issues` or `pulls`
|
||||
only: issues
|
||||
|
||||
# Optionally, specify configuration settings just for `issues` or `pulls`
|
||||
# issues:
|
||||
# exemptLabels:
|
||||
# - help-wanted
|
||||
# lockLabel: outdated
|
||||
|
||||
# pulls:
|
||||
# daysUntilLock: 30
|
||||
|
||||
# Repository to extend settings from
|
||||
# _extends: repo
|
||||
@@ -1,59 +0,0 @@
|
||||
# Configuration for probot-stale - https://github.com/probot/stale
|
||||
|
||||
# Number of days of inactivity before an Issue or Pull Request becomes stale
|
||||
daysUntilStale: 90
|
||||
|
||||
# Number of days of inactivity before an Issue or Pull Request with the stale label is closed.
|
||||
# Set to false to disable. If disabled, issues still need to be closed manually, but will remain marked as stale.
|
||||
daysUntilClose: 30
|
||||
|
||||
# Only issues or pull requests with all of these labels are check if stale. Defaults to `[]` (disabled)
|
||||
onlyLabels: []
|
||||
|
||||
# Issues or Pull Requests with these labels will never be considered stale. Set to `[]` to disable
|
||||
exemptLabels:
|
||||
- "security"
|
||||
- "pending discussion"
|
||||
|
||||
# Set to true to ignore issues in a project (defaults to false)
|
||||
exemptProjects: false
|
||||
|
||||
# Set to true to ignore issues in a milestone (defaults to false)
|
||||
exemptMilestones: false
|
||||
|
||||
# Set to true to ignore issues with an assignee (defaults to false)
|
||||
exemptAssignees: false
|
||||
|
||||
# Label to use when marking as stale
|
||||
staleLabel: stale
|
||||
|
||||
# Comment to post when marking as stale. Set to `false` to disable
|
||||
markComment: >-
|
||||
This issue has been automatically marked as stale because it has not had
|
||||
recent activity. It will be closed after 21 days if no further activity
|
||||
occurs. Thank you for your contributions.
|
||||
# Comment to post when removing the stale label.
|
||||
# unmarkComment: >
|
||||
# Your comment here.
|
||||
|
||||
# Comment to post when closing a stale Issue or Pull Request.
|
||||
# closeComment: >
|
||||
# Your comment here.
|
||||
|
||||
# Limit the number of actions per hour, from 1-30. Default is 30
|
||||
limitPerRun: 1
|
||||
|
||||
# Limit to only `issues` or `pulls`
|
||||
# only: issues
|
||||
|
||||
# Optionally, specify configuration settings that are specific to just 'issues' or 'pulls':
|
||||
# pulls:
|
||||
# daysUntilStale: 30
|
||||
# markComment: >
|
||||
# This pull request has been automatically marked as stale because it has not had
|
||||
# recent activity. It will be closed if no further activity occurs. Thank you
|
||||
# for your contributions.
|
||||
|
||||
# issues:
|
||||
# exemptLabels:
|
||||
# - confirmed
|
||||
@@ -1,39 +0,0 @@
|
||||
name: Crosscompile
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
branches:
|
||||
- master
|
||||
|
||||
# This ensures that previous jobs for the PR are canceled when the PR is
|
||||
# updated.
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.head_ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
build:
|
||||
name: Build Tests with Go ${{ matrix.go-version }} on ${{ matrix.os }}
|
||||
runs-on: ${{ matrix.os }}
|
||||
strategy:
|
||||
matrix:
|
||||
go-version: [1.25.x]
|
||||
os: [ubuntu-latest]
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: ${{ matrix.go-version }}
|
||||
check-latest: true
|
||||
- name: Build on ${{ matrix.os }}
|
||||
if: matrix.os == 'ubuntu-latest'
|
||||
env:
|
||||
CGO_ENABLED: 0
|
||||
GO111MODULE: on
|
||||
run: |
|
||||
sudo sysctl net.ipv6.conf.all.disable_ipv6=0
|
||||
sudo sysctl net.ipv6.conf.default.disable_ipv6=0
|
||||
make crosscompile
|
||||
@@ -1,79 +0,0 @@
|
||||
name: Go
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
branches:
|
||||
- master
|
||||
|
||||
# This ensures that previous jobs for the PR are canceled when the PR is
|
||||
# updated.
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.head_ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
build:
|
||||
name: Test on Go ${{ matrix.go-version }} and ${{ matrix.os }}
|
||||
runs-on: ${{ matrix.os }}
|
||||
env:
|
||||
GO111MODULE: on
|
||||
strategy:
|
||||
matrix:
|
||||
go-version: [1.25.x]
|
||||
os: [ubuntu-latest, macos-latest, windows-latest]
|
||||
steps:
|
||||
- name: Set up Go ${{ matrix.go-version }} on ${{ matrix.os }}
|
||||
uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: ${{ matrix.go-version }}
|
||||
id: go
|
||||
|
||||
- name: Check out code into the Go module directory
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Build on ${{ matrix.os }}
|
||||
if: matrix.os == 'windows-latest'
|
||||
run: |
|
||||
go build --ldflags="-s -w" -o %GOPATH%\bin\mc.exe
|
||||
go test -v -race --timeout 30m ./...
|
||||
- name: Build on ${{ matrix.os }}
|
||||
if: matrix.os == 'macos-latest'
|
||||
run: |
|
||||
go build --ldflags="-s -w" -o %GOPATH%\bin\mc
|
||||
go test -v -race --timeout 30m ./...
|
||||
- name: Build on ${{ matrix.os }}
|
||||
if: matrix.os == 'ubuntu-latest'
|
||||
env:
|
||||
ACCESS_KEY: minioadmin
|
||||
SECRET_KEY: minioadmin
|
||||
ENABLE_HTTPS: 1
|
||||
MINIO_CI_CD: 1
|
||||
SERVER_ENDPOINT: localhost:9000
|
||||
MC_TEST_ENABLE_HTTPS: true
|
||||
MC_TEST_SKIP_INSECURE: true
|
||||
MC_TEST_SKIP_BUILD: true
|
||||
run: |
|
||||
wget https://dl.min.io/server/minio/release/linux-amd64/minio && chmod +x minio
|
||||
mkdir -p ~/.minio/certs/ && cp testdata/localhost.crt ~/.minio/certs/public.crt && cp testdata/localhost.key ~/.minio/certs/private.key
|
||||
sudo cp testdata/localhost.crt /usr/local/share/ca-certificates/ && sudo update-ca-certificates
|
||||
./minio server /tmp/test-xl/{1...4}/ & sleep 10
|
||||
make
|
||||
make test-race
|
||||
make verify
|
||||
./functional-tests.sh
|
||||
vetchecks: # Run vet checks against one version.
|
||||
env:
|
||||
CGO_ENABLED: 0
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@v2
|
||||
with:
|
||||
go-version: 1.24.x
|
||||
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v2
|
||||
|
||||
- name: Test 386
|
||||
run: GOOS=linux GOARCH=386 go test -short ./...
|
||||
|
||||
@@ -1,18 +0,0 @@
|
||||
# @format
|
||||
|
||||
name: Issue Workflow
|
||||
|
||||
on:
|
||||
issues:
|
||||
types:
|
||||
- opened
|
||||
|
||||
jobs:
|
||||
add-to-project:
|
||||
name: Add issue to project
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/add-to-project@v0.5.0
|
||||
with:
|
||||
project-url: https://github.com/orgs/miniohq/projects/2
|
||||
github-token: ${{ secrets.BOT_PAT }}
|
||||
@@ -1,25 +0,0 @@
|
||||
name: VulnCheck
|
||||
on:
|
||||
pull_request:
|
||||
branches:
|
||||
- master
|
||||
push:
|
||||
branches:
|
||||
- master
|
||||
jobs:
|
||||
vulncheck:
|
||||
name: Analysis
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Check out code into the Go module directory
|
||||
uses: actions/checkout@v4
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: 1.25.x
|
||||
- name: Get official govulncheck
|
||||
run: go install golang.org/x/vuln/cmd/govulncheck@latest
|
||||
shell: bash
|
||||
- name: Run govulncheck
|
||||
run: govulncheck ./...
|
||||
shell: bash
|
||||
+3
-18
@@ -1,18 +1,3 @@
|
||||
cover.out
|
||||
*~
|
||||
*.test
|
||||
release
|
||||
experimental
|
||||
coverage.txt
|
||||
*.tar.bz2
|
||||
parts/
|
||||
prime/
|
||||
stage/
|
||||
mc
|
||||
.run*
|
||||
.idea/
|
||||
mc.RELEASE*
|
||||
mc.gz
|
||||
.DS_Store
|
||||
.vscode/
|
||||
.bin/
|
||||
/src/
|
||||
/out/
|
||||
/vezha/SOURCE
|
||||
|
||||
@@ -1,42 +0,0 @@
|
||||
version: "2"
|
||||
linters:
|
||||
default: none
|
||||
enable:
|
||||
- gomodguard
|
||||
- govet
|
||||
- ineffassign
|
||||
- misspell
|
||||
- revive
|
||||
- staticcheck
|
||||
- unused
|
||||
settings:
|
||||
misspell:
|
||||
locale: US
|
||||
exclusions:
|
||||
generated: lax
|
||||
rules:
|
||||
- path: (.+)\.go$
|
||||
text: instead of using struct literal
|
||||
- path: (.+)\.go$
|
||||
text: should have a package comment
|
||||
- path: (.+)\.go$
|
||||
text: error strings should not be capitalized or end with punctuation or a newline
|
||||
- path: (.+)\.go$
|
||||
text: error strings should not end with punctuation or newlines
|
||||
- path: (.+)\.go$
|
||||
text: error strings should not be capitalized
|
||||
paths:
|
||||
- third_party$
|
||||
- builtin$
|
||||
- examples$
|
||||
formatters:
|
||||
enable:
|
||||
- gofmt
|
||||
- gofumpt
|
||||
- goimports
|
||||
exclusions:
|
||||
generated: lax
|
||||
paths:
|
||||
- third_party$
|
||||
- builtin$
|
||||
- examples$
|
||||
-167
@@ -1,167 +0,0 @@
|
||||
project_name: mc
|
||||
|
||||
release:
|
||||
name_template: "Version {{.Version}}"
|
||||
disable: true
|
||||
github:
|
||||
owner: minio
|
||||
name: mc
|
||||
|
||||
env:
|
||||
- CGO_ENABLED=0
|
||||
- GO111MODULE=on
|
||||
|
||||
before:
|
||||
hooks:
|
||||
- make clean
|
||||
- go generate ./...
|
||||
- go mod tidy
|
||||
- go mod download
|
||||
|
||||
builds:
|
||||
-
|
||||
goos:
|
||||
- linux
|
||||
- darwin
|
||||
- windows
|
||||
- freebsd
|
||||
|
||||
goarch:
|
||||
- amd64
|
||||
- arm64
|
||||
- arm
|
||||
- ppc64le
|
||||
- s390x
|
||||
|
||||
goarm:
|
||||
- 7
|
||||
|
||||
ignore:
|
||||
- goos: darwin
|
||||
goarch: arm64
|
||||
- goos: darwin
|
||||
goarch: arm
|
||||
- goos: darwin
|
||||
goarch: ppc64le
|
||||
- goos: darwin
|
||||
goarch: s390x
|
||||
- goos: windows
|
||||
goarch: arm64
|
||||
- goos: windows
|
||||
goarch: arm
|
||||
- goos: windows
|
||||
goarch: ppc64le
|
||||
- goos: windows
|
||||
goarch: s390x
|
||||
- goos: freebsd
|
||||
goarch: arm
|
||||
- goos: freebsd
|
||||
goarch: arm64
|
||||
- goos: freebsd
|
||||
goarch: ppc64le
|
||||
- goos: freebsd
|
||||
goarch: s390x
|
||||
|
||||
flags:
|
||||
- -tags=kqueue
|
||||
- -trimpath
|
||||
|
||||
ldflags:
|
||||
- "-s -w -X github.com/minio/mc/cmd.Version={{.Version}} -X github.com/minio/mc/cmd.ReleaseTag={{.Tag}} -X github.com/minio/mc/cmd.CommitID={{.FullCommit}} -X github.com/minio/mc/cmd.ShortCommitID={{.ShortCommit}}"
|
||||
|
||||
archives:
|
||||
-
|
||||
format: binary
|
||||
name_template: "{{ .Binary }}-release/{{ .Os }}-{{ .Arch }}/{{ .Binary }}.{{ .Version }}"
|
||||
|
||||
nfpms:
|
||||
-
|
||||
id: minio
|
||||
package_name: mc
|
||||
vendor: MinIO, Inc.
|
||||
homepage: https://min.io/
|
||||
maintainer: dev@min.io
|
||||
description: MinIO Client (mc) provides a modern alternative to UNIX commands like ls, cat, cp, mirror, diff, find etc. It supports filesystems and Amazon S3 compatible cloud storage service (AWS Signature v2 and v4).
|
||||
license: Apache 2.0
|
||||
bindir: /usr/bin
|
||||
formats:
|
||||
- deb
|
||||
- rpm
|
||||
overrides:
|
||||
deb:
|
||||
file_name_template: "{{ .Binary }}-release/debs/{{ .ProjectName }}-{{ .Version }}_{{ .Arch }}"
|
||||
replacements:
|
||||
arm: armv7
|
||||
files:
|
||||
"NOTICE": "/usr/share/mc/NOTICE"
|
||||
"CREDITS": "/usr/share/mc/CREDITS"
|
||||
"LICENSE": "/usr/share/mc/LICENSE"
|
||||
"README.md": "/usr/share/mc/README.md"
|
||||
rpm:
|
||||
file_name_template: "{{ .Binary }}-release/rpms/{{ .ProjectName }}-{{ .Version }}.{{ .Arch }}"
|
||||
replacements:
|
||||
amd64: x86_64
|
||||
arm64: aarch64
|
||||
arm: armv7
|
||||
files:
|
||||
"NOTICE": "/usr/share/mc/NOTICE"
|
||||
"CREDITS": "/usr/share/mc/CREDITS"
|
||||
"LICENSE": "/usr/share/mc/LICENSE"
|
||||
"README.md": "/usr/share/mc/README.md"
|
||||
|
||||
checksum:
|
||||
algorithm: sha256
|
||||
|
||||
signs:
|
||||
-
|
||||
signature: "${artifact}.asc"
|
||||
cmd: "sh"
|
||||
args:
|
||||
- '-c'
|
||||
- 'gpg --quiet --detach-sign -a ${artifact}'
|
||||
artifacts: all
|
||||
|
||||
changelog:
|
||||
sort: asc
|
||||
filters:
|
||||
exclude:
|
||||
- '^Update yaml files'
|
||||
|
||||
dockers:
|
||||
-
|
||||
goos: linux
|
||||
goarch: amd64
|
||||
dockerfile: Dockerfile.release
|
||||
image_templates:
|
||||
- minio/mc:{{ .Tag }}
|
||||
- minio/mc:latest
|
||||
|
||||
-
|
||||
goos: linux
|
||||
goarch: ppc64le
|
||||
dockerfile: Dockerfile.ppc64le.release
|
||||
image_templates:
|
||||
- minio/mc:{{ .Tag }}-ppc64le
|
||||
|
||||
-
|
||||
goos: linux
|
||||
goarch: s390x
|
||||
dockerfile: Dockerfile.s390x.release
|
||||
image_templates:
|
||||
- minio/mc:{{ .Tag }}-s390x
|
||||
|
||||
-
|
||||
goos: linux
|
||||
goarch: arm64
|
||||
goarm: ''
|
||||
dockerfile: Dockerfile.arm64.release
|
||||
image_templates:
|
||||
- minio/mc:{{ .Tag }}-arm64
|
||||
|
||||
-
|
||||
goos: linux
|
||||
goarch: arm
|
||||
goarm: '7'
|
||||
dockerfile: Dockerfile.arm.release
|
||||
image_templates:
|
||||
- minio/mc:{{ .Tag }}-arm
|
||||
@@ -1,15 +0,0 @@
|
||||
# Generate CONTRIBUTORS.md: contributors.sh
|
||||
|
||||
# Tip for finding duplicates (besides scanning the output of CONTRIBUTORS.md for name
|
||||
# duplicates that aren't also email duplicates): scan the output of:
|
||||
# git log --format='%aE - %aN' | sort -uf
|
||||
#
|
||||
# For explanation on this file format: man git-shortlog
|
||||
|
||||
Anand Babu (AB) Periasamy <ab@min.io> Anand Babu (AB) Periasamy <abperiasamy@users.noreply.github.com>
|
||||
Anand Babu (AB) Periasamy <ab@min.io> <ab@unlocksmith.org>
|
||||
Anis Elleuch <vadmeste@gmail.com>
|
||||
Frederick F. Kautz IV <fkautz@min.io> <fkautz@alumni.cmu.edu>
|
||||
Harshavardhana <harsha@min.io> <harsha@harshavardhana.net>
|
||||
Krishna Srinivas <krishna@min.io> <krishna.srinivas@gmail.com>
|
||||
Bosky <bosky@helpshift.com>
|
||||
-11
@@ -1,11 +0,0 @@
|
||||
## mc (MinIO Client) v/s Midnight Commander (mc)
|
||||
|
||||
There has been some amount of [requests](https://github.com/minio/mc/issues?q=is%3Aissue+midnight+commander+is%3Aclosed) on renaming this project to avoid the conflict with Midnight Commander for Unix distributions. We struggled with this, it is harder to find a name sweeter and shorter than `mc` for MinIO Client.
|
||||
|
||||
Besides `mc` is a single static binary and can reside inside your application and is fully self contained. Midnight Commander (mc) is a free software clone of Norton Commander (nc). MinIO and Midnight shares no code or ideas. Only their abbreviation matches.
|
||||
|
||||
Package managers are free to choose a different name if they like. One such solution [pointed out](https://github.com/minio/mc/issues/873#issuecomment-267583013) by one of our community members.
|
||||
|
||||
```
|
||||
mv ./mc ./mcli
|
||||
```
|
||||
@@ -1,36 +0,0 @@
|
||||
### Setup your mc Github Repository
|
||||
Fork [mc upstream](https://github.com/minio/mc/fork) source repository to your own personal repository.
|
||||
```
|
||||
$ mkdir -p $GOPATH/src/github.com/minio
|
||||
$ cd $GOPATH/src/github.com/minio
|
||||
$ git clone https://github.com/$USER_ID/mc
|
||||
$ cd mc
|
||||
$ make
|
||||
$ ./mc --help
|
||||
```
|
||||
|
||||
### Developer Guidelines
|
||||
|
||||
``mc`` welcomes your contribution. To make the process as seamless as possible, we ask for the following:
|
||||
|
||||
* Go ahead and fork the project and make your changes. We encourage pull requests to discuss code changes.
|
||||
- Fork it
|
||||
- Create your feature branch (git checkout -b my-new-feature)
|
||||
- Commit your changes (git commit -am 'Add some feature')
|
||||
- Push to the branch (git push origin my-new-feature)
|
||||
- Create new Pull Request
|
||||
|
||||
* If you have additional dependencies for ``mc``, ``mc`` manages its dependencies using `go mod`
|
||||
- Run `go get foo/bar`
|
||||
- Edit your code to import foo/bar
|
||||
- Run `GO111MODULE=on go mod tidy` from top-level folder
|
||||
|
||||
* When you're ready to create a pull request, be sure to:
|
||||
- Have test cases for the new code. If you have questions about how to do it, please ask in your pull request.
|
||||
- Run `go fmt`
|
||||
- Squash your commits into a single commit. `git rebase -i`. It's okay to force update your pull request.
|
||||
- Make sure `make install` completes.
|
||||
|
||||
* Read [Effective Go](https://github.com/golang/go/wiki/CodeReviewComments) article from Golang project
|
||||
- `mc` project is conformant with Golang style
|
||||
- if you happen to observe offending code, please feel free to send a pull request
|
||||
-22
@@ -1,22 +0,0 @@
|
||||
FROM golang:1.22-alpine as build
|
||||
|
||||
LABEL maintainer="MinIO Inc <dev@min.io>"
|
||||
|
||||
ENV GOPATH /go
|
||||
ENV CGO_ENABLED 0
|
||||
|
||||
|
||||
RUN apk add -U --no-cache ca-certificates
|
||||
RUN apk add -U curl
|
||||
RUN curl -s -q https://raw.githubusercontent.com/minio/mc/master/LICENSE -o /go/LICENSE
|
||||
RUN curl -s -q https://raw.githubusercontent.com/minio/mc/master/CREDITS -o /go/CREDITS
|
||||
RUN go install -v -ldflags "$(go run buildscripts/gen-ldflags.go)" "github.com/minio/mc@latest"
|
||||
|
||||
FROM scratch
|
||||
|
||||
COPY --from=build /go/bin/mc /usr/bin/mc
|
||||
COPY --from=build /go/CREDITS /licenses/CREDITS
|
||||
COPY --from=build /go/LICENSE /licenses/LICENSE
|
||||
COPY --from=build /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/
|
||||
|
||||
ENTRYPOINT ["mc"]
|
||||
@@ -1,14 +0,0 @@
|
||||
FROM registry.access.redhat.com/ubi8/ubi-minimal:8.8
|
||||
|
||||
LABEL maintainer="MinIO Inc <dev@min.io>"
|
||||
|
||||
COPY mc /usr/bin/
|
||||
COPY CREDITS /licenses/CREDITS
|
||||
COPY LICENSE /licenses/LICENSE
|
||||
|
||||
RUN \
|
||||
microdnf update --nodocs --assumeyes && \
|
||||
microdnf install ca-certificates --nodocs --assumeyes && \
|
||||
microdnf clean all
|
||||
|
||||
ENTRYPOINT ["mc"]
|
||||
@@ -1,24 +0,0 @@
|
||||
FROM registry.access.redhat.com/ubi9/ubi-minimal:latest as build
|
||||
|
||||
RUN microdnf update --nodocs --assumeyes && microdnf install ca-certificates --nodocs --assumeyes
|
||||
|
||||
FROM registry.access.redhat.com/ubi9/ubi-micro:latest
|
||||
|
||||
ARG TARGETARCH
|
||||
ARG RELEASE
|
||||
|
||||
LABEL maintainer="MinIO Inc <dev@min.io>"
|
||||
|
||||
# On RHEL the certificate bundle is located at:
|
||||
# - /etc/pki/tls/certs/ca-bundle.crt (RHEL 6)
|
||||
# - /etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem (RHEL 7)
|
||||
COPY --from=build /etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem /etc/pki/ca-trust/extracted/pem/
|
||||
|
||||
COPY CREDITS /licenses/CREDITS
|
||||
COPY LICENSE /licenses/LICENSE
|
||||
|
||||
ADD https://dl.min.io/client/mc/hotfixes/linux-${TARGETARCH}/archive/mc.${RELEASE} /usr/bin/mc
|
||||
|
||||
RUN chmod +x /usr/bin/mc
|
||||
|
||||
ENTRYPOINT ["mc"]
|
||||
@@ -1,24 +0,0 @@
|
||||
FROM registry.access.redhat.com/ubi9/ubi-minimal:latest AS build
|
||||
|
||||
RUN microdnf update --nodocs --assumeyes && microdnf install ca-certificates --nodocs --assumeyes
|
||||
|
||||
FROM registry.access.redhat.com/ubi9/ubi-micro:latest
|
||||
|
||||
ARG TARGETARCH
|
||||
ARG RELEASE
|
||||
|
||||
LABEL maintainer="MinIO Inc <dev@min.io>"
|
||||
|
||||
# On RHEL the certificate bundle is located at:
|
||||
# - /etc/pki/tls/certs/ca-bundle.crt (RHEL 6)
|
||||
# - /etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem (RHEL 7)
|
||||
COPY --from=build /etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem /etc/pki/ca-trust/extracted/pem/
|
||||
|
||||
COPY CREDITS /licenses/CREDITS
|
||||
COPY LICENSE /licenses/LICENSE
|
||||
|
||||
ADD https://dl.minio.io/client/mc/release/linux-${TARGETARCH}/archive/mc.${RELEASE} /usr/bin/mc
|
||||
|
||||
RUN chmod +x /usr/bin/mc
|
||||
|
||||
ENTRYPOINT ["mc"]
|
||||
@@ -1,24 +0,0 @@
|
||||
FROM registry.access.redhat.com/ubi8/ubi-minimal:latest AS build
|
||||
|
||||
RUN microdnf update --nodocs --assumeyes && microdnf install ca-certificates --nodocs --assumeyes
|
||||
|
||||
FROM registry.access.redhat.com/ubi8/ubi-micro:latest
|
||||
|
||||
ARG TARGETARCH
|
||||
ARG RELEASE
|
||||
|
||||
LABEL maintainer="MinIO Inc <dev@min.io>"
|
||||
|
||||
# On RHEL the certificate bundle is located at:
|
||||
# - /etc/pki/tls/certs/ca-bundle.crt (RHEL 6)
|
||||
# - /etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem (RHEL 7)
|
||||
COPY --from=build /etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem /etc/pki/ca-trust/extracted/pem/
|
||||
|
||||
COPY CREDITS /licenses/CREDITS
|
||||
COPY LICENSE /licenses/LICENSE
|
||||
|
||||
ADD https://dl.minio.io/client/mc/release/linux-${TARGETARCH}/archive/mc.${RELEASE} /usr/bin/mc
|
||||
|
||||
RUN chmod +x /usr/bin/mc
|
||||
|
||||
ENTRYPOINT ["mc"]
|
||||
@@ -1,661 +0,0 @@
|
||||
GNU AFFERO GENERAL PUBLIC LICENSE
|
||||
Version 3, 19 November 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU Affero General Public License is a free, copyleft license for
|
||||
software and other kinds of works, specifically designed to ensure
|
||||
cooperation with the community in the case of network server software.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
our General Public Licenses are intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
Developers that use our General Public Licenses protect your rights
|
||||
with two steps: (1) assert copyright on the software, and (2) offer
|
||||
you this License which gives you legal permission to copy, distribute
|
||||
and/or modify the software.
|
||||
|
||||
A secondary benefit of defending all users' freedom is that
|
||||
improvements made in alternate versions of the program, if they
|
||||
receive widespread use, become available for other developers to
|
||||
incorporate. Many developers of free software are heartened and
|
||||
encouraged by the resulting cooperation. However, in the case of
|
||||
software used on network servers, this result may fail to come about.
|
||||
The GNU General Public License permits making a modified version and
|
||||
letting the public access it on a server without ever releasing its
|
||||
source code to the public.
|
||||
|
||||
The GNU Affero General Public License is designed specifically to
|
||||
ensure that, in such cases, the modified source code becomes available
|
||||
to the community. It requires the operator of a network server to
|
||||
provide the source code of the modified version running there to the
|
||||
users of that server. Therefore, public use of a modified version, on
|
||||
a publicly accessible server, gives the public access to the source
|
||||
code of the modified version.
|
||||
|
||||
An older license, called the Affero General Public License and
|
||||
published by Affero, was designed to accomplish similar goals. This is
|
||||
a different license, not a version of the Affero GPL, but Affero has
|
||||
released a new version of the Affero GPL which permits relicensing under
|
||||
this license.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU Affero General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Remote Network Interaction; Use with the GNU General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, if you modify the
|
||||
Program, your modified version must prominently offer all users
|
||||
interacting with it remotely through a computer network (if your version
|
||||
supports such interaction) an opportunity to receive the Corresponding
|
||||
Source of your version by providing access to the Corresponding Source
|
||||
from a network server at no charge, through some standard or customary
|
||||
means of facilitating copying of software. This Corresponding Source
|
||||
shall include the Corresponding Source for any work covered by version 3
|
||||
of the GNU General Public License that is incorporated pursuant to the
|
||||
following paragraph.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the work with which it is combined will remain governed by version
|
||||
3 of the GNU General Public License.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU Affero General Public License from time to time. Such new versions
|
||||
will be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU Affero General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU Affero General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU Affero General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If your software can interact with users remotely through a computer
|
||||
network, you should also make sure that it provides a way for users to
|
||||
get its source. For example, if your program is a web application, its
|
||||
interface could display a "Source" link that leads users to an archive
|
||||
of the code. There are many ways you could offer source, and different
|
||||
solutions will be better for different programs; see section 13 for the
|
||||
specific requirements.
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU AGPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
||||
@@ -1,102 +0,0 @@
|
||||
PWD := $(shell pwd)
|
||||
GOPATH := $(shell go env GOPATH)
|
||||
LDFLAGS := $(shell go run buildscripts/gen-ldflags.go)
|
||||
|
||||
TARGET_GOARCH ?= $(shell go env GOARCH)
|
||||
TARGET_GOOS ?= $(shell go env GOOS)
|
||||
|
||||
VERSION ?= $(shell git describe --tags)
|
||||
TAG ?= "minio/mc:$(VERSION)"
|
||||
|
||||
GOLANGCI = $(GOPATH)/bin/golangci-lint
|
||||
|
||||
all: build
|
||||
|
||||
checks:
|
||||
@echo "Checking dependencies"
|
||||
@(env bash $(PWD)/buildscripts/checkdeps.sh)
|
||||
|
||||
getdeps:
|
||||
@mkdir -p ${GOPATH}/bin
|
||||
@echo "Installing tools" && go install tool
|
||||
|
||||
crosscompile:
|
||||
@(env bash $(PWD)/buildscripts/cross-compile.sh)
|
||||
|
||||
verifiers: getdeps vet lint
|
||||
|
||||
docker: build
|
||||
@docker build -t $(TAG) . -f Dockerfile.dev
|
||||
|
||||
vet:
|
||||
@echo "Running $@"
|
||||
@GO111MODULE=on go vet github.com/minio/mc/...
|
||||
|
||||
lint-fix: getdeps ## runs golangci-lint suite of linters with automatic fixes
|
||||
@echo "Running $@ check"
|
||||
@$(GOLANGCI) run --build-tags kqueue --timeout=10m --config ./.golangci.yml --fix
|
||||
|
||||
lint: getdeps
|
||||
@echo "Running $@ check"
|
||||
@$(GOLANGCI) run --build-tags kqueue --timeout=10m --config ./.golangci.yml
|
||||
|
||||
# Builds mc, runs the verifiers then runs the tests.
|
||||
check: test
|
||||
test: verifiers build
|
||||
@echo "Running unit tests"
|
||||
@GO111MODULE=on CGO_ENABLED=0 go test -tags kqueue ./... 1>/dev/null
|
||||
@echo "Running functional tests"
|
||||
@GO111MODULE=on MC_TEST_RUN_FULL_SUITE=true go test -race -v --timeout 20m ./... -run Test_FullSuite
|
||||
|
||||
test-race: verifiers build
|
||||
@echo "Running unit tests under -race"
|
||||
@GO111MODULE=on go test -race -v --timeout 20m ./... 1>/dev/null
|
||||
|
||||
# Verify mc binary
|
||||
verify:
|
||||
@echo "Verifying build with race"
|
||||
@GO111MODULE=on CGO_ENABLED=1 go build -race -tags kqueue -trimpath --ldflags "$(LDFLAGS)" -o $(PWD)/mc 1>/dev/null
|
||||
@echo "Running functional tests"
|
||||
@GO111MODULE=on MC_TEST_RUN_FULL_SUITE=true go test -race -v --timeout 20m ./... -run Test_FullSuite
|
||||
|
||||
# Builds mc locally.
|
||||
build: checks
|
||||
@echo "Building mc binary to './mc'"
|
||||
@GO111MODULE=on GOOS=$(TARGET_GOOS) GOARCH=$(TARGET_GOARCH) CGO_ENABLED=0 go build -trimpath -tags kqueue --ldflags "$(LDFLAGS)" -o $(PWD)/mc
|
||||
|
||||
hotfix-vars:
|
||||
$(eval LDFLAGS := $(shell MC_RELEASE="RELEASE" MC_HOTFIX="hotfix.$(shell git rev-parse --short HEAD)" go run buildscripts/gen-ldflags.go $(shell git describe --tags --abbrev=0 | \
|
||||
sed 's#RELEASE\.\([0-9]\+\)-\([0-9]\+\)-\([0-9]\+\)T\([0-9]\+\)-\([0-9]\+\)-\([0-9]\+\)Z#\1-\2-\3T\4:\5:\6Z#')))
|
||||
$(eval VERSION := $(shell git describe --tags --abbrev=0).hotfix.$(shell git rev-parse --short HEAD))
|
||||
$(eval TAG := "minio/mc:$(VERSION)")
|
||||
|
||||
hotfix: hotfix-vars install ## builds mc binary with hotfix tags
|
||||
@mv -f ./mc ./mc.$(VERSION)
|
||||
@minisign -qQSm ./mc.$(VERSION) -s "${CRED_DIR}/minisign.key" < "${CRED_DIR}/minisign-passphrase"
|
||||
@sha256sum < ./mc.$(VERSION) | sed 's, -,mc.$(VERSION),g' > mc.$(VERSION).sha256sum
|
||||
|
||||
hotfix-push: hotfix
|
||||
@scp -q -r mc.$(VERSION)* minio@dl-0.min.io:~/releases/client/mc/hotfixes/$(TARGET_GOOS)-$(TARGET_GOARCH)/archive/
|
||||
@scp -q -r mc.$(VERSION)* minio@dl-1.min.io:~/releases/client/mc/hotfixes/$(TARGET_GOOS)-$(TARGET_GOARCH)/archive/
|
||||
@echo "Published new hotfix binaries at https://dl.min.io/client/mc/hotfixes/$(TARGET_GOOS)-$(TARGET_GOARCH)/archive/mc.$(VERSION)"
|
||||
|
||||
docker-hotfix-push: docker-hotfix
|
||||
@docker push -q $(TAG) && echo "Published new container $(TAG)"
|
||||
|
||||
docker-hotfix: hotfix-push checks ## builds mc docker container with hotfix tags
|
||||
@echo "Building mc docker image '$(TAG)'"
|
||||
@docker build -q --no-cache -t $(TAG) --build-arg RELEASE=$(VERSION) . -f Dockerfile.hotfix
|
||||
|
||||
# Builds MinIO and installs it to $GOPATH/bin.
|
||||
install: build
|
||||
@echo "Installing mc binary to '$(GOPATH)/bin/mc'"
|
||||
@mkdir -p $(GOPATH)/bin && cp -f $(PWD)/mc $(GOPATH)/bin/mc
|
||||
@echo "Installation successful. To learn more, try \"mc --help\"."
|
||||
|
||||
clean:
|
||||
@echo "Cleaning up all the generated files"
|
||||
@find . -name '*.test' | xargs rm -fv
|
||||
@find . -name '*~' | xargs rm -fv
|
||||
@rm -rvf mc
|
||||
@rm -rvf build
|
||||
@rm -rvf release
|
||||
@@ -1,9 +0,0 @@
|
||||
MinIO Client (C) 2014-2020 MinIO, Inc.
|
||||
|
||||
This product includes software developed at MinIO, Inc.
|
||||
(https://min.io/).
|
||||
|
||||
The MinIO project contains unmodified/modified subcomponents too with
|
||||
separate copyright notices and license terms. Your use of the source
|
||||
code for the these subcomponents is subject to the terms and conditions
|
||||
of the following licenses.
|
||||
@@ -1,252 +0,0 @@
|
||||
# MinIO Client Quickstart Guide
|
||||
[](https://slack.min.io) [](https://goreportcard.com/report/minio/mc) [](https://hub.docker.com/r/minio/mc/) [](https://github.com/minio/mc/blob/master/LICENSE)
|
||||
|
||||
# Documentation
|
||||
- [MC documentation](https://docs.min.io/community/minio-object-store/reference/minio-mc.html)
|
||||
|
||||
MinIO Client (mc) provides a modern alternative to UNIX commands like ls, cat, cp, mirror, diff, find etc. It supports filesystems and Amazon S3 compatible cloud storage service (AWS Signature v2 and v4).
|
||||
|
||||
```
|
||||
alias manage server credentials in configuration file
|
||||
admin manage MinIO servers
|
||||
anonymous manage anonymous access to buckets and objects
|
||||
batch manage batch jobs
|
||||
cp copy objects
|
||||
cat display object contents
|
||||
diff list differences in object name, size, and date between two buckets
|
||||
du summarize disk usage recursively
|
||||
encrypt manage bucket encryption config
|
||||
event manage object notifications
|
||||
find search for objects
|
||||
get get s3 object to local
|
||||
head display first 'n' lines of an object
|
||||
ilm manage bucket lifecycle
|
||||
idp manage MinIO IDentity Provider server configuration
|
||||
license license related commands
|
||||
legalhold manage legal hold for object(s)
|
||||
ls list buckets and objects
|
||||
mb make a bucket
|
||||
mv move objects
|
||||
mirror synchronize object(s) to a remote site
|
||||
od measure single stream upload and download
|
||||
ping perform liveness check
|
||||
pipe stream STDIN to an object
|
||||
put upload an object to a bucket
|
||||
quota manage bucket quota
|
||||
rm remove object(s)
|
||||
retention set retention for object(s)
|
||||
rb remove a bucket
|
||||
replicate configure server side bucket replication
|
||||
ready checks if the cluster is ready or not
|
||||
sql run sql queries on objects
|
||||
stat show object metadata
|
||||
support support related commands
|
||||
share generate URL for temporary access to an object
|
||||
tree list buckets and objects in a tree format
|
||||
tag manage tags for bucket and object(s)
|
||||
undo undo PUT/DELETE operations
|
||||
update update mc to latest release
|
||||
version manage bucket versioning
|
||||
watch listen for object notification events
|
||||
```
|
||||
|
||||
## Docker Container
|
||||
### Stable
|
||||
```
|
||||
docker pull minio/mc
|
||||
docker run minio/mc ls play
|
||||
```
|
||||
|
||||
### Edge
|
||||
```
|
||||
docker pull minio/mc:edge
|
||||
docker run minio/mc:edge ls play
|
||||
```
|
||||
|
||||
**Note:** Above examples run `mc` against MinIO [_play_ environment](#test-your-setup) by default. To run `mc` against other S3 compatible servers, start the container this way:
|
||||
|
||||
```
|
||||
docker run -it --entrypoint=/bin/sh minio/mc
|
||||
```
|
||||
|
||||
then use the [`mc alias` command](#add-a-cloud-storage-service).
|
||||
|
||||
### GitLab CI
|
||||
When using the Docker container in GitLab CI, you must [set the entrypoint to an empty string](https://docs.gitlab.com/ee/ci/docker/using_docker_images.html#override-the-entrypoint-of-an-image).
|
||||
|
||||
```
|
||||
deploy:
|
||||
image:
|
||||
name: minio/mc
|
||||
entrypoint: ['']
|
||||
stage: deploy
|
||||
before_script:
|
||||
- mc alias set minio $MINIO_HOST $MINIO_ACCESS_KEY $MINIO_SECRET_KEY
|
||||
script:
|
||||
- mc cp <source> <destination>
|
||||
```
|
||||
|
||||
## macOS
|
||||
### Homebrew
|
||||
Install mc packages using [Homebrew](http://brew.sh/)
|
||||
|
||||
```
|
||||
brew install minio/stable/mc
|
||||
mc --help
|
||||
```
|
||||
|
||||
## GNU/Linux
|
||||
### Binary Download
|
||||
| Platform | Architecture | URL |
|
||||
| ---------- | -------- |------|
|
||||
|GNU/Linux|64-bit Intel|https://dl.min.io/client/mc/release/linux-amd64/mc |
|
||||
|GNU/Linux|64-bit PPC|https://dl.min.io/client/mc/release/linux-ppc64le/mc |
|
||||
|GNU/Linux|64-bit ARM|https://dl.min.io/client/mc/release/linux-arm64/mc |
|
||||
|Linux/s390x|S390X|https://dl.min.io/client/mc/release/linux-s390x/mc |
|
||||
|
||||
```
|
||||
wget https://dl.min.io/client/mc/release/linux-amd64/mc
|
||||
chmod +x mc
|
||||
./mc --help
|
||||
```
|
||||
|
||||
## Microsoft Windows
|
||||
### Binary Download
|
||||
| Platform | Architecture | URL |
|
||||
| ---------- | -------- |------|
|
||||
|Microsoft Windows|64-bit Intel|https://dl.min.io/client/mc/release/windows-amd64/mc.exe |
|
||||
|
||||
```
|
||||
mc.exe --help
|
||||
```
|
||||
|
||||
## Install from Source
|
||||
Source installation is only intended for developers and advanced users. If you do not have a working Golang environment, please follow [How to install Golang](https://golang.org/doc/install). Minimum version required is [go1.22](https://golang.org/dl/#stable)
|
||||
|
||||
```sh
|
||||
go install github.com/minio/mc@latest
|
||||
```
|
||||
|
||||
## Add a Cloud Storage Service
|
||||
If you are planning to use `mc` only on POSIX compatible filesystems, you may skip this step and proceed to [everyday use](#everyday-use).
|
||||
|
||||
To add one or more Amazon S3 compatible hosts, please follow the instructions below. `mc` stores all its configuration information in ``~/.mc/config.json`` file.
|
||||
|
||||
```
|
||||
mc alias set <ALIAS> <YOUR-S3-ENDPOINT> <YOUR-ACCESS-KEY> <YOUR-SECRET-KEY> --api <API-SIGNATURE> --path <BUCKET-LOOKUP-TYPE>
|
||||
```
|
||||
|
||||
`<ALIAS>` is simply a short name to your cloud storage service. S3 end-point, access and secret keys are supplied by your cloud storage provider. API signature is an optional argument. By default, it is set to "S3v4".
|
||||
|
||||
Path is an optional argument. It is used to indicate whether dns or path style url requests are supported by the server. It accepts "on", "off" as valid values to enable/disable path style requests.. By default, it is set to "auto" and SDK automatically determines the type of url lookup to use.
|
||||
|
||||
### Example - MinIO Cloud Storage
|
||||
MinIO server startup banner displays URL, access and secret keys.
|
||||
|
||||
```
|
||||
mc alias set minio http://192.168.1.51 BKIKJAA5BMMU2RHO6IBB V7f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12
|
||||
```
|
||||
|
||||
### Example - Amazon S3 Cloud Storage
|
||||
Get your AccessKeyID and SecretAccessKey by following [AWS Credentials Guide](http://docs.aws.amazon.com/general/latest/gr/aws-security-credentials.html).
|
||||
|
||||
```
|
||||
mc alias set s3 https://s3.amazonaws.com BKIKJAA5BMMU2RHO6IBB V7f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12
|
||||
```
|
||||
|
||||
**Note**: As an IAM user on Amazon S3 you need to make sure the user has full access to the buckets or set the following restricted policy for your IAM user
|
||||
|
||||
```json
|
||||
{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [
|
||||
{
|
||||
"Sid": "AllowBucketStat",
|
||||
"Effect": "Allow",
|
||||
"Action": [
|
||||
"s3:HeadBucket"
|
||||
],
|
||||
"Resource": "*"
|
||||
},
|
||||
{
|
||||
"Sid": "AllowThisBucketOnly",
|
||||
"Effect": "Allow",
|
||||
"Action": "s3:*",
|
||||
"Resource": [
|
||||
"arn:aws:s3:::<your-restricted-bucket>/*",
|
||||
"arn:aws:s3:::<your-restricted-bucket>"
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
### Example - Google Cloud Storage
|
||||
Get your AccessKeyID and SecretAccessKey by following [Google Credentials Guide](https://cloud.google.com/storage/docs/migrating?hl=en#keys)
|
||||
|
||||
```
|
||||
mc alias set gcs https://storage.googleapis.com BKIKJAA5BMMU2RHO6IBB V8f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12
|
||||
```
|
||||
|
||||
## Test Your Setup
|
||||
`mc` is pre-configured with https://play.min.io, aliased as "play". It is a hosted MinIO server for testing and development purpose. To test Amazon S3, simply replace "play" with "s3" or the alias you used at the time of setup.
|
||||
|
||||
*Example:*
|
||||
|
||||
List all buckets from https://play.min.io
|
||||
|
||||
```
|
||||
mc ls play
|
||||
[2016-03-22 19:47:48 PDT] 0B my-bucketname/
|
||||
[2016-03-22 22:01:07 PDT] 0B mytestbucket/
|
||||
[2016-03-22 20:04:39 PDT] 0B mybucketname/
|
||||
[2016-01-28 17:23:11 PST] 0B newbucket/
|
||||
[2016-03-20 09:08:36 PDT] 0B s3git-test/
|
||||
```
|
||||
|
||||
Make a bucket
|
||||
`mb` command creates a new bucket.
|
||||
|
||||
*Example:*
|
||||
```
|
||||
mc mb play/mybucket
|
||||
Bucket created successfully `play/mybucket`.
|
||||
```
|
||||
|
||||
Copy Objects
|
||||
`cp` command copies data from one or more sources to a target.
|
||||
|
||||
*Example:*
|
||||
```
|
||||
mc cp myobject.txt play/mybucket
|
||||
myobject.txt: 14 B / 14 B ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ 100.00 % 41 B/s 0
|
||||
```
|
||||
|
||||
## Everyday Use
|
||||
|
||||
### Shell aliases
|
||||
You may add shell aliases to override your common Unix tools.
|
||||
|
||||
```
|
||||
alias ls='mc ls'
|
||||
alias cp='mc cp'
|
||||
alias cat='mc cat'
|
||||
alias mkdir='mc mb'
|
||||
alias pipe='mc pipe'
|
||||
alias find='mc find'
|
||||
```
|
||||
|
||||
### Shell autocompletion
|
||||
In case you are using bash, zsh or fish. Shell completion is embedded by default in `mc`, to install auto-completion use `mc --autocompletion`. Restart the shell, mc will auto-complete commands as shown below.
|
||||
|
||||
```
|
||||
mc <TAB>
|
||||
admin config diff find ls mirror policy session sql update watch
|
||||
cat cp event head mb pipe rm share stat version
|
||||
```
|
||||
|
||||
## Contribute to MinIO Project
|
||||
Please follow MinIO [Contributor's Guide](https://github.com/minio/mc/blob/master/CONTRIBUTING.md)
|
||||
|
||||
## License
|
||||
Use of `mc` is governed by the GNU AGPLv3 license that can be found in the [LICENSE](https://github.com/minio/mc/blob/master/LICENSE) file.
|
||||
-173
@@ -1,173 +0,0 @@
|
||||
# MinIO客户端快速入门指南
|
||||
[](https://slack.min.io) [](https://goreportcard.com/report/minio/mc) [](https://hub.docker.com/r/minio/mc/)
|
||||
|
||||
MinIO Client (mc)为ls,cat,cp,mirror,diff,find等UNIX命令提供了一种替代方案。它支持文件系统和兼容Amazon S3的云存储服务(AWS Signature v2和v4)。
|
||||
|
||||
|
||||
```
|
||||
ls 列出文件和文件夹。
|
||||
mb 创建一个存储桶或一个文件夹。
|
||||
cat 显示文件和对象内容。
|
||||
pipe 将一个STDIN重定向到一个对象或者文件或者STDOUT。
|
||||
share 生成用于共享的URL。
|
||||
cp 拷贝文件和对象。
|
||||
mirror 给存储桶和文件夹做镜像。
|
||||
find 基于参数查找文件。
|
||||
diff 对两个文件夹或者存储桶比较差异。
|
||||
rm 删除文件和对象。
|
||||
events 管理对象通知。
|
||||
watch 监听文件和对象的事件。
|
||||
anonymous 管理访问策略。
|
||||
session 为cp命令管理保存的会话。
|
||||
config 管理mc配置文件。
|
||||
update 检查软件更新。
|
||||
version 输出版本信息。
|
||||
```
|
||||
|
||||
## Docker容器
|
||||
### 稳定版
|
||||
```
|
||||
docker pull minio/mc
|
||||
docker run minio/mc ls play
|
||||
```
|
||||
|
||||
### 尝鲜版
|
||||
```
|
||||
docker pull minio/mc:edge
|
||||
docker run minio/mc:edge ls play
|
||||
```
|
||||
|
||||
**注意:** 上述示例默认使用MinIO[演示环境](#test-your-setup)做演示,如果想用`mc`操作其它S3兼容的服务,采用下面的方式来启动容器:
|
||||
|
||||
```
|
||||
docker run -it --entrypoint=/bin/sh minio/mc
|
||||
```
|
||||
|
||||
然后使用[`mc config`命令](#add-a-cloud-storage-service)。
|
||||
|
||||
## macOS
|
||||
### Homebrew
|
||||
使用[Homebrew](http://brew.sh/)安装mc。
|
||||
|
||||
```
|
||||
brew install minio/stable/mc
|
||||
mc --help
|
||||
```
|
||||
|
||||
## GNU/Linux
|
||||
### 下载二进制文件
|
||||
| 平台 | CPU架构 | URL |
|
||||
| ---------- | -------- |------|
|
||||
|GNU/Linux|64-bit Intel|https://dl.min.io/client/mc/release/linux-amd64/mc |
|
||||
|
||||
```
|
||||
chmod +x mc
|
||||
./mc --help
|
||||
```
|
||||
|
||||
## Microsoft Windows
|
||||
### 下载二进制文件
|
||||
| 平台 | CPU架构 | URL |
|
||||
| ---------- | -------- |------|
|
||||
|Microsoft Windows|64-bit Intel|https://dl.min.io/client/mc/release/windows-amd64/mc.exe |
|
||||
|
||||
```
|
||||
mc.exe --help
|
||||
```
|
||||
|
||||
## 通过源码安装
|
||||
通过源码安装仅适用于开发人员和高级用户。`mc update`命令不支持基于源码安装的更新通知。请从https://min.io/download/#minio-client下载官方版本。
|
||||
|
||||
如果您没有Golang环境,请参照[如何安装Golang](https://golang.org/doc/install)。
|
||||
|
||||
```
|
||||
go get -d github.com/minio/mc
|
||||
cd ${GOPATH}/src/github.com/minio/mc
|
||||
make
|
||||
```
|
||||
|
||||
## 添加一个云存储服务
|
||||
如果你打算仅在POSIX兼容文件系统中使用`mc`,那你可以直接略过本节,跳到[日常使用](#everyday-use)。
|
||||
|
||||
添加一个或多个S3兼容的服务,请参考下面说明。`mc`将所有的配置信息都存储在``~/.mc/config.json``文件中。
|
||||
|
||||
```
|
||||
mc alias set <ALIAS> <YOUR-S3-ENDPOINT> <YOUR-ACCESS-KEY> <YOUR-SECRET-KEY> [--api API-SIGNATURE]
|
||||
```
|
||||
|
||||
别名就是给你的云存储服务起了一个短点的外号。S3 endpoint,access key和secret key是你的云存储服务提供的。API签名是可选参数,默认情况下,它被设置为"S3v4"。
|
||||
|
||||
### 示例-MinIO云存储
|
||||
从MinIO服务获得URL、access key和secret key。
|
||||
|
||||
```
|
||||
mc alias set minio http://192.168.1.51 BKIKJAA5BMMU2RHO6IBB V7f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12 --api s3v4
|
||||
```
|
||||
|
||||
### 示例-Amazon S3云存储
|
||||
参考[AWS Credentials指南](http://docs.aws.amazon.com/general/latest/gr/aws-security-credentials.html)获取你的AccessKeyID和SecretAccessKey。
|
||||
|
||||
```
|
||||
mc alias set s3 https://s3.amazonaws.com BKIKJAA5BMMU2RHO6IBB V7f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12 --api s3v4
|
||||
```
|
||||
|
||||
### 示例-Google云存储
|
||||
参考[Google Credentials Guide](https://cloud.google.com/storage/docs/migrating?hl=en#keys)获取你的AccessKeyID和SecretAccessKey。
|
||||
|
||||
```
|
||||
mc alias set gcs https://storage.googleapis.com BKIKJAA5BMMU2RHO6IBB V8f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12 --api s3v2
|
||||
```
|
||||
|
||||
注意:Google云存储只支持旧版签名版本V2,所以你需要选择S3v2。
|
||||
|
||||
## 验证
|
||||
`mc`预先配置了云存储服务URL:https://play.min.io,别名“play”。它是一个用于研发和测试的MinIO服务。如果想测试Amazon S3,你可以将“play”替换为“s3”。
|
||||
|
||||
*示例:*
|
||||
|
||||
列出https://play.min.io上的所有存储桶。
|
||||
|
||||
```
|
||||
mc ls play
|
||||
[2016-03-22 19:47:48 PDT] 0B my-bucketname/
|
||||
[2016-03-22 22:01:07 PDT] 0B mytestbucket/
|
||||
[2016-03-22 20:04:39 PDT] 0B mybucketname/
|
||||
[2016-01-28 17:23:11 PST] 0B newbucket/
|
||||
[2016-03-20 09:08:36 PDT] 0B s3git-test/
|
||||
```
|
||||
<a name="everyday-use"></a>
|
||||
## 日常使用
|
||||
|
||||
### Shell别名
|
||||
你可以添加shell别名来覆盖默认的Unix工具命令。
|
||||
|
||||
```
|
||||
alias ls='mc ls'
|
||||
alias cp='mc cp'
|
||||
alias cat='mc cat'
|
||||
alias mkdir='mc mb'
|
||||
alias pipe='mc pipe'
|
||||
alias find='mc find'
|
||||
```
|
||||
|
||||
### Shell自动补全
|
||||
你也可以下载[`autocomplete/bash_autocomplete`](https://raw.githubusercontent.com/minio/mc/master/autocomplete/bash_autocomplete)到`/etc/bash_completion.d/`,然后将其重命名为`mc`。别忘了在这个文件运行source命令让其在你的当前shell上可用。
|
||||
|
||||
```
|
||||
sudo wget https://raw.githubusercontent.com/minio/mc/master/autocomplete/bash_autocomplete -O /etc/bash_completion.d/mc
|
||||
source /etc/bash_completion.d/mc
|
||||
```
|
||||
|
||||
```
|
||||
mc <TAB>
|
||||
admin config diff ls mirror policy session update watch
|
||||
cat cp events mb pipe rm share version
|
||||
```
|
||||
|
||||
## 了解更多
|
||||
- [MinIO Client完全指南](https://docs.min.io/community/minio-object-store/reference/minio-mc.html?ref=gh)
|
||||
- [MinIO快速入门](https://docs.min.io/community/minio-object-store/operations/deployments/baremetal-deploy-minio-on-redhat-linux.html?ref=gh)
|
||||
- [MinIO官方文档](https://docs.min.io/community/minio-object-store/index.html?ref=gh)
|
||||
|
||||
## 贡献
|
||||
请遵守MinIO[贡献者指南](https://github.com/minio/mc/blob/master/docs/zh_CN/CONTRIBUTING.md)
|
||||
@@ -1 +0,0 @@
|
||||
theme: jekyll-theme-minimal
|
||||
@@ -1,24 +0,0 @@
|
||||
## FIXME:
|
||||
## In OSX, 'sort -V' option does not exist, hence
|
||||
## we have our own version compare function.
|
||||
## Once OSX has the option, below function is good enough.
|
||||
##
|
||||
## check_minimum_version() {
|
||||
## versions=($(echo -e "$1\n$2" | sort -V))
|
||||
## return [ "$1" == "${versions[0]}" ]
|
||||
## }
|
||||
##
|
||||
check_minimum_version() {
|
||||
IFS='.' read -r -a varray1 <<< "$1"
|
||||
IFS='.' read -r -a varray2 <<< "$2"
|
||||
|
||||
for i in "${!varray1[@]}"; do
|
||||
if [[ ${varray1[i]} -lt ${varray2[i]} ]]; then
|
||||
return 0
|
||||
elif [[ ${varray1[i]} -gt ${varray2[i]} ]]; then
|
||||
return 1
|
||||
fi
|
||||
done
|
||||
|
||||
return 0
|
||||
}
|
||||
@@ -1,128 +0,0 @@
|
||||
#!/bin/bash
|
||||
#
|
||||
# Copyright (c) 2015-2021 MinIO, Inc.
|
||||
#
|
||||
# This file is part of MinIO Object Storage stack
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU Affero General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
#
|
||||
|
||||
_init() {
|
||||
# Save release LDFLAGS
|
||||
LDFLAGS=$(go run buildscripts/gen-ldflags.go)
|
||||
|
||||
# Extract release tag
|
||||
release_tag=$(echo $LDFLAGS | awk {'print $6'} | cut -f2 -d=)
|
||||
|
||||
# Verify release tag.
|
||||
if [ -z "$release_tag" ]; then
|
||||
echo "Release tag cannot be empty. Please check return value of \`go run buildscripts/gen-ldflags.go\`"
|
||||
exit 1;
|
||||
fi
|
||||
|
||||
# Extract release string.
|
||||
release_str=$(echo $MC_RELEASE | tr '[:upper:]' '[:lower:]')
|
||||
|
||||
# Verify release string.
|
||||
if [ -z "$release_str" ]; then
|
||||
echo "Release string cannot be empty. Please set \`MC_RELEASE\` env variable."
|
||||
exit 1;
|
||||
fi
|
||||
|
||||
# List of supported architectures
|
||||
SUPPORTED_OSARCH='linux/amd64 linux/ppc64le windows/amd64 darwin/amd64'
|
||||
|
||||
## System binaries
|
||||
CP=`which cp`
|
||||
SHASUM=`which shasum`
|
||||
SHA256SUM="${SHASUM} -a 256"
|
||||
SED=`which sed`
|
||||
}
|
||||
|
||||
go_build() {
|
||||
local osarch=$1
|
||||
os=$(echo $osarch | cut -f1 -d'/')
|
||||
arch=$(echo $osarch | cut -f2 -d'/')
|
||||
package=$(go list -f '{{.ImportPath}}')
|
||||
echo -n "-->"
|
||||
printf "%15s:%s\n" "${osarch}" "${package}"
|
||||
|
||||
# Release binary name
|
||||
release_bin="$release_str/$os-$arch/$(basename $package).$release_tag"
|
||||
# Release binary downloadable name
|
||||
release_real_bin="$release_str/$os-$arch/$(basename $package)"
|
||||
|
||||
# Release sha1sum name
|
||||
release_shasum="$release_str/$os-$arch/$(basename $package).${release_tag}.shasum"
|
||||
# Release sha1sum default
|
||||
release_shasum_default="$release_str/$os-$arch/$(basename $package).shasum"
|
||||
|
||||
# Release sha256sum name
|
||||
release_sha256sum="$release_str/$os-$arch/$(basename $package).${release_tag}.sha256sum"
|
||||
# Release sha256sum default
|
||||
release_sha256sum_default="$release_str/$os-$arch/$(basename $package).sha256sum"
|
||||
|
||||
# Go build to build the binary.
|
||||
CGO_ENABLED=0 GOOS=$os GOARCH=$arch go build -tags kqueue --ldflags "${LDFLAGS}" -o $release_bin
|
||||
|
||||
# Create copy
|
||||
if [ $os == "windows" ]; then
|
||||
$CP -p $release_bin ${release_real_bin}.exe
|
||||
else
|
||||
$CP -p $release_bin $release_real_bin
|
||||
fi
|
||||
|
||||
# Calculate sha1sum
|
||||
shasum_str=$(${SHASUM} ${release_bin})
|
||||
echo ${shasum_str} | $SED "s/$release_str\/$os-$arch\///g" > $release_shasum
|
||||
$CP -p $release_shasum $release_shasum_default
|
||||
|
||||
# Calculate sha256sum
|
||||
sha256sum_str=$(${SHA256SUM} ${release_bin})
|
||||
echo ${sha256sum_str} | $SED "s/$release_str\/$os-$arch\///g" > $release_sha256sum
|
||||
$CP -p $release_sha256sum $release_sha256sum_default
|
||||
}
|
||||
|
||||
main() {
|
||||
# Build releases.
|
||||
echo "Executing $release_str builds for OS: ${SUPPORTED_OSARCH}"
|
||||
echo "Choose an OS Arch from the below"
|
||||
for osarch in ${SUPPORTED_OSARCH}; do
|
||||
echo ${osarch}
|
||||
done
|
||||
|
||||
read -p "If you want to build for all, Just press Enter: " chosen_osarch
|
||||
if [ "$chosen_osarch" = "" ] || [ "$chosen_osarch" = "all" ]; then
|
||||
for each_osarch in ${SUPPORTED_OSARCH}; do
|
||||
go_build ${each_osarch}
|
||||
done
|
||||
else
|
||||
local found=0
|
||||
for each_osarch in ${SUPPORTED_OSARCH}; do
|
||||
if [ "$chosen_osarch" = "$each_osarch" ]; then
|
||||
found=1
|
||||
fi
|
||||
done
|
||||
if [ ${found} -eq 1 ]; then
|
||||
go_build ${chosen_osarch}
|
||||
else
|
||||
echo "Unknown architecture \"${chosen_osarch}\""
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
|
||||
}
|
||||
|
||||
# Run main.
|
||||
_init && main
|
||||
@@ -1,137 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
#
|
||||
# Copyright (c) 2015-2021 MinIO, Inc.
|
||||
#
|
||||
# This file is part of MinIO Object Storage stack
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU Affero General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
#
|
||||
|
||||
# shellcheck source=buildscripts/build.env
|
||||
. "$(pwd)/buildscripts/build.env"
|
||||
|
||||
_init() {
|
||||
|
||||
shopt -s extglob
|
||||
|
||||
## Minimum required versions for build dependencies
|
||||
GIT_VERSION="1.0"
|
||||
GO_VERSION="1.13"
|
||||
OSX_VERSION="10.8"
|
||||
KNAME=$(uname -s)
|
||||
ARCH=$(uname -m)
|
||||
case "${KNAME}" in
|
||||
SunOS )
|
||||
ARCH=$(isainfo -k)
|
||||
;;
|
||||
esac
|
||||
}
|
||||
|
||||
## FIXME:
|
||||
## In OSX, 'readlink -f' option does not exist, hence
|
||||
## we have our own readlink -f behavior here.
|
||||
## Once OSX has the option, below function is good enough.
|
||||
##
|
||||
## readlink() {
|
||||
## return /bin/readlink -f "$1"
|
||||
## }
|
||||
##
|
||||
readlink() {
|
||||
TARGET_FILE=$1
|
||||
|
||||
cd `dirname $TARGET_FILE`
|
||||
TARGET_FILE=`basename $TARGET_FILE`
|
||||
|
||||
# Iterate down a (possible) chain of symlinks
|
||||
while [ -L "$TARGET_FILE" ]
|
||||
do
|
||||
TARGET_FILE=$(env readlink $TARGET_FILE)
|
||||
cd `dirname $TARGET_FILE`
|
||||
TARGET_FILE=`basename $TARGET_FILE`
|
||||
done
|
||||
|
||||
# Compute the canonicalized name by finding the physical path
|
||||
# for the directory we're in and appending the target file.
|
||||
PHYS_DIR=`pwd -P`
|
||||
RESULT=$PHYS_DIR/$TARGET_FILE
|
||||
echo $RESULT
|
||||
}
|
||||
|
||||
assert_is_supported_arch() {
|
||||
case "${ARCH}" in
|
||||
x86_64 | amd64 | ppc64le | aarch64 | arm* | s390x | loong64 | loongarch64 )
|
||||
return
|
||||
;;
|
||||
*)
|
||||
echo "Arch '${ARCH}' is not supported. Supported Arch: [x86_64, amd64, ppc64le, aarch64, arm*, s390x, loong64, loongarch64]"
|
||||
exit 1
|
||||
esac
|
||||
}
|
||||
|
||||
assert_is_supported_os() {
|
||||
case "${KNAME}" in
|
||||
Linux | FreeBSD | OpenBSD | NetBSD | DragonFly | SunOS )
|
||||
return
|
||||
;;
|
||||
Darwin )
|
||||
osx_host_version=$(env sw_vers -productVersion)
|
||||
if ! check_minimum_version "${OSX_VERSION}" "${osx_host_version}"; then
|
||||
echo "OSX version '${osx_host_version}' is not supported. Minimum supported version: ${OSX_VERSION}"
|
||||
exit 1
|
||||
fi
|
||||
return
|
||||
;;
|
||||
*)
|
||||
echo "OS '${KNAME}' is not supported. Supported OS: [Linux, FreeBSD, OpenBSD, NetBSD, Darwin, DragonFly]"
|
||||
exit 1
|
||||
esac
|
||||
}
|
||||
|
||||
assert_check_golang_env() {
|
||||
if ! which go >/dev/null 2>&1; then
|
||||
echo "Cannot find go binary in your PATH configuration, please refer to Go installation document at https://golang.org/doc/install"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
installed_go_version=$(go version | sed 's/^.* go\([0-9.]*\).*$/\1/')
|
||||
if ! check_minimum_version "${GO_VERSION}" "${installed_go_version}"; then
|
||||
echo "Go runtime version '${installed_go_version}' is unsupported. Minimum supported version: ${GO_VERSION} to compile."
|
||||
exit 1
|
||||
fi
|
||||
}
|
||||
|
||||
assert_check_deps() {
|
||||
# support unusual Git versions such as: 2.7.4 (Apple Git-66)
|
||||
installed_git_version=$(git version | perl -ne '$_ =~ m/git version (.*?)( |$)/; print "$1\n";')
|
||||
if ! check_minimum_version "${GIT_VERSION}" "${installed_git_version}"; then
|
||||
echo "Git version '${installed_git_version}' is not supported. Minimum supported version: ${GIT_VERSION}"
|
||||
exit 1
|
||||
fi
|
||||
}
|
||||
|
||||
main() {
|
||||
## Check for supported arch
|
||||
assert_is_supported_arch
|
||||
|
||||
## Check for supported os
|
||||
assert_is_supported_os
|
||||
|
||||
## Check for Go environment
|
||||
assert_check_golang_env
|
||||
|
||||
## Check for dependencies
|
||||
assert_check_deps
|
||||
}
|
||||
|
||||
_init && main "$@"
|
||||
@@ -1,57 +0,0 @@
|
||||
#!/bin/bash
|
||||
#
|
||||
# Copyright (c) 2015-2021 MinIO, Inc.
|
||||
#
|
||||
# This file is part of MinIO Object Storage stack
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU Affero General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
#
|
||||
|
||||
set -e
|
||||
|
||||
# Enable tracing if set.
|
||||
[ -n "$BASH_XTRACEFD" ] && set -x
|
||||
|
||||
function _init() {
|
||||
## All binaries are static make sure to disable CGO.
|
||||
export CGO_ENABLED=0
|
||||
|
||||
## List of architectures and OS to test coss compilation.
|
||||
SUPPORTED_OSARCH="linux/ppc64le linux/s390x linux/mips64 linux/amd64 windows/amd64 darwin/amd64 darwin/arm64 linux/arm64 linux/arm"
|
||||
}
|
||||
|
||||
function _build() {
|
||||
local osarch=$1
|
||||
IFS=/ read -r -a arr <<<"$osarch"
|
||||
os="${arr[0]}"
|
||||
arch="${arr[1]}"
|
||||
package=$(go list -f '{{.ImportPath}}')
|
||||
printf -- "--> %15s:%s\n" "${osarch}" "${package}"
|
||||
|
||||
# Go build to build the binary.
|
||||
export GOOS=$os
|
||||
export GOARCH=$arch
|
||||
export GO111MODULE=on
|
||||
export CGO_ENABLED=0
|
||||
go build -tags kqueue -o /dev/null
|
||||
}
|
||||
|
||||
function main() {
|
||||
echo "Testing builds for OS/Arch: ${SUPPORTED_OSARCH}"
|
||||
for each_osarch in ${SUPPORTED_OSARCH}; do
|
||||
_build "${each_osarch}"
|
||||
done
|
||||
}
|
||||
|
||||
_init && main "$@"
|
||||
@@ -1,120 +0,0 @@
|
||||
//go:build ignore
|
||||
// +build ignore
|
||||
|
||||
// Copyright (c) 2015-2021 MinIO, Inc.
|
||||
//
|
||||
// This file is part of MinIO Object Storage stack
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
func genLDFlags(version string) string {
|
||||
releaseTag, date := releaseTag(version)
|
||||
copyrightYear := fmt.Sprintf("%d", date.Year())
|
||||
|
||||
var ldflagsStr string
|
||||
ldflagsStr = "-s -w -X github.com/minio/mc/cmd.Version=" + version + " "
|
||||
ldflagsStr = ldflagsStr + "-X github.com/minio/mc/cmd.CopyrightYear=" + copyrightYear + " "
|
||||
ldflagsStr = ldflagsStr + "-X github.com/minio/mc/cmd.ReleaseTag=" + releaseTag + " "
|
||||
ldflagsStr = ldflagsStr + "-X github.com/minio/mc/cmd.CommitID=" + commitID() + " "
|
||||
ldflagsStr = ldflagsStr + "-X github.com/minio/mc/cmd.ShortCommitID=" + commitID()[:12]
|
||||
return ldflagsStr
|
||||
}
|
||||
|
||||
// releaseTag prints release tag to the console for easy git tagging.
|
||||
func releaseTag(version string) (string, time.Time) {
|
||||
relPrefix := "DEVELOPMENT"
|
||||
if prefix := os.Getenv("MC_RELEASE"); prefix != "" {
|
||||
relPrefix = prefix
|
||||
}
|
||||
|
||||
relSuffix := ""
|
||||
if hotfix := os.Getenv("MC_HOTFIX"); hotfix != "" {
|
||||
relSuffix = hotfix
|
||||
}
|
||||
|
||||
relTag := strings.ReplaceAll(version, " ", "-")
|
||||
relTag = strings.ReplaceAll(relTag, ":", "-")
|
||||
t, err := time.Parse("2006-01-02T15-04-05Z", relTag)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
relTag = strings.ReplaceAll(relTag, ",", "")
|
||||
relTag = relPrefix + "." + relTag
|
||||
if relSuffix != "" {
|
||||
relTag += "." + relSuffix
|
||||
}
|
||||
|
||||
return relTag, t
|
||||
}
|
||||
|
||||
// commitID returns the abbreviated commit-id hash of the last commit.
|
||||
func commitID() string {
|
||||
// git log --format="%h" -n1
|
||||
var (
|
||||
commit []byte
|
||||
e error
|
||||
)
|
||||
cmdName := "git"
|
||||
cmdArgs := []string{"log", "--format=%H", "-n1"}
|
||||
if commit, e = exec.Command(cmdName, cmdArgs...).Output(); e != nil {
|
||||
fmt.Fprintln(os.Stderr, "Error generating git commit-id: ", e)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
return strings.TrimSpace(string(commit))
|
||||
}
|
||||
|
||||
func commitTime() time.Time {
|
||||
// git log --format=%cD -n1
|
||||
var (
|
||||
commitUnix []byte
|
||||
err error
|
||||
)
|
||||
cmdName := "git"
|
||||
cmdArgs := []string{"log", "--format=%cI", "-n1"}
|
||||
if commitUnix, err = exec.Command(cmdName, cmdArgs...).Output(); err != nil {
|
||||
fmt.Fprintln(os.Stderr, "Error generating git commit-time: ", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
t, err := time.Parse(time.RFC3339, strings.TrimSpace(string(commitUnix)))
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, "Error generating git commit-time: ", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
return t.UTC()
|
||||
}
|
||||
|
||||
func main() {
|
||||
var version string
|
||||
if len(os.Args) > 1 {
|
||||
version = os.Args[1]
|
||||
} else {
|
||||
version = commitTime().Format(time.RFC3339)
|
||||
}
|
||||
|
||||
fmt.Println(genLDFlags(version))
|
||||
}
|
||||
@@ -1,75 +0,0 @@
|
||||
// Copyright (c) 2015-2022 MinIO, Inc.
|
||||
//
|
||||
// This file is part of MinIO Object Storage stack
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"os"
|
||||
|
||||
json "github.com/minio/colorjson"
|
||||
"github.com/minio/minio-go/v7/pkg/policy"
|
||||
)
|
||||
|
||||
// isValidAccessPERM - is provided access perm string supported.
|
||||
func (b accessPerms) isValidAccessPERM() bool {
|
||||
switch b {
|
||||
case accessNone, accessDownload, accessUpload, accessPrivate, accessPublic:
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (b accessPerms) isValidAccessFile() bool {
|
||||
file, err := os.Open(string(b))
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
var policy policy.BucketAccessPolicy
|
||||
if json.NewDecoder(file).Decode(&policy) != nil {
|
||||
fatalIf(errDummy().Trace(), "Unable to parse access file.")
|
||||
return false
|
||||
}
|
||||
|
||||
if policy.Version != "2012-10-17" {
|
||||
fatalIf(errDummy().Trace(), "Invalid policy version. Only 2012-10-17 is supported.")
|
||||
return false
|
||||
}
|
||||
|
||||
for _, statement := range policy.Statements {
|
||||
if statement.Effect != "Allow" && statement.Effect != "Deny" {
|
||||
fatalIf(errDummy().Trace(), "Invalid policy effect. Only Allow and Deny are supported.")
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
// accessPerms - access level.
|
||||
type accessPerms string
|
||||
|
||||
// different types of Access perm's currently supported by policy command.
|
||||
const (
|
||||
accessNone = accessPerms("none")
|
||||
accessDownload = accessPerms("download")
|
||||
accessUpload = accessPerms("upload")
|
||||
accessPrivate = accessPerms("private")
|
||||
accessPublic = accessPerms("public")
|
||||
accessCustom = accessPerms("custom")
|
||||
)
|
||||
@@ -1,194 +0,0 @@
|
||||
// Copyright (c) 2015-2022 MinIO, Inc.
|
||||
//
|
||||
// This file is part of MinIO Object Storage stack
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/pkg/v3/console"
|
||||
|
||||
"github.com/cheggaaa/pb"
|
||||
json "github.com/minio/colorjson"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
)
|
||||
|
||||
// accounter keeps tabs of ongoing data transfer information.
|
||||
type accounter struct {
|
||||
current int64
|
||||
|
||||
total int64
|
||||
startTime time.Time
|
||||
startValue int64
|
||||
refreshRate time.Duration
|
||||
currentValue int64
|
||||
finishOnce sync.Once
|
||||
isFinished chan struct{}
|
||||
}
|
||||
|
||||
// Instantiate a new accounter.
|
||||
func newAccounter(total int64) *accounter {
|
||||
acct := &accounter{
|
||||
total: total,
|
||||
startTime: time.Now(),
|
||||
startValue: 0,
|
||||
refreshRate: time.Millisecond * 200,
|
||||
isFinished: make(chan struct{}),
|
||||
currentValue: -1,
|
||||
}
|
||||
go acct.writer()
|
||||
return acct
|
||||
}
|
||||
|
||||
// write calculate the final speed.
|
||||
func (a *accounter) write(current int64) (float64, time.Duration) {
|
||||
fromStart := time.Since(a.startTime)
|
||||
currentFromStart := current - a.startValue
|
||||
if currentFromStart > 0 {
|
||||
speed := float64(currentFromStart) / (float64(fromStart) / float64(time.Second))
|
||||
return speed, fromStart
|
||||
}
|
||||
return 0.0, 0
|
||||
}
|
||||
|
||||
// writer update new accounting data for a specified refreshRate.
|
||||
func (a *accounter) writer() {
|
||||
a.Update()
|
||||
for {
|
||||
select {
|
||||
case <-a.isFinished:
|
||||
return
|
||||
case <-time.After(a.refreshRate):
|
||||
a.Update()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// accountStat cantainer for current stats captured.
|
||||
type accountStat struct {
|
||||
Status string `json:"status"`
|
||||
Total int64 `json:"total"`
|
||||
Transferred int64 `json:"transferred"`
|
||||
Duration time.Duration `json:"duration"`
|
||||
Speed float64 `json:"speed"`
|
||||
}
|
||||
|
||||
func (c accountStat) JSON() string {
|
||||
c.Status = "success"
|
||||
accountMessageBytes, e := json.MarshalIndent(c, "", " ")
|
||||
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
|
||||
|
||||
return string(accountMessageBytes)
|
||||
}
|
||||
|
||||
func (c accountStat) String() string {
|
||||
dspOrder := []col{colGreen} // Header
|
||||
dspOrder = append(dspOrder, colGrey)
|
||||
var printColors []*color.Color
|
||||
for _, c := range dspOrder {
|
||||
printColors = append(printColors, getPrintCol(c))
|
||||
}
|
||||
|
||||
tbl := console.NewTable(printColors, []bool{false, false, false, false}, 0)
|
||||
|
||||
var builder strings.Builder
|
||||
cellText := make([][]string, 0, 2)
|
||||
cellText = append(cellText, []string{
|
||||
"Total",
|
||||
"Transferred",
|
||||
"Duration",
|
||||
"Speed",
|
||||
})
|
||||
|
||||
speedBox := pb.Format(int64(c.Speed)).To(pb.U_BYTES).String()
|
||||
if speedBox == "" {
|
||||
speedBox = "0 MB"
|
||||
} else {
|
||||
speedBox = speedBox + "/s"
|
||||
}
|
||||
|
||||
cellText = append(cellText, []string{
|
||||
pb.Format(c.Total).To(pb.U_BYTES).String(),
|
||||
pb.Format(c.Transferred).To(pb.U_BYTES).String(),
|
||||
pb.Format(int64(c.Duration)).To(pb.U_DURATION).String(),
|
||||
speedBox,
|
||||
})
|
||||
|
||||
e := tbl.PopulateTable(&builder, cellText)
|
||||
fatalIf(probe.NewError(e), "unable to populate the table")
|
||||
|
||||
return builder.String()
|
||||
}
|
||||
|
||||
// Stat provides current stats captured.
|
||||
func (a *accounter) Stat() accountStat {
|
||||
var acntStat accountStat
|
||||
a.finishOnce.Do(func() {
|
||||
close(a.isFinished)
|
||||
acntStat.Total = a.total
|
||||
acntStat.Transferred = atomic.LoadInt64(&a.current)
|
||||
acntStat.Speed, acntStat.Duration = a.write(atomic.LoadInt64(&a.current))
|
||||
})
|
||||
return acntStat
|
||||
}
|
||||
|
||||
// Update update with new values loaded atomically.
|
||||
func (a *accounter) Update() {
|
||||
c := atomic.LoadInt64(&a.current)
|
||||
if c != a.currentValue {
|
||||
a.write(c)
|
||||
a.currentValue = c
|
||||
}
|
||||
}
|
||||
|
||||
// Set sets the current value atomically.
|
||||
func (a *accounter) Set(n int64) *accounter {
|
||||
atomic.StoreInt64(&a.current, n)
|
||||
return a
|
||||
}
|
||||
|
||||
// Get gets current value atomically
|
||||
func (a *accounter) Get() int64 {
|
||||
return atomic.LoadInt64(&a.current)
|
||||
}
|
||||
|
||||
func (a *accounter) SetTotal(n int64) {
|
||||
atomic.StoreInt64(&a.total, n)
|
||||
}
|
||||
|
||||
// Add add to current value atomically.
|
||||
func (a *accounter) Add(n int64) int64 {
|
||||
return atomic.AddInt64(&a.current, n)
|
||||
}
|
||||
|
||||
// Read implements Reader which internally updates current value.
|
||||
func (a *accounter) Read(p []byte) (n int, err error) {
|
||||
defer func() {
|
||||
// Upload retry can read one object twice; Avoid read to be greater than Total
|
||||
if n, t := a.Get(), atomic.LoadInt64(&a.total); t > 0 && n > t {
|
||||
a.Set(t)
|
||||
}
|
||||
}()
|
||||
|
||||
n = len(p)
|
||||
a.Add(int64(n))
|
||||
return
|
||||
}
|
||||
@@ -1,94 +0,0 @@
|
||||
// Copyright (c) 2015-2024 MinIO, Inc.
|
||||
//
|
||||
// This file is part of MinIO Object Storage stack
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"github.com/minio/cli"
|
||||
)
|
||||
|
||||
var adminAccesskeyCreateFlags = []cli.Flag{
|
||||
cli.StringFlag{
|
||||
Name: "access-key",
|
||||
Usage: "set an access key for the account",
|
||||
},
|
||||
cli.StringFlag{
|
||||
Name: "secret-key",
|
||||
Usage: "set a secret key for the account",
|
||||
},
|
||||
cli.StringFlag{
|
||||
Name: "policy",
|
||||
Usage: "path to a JSON policy file",
|
||||
},
|
||||
cli.StringFlag{
|
||||
Name: "name",
|
||||
Usage: "friendly name for the account",
|
||||
},
|
||||
cli.StringFlag{
|
||||
Name: "description",
|
||||
Usage: "description for the account",
|
||||
},
|
||||
cli.StringFlag{
|
||||
Name: "expiry-duration",
|
||||
Usage: "duration before the access key expires",
|
||||
},
|
||||
cli.StringFlag{
|
||||
Name: "expiry",
|
||||
Usage: "expiry date for the access key",
|
||||
},
|
||||
}
|
||||
|
||||
var adminAccesskeyCreateCmd = cli.Command{
|
||||
Name: "create",
|
||||
Usage: "create access key pairs for users",
|
||||
Action: mainAdminAccesskeyCreate,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: append(adminAccesskeyCreateFlags, globalFlags...),
|
||||
OnUsageError: onUsageError,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
{{.HelpName}} [FLAGS] [TARGET]
|
||||
|
||||
FLAGS:
|
||||
{{range .VisibleFlags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
1. Create a new access key pair with the same policy as the authenticated user
|
||||
{{.Prompt}} {{.HelpName}} myminio/
|
||||
|
||||
2. Create a new access key pair with custom access key and secret key
|
||||
{{.Prompt}} {{.HelpName}} myminio/ --access-key myaccesskey --secret-key mysecretkey
|
||||
|
||||
3. Create a new access key pair for user 'tester' that expires in 1 day
|
||||
{{.Prompt}} {{.HelpName}} myminio/ tester --expiry-duration 24h
|
||||
|
||||
4. Create a new access key pair for authenticated user that expires on 2025-01-01
|
||||
{{.Prompt}} {{.HelpName}} --expiry 2025-01-01
|
||||
|
||||
5. Create a new access key pair for user 'tester' with a custom policy
|
||||
{{.Prompt}} {{.HelpName}} myminio/ tester --policy /path/to/policy.json
|
||||
|
||||
6. Create a new access key pair for user 'tester' with a custom name and description
|
||||
{{.Prompt}} {{.HelpName}} myminio/ tester --name "Tester's Access Key" --description "Access key for tester"
|
||||
`,
|
||||
}
|
||||
|
||||
func mainAdminAccesskeyCreate(ctx *cli.Context) error {
|
||||
return commonAccesskeyCreate(ctx, false)
|
||||
}
|
||||
@@ -1,48 +0,0 @@
|
||||
// Copyright (c) 2015-2024 MinIO, Inc.
|
||||
//
|
||||
// This file is part of MinIO Object Storage stack
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"github.com/minio/cli"
|
||||
)
|
||||
|
||||
var adminAccesskeyDisableCmd = cli.Command{
|
||||
Name: "disable",
|
||||
Usage: "disable an access key",
|
||||
Action: mainAdminAccesskeyDisable,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
OnUsageError: onUsageError,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
{{.HelpName}} [FLAGS] [TARGET]
|
||||
|
||||
FLAGS:
|
||||
{{range .VisibleFlags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
1. Disable access key
|
||||
{{.Prompt}} {{.HelpName}} myminio myaccesskey
|
||||
`,
|
||||
}
|
||||
|
||||
func mainAdminAccesskeyDisable(ctx *cli.Context) error {
|
||||
return enableDisableAccesskey(ctx, false)
|
||||
}
|
||||
@@ -1,77 +0,0 @@
|
||||
// Copyright (c) 2015-2024 MinIO, Inc.
|
||||
//
|
||||
// This file is part of MinIO Object Storage stack
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"github.com/minio/cli"
|
||||
)
|
||||
|
||||
var adminAccesskeyEditFlags = []cli.Flag{
|
||||
cli.StringFlag{
|
||||
Name: "secret-key",
|
||||
Usage: "set a secret key for the account",
|
||||
},
|
||||
cli.StringFlag{
|
||||
Name: "policy",
|
||||
Usage: "path to a JSON policy file",
|
||||
},
|
||||
cli.StringFlag{
|
||||
Name: "name",
|
||||
Usage: "friendly name for the account",
|
||||
},
|
||||
cli.StringFlag{
|
||||
Name: "description",
|
||||
Usage: "description for the account",
|
||||
},
|
||||
cli.StringFlag{
|
||||
Name: "expiry-duration",
|
||||
Usage: "duration before the access key expires",
|
||||
},
|
||||
cli.StringFlag{
|
||||
Name: "expiry",
|
||||
Usage: "expiry date for the access key",
|
||||
},
|
||||
}
|
||||
|
||||
var adminAccesskeyEditCmd = cli.Command{
|
||||
Name: "edit",
|
||||
Usage: "edit existing access keys",
|
||||
Action: mainAdminAccesskeyEdit,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: append(adminAccesskeyEditFlags, globalFlags...),
|
||||
OnUsageError: onUsageError,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
{{.HelpName}} [FLAGS] [TARGET]
|
||||
|
||||
FLAGS:
|
||||
{{range .VisibleFlags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
1. Change the secret key for the access key "testkey"
|
||||
{{.Prompt}} {{.HelpName}} myminio/ testkey --secret-key 'xxxxxxx'
|
||||
2. Change the expiry duration for the access key "testkey"
|
||||
{{.Prompt}} {{.HelpName}} myminio/ testkey ---expiry-duration 24h
|
||||
`,
|
||||
}
|
||||
|
||||
func mainAdminAccesskeyEdit(ctx *cli.Context) error {
|
||||
return commonAccesskeyEdit(ctx)
|
||||
}
|
||||
@@ -1,48 +0,0 @@
|
||||
// Copyright (c) 2015-2024 MinIO, Inc.
|
||||
//
|
||||
// This file is part of MinIO Object Storage stack
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"github.com/minio/cli"
|
||||
)
|
||||
|
||||
var adminAccesskeyEnableCmd = cli.Command{
|
||||
Name: "enable",
|
||||
Usage: "enable an access key",
|
||||
Action: mainAdminAccesskeyEnable,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
OnUsageError: onUsageError,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
{{.HelpName}} [FLAGS] [TARGET]
|
||||
|
||||
FLAGS:
|
||||
{{range .VisibleFlags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
1. Enable access key
|
||||
{{.Prompt}} {{.HelpName}} myminio myaccesskey
|
||||
`,
|
||||
}
|
||||
|
||||
func mainAdminAccesskeyEnable(ctx *cli.Context) error {
|
||||
return enableDisableAccesskey(ctx, true)
|
||||
}
|
||||
@@ -1,202 +0,0 @@
|
||||
// Copyright (c) 2015-2023 MinIO, Inc.
|
||||
//
|
||||
// This file is part of MinIO Object Storage stack
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/charmbracelet/lipgloss"
|
||||
humanize "github.com/dustin/go-humanize"
|
||||
"github.com/minio/cli"
|
||||
json "github.com/minio/colorjson"
|
||||
"github.com/minio/madmin-go/v3"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
)
|
||||
|
||||
var adminAccesskeyInfoCmd = cli.Command{
|
||||
Name: "info",
|
||||
Usage: "info about given access key pairs",
|
||||
Action: mainAdminAccesskeyInfo,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
OnUsageError: onUsageError,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
{{.HelpName}} [FLAGS] TARGET ACCESSKEY [ACCESSKEY...]
|
||||
|
||||
FLAGS:
|
||||
{{range .VisibleFlags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
1. Get info for the access key "testkey"
|
||||
{{.Prompt}} {{.HelpName}} local/ testkey
|
||||
2. Get info for the access keys "testkey" and "testkey2"
|
||||
{{.Prompt}} {{.HelpName}} local/ testkey testkey2
|
||||
`,
|
||||
}
|
||||
|
||||
type accesskeyMessage struct {
|
||||
op string
|
||||
Status string `json:"status"`
|
||||
AccessKey string `json:"accessKey"`
|
||||
SecretKey string `json:"secretKey,omitempty"`
|
||||
STS bool `json:"sts,omitempty"`
|
||||
ParentUser string `json:"parentUser,omitempty"`
|
||||
AccountStatus string `json:"accountStatus,omitempty"`
|
||||
ImpliedPolicy bool `json:"impliedPolicy,omitempty"`
|
||||
Policy json.RawMessage `json:"policy,omitempty"`
|
||||
Name string `json:"name,omitempty"`
|
||||
Description string `json:"description,omitempty"`
|
||||
Expiration *time.Time `json:"expiration,omitempty"`
|
||||
Provider string `json:"provider,omitempty"`
|
||||
ProviderInfo providerInfo `json:"providerInfo,omitempty"`
|
||||
}
|
||||
|
||||
func (m accesskeyMessage) String() string {
|
||||
labelStyle := lipgloss.NewStyle().Foreground(lipgloss.Color("#04B575")) // green
|
||||
o := strings.Builder{}
|
||||
switch m.op {
|
||||
case "info":
|
||||
expirationStr := "NONE"
|
||||
if m.Expiration != nil && !m.Expiration.IsZero() && !m.Expiration.Equal(timeSentinel) {
|
||||
expirationStr = humanize.Time(*m.Expiration)
|
||||
}
|
||||
policyStr := "embedded"
|
||||
if m.ImpliedPolicy {
|
||||
policyStr = "implied"
|
||||
}
|
||||
statusStr := "enabled"
|
||||
if m.AccountStatus == "off" {
|
||||
statusStr = "disabled"
|
||||
}
|
||||
stsStr := "false"
|
||||
if m.STS {
|
||||
stsStr = "true"
|
||||
}
|
||||
o.WriteString(iFmt(0, "%s %s\n", labelStyle.Render("Access Key:"), m.AccessKey))
|
||||
o.WriteString(iFmt(0, "%s %s\n", labelStyle.Render("Parent User:"), m.ParentUser))
|
||||
o.WriteString(iFmt(0, "%s %s\n", labelStyle.Render("Status:"), statusStr))
|
||||
o.WriteString(iFmt(0, "%s %s\n", labelStyle.Render("Policy:"), policyStr))
|
||||
o.WriteString(iFmt(0, "%s %s\n", labelStyle.Render("Name:"), m.Name))
|
||||
o.WriteString(iFmt(0, "%s %s\n", labelStyle.Render("Description:"), m.Description))
|
||||
o.WriteString(iFmt(0, "%s %s\n", labelStyle.Render("Expiration:"), expirationStr))
|
||||
o.WriteString(iFmt(0, "%s %s\n", labelStyle.Render("STS:"), stsStr))
|
||||
o.WriteString(iFmt(0, "%s %s\n", labelStyle.Render("Provider:"), m.Provider))
|
||||
if m.ProviderInfo != nil {
|
||||
o.WriteString(iFmt(0, "%s\n", labelStyle.Render("Provider Specific Info:")))
|
||||
o.WriteString(m.ProviderInfo.String())
|
||||
}
|
||||
case "create":
|
||||
expirationStr := "NONE"
|
||||
if m.Expiration != nil && !m.Expiration.IsZero() && !m.Expiration.Equal(timeSentinel) {
|
||||
expirationStr = m.Expiration.String()
|
||||
}
|
||||
o.WriteString(iFmt(0, "%s %s\n", labelStyle.Render("Access Key:"), m.AccessKey))
|
||||
o.WriteString(iFmt(0, "%s %s\n", labelStyle.Render("Secret Key:"), m.SecretKey))
|
||||
o.WriteString(iFmt(0, "%s %s\n", labelStyle.Render("Expiration:"), expirationStr))
|
||||
o.WriteString(iFmt(0, "%s %s\n", labelStyle.Render("Name:"), m.Name))
|
||||
o.WriteString(iFmt(0, "%s %s\n", labelStyle.Render("Description:"), m.Description))
|
||||
case "remove":
|
||||
o.WriteString(labelStyle.Render(iFmt(0, "Successfully removed access key `%s`.", m.AccessKey)))
|
||||
case "edit":
|
||||
o.WriteString(labelStyle.Render(iFmt(0, "Successfully edited access key `%s`.", m.AccessKey)))
|
||||
case "enable":
|
||||
o.WriteString(labelStyle.Render(iFmt(0, "Successfully enabled access key `%s`.", m.AccessKey)))
|
||||
case "disable":
|
||||
o.WriteString(labelStyle.Render(iFmt(0, "Successfully disabled access key `%s`.", m.AccessKey)))
|
||||
}
|
||||
return o.String()
|
||||
}
|
||||
|
||||
func (m accesskeyMessage) JSON() string {
|
||||
m.Status = "success"
|
||||
jsonMessageBytes, e := json.MarshalIndent(m, "", " ")
|
||||
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
|
||||
|
||||
return string(jsonMessageBytes)
|
||||
}
|
||||
|
||||
type providerInfo interface {
|
||||
String() string
|
||||
}
|
||||
|
||||
func mainAdminAccesskeyInfo(ctx *cli.Context) error {
|
||||
return commonAccesskeyInfo(ctx)
|
||||
}
|
||||
|
||||
func commonAccesskeyInfo(ctx *cli.Context) error {
|
||||
if len(ctx.Args()) < 2 {
|
||||
showCommandHelpAndExit(ctx, 1) // last argument is exit code
|
||||
}
|
||||
|
||||
args := ctx.Args()
|
||||
aliasedURL := args.Get(0)
|
||||
accessKeys := args.Tail()
|
||||
|
||||
// Create a new MinIO Admin Client
|
||||
client, err := newAdminClient(aliasedURL)
|
||||
fatalIf(err, "Unable to initialize admin connection.")
|
||||
|
||||
for _, accessKey := range accessKeys {
|
||||
// Assume service account by default
|
||||
res, e := client.InfoAccessKey(globalContext, accessKey)
|
||||
fatalIf(probe.NewError(e), "Unable to get info for access key.")
|
||||
m := accesskeyMessage{
|
||||
op: "info",
|
||||
AccessKey: accessKey,
|
||||
ParentUser: res.ParentUser,
|
||||
AccountStatus: res.AccountStatus,
|
||||
ImpliedPolicy: res.ImpliedPolicy,
|
||||
Policy: json.RawMessage(res.Policy),
|
||||
Name: res.Name,
|
||||
Description: res.Description,
|
||||
Expiration: nilExpiry(res.Expiration),
|
||||
Provider: res.UserProvider,
|
||||
}
|
||||
|
||||
switch res.UserProvider {
|
||||
case madmin.LDAPProvider:
|
||||
info := res.LDAPSpecificInfo
|
||||
m.ProviderInfo = ldapAccessKeyInfo{
|
||||
Username: info.Username,
|
||||
}
|
||||
case madmin.OpenIDProvider:
|
||||
info := res.OpenIDSpecificInfo
|
||||
m.ProviderInfo = openIDAccessKeyInfo{
|
||||
ConfigName: info.ConfigName,
|
||||
UserID: info.UserID,
|
||||
UserIDClaim: info.UserIDClaim,
|
||||
DisplayName: info.DisplayName,
|
||||
DisplayNameClaim: info.DisplayNameClaim,
|
||||
}
|
||||
}
|
||||
printMsg(m)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func nilExpiry(expiry *time.Time) *time.Time {
|
||||
if expiry != nil && expiry.Equal(timeSentinel) {
|
||||
return nil
|
||||
}
|
||||
return expiry
|
||||
}
|
||||
@@ -1,168 +0,0 @@
|
||||
// Copyright (c) 2015-2024 MinIO, Inc.
|
||||
//
|
||||
// This file is part of MinIO Object Storage stack
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"github.com/charmbracelet/lipgloss"
|
||||
humanize "github.com/dustin/go-humanize"
|
||||
"github.com/minio/cli"
|
||||
json "github.com/minio/colorjson"
|
||||
"github.com/minio/madmin-go/v3"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
)
|
||||
|
||||
var adminAccesskeyListFlags = []cli.Flag{
|
||||
cli.BoolFlag{
|
||||
Name: "users-only",
|
||||
Usage: "only list user DNs",
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "temp-only",
|
||||
Usage: "only list temporary access keys",
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "svcacc-only",
|
||||
Usage: "only list service account access keys",
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "self",
|
||||
Usage: "list access keys for the authenticated user",
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "all",
|
||||
Usage: "list all access keys for all builtin users",
|
||||
},
|
||||
}
|
||||
|
||||
var adminAccesskeyListCmd = cli.Command{
|
||||
Name: "list",
|
||||
ShortName: "ls",
|
||||
Usage: "list access key pairs for builtin users",
|
||||
Action: mainAdminAccesskeyList,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: append(adminAccesskeyListFlags, globalFlags...),
|
||||
OnUsageError: onUsageError,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
{{.HelpName}} [FLAGS] TARGET [DN...]
|
||||
|
||||
FLAGS:
|
||||
{{range .VisibleFlags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
1. Get list of all builtin users and associated access keys in local server
|
||||
{{.Prompt}} {{.HelpName}} local/ --all
|
||||
|
||||
2. Get list of access keys for the authenticated user in local server
|
||||
{{.Prompt}} {{.HelpName}} local/ --self
|
||||
|
||||
3. Get list of builtin users in local server
|
||||
{{.Prompt}} {{.HelpName}} local/ --all --users-only
|
||||
|
||||
4. Get list of all builtin users and associated temporary access keys in play server (if admin)
|
||||
{{.Prompt}} {{.HelpName}} play/ --temp-only
|
||||
|
||||
5. Get list of access keys associated with user 'foobar'
|
||||
{{.Prompt}} {{.HelpName}} play/ foobar
|
||||
|
||||
6. Get list of access keys associated with users 'foobar' and 'tester'
|
||||
{{.Prompt}} {{.HelpName}} play/ foobar tester
|
||||
|
||||
7. Get all users and access keys if admin, else get authenticated user and associated access keys
|
||||
{{.Prompt}} {{.HelpName}} local/
|
||||
`,
|
||||
}
|
||||
|
||||
type userAccesskeyList struct {
|
||||
Status string `json:"status"`
|
||||
User string `json:"user"`
|
||||
STSKeys []madmin.ServiceAccountInfo `json:"stsKeys"`
|
||||
ServiceAccounts []madmin.ServiceAccountInfo `json:"svcaccs"`
|
||||
LDAP bool `json:"ldap,omitempty"`
|
||||
}
|
||||
|
||||
func (m userAccesskeyList) String() string {
|
||||
labelStyle := lipgloss.NewStyle().Foreground(lipgloss.Color("#04B575"))
|
||||
o := strings.Builder{}
|
||||
|
||||
userStr := "User"
|
||||
if m.LDAP {
|
||||
userStr = "DN"
|
||||
}
|
||||
o.WriteString(iFmt(0, "%s %s\n", labelStyle.Render(userStr+":"), m.User))
|
||||
if len(m.STSKeys) > 0 || len(m.ServiceAccounts) > 0 {
|
||||
o.WriteString(iFmt(2, "%s\n", labelStyle.Render("Access Keys:")))
|
||||
}
|
||||
for _, k := range m.STSKeys {
|
||||
expiration := "never"
|
||||
if nilExpiry(k.Expiration) != nil {
|
||||
expiration = humanize.Time(*k.Expiration)
|
||||
}
|
||||
o.WriteString(iFmt(4, "%s, expires: %s, sts: true\n", k.AccessKey, expiration))
|
||||
}
|
||||
for _, k := range m.ServiceAccounts {
|
||||
expiration := "never"
|
||||
if nilExpiry(k.Expiration) != nil {
|
||||
expiration = humanize.Time(*k.Expiration)
|
||||
}
|
||||
o.WriteString(iFmt(4, "%s, expires: %s, sts: false\n", k.AccessKey, expiration))
|
||||
}
|
||||
|
||||
return o.String()
|
||||
}
|
||||
|
||||
func (m userAccesskeyList) JSON() string {
|
||||
jsonMessageBytes, e := json.MarshalIndent(m, "", " ")
|
||||
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
|
||||
|
||||
return string(jsonMessageBytes)
|
||||
}
|
||||
|
||||
func mainAdminAccesskeyList(ctx *cli.Context) error {
|
||||
aliasedURL, tentativeAll, users, opts := commonAccesskeyList(ctx)
|
||||
|
||||
// Create a new MinIO Admin Client
|
||||
client, err := newAdminClient(aliasedURL)
|
||||
fatalIf(err, "Unable to initialize admin connection.")
|
||||
|
||||
accessKeysMap, e := client.ListAccessKeysBulk(globalContext, users, opts)
|
||||
if e != nil {
|
||||
if e.Error() == "Access Denied." && tentativeAll {
|
||||
// retry with self
|
||||
opts.All = false
|
||||
accessKeysMap, e = client.ListAccessKeysBulk(globalContext, users, opts)
|
||||
}
|
||||
fatalIf(probe.NewError(e), "Unable to list access keys.")
|
||||
}
|
||||
|
||||
for user, accessKeys := range accessKeysMap {
|
||||
m := userAccesskeyList{
|
||||
Status: "success",
|
||||
User: user,
|
||||
ServiceAccounts: accessKeys.ServiceAccounts,
|
||||
STSKeys: accessKeys.STSKeys,
|
||||
LDAP: false,
|
||||
}
|
||||
printMsg(m)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -1,49 +0,0 @@
|
||||
// Copyright (c) 2015-2024 MinIO, Inc.
|
||||
//
|
||||
// This file is part of MinIO Object Storage stack
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"github.com/minio/cli"
|
||||
)
|
||||
|
||||
var adminAccesskeyRemoveCmd = cli.Command{
|
||||
Name: "remove",
|
||||
ShortName: "rm",
|
||||
Usage: "delete access key pairs for builtin users",
|
||||
Action: mainAdminAccesskeyRemove,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
OnUsageError: onUsageError,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
{{.HelpName}} [FLAGS] TARGET ACCESSKEY
|
||||
|
||||
FLAGS:
|
||||
{{range .VisibleFlags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
1. Remove the access key "testkey" from local server
|
||||
{{.Prompt}} {{.HelpName}} local/ testkey
|
||||
`,
|
||||
}
|
||||
|
||||
func mainAdminAccesskeyRemove(ctx *cli.Context) error {
|
||||
return commonAccesskeyRemove(ctx)
|
||||
}
|
||||
@@ -1,149 +0,0 @@
|
||||
// Copyright (c) 2015-2025 MinIO, Inc.
|
||||
//
|
||||
// This file is part of MinIO Object Storage stack
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"github.com/minio/cli"
|
||||
json "github.com/minio/colorjson"
|
||||
"github.com/minio/madmin-go/v3"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
)
|
||||
|
||||
var adminAccesskeySTSRevokeFlags = []cli.Flag{
|
||||
cli.BoolFlag{
|
||||
Name: "all",
|
||||
Usage: "revoke all STS accounts for the specified user",
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "self",
|
||||
Usage: "revoke all STS accounts for the authenticated user",
|
||||
},
|
||||
cli.StringFlag{
|
||||
Name: "token-type",
|
||||
Usage: "specify the token type to revoke",
|
||||
},
|
||||
}
|
||||
|
||||
var adminAccesskeySTSRevokeCmd = cli.Command{
|
||||
Name: "sts-revoke",
|
||||
Usage: "revokes all STS accounts or specified types for the specified user",
|
||||
Action: mainAdminAccesskeySTSRevoke,
|
||||
OnUsageError: onUsageError,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: append(adminAccesskeySTSRevokeFlags, globalFlags...),
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
{{.HelpName}} ALIAS USER [--all | --token-type TOKEN_TYPE]
|
||||
|
||||
Exactly one of --all or --token-type must be specified.
|
||||
|
||||
FLAGS:
|
||||
{{range .VisibleFlags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
1. Revoke all STS accounts for user "user1"
|
||||
{{.Prompt}} {{.HelpName}} myminio user1 --all
|
||||
|
||||
2. Revoke STS accounts of a token type "app-1" for user "user1"
|
||||
{{.Prompt}} {{.HelpName}} myminio user1 --token-type app-1
|
||||
|
||||
3. Revoke all STS accounts for the authenticated user
|
||||
{{.Prompt}} {{.HelpName}} myminio --self
|
||||
|
||||
4. Revoke STS accounts of a token type "app-1" for the authenticated user
|
||||
{{.Prompt}} {{.HelpName}} myminio --self --token-type app-1
|
||||
`,
|
||||
}
|
||||
|
||||
type stsRevokeMessage struct {
|
||||
Status string `json:"status"`
|
||||
User string `json:"user"`
|
||||
TokenRevokeType string `json:"tokenRevokeType,omitempty"`
|
||||
}
|
||||
|
||||
func (m stsRevokeMessage) String() string {
|
||||
userString := "user " + m.User
|
||||
if m.User == "" {
|
||||
userString = "authenticated user"
|
||||
}
|
||||
if m.TokenRevokeType == "" {
|
||||
return "Successfully revoked all STS accounts for " + userString
|
||||
}
|
||||
return "Successfully revoked all STS accounts of type " + m.TokenRevokeType + " for " + userString
|
||||
}
|
||||
|
||||
func (m stsRevokeMessage) JSON() string {
|
||||
if m.Status == "" {
|
||||
m.Status = "success"
|
||||
}
|
||||
jsonMessageBytes, e := json.MarshalIndent(m, "", " ")
|
||||
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
|
||||
|
||||
return string(jsonMessageBytes)
|
||||
}
|
||||
|
||||
// checkSTSRevokeSyntax - validate all the passed arguments
|
||||
func checkSTSRevokeSyntax(ctx *cli.Context) {
|
||||
if len(ctx.Args()) > 2 || len(ctx.Args()) == 0 {
|
||||
showCommandHelpAndExit(ctx, 1)
|
||||
}
|
||||
|
||||
if !ctx.Bool("self") && ctx.Args().Get(1) == "" {
|
||||
fatalIf(errInvalidArgument().Trace(), "Must specify user or use --self flag.")
|
||||
}
|
||||
|
||||
if ctx.Bool("self") && ctx.Args().Get(1) != "" {
|
||||
fatalIf(errInvalidArgument().Trace(), "Cannot specify user with --self flag.")
|
||||
}
|
||||
|
||||
if (!ctx.Bool("all") && ctx.String("token-type") == "") || (ctx.Bool("all") && ctx.String("token-type") != "") {
|
||||
fatalIf(errDummy().Trace(), "Exactly one of --all or --token-type must be specified.")
|
||||
}
|
||||
}
|
||||
|
||||
// mainAdminAccesskeySTSRevoke is the handle for "mc admin accesskey sts-revoke" command.
|
||||
func mainAdminAccesskeySTSRevoke(ctx *cli.Context) error {
|
||||
checkSTSRevokeSyntax(ctx)
|
||||
|
||||
// Get the alias parameter from cli
|
||||
args := ctx.Args()
|
||||
aliasedURL := args.Get(0)
|
||||
user := args.Get(1) // will be empty if --self flag is set
|
||||
tokenRevokeType := ctx.String("token-type")
|
||||
fullRevoke := ctx.Bool("all")
|
||||
|
||||
// Create a new MinIO Admin Client
|
||||
client, err := newAdminClient(aliasedURL)
|
||||
fatalIf(err, "Unable to initialize admin connection.")
|
||||
|
||||
e := client.RevokeTokens(globalContext, madmin.RevokeTokensReq{
|
||||
User: user,
|
||||
TokenRevokeType: tokenRevokeType,
|
||||
FullRevoke: fullRevoke,
|
||||
})
|
||||
fatalIf(probe.NewError(e).Trace(args...), "Unable to revoke tokens for %s", user)
|
||||
|
||||
printMsg(stsRevokeMessage{
|
||||
User: user,
|
||||
TokenRevokeType: tokenRevokeType,
|
||||
})
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -1,46 +0,0 @@
|
||||
// Copyright (c) 2015-2024 MinIO, Inc.
|
||||
//
|
||||
// This file is part of MinIO Object Storage stack
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package cmd
|
||||
|
||||
import "github.com/minio/cli"
|
||||
|
||||
var adminAccesskeySubcommands = []cli.Command{
|
||||
adminAccesskeyListCmd,
|
||||
adminAccesskeyRemoveCmd,
|
||||
adminAccesskeyInfoCmd,
|
||||
adminAccesskeyCreateCmd,
|
||||
adminAccesskeyEditCmd,
|
||||
adminAccesskeyEnableCmd,
|
||||
adminAccesskeyDisableCmd,
|
||||
adminAccesskeySTSRevokeCmd,
|
||||
}
|
||||
|
||||
var adminAccesskeyCmd = cli.Command{
|
||||
Name: "accesskey",
|
||||
Usage: "manage access keys defined in the MinIO server",
|
||||
Action: mainAdminAccesskey,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
Subcommands: adminAccesskeySubcommands,
|
||||
HideHelpCommand: true,
|
||||
}
|
||||
|
||||
func mainAdminAccesskey(ctx *cli.Context) error {
|
||||
commandNotFound(ctx, adminAccesskeySubcommands)
|
||||
return nil
|
||||
}
|
||||
@@ -1,40 +0,0 @@
|
||||
// Copyright (c) 2022 MinIO, Inc.
|
||||
//
|
||||
// This file is part of MinIO Object Storage stack
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"github.com/minio/cli"
|
||||
)
|
||||
|
||||
var adminBucketInfoFlags = []cli.Flag{}
|
||||
|
||||
var adminBucketInfoCmd = cli.Command{
|
||||
Name: "info",
|
||||
Usage: "display bucket information",
|
||||
Action: mainAdminBucketInfo,
|
||||
OnUsageError: onUsageError,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: append(adminBucketInfoFlags, globalFlags...),
|
||||
HideHelpCommand: true,
|
||||
}
|
||||
|
||||
// mainAdminBucketInfo is the handler for "mc admin bucket info" command.
|
||||
func mainAdminBucketInfo(_ *cli.Context) error {
|
||||
deprecatedError("mc stat")
|
||||
return nil
|
||||
}
|
||||
@@ -1,49 +0,0 @@
|
||||
// Copyright (c) 2015-2022 MinIO, Inc.
|
||||
//
|
||||
// This file is part of MinIO Object Storage stack
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"github.com/minio/cli"
|
||||
)
|
||||
|
||||
var adminQuotaFlags = []cli.Flag{
|
||||
cli.StringFlag{
|
||||
Name: "hard",
|
||||
Usage: "set a hard quota, disallowing writes after quota is reached",
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "clear",
|
||||
Usage: "clears bucket quota configured for bucket",
|
||||
},
|
||||
}
|
||||
|
||||
var adminBucketQuotaCmd = cli.Command{
|
||||
Name: "quota",
|
||||
Usage: "manage bucket quota",
|
||||
Action: mainAdminBucketQuota,
|
||||
OnUsageError: onUsageError,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: append(adminQuotaFlags, globalFlags...),
|
||||
HideHelpCommand: true,
|
||||
}
|
||||
|
||||
// mainAdminBucketQuota is the handler for "mc admin bucket quota" command.
|
||||
func mainAdminBucketQuota(_ *cli.Context) error {
|
||||
deprecatedError("mc quota")
|
||||
return nil
|
||||
}
|
||||
@@ -1,38 +0,0 @@
|
||||
// Copyright (c) 2015-2022 MinIO, Inc.
|
||||
//
|
||||
// This file is part of MinIO Object Storage stack
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"github.com/minio/cli"
|
||||
)
|
||||
|
||||
var adminBucketRemoteAddCmd = cli.Command{
|
||||
Name: "add",
|
||||
Usage: "add a new remote target",
|
||||
Action: mainAdminBucketRemoteAdd,
|
||||
OnUsageError: onUsageError,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
HideHelp: true,
|
||||
}
|
||||
|
||||
// mainAdminBucketRemoteAdd is the handle for "mc admin bucket remote set" command.
|
||||
func mainAdminBucketRemoteAdd(_ *cli.Context) error {
|
||||
deprecatedError("mc replicate add")
|
||||
return nil
|
||||
}
|
||||
@@ -1,130 +0,0 @@
|
||||
// Copyright (c) 2015-2022 MinIO, Inc.
|
||||
//
|
||||
// This file is part of MinIO Object Storage stack
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestGetBandwidthInBytes(t *testing.T) {
|
||||
type args struct {
|
||||
bandwidthStr string
|
||||
}
|
||||
f1 := 999.1234567 * 1024 * 1024
|
||||
f2 := 10.123456789 * 1024 * 1024 * 1024
|
||||
f3 := 10000.123456789 * 1024 * 1024 * 1024
|
||||
f4 := 0.001 * 1024 * 1024 * 1024
|
||||
tests := []struct {
|
||||
name string
|
||||
args args
|
||||
want uint64
|
||||
}{
|
||||
{
|
||||
name: "1MegaByte",
|
||||
args: args{
|
||||
bandwidthStr: "1Mi",
|
||||
},
|
||||
want: 1024 * 1024,
|
||||
},
|
||||
{
|
||||
name: "1MegaBit",
|
||||
args: args{
|
||||
bandwidthStr: "1M",
|
||||
},
|
||||
want: 1000000,
|
||||
},
|
||||
{
|
||||
name: "1GigaByte",
|
||||
args: args{
|
||||
bandwidthStr: "1G",
|
||||
},
|
||||
want: 1000000000,
|
||||
},
|
||||
{
|
||||
name: "1GibiByte",
|
||||
args: args{
|
||||
bandwidthStr: "1Gi",
|
||||
},
|
||||
want: 1024 * 1024 * 1024,
|
||||
},
|
||||
{
|
||||
name: "FractionalMegaBytes",
|
||||
args: args{
|
||||
bandwidthStr: "999.123456789123456789M",
|
||||
},
|
||||
want: 999123456,
|
||||
},
|
||||
{
|
||||
name: "FractionalGigaBytes",
|
||||
args: args{
|
||||
bandwidthStr: "10.123456789123456789123456G",
|
||||
},
|
||||
want: 10123456789,
|
||||
},
|
||||
{
|
||||
name: "FractionalBigGigaBytes",
|
||||
args: args{
|
||||
bandwidthStr: "10000.123456789123456789123456G",
|
||||
},
|
||||
want: 10000123456789,
|
||||
},
|
||||
{
|
||||
name: "FractionalMebiBytes",
|
||||
args: args{
|
||||
bandwidthStr: "999.123456789123456789Mi",
|
||||
},
|
||||
want: uint64(f1),
|
||||
},
|
||||
{
|
||||
name: "FractionalGibiBytes",
|
||||
args: args{
|
||||
bandwidthStr: "10.123456789123456789123456Gi",
|
||||
},
|
||||
want: uint64(f2),
|
||||
},
|
||||
{
|
||||
name: "FractionalBigGibiBytes",
|
||||
args: args{
|
||||
bandwidthStr: "10000.123456789123456789123456Gi",
|
||||
},
|
||||
want: uint64(f3),
|
||||
},
|
||||
{
|
||||
name: "SmallGiga",
|
||||
args: args{
|
||||
bandwidthStr: "0.001Gi",
|
||||
},
|
||||
want: uint64(f4),
|
||||
},
|
||||
{
|
||||
name: "LargeK",
|
||||
args: args{
|
||||
bandwidthStr: "1024Ki",
|
||||
},
|
||||
want: 1024 * 1024,
|
||||
},
|
||||
}
|
||||
t.Parallel()
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if got, err := getBandwidthInBytes(tt.args.bandwidthStr); err != nil || got != tt.want {
|
||||
t.Errorf("getBandwidthInBytes() = %v, want %v", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,38 +0,0 @@
|
||||
// Copyright (c) 2015-2022 MinIO, Inc.
|
||||
//
|
||||
// This file is part of MinIO Object Storage stack
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"github.com/minio/cli"
|
||||
)
|
||||
|
||||
var adminBucketRemoteEditCmd = cli.Command{
|
||||
Name: "edit",
|
||||
Usage: "edit remote target",
|
||||
Action: mainAdminBucketRemoteEdit,
|
||||
Before: setGlobalsFromContext,
|
||||
OnUsageError: onUsageError,
|
||||
Flags: globalFlags,
|
||||
HideHelp: true,
|
||||
}
|
||||
|
||||
// mainAdminBucketRemoteEdit is the handle for "mc admin bucket remote edit" command.
|
||||
func mainAdminBucketRemoteEdit(_ *cli.Context) error {
|
||||
deprecatedError("mc replicate update")
|
||||
return nil
|
||||
}
|
||||
@@ -1,43 +0,0 @@
|
||||
// Copyright (c) 2015-2022 MinIO, Inc.
|
||||
//
|
||||
// This file is part of MinIO Object Storage stack
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package cmd
|
||||
|
||||
import "github.com/minio/cli"
|
||||
|
||||
var adminBucketRemoteSubcommands = []cli.Command{
|
||||
adminBucketRemoteAddCmd,
|
||||
adminBucketRemoteEditCmd,
|
||||
adminBucketRemoteRmCmd,
|
||||
}
|
||||
|
||||
var adminBucketRemoteCmd = cli.Command{
|
||||
Name: "remote",
|
||||
Usage: "configure remote target buckets",
|
||||
Action: mainadminBucketRemote,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
Subcommands: adminBucketRemoteSubcommands,
|
||||
HideHelpCommand: true,
|
||||
}
|
||||
|
||||
// mainadminBucketRemote is the handle for "mc admin bucket remote" command.
|
||||
func mainadminBucketRemote(ctx *cli.Context) error {
|
||||
commandNotFound(ctx, adminBucketRemoteSubcommands)
|
||||
return nil
|
||||
// Sub-commands like "add", "ls", "rm" have their own main.
|
||||
}
|
||||
@@ -1,39 +0,0 @@
|
||||
// Copyright (c) 2015-2022 MinIO, Inc.
|
||||
//
|
||||
// This file is part of MinIO Object Storage stack
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"github.com/minio/cli"
|
||||
)
|
||||
|
||||
var adminBucketRemoteRmCmd = cli.Command{
|
||||
Name: "remove",
|
||||
ShortName: "rm",
|
||||
Usage: "remove configured remote target",
|
||||
Action: mainAdminBucketRemoteRemove,
|
||||
OnUsageError: onUsageError,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
HideHelp: true,
|
||||
}
|
||||
|
||||
// mainAdminBucketRemoteRemove is the handle for "mc admin bucket remote rm" command.
|
||||
func mainAdminBucketRemoteRemove(_ *cli.Context) error {
|
||||
deprecatedError("mc replicate rm")
|
||||
return nil
|
||||
}
|
||||
@@ -1,44 +0,0 @@
|
||||
// Copyright (c) 2015-2022 MinIO, Inc.
|
||||
//
|
||||
// This file is part of MinIO Object Storage stack
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package cmd
|
||||
|
||||
import "github.com/minio/cli"
|
||||
|
||||
var adminBucketSubcommands = []cli.Command{
|
||||
adminBucketRemoteCmd,
|
||||
adminBucketQuotaCmd,
|
||||
adminBucketInfoCmd,
|
||||
}
|
||||
|
||||
var adminBucketCmd = cli.Command{
|
||||
Name: "bucket",
|
||||
Usage: "manage buckets defined in the MinIO server",
|
||||
Action: mainAdminBucket,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
Subcommands: adminBucketSubcommands,
|
||||
HideHelpCommand: true,
|
||||
Hidden: true,
|
||||
}
|
||||
|
||||
// mainAdminBucket is the handle for "mc admin bucket" command.
|
||||
func mainAdminBucket(ctx *cli.Context) error {
|
||||
commandNotFound(ctx, adminBucketSubcommands)
|
||||
return nil
|
||||
// Sub-commands like "quota", "remote" have their own main.
|
||||
}
|
||||
@@ -1,141 +0,0 @@
|
||||
// Copyright (c) 2022 MinIO, Inc.
|
||||
//
|
||||
// This file is part of MinIO Object Storage stack
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/cli"
|
||||
json "github.com/minio/colorjson"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/pkg/v3/console"
|
||||
)
|
||||
|
||||
var adminClusterBucketExportCmd = cli.Command{
|
||||
Name: "export",
|
||||
Usage: "backup bucket metadata to a zip file",
|
||||
Action: mainClusterBucketExport,
|
||||
OnUsageError: onUsageError,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
HideHelpCommand: true,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
{{.HelpName}} [FLAGS] TARGET/[BUCKET]
|
||||
|
||||
FLAGS:
|
||||
{{range .VisibleFlags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
1. Save metadata of all buckets to a zip file.
|
||||
{{.Prompt}} {{.HelpName}} myminio
|
||||
`,
|
||||
}
|
||||
|
||||
func checkBucketExportSyntax(ctx *cli.Context) {
|
||||
if len(ctx.Args()) != 1 {
|
||||
showCommandHelpAndExit(ctx, 1) // last argument is exit code
|
||||
}
|
||||
}
|
||||
|
||||
// mainClusterBucketExport - metadata export command
|
||||
func mainClusterBucketExport(ctx *cli.Context) error {
|
||||
// Check for command syntax
|
||||
checkBucketExportSyntax(ctx)
|
||||
|
||||
// Get the alias parameter from cli
|
||||
args := ctx.Args()
|
||||
aliasedURL := args.Get(0)
|
||||
console.SetColor("File", color.New(color.FgWhite, color.Bold))
|
||||
|
||||
// Create a new MinIO Admin Client
|
||||
client, err := newAdminClient(aliasedURL)
|
||||
if err != nil {
|
||||
fatalIf(err.Trace(aliasedURL), "Unable to initialize admin client.")
|
||||
return nil
|
||||
}
|
||||
|
||||
// Compute bucket and object from the aliased URL
|
||||
aliasedURL = filepath.ToSlash(aliasedURL)
|
||||
aliasedURL = filepath.Clean(aliasedURL)
|
||||
_, bucket := url2Alias(aliasedURL)
|
||||
r, e := client.ExportBucketMetadata(context.Background(), bucket)
|
||||
fatalIf(probe.NewError(e).Trace(aliasedURL), "Unable to export bucket metadata.")
|
||||
|
||||
if bucket == "" {
|
||||
bucket = "bucket"
|
||||
}
|
||||
// Create bucket metadata zip file
|
||||
tmpFile, e := os.CreateTemp("", fmt.Sprintf("%s-%s-metadata-", strings.ReplaceAll(aliasedURL, "/", "-"), bucket))
|
||||
fatalIf(probe.NewError(e), "Unable to download file data.")
|
||||
|
||||
ext := "zip"
|
||||
// Copy zip content to target download file
|
||||
_, e = io.Copy(tmpFile, r)
|
||||
fatalIf(probe.NewError(e), "Unable to download bucket metadata.")
|
||||
// Close everything
|
||||
r.Close()
|
||||
tmpFile.Close()
|
||||
// We use 4 bytes of the 32 bytes to identify the file.
|
||||
downloadPath := fmt.Sprintf("%s-%s-metadata.%s", aliasedURL, bucket, ext)
|
||||
// Create necessary directories.
|
||||
dir := filepath.Dir(downloadPath)
|
||||
if e := os.MkdirAll(dir, 0o755); e != nil {
|
||||
fatalIf(probe.NewError(e).Trace(dir), "Unable to create download directory")
|
||||
}
|
||||
|
||||
fi, e := os.Stat(downloadPath)
|
||||
if e == nil && !fi.IsDir() {
|
||||
e = moveFile(downloadPath, downloadPath+"."+time.Now().Format(dateTimeFormatFilename))
|
||||
fatalIf(probe.NewError(e), "Unable to create a backup of "+downloadPath)
|
||||
} else {
|
||||
if !os.IsNotExist(e) {
|
||||
fatal(probe.NewError(e), "Unable to download file data")
|
||||
}
|
||||
}
|
||||
fatalIf(probe.NewError(moveFile(tmpFile.Name(), downloadPath)), "Unable to rename downloaded data, file exists at %s", tmpFile.Name())
|
||||
|
||||
// Explicitly set permissions to 0o600 and override umask
|
||||
// to ensure that the file is not world-readable.
|
||||
e = os.Chmod(downloadPath, 0o600)
|
||||
fatalIf(probe.NewError(e), "Unable to set file permissions for "+downloadPath)
|
||||
|
||||
if !globalJSON {
|
||||
console.Infof("Bucket metadata successfully downloaded as %s\n", downloadPath)
|
||||
return nil
|
||||
}
|
||||
v := struct {
|
||||
File string `json:"file"`
|
||||
Key string `json:"key,omitempty"`
|
||||
}{
|
||||
File: downloadPath,
|
||||
}
|
||||
b, e := json.Marshal(v)
|
||||
fatalIf(probe.NewError(e), "Unable to serialize data")
|
||||
console.Println(string(b))
|
||||
return nil
|
||||
}
|
||||
@@ -1,242 +0,0 @@
|
||||
// Copyright (c) 2022 MinIO, Inc.
|
||||
//
|
||||
// This file is part of MinIO Object Storage stack
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/fatih/color"
|
||||
"github.com/klauspost/compress/zip"
|
||||
"github.com/minio/cli"
|
||||
json "github.com/minio/colorjson"
|
||||
"github.com/minio/madmin-go/v3"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/pkg/v3/console"
|
||||
)
|
||||
|
||||
var adminClusterBucketImportCmd = cli.Command{
|
||||
Name: "import",
|
||||
Usage: "restore bucket metadata from a zip file",
|
||||
Action: mainClusterBucketImport,
|
||||
OnUsageError: onUsageError,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
HideHelpCommand: true,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
{{.HelpName}} [FLAGS] TARGET/[BUCKET] /path/to/backups/bucket-metadata.zip
|
||||
|
||||
FLAGS:
|
||||
{{range .VisibleFlags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
1. Recover bucket metadata for all buckets from previously saved bucket metadata backup.
|
||||
{{.Prompt}} {{.HelpName}} myminio /backups/myminio-bucket-metadata.zip
|
||||
`,
|
||||
}
|
||||
|
||||
func checkBucketImportSyntax(ctx *cli.Context) {
|
||||
if len(ctx.Args()) != 2 {
|
||||
showCommandHelpAndExit(ctx, 1) // last argument is exit code
|
||||
}
|
||||
}
|
||||
|
||||
// mainClusterBucketImport - bucket metadata import command
|
||||
func mainClusterBucketImport(ctx *cli.Context) error {
|
||||
// Check for command syntax
|
||||
checkBucketImportSyntax(ctx)
|
||||
console.SetColor("Name", color.New(color.Bold, color.FgCyan))
|
||||
console.SetColor("success", color.New(color.Bold, color.FgGreen))
|
||||
console.SetColor("warning", color.New(color.Bold, color.FgYellow))
|
||||
console.SetColor("errors", color.New(color.Bold, color.FgRed))
|
||||
console.SetColor("statusMsg", color.New(color.Bold, color.FgHiWhite))
|
||||
console.SetColor("failCell", color.New(color.FgRed))
|
||||
console.SetColor("passCell", color.New(color.FgGreen))
|
||||
|
||||
// Get the alias parameter from cli
|
||||
args := ctx.Args()
|
||||
aliasedURL := args.Get(0)
|
||||
var r io.Reader
|
||||
var sz int64
|
||||
f, e := os.Open(args.Get(1))
|
||||
if e != nil {
|
||||
fatalIf(probe.NewError(e).Trace(args...), "Unable to get bucket metadata")
|
||||
}
|
||||
if st, e := f.Stat(); e == nil {
|
||||
sz = st.Size()
|
||||
}
|
||||
defer f.Close()
|
||||
r = f
|
||||
|
||||
_, e = zip.NewReader(r.(io.ReaderAt), sz)
|
||||
fatalIf(probe.NewError(e).Trace(args...), fmt.Sprintf("Unable to read zip file %s", args.Get(1)))
|
||||
|
||||
f, e = os.Open(args.Get(1))
|
||||
fatalIf(probe.NewError(e).Trace(args...), "Unable to get bucket metadata")
|
||||
defer f.Close()
|
||||
|
||||
// Create a new MinIO Admin Client
|
||||
client, err := newAdminClient(aliasedURL)
|
||||
if err != nil {
|
||||
fatalIf(err.Trace(aliasedURL), "Unable to initialize admin client.")
|
||||
return nil
|
||||
}
|
||||
|
||||
// Compute bucket and object from the aliased URL
|
||||
aliasedURL = filepath.ToSlash(aliasedURL)
|
||||
aliasedURL = filepath.Clean(aliasedURL)
|
||||
_, bucket := url2Alias(aliasedURL)
|
||||
|
||||
rpt, e := client.ImportBucketMetadata(context.Background(), bucket, f)
|
||||
fatalIf(probe.NewError(e).Trace(aliasedURL), "Unable to import bucket metadata.")
|
||||
|
||||
printMsg(importMetaMsg{
|
||||
BucketMetaImportErrs: rpt,
|
||||
Status: "success",
|
||||
URL: aliasedURL,
|
||||
Op: ctx.Command.Name,
|
||||
})
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
type importMetaMsg struct {
|
||||
madmin.BucketMetaImportErrs
|
||||
Op string
|
||||
URL string `json:"url"`
|
||||
Status string `json:"status"`
|
||||
}
|
||||
|
||||
func statusTick(s madmin.MetaStatus) string {
|
||||
switch {
|
||||
case s.Err != "":
|
||||
return console.Colorize("failCell", crossTickCell)
|
||||
case !s.IsSet:
|
||||
return blankCell
|
||||
default:
|
||||
return console.Colorize("passCell", tickCell)
|
||||
}
|
||||
}
|
||||
|
||||
func (i importMetaMsg) String() string {
|
||||
m := i.Buckets
|
||||
totBuckets := len(m)
|
||||
totErrs := 0
|
||||
for _, st := range m {
|
||||
if st.ObjectLock.Err != "" || st.Versioning.Err != "" ||
|
||||
st.SSEConfig.Err != "" || st.Tagging.Err != "" ||
|
||||
st.Lifecycle.Err != "" || st.Quota.Err != "" ||
|
||||
st.Policy.Err != "" || st.Notification.Err != "" ||
|
||||
st.Cors.Err != "" || st.Err != "" {
|
||||
totErrs++
|
||||
}
|
||||
}
|
||||
var b strings.Builder
|
||||
numSch := "success"
|
||||
if totErrs > 0 {
|
||||
numSch = "warning"
|
||||
}
|
||||
msg := "\n" + console.Colorize(numSch, totBuckets-totErrs) +
|
||||
console.Colorize("statusMsg", "/") +
|
||||
console.Colorize("success", totBuckets) +
|
||||
console.Colorize("statusMsg", " buckets were imported successfully.")
|
||||
fmt.Fprintln(&b, msg)
|
||||
if totErrs > 0 {
|
||||
fmt.Fprintln(&b, console.Colorize("errors", "Errors: \n"))
|
||||
for bucket, st := range m {
|
||||
if st.ObjectLock.Err != "" || st.Versioning.Err != "" ||
|
||||
st.SSEConfig.Err != "" || st.Tagging.Err != "" ||
|
||||
st.Lifecycle.Err != "" || st.Quota.Err != "" ||
|
||||
st.Policy.Err != "" || st.Notification.Err != "" ||
|
||||
st.Cors.Err != "" || st.Err != "" {
|
||||
fmt.Fprintln(&b, printImportErrs(bucket, st))
|
||||
}
|
||||
}
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
func (i importMetaMsg) JSON() string {
|
||||
buf := &bytes.Buffer{}
|
||||
enc := json.NewEncoder(buf)
|
||||
enc.SetIndent("", " ")
|
||||
// Disable escaping special chars to display XML tags correctly
|
||||
enc.SetEscapeHTML(false)
|
||||
|
||||
fatalIf(probe.NewError(enc.Encode(i.Buckets)), "Unable to marshal into JSON.")
|
||||
return buf.String()
|
||||
}
|
||||
|
||||
// pretty print import errors
|
||||
func printImportErrs(bucket string, r madmin.BucketStatus) string {
|
||||
var b strings.Builder
|
||||
placeHolder := ""
|
||||
key := fmt.Sprintf("%-10s: %s", "Name", bucket)
|
||||
fmt.Fprintln(&b, console.Colorize("Name", key))
|
||||
|
||||
if r.Err != "" {
|
||||
fmt.Fprintf(&b, "%2s%s %s", placeHolder, console.Colorize("errors", "Error: "), r.Err)
|
||||
fmt.Fprintln(&b)
|
||||
}
|
||||
if r.ObjectLock.IsSet {
|
||||
fmt.Fprintf(&b, "%2s%s %s", placeHolder, "Object lock: ", statusTick(r.ObjectLock))
|
||||
fmt.Fprintln(&b)
|
||||
}
|
||||
if r.Versioning.IsSet {
|
||||
fmt.Fprintf(&b, "%2s%s %s", placeHolder, "Versioning: ", statusTick(r.Versioning))
|
||||
fmt.Fprintln(&b)
|
||||
}
|
||||
|
||||
if r.SSEConfig.IsSet {
|
||||
fmt.Fprintf(&b, "%2s%s %s", placeHolder, "Encryption: ", statusTick(r.SSEConfig))
|
||||
fmt.Fprintln(&b)
|
||||
}
|
||||
if r.Lifecycle.IsSet {
|
||||
fmt.Fprintf(&b, "%2s%s %s", placeHolder, "Lifecycle: ", statusTick(r.Lifecycle))
|
||||
fmt.Fprintln(&b)
|
||||
}
|
||||
if r.Notification.IsSet {
|
||||
fmt.Fprintf(&b, "%2s%s %s", placeHolder, "Notification: ", statusTick(r.Notification))
|
||||
fmt.Fprintln(&b)
|
||||
}
|
||||
if r.Quota.IsSet {
|
||||
fmt.Fprintf(&b, "%2s%s %s", placeHolder, "Quota: ", statusTick(r.Quota))
|
||||
fmt.Fprintln(&b)
|
||||
}
|
||||
if r.Policy.IsSet {
|
||||
fmt.Fprintf(&b, "%2s%s %s", placeHolder, "Policy: ", statusTick(r.Policy))
|
||||
fmt.Fprintln(&b)
|
||||
}
|
||||
if r.Tagging.IsSet {
|
||||
fmt.Fprintf(&b, "%2s%s %s", placeHolder, "Tagging: ", statusTick(r.Tagging))
|
||||
fmt.Fprintln(&b)
|
||||
}
|
||||
if r.Cors.IsSet {
|
||||
fmt.Fprintf(&b, "%2s%s %s", placeHolder, "CORS: ", statusTick(r.Cors))
|
||||
fmt.Fprintln(&b)
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
@@ -1,42 +0,0 @@
|
||||
// Copyright (c) 2022 MinIO, Inc.
|
||||
//
|
||||
// This file is part of MinIO Object Storage stack
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package cmd
|
||||
|
||||
import "github.com/minio/cli"
|
||||
|
||||
var adminClusterBucketSubcommands = []cli.Command{
|
||||
adminClusterBucketImportCmd,
|
||||
adminClusterBucketExportCmd,
|
||||
}
|
||||
|
||||
var adminClusterBucketCmd = cli.Command{
|
||||
Name: "bucket",
|
||||
Usage: "manage bucket metadata on MinIO cluster",
|
||||
Action: mainAdminClusterBucket,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
Subcommands: adminClusterBucketSubcommands,
|
||||
HideHelpCommand: true,
|
||||
}
|
||||
|
||||
// mainAdminClusterBucket is the handle for "mc admin cluster bucket" command.
|
||||
func mainAdminClusterBucket(ctx *cli.Context) error {
|
||||
commandNotFound(ctx, adminClusterBucketSubcommands)
|
||||
return nil
|
||||
// Sub-commands like "export", "import" have their own main.
|
||||
}
|
||||
@@ -1,148 +0,0 @@
|
||||
// Copyright (c) 2022 MinIO, Inc.
|
||||
//
|
||||
// This file is part of MinIO Object Storage stack
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"time"
|
||||
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/cli"
|
||||
json "github.com/minio/colorjson"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/pkg/v3/console"
|
||||
)
|
||||
|
||||
// iam export specific flags.
|
||||
var (
|
||||
iamExportFlags = []cli.Flag{
|
||||
cli.StringFlag{
|
||||
Name: "output,o",
|
||||
Usage: "output iam export to a custom file path",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
var adminClusterIAMExportCmd = cli.Command{
|
||||
Name: "export",
|
||||
Usage: "exports IAM info to zipped file",
|
||||
Action: mainClusterIAMExport,
|
||||
OnUsageError: onUsageError,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: append(iamExportFlags, globalFlags...),
|
||||
HideHelpCommand: true,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
{{.HelpName}} [FLAGS] TARGET
|
||||
|
||||
FLAGS:
|
||||
{{range .VisibleFlags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
1. Download all IAM metadata for cluster into zip file.
|
||||
{{.Prompt}} {{.HelpName}} myminio
|
||||
|
||||
2. Download all IAM metadata to a custom file.
|
||||
{{.Prompt}} {{.HelpName}} myminio --output /tmp/myminio-iam.zip
|
||||
`,
|
||||
}
|
||||
|
||||
func checkIAMExportSyntax(ctx *cli.Context) {
|
||||
if len(ctx.Args()) != 1 {
|
||||
showCommandHelpAndExit(ctx, 1) // last argument is exit code
|
||||
}
|
||||
}
|
||||
|
||||
// mainClusterIAMExport - metadata export command
|
||||
func mainClusterIAMExport(ctx *cli.Context) error {
|
||||
// Check for command syntax
|
||||
checkIAMExportSyntax(ctx)
|
||||
|
||||
// Get the alias parameter from cli
|
||||
args := ctx.Args()
|
||||
aliasedURL := filepath.ToSlash(args.Get(0))
|
||||
aliasedURL = filepath.Clean(aliasedURL)
|
||||
|
||||
console.SetColor("File", color.New(color.FgWhite, color.Bold))
|
||||
|
||||
// Create a new MinIO Admin Client
|
||||
client, err := newAdminClient(aliasedURL)
|
||||
if err != nil {
|
||||
fatalIf(err.Trace(aliasedURL), "Unable to initialize admin client.")
|
||||
return nil
|
||||
}
|
||||
|
||||
r, e := client.ExportIAM(context.Background())
|
||||
fatalIf(probe.NewError(e).Trace(aliasedURL), "Unable to export IAM info.")
|
||||
|
||||
// Create iam info zip file
|
||||
tmpFile, e := os.CreateTemp("", fmt.Sprintf("%s-iam-info", aliasedURL))
|
||||
fatalIf(probe.NewError(e), "Unable to download file data.")
|
||||
|
||||
ext := "zip"
|
||||
// Copy zip content to target download file
|
||||
_, e = io.Copy(tmpFile, r)
|
||||
fatalIf(probe.NewError(e), "Unable to download IAM info.")
|
||||
|
||||
// Close everything
|
||||
r.Close()
|
||||
tmpFile.Close()
|
||||
|
||||
downloadPath := fmt.Sprintf("%s-iam-info.%s", aliasedURL, ext)
|
||||
if ctx.String("output") != "" {
|
||||
downloadPath = ctx.String("output")
|
||||
}
|
||||
fi, e := os.Stat(downloadPath)
|
||||
if e == nil && !fi.IsDir() {
|
||||
e = moveFile(downloadPath, downloadPath+"."+time.Now().Format(dateTimeFormatFilename))
|
||||
fatalIf(probe.NewError(e), "Unable to create a backup of "+downloadPath)
|
||||
} else {
|
||||
if !os.IsNotExist(e) {
|
||||
fatal(probe.NewError(e), "Unable to download file data")
|
||||
}
|
||||
}
|
||||
|
||||
fatalIf(probe.NewError(moveFile(tmpFile.Name(), downloadPath)), "Unable to rename downloaded data, file exists at %s", tmpFile.Name())
|
||||
|
||||
// Explicitly set permissions to 0o600 and override umask
|
||||
// to ensure that the file is not world-readable.
|
||||
e = os.Chmod(downloadPath, 0o600)
|
||||
fatalIf(probe.NewError(e), "Unable to set file permissions for "+downloadPath)
|
||||
|
||||
if !globalJSON {
|
||||
console.Infof("IAM info successfully downloaded as %s\n", downloadPath)
|
||||
return nil
|
||||
}
|
||||
|
||||
v := struct {
|
||||
File string `json:"file"`
|
||||
Key string `json:"key,omitempty"`
|
||||
}{
|
||||
File: downloadPath,
|
||||
}
|
||||
b, e := json.Marshal(v)
|
||||
fatalIf(probe.NewError(e), "Unable to serialize data")
|
||||
console.Println(string(b))
|
||||
return nil
|
||||
}
|
||||
@@ -1,232 +0,0 @@
|
||||
// Copyright (c) 2022 MinIO, Inc.
|
||||
//
|
||||
// This file is part of MinIO Object Storage stack
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/klauspost/compress/zip"
|
||||
"github.com/minio/cli"
|
||||
json "github.com/minio/colorjson"
|
||||
"github.com/minio/madmin-go/v3"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/pkg/v3/console"
|
||||
)
|
||||
|
||||
var adminClusterIAMImportCmd = cli.Command{
|
||||
Name: "import",
|
||||
Usage: "imports IAM info from zipped file",
|
||||
Action: mainClusterIAMImport,
|
||||
OnUsageError: onUsageError,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
HideHelpCommand: true,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
{{.HelpName}} [FLAGS] TARGET/BUCKET /path/to/myminio-iam-info.zip
|
||||
|
||||
FLAGS:
|
||||
{{range .VisibleFlags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
1. Set IAM info from previously exported metadata zip file.
|
||||
{{.Prompt}} {{.HelpName}} myminio /tmp/myminio-iam-info.zip
|
||||
|
||||
`,
|
||||
}
|
||||
|
||||
type iamImportInfo madmin.ImportIAMResult
|
||||
|
||||
func (i iamImportInfo) JSON() string {
|
||||
bs, e := json.MarshalIndent(madmin.ImportIAMResult(i), "", " ")
|
||||
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
|
||||
return string(bs)
|
||||
}
|
||||
|
||||
func (i iamImportInfo) String() string {
|
||||
var messages []string
|
||||
info := madmin.ImportIAMResult(i)
|
||||
messages = append(messages, processIAMEntities(info.Skipped, "Skipped")...)
|
||||
messages = append(messages, processIAMEntities(info.Removed, "Removed")...)
|
||||
messages = append(messages, processIAMEntities(info.Added, "Added")...)
|
||||
messages = append(messages, processErrIAMEntities(info.Failed)...)
|
||||
return strings.Join(messages, "\n")
|
||||
}
|
||||
|
||||
func processIAMEntities(entities madmin.IAMEntities, action string) []string {
|
||||
var messages []string
|
||||
if len(entities.Policies) > 0 {
|
||||
messages = append(messages, fmt.Sprintf("%s policies: %v", action, strings.Join(entities.Policies, ", ")))
|
||||
}
|
||||
if len(entities.Users) > 0 {
|
||||
messages = append(messages, fmt.Sprintf("%s users: %v", action, strings.Join(entities.Users, ", ")))
|
||||
}
|
||||
if len(entities.Groups) > 0 {
|
||||
messages = append(messages, fmt.Sprintf("%s groups: %v", action, strings.Join(entities.Groups, ", ")))
|
||||
}
|
||||
if len(entities.ServiceAccounts) > 0 {
|
||||
messages = append(messages, fmt.Sprintf("%s service accounts: %v", action, strings.Join(entities.ServiceAccounts, ", ")))
|
||||
}
|
||||
var users []string
|
||||
for _, pol := range entities.UserPolicies {
|
||||
for name := range pol {
|
||||
users = append(users, name)
|
||||
}
|
||||
}
|
||||
if len(users) > 0 {
|
||||
messages = append(messages, fmt.Sprintf("%s policies for users: %v", action, strings.Join(users, ", ")))
|
||||
}
|
||||
var groups []string
|
||||
for _, pol := range entities.GroupPolicies {
|
||||
for name := range pol {
|
||||
groups = append(groups, name)
|
||||
}
|
||||
}
|
||||
if len(groups) > 0 {
|
||||
messages = append(messages, fmt.Sprintf("%s policies for groups: %v", action, strings.Join(groups, ", ")))
|
||||
}
|
||||
var stsarr []string
|
||||
for _, pol := range entities.STSPolicies {
|
||||
for name := range pol {
|
||||
stsarr = append(stsarr, name)
|
||||
}
|
||||
}
|
||||
if len(stsarr) > 0 {
|
||||
messages = append(messages, fmt.Sprintf("%s policies for sts: %v", action, strings.Join(stsarr, ", ")))
|
||||
}
|
||||
return messages
|
||||
}
|
||||
|
||||
func processErrIAMEntities(entities madmin.IAMErrEntities) []string {
|
||||
var messages []string
|
||||
|
||||
var policies []string
|
||||
for _, entry := range entities.Policies {
|
||||
policies = append(policies, entry.Name)
|
||||
}
|
||||
if len(policies) > 0 {
|
||||
messages = append(messages, fmt.Sprintf("Failed to add policies: %v", strings.Join(policies, ", ")))
|
||||
}
|
||||
var users []string
|
||||
for _, entry := range entities.Users {
|
||||
users = append(users, entry.Name)
|
||||
}
|
||||
if len(users) > 0 {
|
||||
messages = append(messages, fmt.Sprintf("Failed to add users: %v", strings.Join(users, ", ")))
|
||||
}
|
||||
var groups []string
|
||||
for _, entry := range entities.Groups {
|
||||
groups = append(groups, entry.Name)
|
||||
}
|
||||
if len(groups) > 0 {
|
||||
messages = append(messages, fmt.Sprintf("Failed to add groups: %v", strings.Join(groups, ", ")))
|
||||
}
|
||||
var sas []string
|
||||
for _, entry := range entities.ServiceAccounts {
|
||||
sas = append(sas, entry.Name)
|
||||
}
|
||||
if len(sas) > 0 {
|
||||
messages = append(messages, fmt.Sprintf("Failed to add service accounts: %v", strings.Join(sas, ", ")))
|
||||
}
|
||||
var polusers []string
|
||||
for _, pol := range entities.UserPolicies {
|
||||
polusers = append(polusers, pol.Name)
|
||||
}
|
||||
if len(polusers) > 0 {
|
||||
messages = append(messages, fmt.Sprintf("Failed to add policies for users: %v", strings.Join(polusers, ", ")))
|
||||
}
|
||||
var polgroups []string
|
||||
for _, pol := range entities.GroupPolicies {
|
||||
polgroups = append(polgroups, pol.Name)
|
||||
}
|
||||
if len(polgroups) > 0 {
|
||||
messages = append(messages, fmt.Sprintf("Failed to add policies for groups: %v", strings.Join(polgroups, ", ")))
|
||||
}
|
||||
var polsts []string
|
||||
for _, pol := range entities.STSPolicies {
|
||||
polsts = append(polsts, pol.Name)
|
||||
}
|
||||
if len(polsts) > 0 {
|
||||
messages = append(messages, fmt.Sprintf("Failed to add policies for sts: %v", strings.Join(polsts, ", ")))
|
||||
}
|
||||
return messages
|
||||
}
|
||||
|
||||
func checkIAMImportSyntax(ctx *cli.Context) {
|
||||
if len(ctx.Args()) != 2 {
|
||||
showCommandHelpAndExit(ctx, 1) // last argument is exit code
|
||||
}
|
||||
}
|
||||
|
||||
// mainClusterIAMImport - iam info import command
|
||||
func mainClusterIAMImport(ctx *cli.Context) error {
|
||||
// Check for command syntax
|
||||
checkIAMImportSyntax(ctx)
|
||||
|
||||
// Get the alias parameter from cli
|
||||
args := ctx.Args()
|
||||
aliasedURL := filepath.ToSlash(args.Get(0))
|
||||
aliasedURL = filepath.Clean(aliasedURL)
|
||||
|
||||
var r io.Reader
|
||||
var sz int64
|
||||
f, e := os.Open(args.Get(1))
|
||||
if e != nil {
|
||||
fatalIf(probe.NewError(e).Trace(args...), "Unable to get IAM info")
|
||||
}
|
||||
if st, e := f.Stat(); e == nil {
|
||||
sz = st.Size()
|
||||
}
|
||||
defer f.Close()
|
||||
r = f
|
||||
|
||||
_, e = zip.NewReader(r.(io.ReaderAt), sz)
|
||||
fatalIf(probe.NewError(e).Trace(args...), fmt.Sprintf("Unable to read zip file %s", args.Get(1)))
|
||||
|
||||
f, e = os.Open(args.Get(1))
|
||||
fatalIf(probe.NewError(e).Trace(args...), "Unable to get IAM info")
|
||||
defer f.Close()
|
||||
|
||||
// Create a new MinIO Admin Client
|
||||
client, err := newAdminClient(aliasedURL)
|
||||
if err != nil {
|
||||
fatalIf(err.Trace(aliasedURL), "Unable to initialize admin client.")
|
||||
return nil
|
||||
}
|
||||
|
||||
iamr, e := client.ImportIAMV2(context.Background(), f)
|
||||
if e != nil {
|
||||
f.Seek(0, 0)
|
||||
e = client.ImportIAM(context.Background(), f)
|
||||
fatalIf(probe.NewError(e).Trace(aliasedURL), "Unable to import IAM info.")
|
||||
if !globalJSON {
|
||||
console.Infof("IAM info imported to %s from %s\n", aliasedURL, args.Get(1))
|
||||
}
|
||||
} else {
|
||||
printMsg(iamImportInfo(iamr))
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -1,42 +0,0 @@
|
||||
// Copyright (c) 2022 MinIO, Inc.
|
||||
//
|
||||
// This file is part of MinIO Object Storage stack
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package cmd
|
||||
|
||||
import "github.com/minio/cli"
|
||||
|
||||
var adminClusterIAMSubcommands = []cli.Command{
|
||||
adminClusterIAMImportCmd,
|
||||
adminClusterIAMExportCmd,
|
||||
}
|
||||
|
||||
var adminClusterIAMCmd = cli.Command{
|
||||
Name: "iam",
|
||||
Usage: "manage IAM info on MinIO cluster",
|
||||
Action: mainadminClusterIAM,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
Subcommands: adminClusterIAMSubcommands,
|
||||
HideHelpCommand: true,
|
||||
}
|
||||
|
||||
// mainadminClusterIAM is the handle for "mc admin cluster bucket" command.
|
||||
func mainadminClusterIAM(ctx *cli.Context) error {
|
||||
commandNotFound(ctx, adminClusterIAMSubcommands)
|
||||
return nil
|
||||
// Sub-commands like "export", "import" have their own main.
|
||||
}
|
||||
@@ -1,42 +0,0 @@
|
||||
// Copyright (c) 2022 MinIO, Inc.
|
||||
//
|
||||
// This file is part of MinIO Object Storage stack
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package cmd
|
||||
|
||||
import "github.com/minio/cli"
|
||||
|
||||
var adminClusterSubcommands = []cli.Command{
|
||||
adminClusterBucketCmd,
|
||||
adminClusterIAMCmd,
|
||||
}
|
||||
|
||||
var adminClusterCmd = cli.Command{
|
||||
Name: "cluster",
|
||||
Usage: "manage MinIO cluster metadata",
|
||||
Action: mainAdminCluster,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
Subcommands: adminClusterSubcommands,
|
||||
HideHelpCommand: true,
|
||||
}
|
||||
|
||||
// mainAdminCluster is the handle for "mc admin cluster" command.
|
||||
func mainAdminCluster(ctx *cli.Context) error {
|
||||
commandNotFound(ctx, adminClusterSubcommands)
|
||||
return nil
|
||||
// Sub-commands like "bucket", "iam" have their own main.
|
||||
}
|
||||
@@ -1,125 +0,0 @@
|
||||
// Copyright (c) 2015-2022 MinIO, Inc.
|
||||
//
|
||||
// This file is part of MinIO Object Storage stack
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"fmt"
|
||||
"io"
|
||||
"strings"
|
||||
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/cli"
|
||||
json "github.com/minio/colorjson"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/pkg/v3/console"
|
||||
)
|
||||
|
||||
var adminConfigExportCmd = cli.Command{
|
||||
Name: "export",
|
||||
Usage: "export all config keys to STDOUT",
|
||||
Before: setGlobalsFromContext,
|
||||
Action: mainAdminConfigExport,
|
||||
OnUsageError: onUsageError,
|
||||
Flags: globalFlags,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
{{.HelpName}} TARGET
|
||||
|
||||
FLAGS:
|
||||
{{range .VisibleFlags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
The output includes environment variables set on the server. These cannot be overridden from the client.
|
||||
|
||||
1. Export the current config from MinIO server
|
||||
{{.Prompt}} {{.HelpName}} play/ > config.txt
|
||||
`,
|
||||
}
|
||||
|
||||
// configExportMessage container to hold locks information.
|
||||
type configExportMessage struct {
|
||||
Status string `json:"status"`
|
||||
Value []byte `json:"value"`
|
||||
}
|
||||
|
||||
// String colorized service status message.
|
||||
func (u configExportMessage) String() string {
|
||||
console.SetColor("EnvVar", color.New(color.FgYellow))
|
||||
bio := bufio.NewReader(bytes.NewReader(u.Value))
|
||||
var lines []string
|
||||
for {
|
||||
s, e := bio.ReadString('\n')
|
||||
// Make lines displaying environment variables bold.
|
||||
if strings.HasPrefix(s, "# MINIO_") {
|
||||
s = strings.TrimPrefix(s, "# ")
|
||||
parts := strings.SplitN(s, "=", 2)
|
||||
s = fmt.Sprintf("# %s=%s", console.Colorize("EnvVar", parts[0]), parts[1])
|
||||
lines = append(lines, s)
|
||||
} else {
|
||||
lines = append(lines, s)
|
||||
}
|
||||
if e == io.EOF {
|
||||
break
|
||||
}
|
||||
fatalIf(probe.NewError(e), "Unable to marshal to string.")
|
||||
}
|
||||
return strings.Join(lines, "")
|
||||
}
|
||||
|
||||
// JSON jsonified service status Message message.
|
||||
func (u configExportMessage) JSON() string {
|
||||
u.Status = "success"
|
||||
statusJSONBytes, e := json.MarshalIndent(u, "", " ")
|
||||
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
|
||||
|
||||
return string(statusJSONBytes)
|
||||
}
|
||||
|
||||
// checkAdminConfigExportSyntax - validate all the passed arguments
|
||||
func checkAdminConfigExportSyntax(ctx *cli.Context) {
|
||||
if !ctx.Args().Present() || len(ctx.Args()) > 1 {
|
||||
showCommandHelpAndExit(ctx, 1) // last argument is exit code
|
||||
}
|
||||
}
|
||||
|
||||
func mainAdminConfigExport(ctx *cli.Context) error {
|
||||
checkAdminConfigExportSyntax(ctx)
|
||||
|
||||
// Export the alias parameter from cli
|
||||
args := ctx.Args()
|
||||
aliasedURL := args.Get(0)
|
||||
|
||||
// Create a new MinIO Admin Client
|
||||
client, err := newAdminClient(aliasedURL)
|
||||
fatalIf(err, "Unable to initialize admin connection.")
|
||||
|
||||
// Call get config API
|
||||
buf, e := client.GetConfig(globalContext)
|
||||
fatalIf(probe.NewError(e), "Unable to get server config")
|
||||
|
||||
// Print
|
||||
printMsg(configExportMessage{
|
||||
Value: buf,
|
||||
})
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -1,161 +0,0 @@
|
||||
// Copyright (c) 2015-2022 MinIO, Inc.
|
||||
//
|
||||
// This file is part of MinIO Object Storage stack
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"fmt"
|
||||
"io"
|
||||
"strings"
|
||||
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/cli"
|
||||
json "github.com/minio/colorjson"
|
||||
"github.com/minio/madmin-go/v3"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/pkg/v3/console"
|
||||
)
|
||||
|
||||
var adminConfigGetCmd = cli.Command{
|
||||
Name: "get",
|
||||
Usage: "interactively retrieve a config key parameters",
|
||||
Before: setGlobalsFromContext,
|
||||
Action: mainAdminConfigGet,
|
||||
OnUsageError: onUsageError,
|
||||
Flags: globalFlags,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
{{.HelpName}} TARGET
|
||||
|
||||
FLAGS:
|
||||
{{range .VisibleFlags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
The output includes environment variables set on the server. These cannot be overridden from the client.
|
||||
|
||||
1. Get the current region setting on MinIO server.
|
||||
{{.Prompt}} {{.HelpName}} play/ region
|
||||
region name=us-east-1
|
||||
|
||||
2. Get the current notification settings for Webhook target on MinIO server
|
||||
{{.Prompt}} {{.HelpName}} myminio/ notify_webhook
|
||||
notify_webhook endpoint="http://localhost:8080" auth_token= queue_limit=10000 queue_dir="/home/events"
|
||||
|
||||
3. Get the current compression settings on MinIO server
|
||||
{{.Prompt}} {{.HelpName}} myminio/ compression
|
||||
compression extensions=".txt,.csv" mime_types="text/*"
|
||||
`,
|
||||
}
|
||||
|
||||
type configGetMessage struct {
|
||||
Status string `json:"status"`
|
||||
Config []madmin.SubsysConfig `json:"config"`
|
||||
value []byte
|
||||
}
|
||||
|
||||
// String colorized service status message.
|
||||
func (u configGetMessage) String() string {
|
||||
console.SetColor("EnvVar", color.New(color.FgYellow))
|
||||
bio := bufio.NewReader(bytes.NewReader(u.value))
|
||||
var lines []string
|
||||
for {
|
||||
s, e := bio.ReadString('\n')
|
||||
// Make lines displaying environment variables bold.
|
||||
if strings.HasPrefix(s, "# MINIO_") {
|
||||
s = strings.TrimPrefix(s, "# ")
|
||||
parts := strings.SplitN(s, "=", 2)
|
||||
s = fmt.Sprintf("# %s=%s", console.Colorize("EnvVar", parts[0]), parts[1])
|
||||
lines = append(lines, s)
|
||||
} else {
|
||||
lines = append(lines, s)
|
||||
}
|
||||
if e == io.EOF {
|
||||
break
|
||||
}
|
||||
fatalIf(probe.NewError(e), "Unable to marshal to string.")
|
||||
}
|
||||
return strings.Join(lines, "")
|
||||
}
|
||||
|
||||
// JSON jsonified service status Message message.
|
||||
func (u configGetMessage) JSON() string {
|
||||
u.Status = "success"
|
||||
var err error
|
||||
u.Config, err = madmin.ParseServerConfigOutput(string(u.value))
|
||||
fatalIf(probe.NewError(err), "Unable to marshal into JSON.")
|
||||
|
||||
statusJSONBytes, e := json.MarshalIndent(u, "", " ")
|
||||
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
|
||||
|
||||
return string(statusJSONBytes)
|
||||
}
|
||||
|
||||
// checkAdminConfigGetSyntax - validate all the passed arguments
|
||||
func checkAdminConfigGetSyntax(ctx *cli.Context) {
|
||||
if !ctx.Args().Present() || len(ctx.Args()) < 1 {
|
||||
showCommandHelpAndExit(ctx, 1) // last argument is exit code
|
||||
}
|
||||
}
|
||||
|
||||
func mainAdminConfigGet(ctx *cli.Context) error {
|
||||
checkAdminConfigGetSyntax(ctx)
|
||||
|
||||
// Get the alias parameter from cli
|
||||
args := ctx.Args()
|
||||
aliasedURL := args.Get(0)
|
||||
|
||||
// Create a new MinIO Admin Client
|
||||
client, err := newAdminClient(aliasedURL)
|
||||
fatalIf(err, "Unable to initialize admin connection.")
|
||||
|
||||
if len(ctx.Args()) == 1 {
|
||||
// Call get config API
|
||||
hr, e := client.HelpConfigKV(globalContext, "", "", false)
|
||||
fatalIf(probe.NewError(e), "Unable to get help for the sub-system")
|
||||
|
||||
// Print
|
||||
printMsg(configHelpMessage{
|
||||
Value: hr,
|
||||
envOnly: false,
|
||||
})
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
subSys := strings.Join(args.Tail(), " ")
|
||||
|
||||
// Call get config API
|
||||
buf, e := client.GetConfigKV(globalContext, subSys)
|
||||
fatalIf(probe.NewError(e), "Unable to get server '%s' config", args.Tail())
|
||||
|
||||
if globalJSON {
|
||||
printMsg(configGetMessage{
|
||||
value: buf,
|
||||
})
|
||||
} else {
|
||||
// Print
|
||||
printMsg(configGetMessage{
|
||||
value: buf,
|
||||
})
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -1,84 +0,0 @@
|
||||
// Copyright (c) 2015-2022 MinIO, Inc.
|
||||
//
|
||||
// This file is part of MinIO Object Storage stack
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"text/tabwriter"
|
||||
"text/template"
|
||||
|
||||
"github.com/fatih/color"
|
||||
json "github.com/minio/colorjson"
|
||||
"github.com/minio/madmin-go/v3"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
)
|
||||
|
||||
// HelpTmpl template used by all sub-systems
|
||||
const HelpTmpl = `{{if ne .SubSys ""}}{{colorBlueBold "KEY:"}}
|
||||
{{if .MultipleTargets}}{{colorYellowBold .SubSys}}[:name]{{"\t"}}{{else}}{{colorYellowBold .SubSys}}{{"\t"}}{{end}}{{.Description}}
|
||||
|
||||
{{colorBlueBold "ARGS:"}}{{range .KeysHelp}}
|
||||
{{if .Optional}}{{colorYellowBold .Key}}{{else}}{{colorRedBold .Key}}*{{end}}{{"\t"}}({{.Type}}){{"\t"}}{{.Description}}{{end}}{{else}}{{colorBlueBold "KEYS:"}}{{range .KeysHelp}}
|
||||
{{colorGreenBold .Key}}{{"\t"}}{{.Description}}{{end}}{{end}}`
|
||||
|
||||
var funcMap = template.FuncMap{
|
||||
"colorBlueBold": color.New(color.FgBlue, color.Bold).SprintfFunc(),
|
||||
"colorYellowBold": color.New(color.FgYellow, color.Bold).SprintfFunc(),
|
||||
"colorCyanBold": color.New(color.FgCyan, color.Bold).SprintFunc(),
|
||||
"colorRedBold": color.New(color.FgRed, color.Bold).SprintfFunc(),
|
||||
"colorGreenBold": color.New(color.FgGreen, color.Bold).SprintfFunc(),
|
||||
}
|
||||
|
||||
// HelpTemplate - captures config help template
|
||||
var HelpTemplate = template.Must(template.New("config-help").Funcs(funcMap).Parse(HelpTmpl))
|
||||
|
||||
// HelpEnvTemplate - captures config help template
|
||||
var HelpEnvTemplate = template.Must(template.New("config-help-env").Funcs(funcMap).Parse(HelpTmpl))
|
||||
|
||||
// configHelpMessage container to hold locks information.
|
||||
type configHelpMessage struct {
|
||||
Status string `json:"status"`
|
||||
Value madmin.Help `json:"help"`
|
||||
envOnly bool
|
||||
}
|
||||
|
||||
// String colorized service status message.
|
||||
func (u configHelpMessage) String() string {
|
||||
var s strings.Builder
|
||||
w := tabwriter.NewWriter(&s, 1, 8, 2, ' ', 0)
|
||||
var e error
|
||||
if !u.envOnly {
|
||||
e = HelpTemplate.Execute(w, u.Value)
|
||||
} else {
|
||||
e = HelpEnvTemplate.Execute(w, u.Value)
|
||||
}
|
||||
fatalIf(probe.NewError(e), "Unable to initialize template writer")
|
||||
|
||||
w.Flush()
|
||||
|
||||
return s.String()
|
||||
}
|
||||
|
||||
// JSON jsonified service status Message message.
|
||||
func (u configHelpMessage) JSON() string {
|
||||
u.Status = "success"
|
||||
statusJSONBytes, e := json.MarshalIndent(u, "", " ")
|
||||
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
|
||||
|
||||
return string(statusJSONBytes)
|
||||
}
|
||||
@@ -1,156 +0,0 @@
|
||||
// Copyright (c) 2015-2022 MinIO, Inc.
|
||||
//
|
||||
// This file is part of MinIO Object Storage stack
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"text/tabwriter"
|
||||
"text/template"
|
||||
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/cli"
|
||||
json "github.com/minio/colorjson"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/pkg/v3/console"
|
||||
)
|
||||
|
||||
var historyListFlags = []cli.Flag{
|
||||
cli.IntFlag{
|
||||
Name: "count, n",
|
||||
Usage: "list only last 'n' entries",
|
||||
Value: 10,
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "clear, c",
|
||||
Usage: "clear all history",
|
||||
},
|
||||
}
|
||||
|
||||
var adminConfigHistoryCmd = cli.Command{
|
||||
Name: "history",
|
||||
Usage: "show all historic configuration changes",
|
||||
Before: setGlobalsFromContext,
|
||||
Action: mainAdminConfigHistory,
|
||||
OnUsageError: onUsageError,
|
||||
Flags: append(append([]cli.Flag{}, globalFlags...), historyListFlags...),
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
{{.HelpName}} TARGET
|
||||
|
||||
FLAGS:
|
||||
{{range .VisibleFlags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
1. List all history entries sorted by time.
|
||||
{{.Prompt}} {{.HelpName}} play/
|
||||
`,
|
||||
}
|
||||
|
||||
// History template used by all sub-systems
|
||||
const History = `{{range .}}{{colorYellowBold "RestoreId:"}} {{colorYellowBold .RestoreID}}
|
||||
Date: {{.CreateTime}}
|
||||
|
||||
{{.Targets}}
|
||||
|
||||
{{end}}`
|
||||
|
||||
// HistoryTemplate - captures history list template
|
||||
var HistoryTemplate = template.Must(template.New("history-list").Funcs(funcMap).Parse(History))
|
||||
|
||||
type historyEntry struct {
|
||||
RestoreID string `json:"restoreId"`
|
||||
CreateTime string `json:"createTime"`
|
||||
Targets string `json:"targets"`
|
||||
}
|
||||
|
||||
// configHistoryMessage container to hold locks information.
|
||||
type configHistoryMessage struct {
|
||||
Status string `json:"status"`
|
||||
Entries []historyEntry `json:"entries"`
|
||||
}
|
||||
|
||||
// String colorized service status message.
|
||||
func (u configHistoryMessage) String() string {
|
||||
var s strings.Builder
|
||||
w := tabwriter.NewWriter(&s, 1, 8, 2, ' ', 0)
|
||||
e := HistoryTemplate.Execute(w, u.Entries)
|
||||
fatalIf(probe.NewError(e), "Unable to initialize template writer")
|
||||
|
||||
w.Flush()
|
||||
return s.String()
|
||||
}
|
||||
|
||||
// JSON jsonified service status Message message.
|
||||
func (u configHistoryMessage) JSON() string {
|
||||
u.Status = "success"
|
||||
statusJSONBytes, e := json.MarshalIndent(u, "", " ")
|
||||
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
|
||||
|
||||
return string(statusJSONBytes)
|
||||
}
|
||||
|
||||
// checkAdminConfigHistorySyntax - validate all the passed arguments
|
||||
func checkAdminConfigHistorySyntax(ctx *cli.Context) {
|
||||
if !ctx.Args().Present() || len(ctx.Args()) > 1 {
|
||||
showCommandHelpAndExit(ctx, 1) // last argument is exit code
|
||||
}
|
||||
}
|
||||
|
||||
func mainAdminConfigHistory(ctx *cli.Context) error {
|
||||
checkAdminConfigHistorySyntax(ctx)
|
||||
|
||||
console.SetColor("ConfigHistoryMessageRestoreID", color.New(color.Bold))
|
||||
console.SetColor("ConfigHistoryMessageTime", color.New(color.FgGreen))
|
||||
|
||||
// Get the alias parameter from cli
|
||||
args := ctx.Args()
|
||||
aliasedURL := args.Get(0)
|
||||
|
||||
// Create a new MinIO Admin Client
|
||||
client, err := newAdminClient(aliasedURL)
|
||||
fatalIf(err, "Unable to initialize admin connection.")
|
||||
|
||||
if ctx.Bool("clear") {
|
||||
fatalIf(probe.NewError(client.ClearConfigHistoryKV(globalContext, "all")), "Unable to clear server configuration.")
|
||||
|
||||
// Print
|
||||
printMsg(configHistoryMessage{})
|
||||
return nil
|
||||
}
|
||||
|
||||
chEntries, e := client.ListConfigHistoryKV(globalContext, ctx.Int("count"))
|
||||
fatalIf(probe.NewError(e), "Unable to list server history configuration.")
|
||||
|
||||
hentries := make([]historyEntry, len(chEntries))
|
||||
for i, chEntry := range chEntries {
|
||||
hentries[i] = historyEntry{
|
||||
RestoreID: chEntry.RestoreID,
|
||||
CreateTime: chEntry.CreateTimeFormatted(),
|
||||
}
|
||||
hentries[i].Targets = chEntry.Data
|
||||
}
|
||||
|
||||
// Print
|
||||
printMsg(configHistoryMessage{
|
||||
Entries: hentries,
|
||||
})
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -1,108 +0,0 @@
|
||||
// Copyright (c) 2015-2022 MinIO, Inc.
|
||||
//
|
||||
// This file is part of MinIO Object Storage stack
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/cli"
|
||||
json "github.com/minio/colorjson"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/pkg/v3/console"
|
||||
)
|
||||
|
||||
var adminConfigImportCmd = cli.Command{
|
||||
Name: "import",
|
||||
Usage: "import multiple config keys from STDIN",
|
||||
Before: setGlobalsFromContext,
|
||||
Action: mainAdminConfigImport,
|
||||
OnUsageError: onUsageError,
|
||||
Flags: globalFlags,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
{{.HelpName}} TARGET
|
||||
|
||||
FLAGS:
|
||||
{{range .VisibleFlags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
1. Import the new local config and apply to the MinIO server
|
||||
{{.Prompt}} {{.HelpName}} play/ < config.txt
|
||||
`,
|
||||
}
|
||||
|
||||
// configImportMessage container to hold locks information.
|
||||
type configImportMessage struct {
|
||||
Status string `json:"status"`
|
||||
targetAlias string
|
||||
}
|
||||
|
||||
// String colorized service status message.
|
||||
func (u configImportMessage) String() (msg string) {
|
||||
msg += console.Colorize("SetConfigSuccess",
|
||||
"Setting new key has been successful.\n")
|
||||
suggestion := fmt.Sprintf("mc admin service restart %s", u.targetAlias)
|
||||
msg += console.Colorize("SetConfigSuccess",
|
||||
fmt.Sprintf("Please restart your server with `%s`.\n", suggestion))
|
||||
return msg
|
||||
}
|
||||
|
||||
// JSON jsonified service status Message message.
|
||||
func (u configImportMessage) JSON() string {
|
||||
u.Status = "success"
|
||||
statusJSONBytes, e := json.MarshalIndent(u, "", " ")
|
||||
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
|
||||
|
||||
return string(statusJSONBytes)
|
||||
}
|
||||
|
||||
// checkAdminConfigImportSyntax - validate all the passed arguments
|
||||
func checkAdminConfigImportSyntax(ctx *cli.Context) {
|
||||
if !ctx.Args().Present() || len(ctx.Args()) > 1 {
|
||||
showCommandHelpAndExit(ctx, 1) // last argument is exit code
|
||||
}
|
||||
}
|
||||
|
||||
func mainAdminConfigImport(ctx *cli.Context) error {
|
||||
checkAdminConfigImportSyntax(ctx)
|
||||
|
||||
// Set color preference of command outputs
|
||||
console.SetColor("SetConfigSuccess", color.New(color.FgGreen, color.Bold))
|
||||
|
||||
// Import the alias parameter from cli
|
||||
args := ctx.Args()
|
||||
aliasedURL := args.Get(0)
|
||||
|
||||
// Create a new MinIO Admin Client
|
||||
client, err := newAdminClient(aliasedURL)
|
||||
fatalIf(err, "Unable to initialize admin connection.")
|
||||
|
||||
// Call set config API
|
||||
fatalIf(probe.NewError(client.SetConfig(globalContext, os.Stdin)), "Unable to set server config")
|
||||
|
||||
// Print
|
||||
printMsg(configImportMessage{
|
||||
targetAlias: aliasedURL,
|
||||
})
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -1,152 +0,0 @@
|
||||
// Copyright (c) 2015-2022 MinIO, Inc.
|
||||
//
|
||||
// This file is part of MinIO Object Storage stack
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/cli"
|
||||
json "github.com/minio/colorjson"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/pkg/v3/console"
|
||||
)
|
||||
|
||||
var adminConfigEnvFlags = []cli.Flag{
|
||||
cli.BoolFlag{
|
||||
Name: "env",
|
||||
Usage: "list all the env only help",
|
||||
},
|
||||
}
|
||||
|
||||
var adminConfigResetCmd = cli.Command{
|
||||
Name: "reset",
|
||||
Usage: "interactively reset a config key parameters",
|
||||
Before: setGlobalsFromContext,
|
||||
Action: mainAdminConfigReset,
|
||||
OnUsageError: onUsageError,
|
||||
Flags: append(adminConfigEnvFlags, globalFlags...),
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
{{.HelpName}} TARGET [CONFIG-KEY...]
|
||||
|
||||
FLAGS:
|
||||
{{range .VisibleFlags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
1. Reset MQTT notifcation target 'name1' settings to default values.
|
||||
{{.Prompt}} {{.HelpName}} myminio/ notify_mqtt:name1
|
||||
2. Reset compression's 'extensions' setting to default value.
|
||||
{{.Prompt}} {{.HelpName}} myminio/ compression extensions
|
||||
3. Reset site name and site region to default values.
|
||||
{{.Prompt}} {{.HelpName}} myminio/ site name region
|
||||
`,
|
||||
}
|
||||
|
||||
// configResetMessage container to hold locks information.
|
||||
type configResetMessage struct {
|
||||
Status string `json:"status"`
|
||||
targetAlias string
|
||||
key string
|
||||
restart bool
|
||||
}
|
||||
|
||||
// String colorized service status message.
|
||||
func (u configResetMessage) String() (msg string) {
|
||||
msg += console.Colorize("ResetConfigSuccess",
|
||||
fmt.Sprintf("'%s' is successfully reset.", u.key))
|
||||
if u.restart {
|
||||
suggestion := fmt.Sprintf("mc admin service restart %s", u.targetAlias)
|
||||
msg += console.Colorize("ResetConfigSuccess",
|
||||
fmt.Sprintf("\nPlease restart your server with `%s`.", suggestion))
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// JSON jsonified service status message.
|
||||
func (u configResetMessage) JSON() string {
|
||||
u.Status = "success"
|
||||
statusJSONBytes, e := json.MarshalIndent(u, "", " ")
|
||||
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
|
||||
|
||||
return string(statusJSONBytes)
|
||||
}
|
||||
|
||||
// checkAdminConfigResetSyntax - validate all the passed arguments
|
||||
func checkAdminConfigResetSyntax(ctx *cli.Context) {
|
||||
if !ctx.Args().Present() {
|
||||
showCommandHelpAndExit(ctx, 1) // last argument is exit code
|
||||
}
|
||||
}
|
||||
|
||||
// main config set function
|
||||
func mainAdminConfigReset(ctx *cli.Context) error {
|
||||
// Check command arguments
|
||||
checkAdminConfigResetSyntax(ctx)
|
||||
|
||||
// Reset color preference of command outputs
|
||||
console.SetColor("ResetConfigSuccess", color.New(color.FgGreen, color.Bold))
|
||||
console.SetColor("ResetConfigFailure", color.New(color.FgRed, color.Bold))
|
||||
|
||||
// Get the alias parameter from cli
|
||||
args := ctx.Args()
|
||||
aliasedURL := args.Get(0)
|
||||
|
||||
// Create a new MinIO Admin Client
|
||||
client, err := newAdminClient(aliasedURL)
|
||||
fatalIf(err, "Unable to initialize admin connection.")
|
||||
|
||||
if len(ctx.Args()) == 1 {
|
||||
// Call get config API
|
||||
hr, e := client.HelpConfigKV(globalContext, "", "", ctx.Bool("env"))
|
||||
fatalIf(probe.NewError(e), "Unable to get help for the sub-system")
|
||||
|
||||
// Print
|
||||
printMsg(configHelpMessage{
|
||||
Value: hr,
|
||||
envOnly: ctx.Bool("env"),
|
||||
})
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
input := strings.Join(args.Tail(), " ")
|
||||
// Check if user has attempted to set values
|
||||
for _, k := range args.Tail() {
|
||||
if strings.Contains(k, "=") {
|
||||
e := fmt.Errorf("new settings may not be provided for sub-system keys")
|
||||
fatalIf(probe.NewError(e), "Unable to reset '%s' on the server", args.Tail()[0])
|
||||
}
|
||||
}
|
||||
|
||||
// Call reset config API
|
||||
restart, e := client.DelConfigKV(globalContext, input)
|
||||
fatalIf(probe.NewError(e), "Unable to reset '%s' on the server", input)
|
||||
|
||||
// Print set config result
|
||||
printMsg(configResetMessage{
|
||||
targetAlias: aliasedURL,
|
||||
restart: restart,
|
||||
key: input,
|
||||
})
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -1,107 +0,0 @@
|
||||
// Copyright (c) 2015-2022 MinIO, Inc.
|
||||
//
|
||||
// This file is part of MinIO Object Storage stack
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/cli"
|
||||
json "github.com/minio/colorjson"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/pkg/v3/console"
|
||||
)
|
||||
|
||||
var adminConfigRestoreCmd = cli.Command{
|
||||
Name: "restore",
|
||||
Usage: "rollback back changes to a specific config history",
|
||||
Before: setGlobalsFromContext,
|
||||
Action: mainAdminConfigRestore,
|
||||
OnUsageError: onUsageError,
|
||||
Flags: globalFlags,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
{{.HelpName}} TARGET RESTOREID
|
||||
|
||||
FLAGS:
|
||||
{{range .VisibleFlags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
1. Restore 'restore-id' history key value on MinIO server.
|
||||
{{.Prompt}} {{.HelpName}} play/ <restore-id>
|
||||
`,
|
||||
}
|
||||
|
||||
// configRestoreMessage container to hold locks information.
|
||||
type configRestoreMessage struct {
|
||||
Status string `json:"status"`
|
||||
RestoreID string `json:"restoreID"`
|
||||
targetAlias string
|
||||
}
|
||||
|
||||
// String colorized service status message.
|
||||
func (u configRestoreMessage) String() (msg string) {
|
||||
suggestion := fmt.Sprintf("mc admin service restart %s", u.targetAlias)
|
||||
msg += console.Colorize("ConfigRestoreMessage",
|
||||
fmt.Sprintf("Please restart your server with `%s`.\n", suggestion))
|
||||
msg += console.Colorize("ConfigRestoreMessage", "Restored "+u.RestoreID+" kv successfully.")
|
||||
return msg
|
||||
}
|
||||
|
||||
// JSON jsonified service status Message message.
|
||||
func (u configRestoreMessage) JSON() string {
|
||||
u.Status = "success"
|
||||
statusJSONBytes, e := json.MarshalIndent(u, "", " ")
|
||||
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
|
||||
|
||||
return string(statusJSONBytes)
|
||||
}
|
||||
|
||||
// checkAdminConfigRestoreSyntax - validate all the passed arguments
|
||||
func checkAdminConfigRestoreSyntax(ctx *cli.Context) {
|
||||
if !ctx.Args().Present() || len(ctx.Args()) > 2 {
|
||||
showCommandHelpAndExit(ctx, 1) // last argument is exit code
|
||||
}
|
||||
}
|
||||
|
||||
func mainAdminConfigRestore(ctx *cli.Context) error {
|
||||
checkAdminConfigRestoreSyntax(ctx)
|
||||
|
||||
console.SetColor("ConfigRestoreMessage", color.New(color.FgGreen))
|
||||
|
||||
// Get the alias parameter from cli
|
||||
args := ctx.Args()
|
||||
aliasedURL := args.Get(0)
|
||||
|
||||
// Create a new MinIO Admin Client
|
||||
client, err := newAdminClient(aliasedURL)
|
||||
fatalIf(err, "Unable to initialize admin connection.")
|
||||
|
||||
// Call get config API
|
||||
fatalIf(probe.NewError(client.RestoreConfigHistoryKV(globalContext, args.Get(1))), "Unable to restore server configuration.")
|
||||
|
||||
// Print
|
||||
printMsg(configRestoreMessage{
|
||||
RestoreID: args.Get(1),
|
||||
targetAlias: aliasedURL,
|
||||
})
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -1,139 +0,0 @@
|
||||
// Copyright (c) 2015-2022 MinIO, Inc.
|
||||
//
|
||||
// This file is part of MinIO Object Storage stack
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/cli"
|
||||
json "github.com/minio/colorjson"
|
||||
"github.com/minio/madmin-go/v3"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/pkg/v3/console"
|
||||
)
|
||||
|
||||
var adminConfigSetCmd = cli.Command{
|
||||
Name: "set",
|
||||
Usage: "interactively set a config key parameters",
|
||||
Before: setGlobalsFromContext,
|
||||
Action: mainAdminConfigSet,
|
||||
OnUsageError: onUsageError,
|
||||
Flags: append(adminConfigEnvFlags, globalFlags...),
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
{{.HelpName}} TARGET
|
||||
|
||||
FLAGS:
|
||||
{{range .VisibleFlags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
1. Enable webhook notification target for MinIO server.
|
||||
{{.Prompt}} {{.HelpName}} myminio/ notify_webhook endpoint="http://localhost:8080/minio/events"
|
||||
|
||||
2. Change region name for the MinIO server to 'us-west-1'.
|
||||
{{.Prompt}} {{.HelpName}} myminio/ region name=us-west-1
|
||||
|
||||
3. Change healing settings on a distributed MinIO server setup.
|
||||
{{.Prompt}} {{.HelpName}} mydist/ heal max_delay=300ms max_io=50
|
||||
`,
|
||||
}
|
||||
|
||||
// configSetMessage container to hold locks information.
|
||||
type configSetMessage struct {
|
||||
Status string `json:"status"`
|
||||
targetAlias string
|
||||
restart bool
|
||||
}
|
||||
|
||||
// String colorized service status message.
|
||||
func (u configSetMessage) String() (msg string) {
|
||||
msg += console.Colorize("SetConfigSuccess",
|
||||
"Successfully applied new settings.")
|
||||
if u.restart {
|
||||
suggestion := color.RedString("mc admin service restart %s", u.targetAlias)
|
||||
msg += console.Colorize("SetConfigSuccess",
|
||||
fmt.Sprintf("\nPlease restart your server '%s'.", suggestion))
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// JSON jsonified service status message.
|
||||
func (u configSetMessage) JSON() string {
|
||||
u.Status = "success"
|
||||
statusJSONBytes, e := json.MarshalIndent(u, "", " ")
|
||||
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
|
||||
|
||||
return string(statusJSONBytes)
|
||||
}
|
||||
|
||||
// checkAdminConfigSetSyntax - validate all the passed arguments
|
||||
func checkAdminConfigSetSyntax(ctx *cli.Context) {
|
||||
if !ctx.Args().Present() && len(ctx.Args()) < 1 {
|
||||
showCommandHelpAndExit(ctx, 1) // last argument is exit code
|
||||
}
|
||||
}
|
||||
|
||||
// main config set function
|
||||
func mainAdminConfigSet(ctx *cli.Context) error {
|
||||
// Check command arguments
|
||||
checkAdminConfigSetSyntax(ctx)
|
||||
|
||||
// Set color preference of command outputs
|
||||
console.SetColor("SetConfigSuccess", color.New(color.FgGreen, color.Bold))
|
||||
|
||||
// Get the alias parameter from cli
|
||||
args := ctx.Args()
|
||||
aliasedURL := args.Get(0)
|
||||
|
||||
// Create a new MinIO Admin Client
|
||||
client, err := newAdminClient(aliasedURL)
|
||||
fatalIf(err, "Unable to initialize admin connection.")
|
||||
|
||||
input := strings.Join(args.Tail(), " ")
|
||||
|
||||
if !strings.Contains(input, madmin.KvSeparator) {
|
||||
// Call get config API
|
||||
hr, e := client.HelpConfigKV(globalContext, args.Get(1), args.Get(2), ctx.Bool("env"))
|
||||
fatalIf(probe.NewError(e), "Unable to get help for the sub-system")
|
||||
|
||||
// Print
|
||||
printMsg(configHelpMessage{
|
||||
Value: hr,
|
||||
envOnly: ctx.Bool("env"),
|
||||
})
|
||||
|
||||
return nil
|
||||
|
||||
}
|
||||
|
||||
// Call set config API
|
||||
restart, e := client.SetConfigKV(globalContext, input)
|
||||
fatalIf(probe.NewError(e), "Unable to set '%s' to server", input)
|
||||
|
||||
// Print set config result
|
||||
printMsg(configSetMessage{
|
||||
targetAlias: aliasedURL,
|
||||
restart: restart,
|
||||
})
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -1,47 +0,0 @@
|
||||
// Copyright (c) 2015-2022 MinIO, Inc.
|
||||
//
|
||||
// This file is part of MinIO Object Storage stack
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package cmd
|
||||
|
||||
import "github.com/minio/cli"
|
||||
|
||||
var adminConfigSubcommands = []cli.Command{
|
||||
adminConfigGetCmd,
|
||||
adminConfigSetCmd,
|
||||
adminConfigResetCmd,
|
||||
adminConfigHistoryCmd,
|
||||
adminConfigRestoreCmd,
|
||||
adminConfigExportCmd,
|
||||
adminConfigImportCmd,
|
||||
}
|
||||
|
||||
var adminConfigCmd = cli.Command{
|
||||
Name: "config",
|
||||
Usage: "manage MinIO server configuration",
|
||||
Action: mainAdminConfig,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
Subcommands: adminConfigSubcommands,
|
||||
HideHelpCommand: true,
|
||||
}
|
||||
|
||||
// mainAdminConfig is the handle for "mc admin config" command.
|
||||
func mainAdminConfig(ctx *cli.Context) error {
|
||||
commandNotFound(ctx, adminConfigSubcommands)
|
||||
return nil
|
||||
// Sub-commands like "get", "set" have their own main.
|
||||
}
|
||||
@@ -1,71 +0,0 @@
|
||||
// Copyright (c) 2015-2022 MinIO, Inc.
|
||||
//
|
||||
// This file is part of MinIO Object Storage stack
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/minio/cli"
|
||||
)
|
||||
|
||||
var adminConsoleFlags = []cli.Flag{
|
||||
cli.IntFlag{
|
||||
Name: "limit, l",
|
||||
Usage: "show last n log entries",
|
||||
Value: 10,
|
||||
},
|
||||
cli.StringFlag{
|
||||
Name: "type, t",
|
||||
Usage: "list error logs by type. Valid options are '[minio, application, all]'",
|
||||
Value: "all",
|
||||
},
|
||||
}
|
||||
|
||||
var adminConsoleCmd = cli.Command{
|
||||
Name: "console",
|
||||
Usage: "show MinIO logs",
|
||||
Action: mainAdminConsole,
|
||||
OnUsageError: onUsageError,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: append(adminConsoleFlags, globalFlags...),
|
||||
Hidden: true,
|
||||
HideHelpCommand: true,
|
||||
CustomHelpTemplate: "This command is not supported now and replaced by 'admin logs' command. Please use 'mc admin logs'.\n",
|
||||
}
|
||||
|
||||
// mainAdminConsole - the entry function of console command
|
||||
func mainAdminConsole(ctx *cli.Context) error {
|
||||
newCmd := []string{"mc admin logs"}
|
||||
|
||||
var flgStr string
|
||||
|
||||
if ctx.IsSet("limit") {
|
||||
flgStr = fmt.Sprintf("%s %d", "--last", ctx.Int("limit"))
|
||||
newCmd = append(newCmd, flgStr)
|
||||
}
|
||||
|
||||
if ctx.IsSet("type") {
|
||||
flgStr = fmt.Sprintf("%s %s", "--type", strings.ToLower(ctx.String("type")))
|
||||
newCmd = append(newCmd, flgStr)
|
||||
}
|
||||
newCmd = append(newCmd, ctx.Args()...)
|
||||
|
||||
deprecatedError(strings.Join(newCmd, " "))
|
||||
return nil
|
||||
}
|
||||
@@ -1,139 +0,0 @@
|
||||
// Copyright (c) 2015-2022 MinIO, Inc.
|
||||
//
|
||||
// This file is part of MinIO Object Storage stack
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"path/filepath"
|
||||
|
||||
humanize "github.com/dustin/go-humanize"
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/madmin-go/v3"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/pkg/v3/console"
|
||||
)
|
||||
|
||||
var adminDecommissionCancelCmd = cli.Command{
|
||||
Name: "cancel",
|
||||
Usage: "cancel an ongoing decommissioning of a pool",
|
||||
Action: mainAdminDecommissionCancel,
|
||||
OnUsageError: onUsageError,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
{{.HelpName}} TARGET
|
||||
|
||||
FLAGS:
|
||||
{{range .VisibleFlags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
1. Cancel an ongoing decommissioning of a pool.
|
||||
{{.Prompt}} {{.HelpName}} myminio/ http://server{5...8}/disk{1...4}
|
||||
|
||||
2. Cancel all ongoing decommissioning of pools.
|
||||
{{.Prompt}} {{.HelpName}} myminio/
|
||||
`,
|
||||
}
|
||||
|
||||
// checkAdminDecommissionCancelSyntax - validate all the passed arguments
|
||||
func checkAdminDecommissionCancelSyntax(ctx *cli.Context) {
|
||||
if len(ctx.Args()) > 2 || len(ctx.Args()) == 0 {
|
||||
showCommandHelpAndExit(ctx, 1) // last argument is exit code
|
||||
}
|
||||
}
|
||||
|
||||
// mainAdminDecommissionCancel is the handle for "mc admin decommission cancel" command.
|
||||
func mainAdminDecommissionCancel(ctx *cli.Context) error {
|
||||
checkAdminDecommissionCancelSyntax(ctx)
|
||||
|
||||
// Get the alias parameter from cli
|
||||
args := ctx.Args()
|
||||
aliasedURL := args.Get(0)
|
||||
aliasedURL = filepath.Clean(aliasedURL)
|
||||
|
||||
// Create a new MinIO Admin Client
|
||||
client, err := newAdminClient(aliasedURL)
|
||||
fatalIf(err, "Unable to initialize admin connection.")
|
||||
|
||||
if pool := args.Get(1); pool != "" {
|
||||
e := client.CancelDecommissionPool(globalContext, pool)
|
||||
fatalIf(probe.NewError(e).Trace(args...), "Unable to cancel decommissioning, please try again")
|
||||
return nil
|
||||
}
|
||||
|
||||
poolStatuses, e := client.ListPoolsStatus(globalContext)
|
||||
fatalIf(probe.NewError(e).Trace(args...), "Unable to get status for all pools")
|
||||
|
||||
var newPoolStatuses []madmin.PoolStatus
|
||||
for _, pool := range poolStatuses {
|
||||
if pool.Decommission != nil {
|
||||
if pool.Decommission.StartTime.IsZero() {
|
||||
continue
|
||||
}
|
||||
if pool.Decommission.Complete {
|
||||
continue
|
||||
}
|
||||
}
|
||||
newPoolStatuses = append(newPoolStatuses, pool)
|
||||
}
|
||||
|
||||
dspOrder := []col{colGreen} // Header
|
||||
for i := 0; i < len(newPoolStatuses); i++ {
|
||||
dspOrder = append(dspOrder, colGrey)
|
||||
}
|
||||
var printColors []*color.Color
|
||||
for _, c := range dspOrder {
|
||||
printColors = append(printColors, getPrintCol(c))
|
||||
}
|
||||
|
||||
tbl := console.NewTable(printColors, []bool{false, false, false, false}, 0)
|
||||
|
||||
cellText := make([][]string, len(newPoolStatuses)+1)
|
||||
cellText[0] = []string{
|
||||
"ID",
|
||||
"Pools",
|
||||
"Capacity",
|
||||
"Status",
|
||||
}
|
||||
for idx, pool := range poolStatuses {
|
||||
idx++
|
||||
totalSize := uint64(pool.Decommission.TotalSize)
|
||||
currentSize := uint64(pool.Decommission.CurrentSize)
|
||||
capacity := humanize.IBytes(totalSize-currentSize) + " (used) / " + humanize.IBytes(totalSize) + " (total)"
|
||||
status := ""
|
||||
if pool.Decommission != nil {
|
||||
if pool.Decommission.StartTime.IsZero() {
|
||||
continue
|
||||
}
|
||||
if pool.Decommission.Complete {
|
||||
continue
|
||||
}
|
||||
status = "Draining"
|
||||
}
|
||||
cellText[idx] = []string{
|
||||
humanize.Ordinal(pool.ID + 1),
|
||||
pool.CmdLine,
|
||||
capacity,
|
||||
status,
|
||||
}
|
||||
}
|
||||
return tbl.DisplayTable(cellText)
|
||||
}
|
||||
@@ -1,102 +0,0 @@
|
||||
// Copyright (c) 2015-2022 MinIO, Inc.
|
||||
//
|
||||
// This file is part of MinIO Object Storage stack
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"path/filepath"
|
||||
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/cli"
|
||||
json "github.com/minio/colorjson"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/pkg/v3/console"
|
||||
)
|
||||
|
||||
var adminDecommissionStartCmd = cli.Command{
|
||||
Name: "start",
|
||||
Usage: "start decommissioning a pool",
|
||||
Action: mainAdminDecommissionStart,
|
||||
OnUsageError: onUsageError,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
{{.HelpName}} TARGET
|
||||
|
||||
FLAGS:
|
||||
{{range .VisibleFlags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
1. Start decommissioning a pool for removal.
|
||||
{{.Prompt}} {{.HelpName}} myminio/ http://server{5...8}/disk{1...4}
|
||||
`,
|
||||
}
|
||||
|
||||
// checkAdminDecommissionStartSyntax - validate all the passed arguments
|
||||
func checkAdminDecommissionStartSyntax(ctx *cli.Context) {
|
||||
if len(ctx.Args()) != 2 {
|
||||
showCommandHelpAndExit(ctx, 1) // last argument is exit code
|
||||
}
|
||||
}
|
||||
|
||||
// startDecomMessage is container for make bucket success and failure messages.
|
||||
type startDecomMessage struct {
|
||||
Status string `json:"status"`
|
||||
Pool string `json:"pool"`
|
||||
}
|
||||
|
||||
// String colorized construct a string message.
|
||||
func (s startDecomMessage) String() string {
|
||||
return console.Colorize("DecomPool", "Decommission started successfully for `"+s.Pool+"`.")
|
||||
}
|
||||
|
||||
// JSON jsonified decom message.
|
||||
func (s startDecomMessage) JSON() string {
|
||||
startDecomBytes, e := json.MarshalIndent(s, "", " ")
|
||||
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
|
||||
|
||||
return string(startDecomBytes)
|
||||
}
|
||||
|
||||
// mainAdminDecommissionStart is the handle for "mc admin decommission start" command.
|
||||
func mainAdminDecommissionStart(ctx *cli.Context) error {
|
||||
checkAdminDecommissionStartSyntax(ctx)
|
||||
|
||||
// Additional command speific theme customization.
|
||||
console.SetColor("DecomPool", color.New(color.FgGreen, color.Bold))
|
||||
|
||||
// Get the alias parameter from cli
|
||||
args := ctx.Args()
|
||||
aliasedURL := args.Get(0)
|
||||
aliasedURL = filepath.Clean(aliasedURL)
|
||||
|
||||
// Create a new MinIO Admin Client
|
||||
client, err := newAdminClient(aliasedURL)
|
||||
fatalIf(err, "Unable to initialize admin connection.")
|
||||
|
||||
e := client.DecommissionPool(globalContext, args.Get(1))
|
||||
fatalIf(probe.NewError(e).Trace(args...), "Unable to start decommission on the specified pool")
|
||||
|
||||
printMsg(startDecomMessage{
|
||||
Status: "success",
|
||||
Pool: args.Get(1),
|
||||
})
|
||||
return nil
|
||||
}
|
||||
@@ -1,175 +0,0 @@
|
||||
// Copyright (c) 2015-2022 MinIO, Inc.
|
||||
//
|
||||
// This file is part of MinIO Object Storage stack
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
"time"
|
||||
|
||||
"github.com/dustin/go-humanize"
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/cli"
|
||||
json "github.com/minio/colorjson"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/pkg/v3/console"
|
||||
)
|
||||
|
||||
var adminDecommissionStatusCmd = cli.Command{
|
||||
Name: "status",
|
||||
Usage: "show current decommissioning status",
|
||||
Action: mainAdminDecommissionStatus,
|
||||
OnUsageError: onUsageError,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
{{.HelpName}} TARGET
|
||||
|
||||
FLAGS:
|
||||
{{range .VisibleFlags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
1. Show current decommissioning status.
|
||||
{{.Prompt}} {{.HelpName}} myminio/ http://server{5...8}/disk{1...4}
|
||||
2. List all current decommissioning status of all pools.
|
||||
{{.Prompt}} {{.HelpName}} myminio/
|
||||
`,
|
||||
}
|
||||
|
||||
// checkAdminDecommissionStatusSyntax - validate all the passed arguments
|
||||
func checkAdminDecommissionStatusSyntax(ctx *cli.Context) {
|
||||
if len(ctx.Args()) > 2 || len(ctx.Args()) == 0 {
|
||||
showCommandHelpAndExit(ctx, 1) // last argument is exit code
|
||||
}
|
||||
}
|
||||
|
||||
// mainAdminDecommissionStatus is the handle for "mc admin decomission status" command.
|
||||
func mainAdminDecommissionStatus(ctx *cli.Context) error {
|
||||
checkAdminDecommissionStatusSyntax(ctx)
|
||||
|
||||
// Get the alias parameter from cli
|
||||
args := ctx.Args()
|
||||
aliasedURL := args.Get(0)
|
||||
aliasedURL = filepath.Clean(aliasedURL)
|
||||
|
||||
// Create a new MinIO Admin Client
|
||||
client, err := newAdminClient(aliasedURL)
|
||||
fatalIf(err, "Unable to initialize admin connection.")
|
||||
|
||||
if pool := args.Get(1); pool != "" {
|
||||
poolStatus, e := client.StatusPool(globalContext, pool)
|
||||
fatalIf(probe.NewError(e).Trace(args...), "Unable to get status per pool")
|
||||
|
||||
if globalJSON {
|
||||
statusJSONBytes, e := json.MarshalIndent(poolStatus, "", " ")
|
||||
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
|
||||
console.Println(string(statusJSONBytes))
|
||||
return nil
|
||||
}
|
||||
|
||||
var msg string
|
||||
if poolStatus.Decommission.Complete {
|
||||
msg = color.GreenString(fmt.Sprintf("Decommission of pool %s is complete, you may now remove it from server command line", poolStatus.CmdLine))
|
||||
} else if poolStatus.Decommission.Failed {
|
||||
msg = color.GreenString(fmt.Sprintf("Decommission of pool %s failed, please retry again", poolStatus.CmdLine))
|
||||
} else if poolStatus.Decommission.Canceled {
|
||||
msg = color.GreenString(fmt.Sprintf("Decommission of pool %s was canceled, you may start again", poolStatus.CmdLine))
|
||||
} else if !poolStatus.Decommission.StartTime.IsZero() {
|
||||
usedStart := (poolStatus.Decommission.TotalSize - poolStatus.Decommission.StartSize)
|
||||
usedCurrent := (poolStatus.Decommission.TotalSize - poolStatus.Decommission.CurrentSize)
|
||||
|
||||
duration := float64(time.Since(poolStatus.Decommission.StartTime)) / float64(time.Second)
|
||||
if usedStart > usedCurrent && duration > 10 {
|
||||
copied := uint64(usedStart - usedCurrent)
|
||||
speed := uint64(float64(copied) / duration)
|
||||
msg = "Decommissioning rate at " + humanize.IBytes(speed) + "/sec " + "[" + humanize.IBytes(
|
||||
uint64(usedCurrent)) + "/" + humanize.IBytes(uint64(poolStatus.Decommission.TotalSize)) + "]"
|
||||
msg += "\nStarted: " + humanize.RelTime(time.Now().UTC(), poolStatus.Decommission.StartTime, "", "ago")
|
||||
} else {
|
||||
msg = "Decommissioning is starting..."
|
||||
}
|
||||
msg = color.GreenString(msg)
|
||||
} else {
|
||||
errorIf(errDummy().Trace(args...), "This pool is currently not scheduled for decomissioning")
|
||||
return nil
|
||||
}
|
||||
fmt.Println(msg)
|
||||
return nil
|
||||
}
|
||||
poolStatuses, e := client.ListPoolsStatus(globalContext)
|
||||
fatalIf(probe.NewError(e).Trace(args...), "Unable to get status for all pools")
|
||||
|
||||
if globalJSON {
|
||||
statusJSONBytes, e := json.MarshalIndent(poolStatuses, "", " ")
|
||||
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
|
||||
console.Println(string(statusJSONBytes))
|
||||
return nil
|
||||
}
|
||||
|
||||
dspOrder := []col{colGreen} // Header
|
||||
for range poolStatuses {
|
||||
dspOrder = append(dspOrder, colGrey)
|
||||
}
|
||||
var printColors []*color.Color
|
||||
for _, c := range dspOrder {
|
||||
printColors = append(printColors, getPrintCol(c))
|
||||
}
|
||||
|
||||
tbl := console.NewTable(printColors, []bool{false, false, false, false}, 0)
|
||||
|
||||
cellText := make([][]string, len(poolStatuses)+1)
|
||||
cellText[0] = []string{
|
||||
"ID",
|
||||
"Pools",
|
||||
"Drives Usage",
|
||||
"Status",
|
||||
}
|
||||
for idx, pool := range poolStatuses {
|
||||
idx++
|
||||
totalSize := uint64(pool.Decommission.TotalSize)
|
||||
usedCurrent := uint64(pool.Decommission.TotalSize - pool.Decommission.CurrentSize)
|
||||
var capacity string
|
||||
if totalSize == 0 {
|
||||
capacity = "0% (total: 0B)"
|
||||
} else {
|
||||
capacity = fmt.Sprintf("%.1f%% (total: %s)", 100*float64(usedCurrent)/float64(totalSize), humanize.IBytes(totalSize))
|
||||
}
|
||||
status := "Active"
|
||||
if pool.Decommission != nil {
|
||||
if pool.Decommission.Complete {
|
||||
status = "Complete"
|
||||
} else if pool.Decommission.Failed {
|
||||
status = "Draining(Failed)"
|
||||
} else if pool.Decommission.Canceled {
|
||||
status = "Draining(Canceled)"
|
||||
} else if !pool.Decommission.StartTime.IsZero() {
|
||||
status = "Draining"
|
||||
}
|
||||
}
|
||||
cellText[idx] = []string{
|
||||
humanize.Ordinal(pool.ID + 1),
|
||||
pool.CmdLine,
|
||||
capacity,
|
||||
status,
|
||||
}
|
||||
}
|
||||
return tbl.DisplayTable(cellText)
|
||||
}
|
||||
@@ -1,46 +0,0 @@
|
||||
// Copyright (c) 2015-2022 MinIO, Inc.
|
||||
//
|
||||
// This file is part of MinIO Object Storage stack
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"github.com/minio/cli"
|
||||
)
|
||||
|
||||
var adminDecommissionSubcommands = []cli.Command{
|
||||
adminDecommissionStartCmd,
|
||||
adminDecommissionStatusCmd,
|
||||
adminDecommissionCancelCmd,
|
||||
}
|
||||
|
||||
var adminDecommissionCmd = cli.Command{
|
||||
Name: "decommission",
|
||||
Aliases: []string{"decom"},
|
||||
Usage: "manage MinIO server pool decommissioning",
|
||||
Action: mainAdminDecommission,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
Subcommands: adminDecommissionSubcommands,
|
||||
HideHelpCommand: true,
|
||||
}
|
||||
|
||||
// mainAdminDecommission is the handle for "mc admin decommission" command.
|
||||
func mainAdminDecommission(ctx *cli.Context) error {
|
||||
commandNotFound(ctx, adminDecommissionSubcommands)
|
||||
return nil
|
||||
// Sub-commands like "get", "set" have their own main.
|
||||
}
|
||||
@@ -1,149 +0,0 @@
|
||||
// Copyright (c) 2015-2022 MinIO, Inc.
|
||||
//
|
||||
// This file is part of MinIO Object Storage stack
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/cli"
|
||||
json "github.com/minio/colorjson"
|
||||
"github.com/minio/madmin-go/v3"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/pkg/v3/console"
|
||||
)
|
||||
|
||||
var adminGroupAddCmd = cli.Command{
|
||||
Name: "add",
|
||||
Usage: "add users to a new or existing group",
|
||||
Action: mainAdminGroupAdd,
|
||||
OnUsageError: onUsageError,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
{{.HelpName}} TARGET GROUPNAME MEMBERS...
|
||||
|
||||
FLAGS:
|
||||
{{range .VisibleFlags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
1. Add users 'fivecent' and 'tencent' to the group 'allcents':
|
||||
{{.Prompt}} {{.HelpName}} myminio allcents fivecent tencent
|
||||
|
||||
2. Add user "james" to group "staff", then add the "readwrite" policy to the group "staff".
|
||||
{{.Prompt}} {{.HelpName}} myminio staff james
|
||||
{{.Prompt}} mc admin policy attach myminio readwrite --group staff
|
||||
`,
|
||||
}
|
||||
|
||||
// checkAdminGroupAddSyntax - validate all the passed arguments
|
||||
func checkAdminGroupAddSyntax(ctx *cli.Context) {
|
||||
if len(ctx.Args()) < 3 {
|
||||
showCommandHelpAndExit(ctx, 1) // last argument is exit code
|
||||
}
|
||||
}
|
||||
|
||||
// groupMessage container for content message structure
|
||||
type groupMessage struct {
|
||||
op string
|
||||
Status string `json:"status"`
|
||||
GroupName string `json:"groupName,omitempty"`
|
||||
Groups []string `json:"groups,omitempty"`
|
||||
Members []string `json:"members,omitempty"`
|
||||
GroupStatus string `json:"groupStatus,omitempty"`
|
||||
GroupPolicy string `json:"groupPolicy,omitempty"`
|
||||
}
|
||||
|
||||
func (u groupMessage) String() string {
|
||||
switch u.op {
|
||||
case "list":
|
||||
var s []string
|
||||
for _, g := range u.Groups {
|
||||
s = append(s, console.Colorize("GroupMessage", g))
|
||||
}
|
||||
return strings.Join(s, "\n")
|
||||
case "disable":
|
||||
return console.Colorize("GroupMessage", "Disabled group `"+u.GroupName+"` successfully.")
|
||||
case "enable":
|
||||
return console.Colorize("GroupMessage", "Enabled group `"+u.GroupName+"` successfully.")
|
||||
case "add":
|
||||
membersStr := fmt.Sprintf("`%s`", strings.Join(u.Members, ","))
|
||||
return console.Colorize("GroupMessage", "Added members "+membersStr+" to group `"+u.GroupName+"` successfully.")
|
||||
case "remove":
|
||||
if len(u.Members) > 0 {
|
||||
membersStr := fmt.Sprintf("{%s}", strings.Join(u.Members, ","))
|
||||
return console.Colorize("GroupMessage", "Removed members "+membersStr+" from group "+u.GroupName+" successfully.")
|
||||
}
|
||||
return console.Colorize("GroupMessage", "Removed group "+u.GroupName+" successfully.")
|
||||
case "info":
|
||||
return strings.Join([]string{
|
||||
console.Colorize("GroupMessage", "Group: "+u.GroupName),
|
||||
console.Colorize("GroupMessage", "Status: "+u.GroupStatus),
|
||||
console.Colorize("GroupMessage", "Policy: "+u.GroupPolicy),
|
||||
console.Colorize("GroupMessage", "Members: "+strings.Join(u.Members, ",")),
|
||||
}, "\n")
|
||||
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (u groupMessage) JSON() string {
|
||||
u.Status = "success"
|
||||
jsonMessageBytes, e := json.MarshalIndent(u, "", " ")
|
||||
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
|
||||
|
||||
return string(jsonMessageBytes)
|
||||
}
|
||||
|
||||
// mainAdminGroupAdd is the handle for "mc admin group add" command.
|
||||
func mainAdminGroupAdd(ctx *cli.Context) error {
|
||||
checkAdminGroupAddSyntax(ctx)
|
||||
|
||||
console.SetColor("GroupMessage", color.New(color.FgGreen))
|
||||
|
||||
// Get the alias parameter from cli
|
||||
args := ctx.Args()
|
||||
aliasedURL := args.Get(0)
|
||||
|
||||
// Create a new MinIO Admin Client
|
||||
client, err := newAdminClient(aliasedURL)
|
||||
fatalIf(err, "Unable to initialize admin connection.")
|
||||
|
||||
members := []string{}
|
||||
for i := 2; i < ctx.NArg(); i++ {
|
||||
members = append(members, args.Get(i))
|
||||
}
|
||||
gAddRemove := madmin.GroupAddRemove{
|
||||
Group: args.Get(1),
|
||||
Members: members,
|
||||
IsRemove: false,
|
||||
}
|
||||
fatalIf(probe.NewError(client.UpdateGroupMembers(globalContext, gAddRemove)).Trace(args...), "Unable to add new group")
|
||||
|
||||
printMsg(groupMessage{
|
||||
op: ctx.Command.Name,
|
||||
GroupName: args.Get(1),
|
||||
Members: members,
|
||||
})
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -1,44 +0,0 @@
|
||||
// Copyright (c) 2015-2022 MinIO, Inc.
|
||||
//
|
||||
// This file is part of MinIO Object Storage stack
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"github.com/minio/cli"
|
||||
)
|
||||
|
||||
var adminGroupDisableCmd = cli.Command{
|
||||
Name: "disable",
|
||||
Usage: "disable a group",
|
||||
Action: mainAdminGroupEnableDisable,
|
||||
OnUsageError: onUsageError,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
{{.HelpName}} TARGET GROUPNAME
|
||||
|
||||
FLAGS:
|
||||
{{range .VisibleFlags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
1. Disable group 'allcents'.
|
||||
{{.Prompt}} {{.HelpName}} myminio allcents
|
||||
`,
|
||||
}
|
||||
@@ -1,91 +0,0 @@
|
||||
// Copyright (c) 2015-2022 MinIO, Inc.
|
||||
//
|
||||
// This file is part of MinIO Object Storage stack
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/madmin-go/v3"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/pkg/v3/console"
|
||||
)
|
||||
|
||||
var adminGroupEnableCmd = cli.Command{
|
||||
Name: "enable",
|
||||
Usage: "enable a group",
|
||||
Action: mainAdminGroupEnableDisable,
|
||||
OnUsageError: onUsageError,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
{{.HelpName}} TARGET GROUPNAME
|
||||
|
||||
FLAGS:
|
||||
{{range .VisibleFlags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
1. Enable group 'allcents'.
|
||||
{{.Prompt}} {{.HelpName}} myminio allcents
|
||||
`,
|
||||
}
|
||||
|
||||
// checkAdminGroupEnableSyntax - validate all the passed arguments
|
||||
func checkAdminGroupEnableSyntax(ctx *cli.Context) {
|
||||
if len(ctx.Args()) != 2 {
|
||||
showCommandHelpAndExit(ctx, 1) // last argument is exit code
|
||||
}
|
||||
}
|
||||
|
||||
// mainAdminGroupEnableDisable is the handle for "mc admin group enable|disable" command.
|
||||
func mainAdminGroupEnableDisable(ctx *cli.Context) error {
|
||||
checkAdminGroupEnableSyntax(ctx)
|
||||
|
||||
console.SetColor("GroupMessage", color.New(color.FgGreen))
|
||||
|
||||
// Get the alias parameter from cli
|
||||
args := ctx.Args()
|
||||
aliasedURL := args.Get(0)
|
||||
|
||||
// Create a new MinIO Admin Client
|
||||
client, err := newAdminClient(aliasedURL)
|
||||
fatalIf(err, "Unable to initialize admin connection.")
|
||||
|
||||
group := args.Get(1)
|
||||
var status madmin.GroupStatus
|
||||
switch ctx.Command.Name {
|
||||
case "enable":
|
||||
status = madmin.GroupEnabled
|
||||
case "disable":
|
||||
status = madmin.GroupDisabled
|
||||
default:
|
||||
fatalIf(errInvalidArgument().Trace(ctx.Command.Name), "Invalid group status name")
|
||||
}
|
||||
e := client.SetGroupStatus(globalContext, group, status)
|
||||
fatalIf(probe.NewError(e).Trace(args...), "Unable set group status")
|
||||
|
||||
printMsg(groupMessage{
|
||||
op: ctx.Command.Name,
|
||||
GroupName: group,
|
||||
GroupStatus: string(status),
|
||||
})
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -1,83 +0,0 @@
|
||||
// Copyright (c) 2015-2022 MinIO, Inc.
|
||||
//
|
||||
// This file is part of MinIO Object Storage stack
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/pkg/v3/console"
|
||||
)
|
||||
|
||||
var adminGroupInfoCmd = cli.Command{
|
||||
Name: "info",
|
||||
Usage: "display group info",
|
||||
Action: mainAdminGroupInfo,
|
||||
OnUsageError: onUsageError,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
{{.HelpName}} TARGET GROUPNAME
|
||||
|
||||
FLAGS:
|
||||
{{range .VisibleFlags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
1. Get info on group 'allcents'.
|
||||
{{.Prompt}} {{.HelpName}} myminio allcents
|
||||
`,
|
||||
}
|
||||
|
||||
// checkAdminGroupInfoSyntax - validate all the passed arguments
|
||||
func checkAdminGroupInfoSyntax(ctx *cli.Context) {
|
||||
if len(ctx.Args()) != 2 {
|
||||
showCommandHelpAndExit(ctx, 1) // last argument is exit code
|
||||
}
|
||||
}
|
||||
|
||||
// mainAdminGroupInfo is the handle for "mc admin group info" command.
|
||||
func mainAdminGroupInfo(ctx *cli.Context) error {
|
||||
checkAdminGroupInfoSyntax(ctx)
|
||||
|
||||
console.SetColor("GroupMessage", color.New(color.FgGreen))
|
||||
|
||||
// Get the alias parameter from cli
|
||||
args := ctx.Args()
|
||||
aliasedURL := args.Get(0)
|
||||
|
||||
// Create a new MinIO Admin Client
|
||||
client, err := newAdminClient(aliasedURL)
|
||||
fatalIf(err, "Unable to initialize admin connection.")
|
||||
|
||||
group := args.Get(1)
|
||||
gd, e := client.GetGroupDescription(globalContext, group)
|
||||
fatalIf(probe.NewError(e).Trace(args...), "Unable to fetch group info")
|
||||
|
||||
printMsg(groupMessage{
|
||||
op: ctx.Command.Name,
|
||||
GroupName: group,
|
||||
GroupStatus: gd.Status,
|
||||
GroupPolicy: gd.Policy,
|
||||
Members: gd.Members,
|
||||
})
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -1,80 +0,0 @@
|
||||
// Copyright (c) 2015-2022 MinIO, Inc.
|
||||
//
|
||||
// This file is part of MinIO Object Storage stack
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/pkg/v3/console"
|
||||
)
|
||||
|
||||
var adminGroupListCmd = cli.Command{
|
||||
Name: "list",
|
||||
ShortName: "ls",
|
||||
Usage: "display list of groups",
|
||||
Action: mainAdminGroupList,
|
||||
OnUsageError: onUsageError,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
{{.HelpName}} TARGET
|
||||
|
||||
FLAGS:
|
||||
{{range .VisibleFlags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
1. List all groups.
|
||||
{{.Prompt}} {{.HelpName}} myminio
|
||||
`,
|
||||
}
|
||||
|
||||
// checkAdminGroupListSyntax - validate all the passed arguments
|
||||
func checkAdminGroupListSyntax(ctx *cli.Context) {
|
||||
if len(ctx.Args()) != 1 {
|
||||
showCommandHelpAndExit(ctx, 1) // last argument is exit code
|
||||
}
|
||||
}
|
||||
|
||||
// mainAdminGroupList is the handle for "mc admin group list" command.
|
||||
func mainAdminGroupList(ctx *cli.Context) error {
|
||||
checkAdminGroupListSyntax(ctx)
|
||||
|
||||
console.SetColor("GroupMessage", color.New(color.FgGreen))
|
||||
|
||||
// Get the alias parameter from cli
|
||||
args := ctx.Args()
|
||||
aliasedURL := args.Get(0)
|
||||
|
||||
// Create a new MinIO Admin Client
|
||||
client, err := newAdminClient(aliasedURL)
|
||||
fatalIf(err, "Unable to initialize admin connection.")
|
||||
|
||||
gs, e := client.ListGroups(globalContext)
|
||||
fatalIf(probe.NewError(e).Trace(args...), "Unable to list groups")
|
||||
|
||||
printMsg(groupMessage{
|
||||
op: ctx.Command.Name,
|
||||
Groups: gs,
|
||||
})
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -1,95 +0,0 @@
|
||||
// Copyright (c) 2015-2022 MinIO, Inc.
|
||||
//
|
||||
// This file is part of MinIO Object Storage stack
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/madmin-go/v3"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/pkg/v3/console"
|
||||
)
|
||||
|
||||
var adminGroupRemoveCmd = cli.Command{
|
||||
Name: "remove",
|
||||
ShortName: "rm",
|
||||
Usage: "remove group or members from a group",
|
||||
Action: mainAdminGroupRemove,
|
||||
OnUsageError: onUsageError,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
{{.HelpName}} TARGET GROUPNAME [USERNAMES...]
|
||||
|
||||
FLAGS:
|
||||
{{range .VisibleFlags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
1. Remove members 'tencent' and 'fivecent' from group 'allcents'.
|
||||
{{.Prompt}} {{.HelpName}} myminio allcents tencent fivecent
|
||||
|
||||
2. Remove group 'allcents'.
|
||||
{{.Prompt}} {{.HelpName}} myminio allcents
|
||||
`,
|
||||
}
|
||||
|
||||
// checkAdminGroupRemoveSyntax - validate all the passed arguments
|
||||
func checkAdminGroupRemoveSyntax(ctx *cli.Context) {
|
||||
if len(ctx.Args()) < 2 {
|
||||
showCommandHelpAndExit(ctx, 1) // last argument is exit code
|
||||
}
|
||||
}
|
||||
|
||||
// mainAdminGroupRemove is the handle for "mc admin group remove" command.
|
||||
func mainAdminGroupRemove(ctx *cli.Context) error {
|
||||
checkAdminGroupRemoveSyntax(ctx)
|
||||
|
||||
console.SetColor("GroupMessage", color.New(color.FgGreen))
|
||||
|
||||
// Get the alias parameter from cli
|
||||
args := ctx.Args()
|
||||
aliasedURL := args.Get(0)
|
||||
|
||||
// Create a new MinIO Admin Client
|
||||
client, err := newAdminClient(aliasedURL)
|
||||
fatalIf(err, "Unable to initialize admin connection.")
|
||||
|
||||
members := []string{}
|
||||
for i := 2; i < ctx.NArg(); i++ {
|
||||
members = append(members, args.Get(i))
|
||||
}
|
||||
gAddRemove := madmin.GroupAddRemove{
|
||||
Group: args.Get(1),
|
||||
Members: members,
|
||||
IsRemove: true,
|
||||
}
|
||||
|
||||
e := client.UpdateGroupMembers(globalContext, gAddRemove)
|
||||
fatalIf(probe.NewError(e).Trace(args...), "Could not perform remove operation")
|
||||
|
||||
printMsg(groupMessage{
|
||||
op: ctx.Command.Name,
|
||||
GroupName: args.Get(1),
|
||||
Members: members,
|
||||
})
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -1,46 +0,0 @@
|
||||
// Copyright (c) 2015-2022 MinIO, Inc.
|
||||
//
|
||||
// This file is part of MinIO Object Storage stack
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package cmd
|
||||
|
||||
import "github.com/minio/cli"
|
||||
|
||||
var adminGroupSubcommands = []cli.Command{
|
||||
adminGroupAddCmd,
|
||||
adminGroupRemoveCmd,
|
||||
adminGroupInfoCmd,
|
||||
adminGroupListCmd,
|
||||
adminGroupEnableCmd,
|
||||
adminGroupDisableCmd,
|
||||
}
|
||||
|
||||
var adminGroupCmd = cli.Command{
|
||||
Name: "group",
|
||||
Usage: "manage groups",
|
||||
Action: mainAdminGroup,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
Subcommands: adminGroupSubcommands,
|
||||
HideHelpCommand: true,
|
||||
}
|
||||
|
||||
// mainAdminGroup is the handle for "mc admin config" command.
|
||||
func mainAdminGroup(ctx *cli.Context) error {
|
||||
commandNotFound(ctx, adminGroupSubcommands)
|
||||
return nil
|
||||
// Sub-commands like "get", "set" have their own main.
|
||||
}
|
||||
@@ -1,173 +0,0 @@
|
||||
// Copyright (c) 2015-2022 MinIO, Inc.
|
||||
//
|
||||
// This file is part of MinIO Object Storage stack
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/minio/madmin-go/v3"
|
||||
)
|
||||
|
||||
type hri struct {
|
||||
*madmin.HealResultItem
|
||||
}
|
||||
|
||||
func newHRI(i *madmin.HealResultItem) *hri {
|
||||
return &hri{i}
|
||||
}
|
||||
|
||||
// getObjectHCCChange - returns before and after color change for
|
||||
// objects
|
||||
func (h hri) getObjectHCCChange() (b, a col, err error) {
|
||||
parityShards := h.ParityBlocks
|
||||
dataShards := h.DataBlocks
|
||||
|
||||
onlineBefore, onlineAfter := h.GetOnlineCounts()
|
||||
surplusShardsBeforeHeal := onlineBefore - dataShards
|
||||
surplusShardsAfterHeal := onlineAfter - dataShards
|
||||
|
||||
b, err = getHColCode(surplusShardsBeforeHeal, parityShards)
|
||||
if err != nil {
|
||||
err = fmt.Errorf("%w: surplusShardsBeforeHeal: %d, parityShards: %d",
|
||||
err, surplusShardsBeforeHeal, parityShards)
|
||||
return
|
||||
}
|
||||
a, err = getHColCode(surplusShardsAfterHeal, parityShards)
|
||||
if err != nil {
|
||||
err = fmt.Errorf("%w: surplusShardsAfterHeal: %d, parityShards: %d",
|
||||
err, surplusShardsAfterHeal, parityShards)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// getBucketHCCChange - fetches health color code for bucket healing
|
||||
// this does not return a Grey color since it does not have any meaning
|
||||
// for a bucket healing. Return green if the bucket is found in a drive,
|
||||
// yellow for missing, and red for everything else, grey for weird situations
|
||||
func (h hri) getBucketHCCChange() (b, a col, err error) {
|
||||
if h.HealResultItem == nil {
|
||||
return colGrey, colGrey, errors.New("empty result")
|
||||
}
|
||||
|
||||
getColCode := func(drives []madmin.HealDriveInfo) (c col) {
|
||||
var missing, unavailable int
|
||||
for i := range drives {
|
||||
switch drives[i].State {
|
||||
case madmin.DriveStateOk:
|
||||
case madmin.DriveStateMissing:
|
||||
missing++
|
||||
default:
|
||||
unavailable++
|
||||
}
|
||||
}
|
||||
if unavailable > 0 {
|
||||
return colRed
|
||||
}
|
||||
if missing > 0 {
|
||||
return colYellow
|
||||
}
|
||||
return colGreen
|
||||
}
|
||||
|
||||
a, b = colGrey, colGrey
|
||||
|
||||
if len(h.Before.Drives) > 0 {
|
||||
b = getColCode(h.Before.Drives)
|
||||
}
|
||||
if len(h.After.Drives) > 0 {
|
||||
a = getColCode(h.After.Drives)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// getReplicatedFileHCCChange - fetches health color code for metadata
|
||||
// files that are replicated.
|
||||
func (h hri) getReplicatedFileHCCChange() (b, a col, err error) {
|
||||
getColCode := func(numAvail int) (c col, err error) {
|
||||
// calculate color code for replicated object similar
|
||||
// to erasure coded objects
|
||||
var quorum, surplus, parity int
|
||||
if h.SetCount > 0 {
|
||||
quorum = h.DiskCount/h.SetCount/2 + 1
|
||||
surplus = numAvail/h.SetCount - quorum
|
||||
parity = h.DiskCount/h.SetCount - quorum
|
||||
} else {
|
||||
// in case of bucket healing, disk count is for the node
|
||||
// also explicitly set count would be set to invalid value of -1
|
||||
quorum = h.DiskCount/2 + 1
|
||||
surplus = numAvail - quorum
|
||||
parity = h.DiskCount - quorum
|
||||
}
|
||||
c, err = getHColCode(surplus, parity)
|
||||
return
|
||||
}
|
||||
|
||||
onlineBefore, onlineAfter := h.GetOnlineCounts()
|
||||
b, err = getColCode(onlineBefore)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
a, err = getColCode(onlineAfter)
|
||||
return
|
||||
}
|
||||
|
||||
func (h hri) makeHealEntityString() string {
|
||||
switch h.Type {
|
||||
case madmin.HealItemObject:
|
||||
return h.Bucket + "/" + h.Object
|
||||
case madmin.HealItemBucket:
|
||||
return h.Bucket
|
||||
case madmin.HealItemMetadata:
|
||||
return "[disk-format]"
|
||||
case madmin.HealItemBucketMetadata:
|
||||
return fmt.Sprintf("[bucket-metadata]%s/%s", h.Bucket, h.Object)
|
||||
}
|
||||
return "** unexpected **"
|
||||
}
|
||||
|
||||
func (h hri) getHRTypeAndName() (typ, name string) {
|
||||
name = fmt.Sprintf("%s/%s", h.Bucket, h.Object)
|
||||
switch h.Type {
|
||||
case madmin.HealItemMetadata:
|
||||
typ = "system"
|
||||
name = h.Detail
|
||||
case madmin.HealItemBucketMetadata:
|
||||
typ = "system"
|
||||
name = "bucket-metadata:" + name
|
||||
case madmin.HealItemBucket:
|
||||
typ = "bucket"
|
||||
case madmin.HealItemObject:
|
||||
typ = "object"
|
||||
default:
|
||||
typ = fmt.Sprintf("!! Unknown heal result record %#v !!", h)
|
||||
name = typ
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (h hri) getHealResultStr() string {
|
||||
typ, name := h.getHRTypeAndName()
|
||||
|
||||
switch h.Type {
|
||||
case madmin.HealItemMetadata, madmin.HealItemBucketMetadata:
|
||||
return typ + ":" + name
|
||||
default:
|
||||
return name
|
||||
}
|
||||
}
|
||||
@@ -1,454 +0,0 @@
|
||||
// Copyright (c) 2015-2022 MinIO, Inc.
|
||||
//
|
||||
// This file is part of MinIO Object Storage stack
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"math"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
humanize "github.com/dustin/go-humanize"
|
||||
"github.com/fatih/color"
|
||||
json "github.com/minio/colorjson"
|
||||
"github.com/minio/madmin-go/v3"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/pkg/v3/console"
|
||||
)
|
||||
|
||||
const (
|
||||
lineWidth = 80
|
||||
)
|
||||
|
||||
var (
|
||||
hColOrder = []col{colRed, colYellow, colGreen}
|
||||
hColTable = map[int][]int{
|
||||
1: {0, -1, 1},
|
||||
2: {0, 1, 2},
|
||||
3: {1, 2, 3},
|
||||
4: {1, 2, 4},
|
||||
5: {1, 3, 5},
|
||||
6: {2, 4, 6},
|
||||
7: {2, 4, 7},
|
||||
8: {2, 5, 8},
|
||||
}
|
||||
)
|
||||
|
||||
func getHColCode(surplusShards, parityShards int) (c col, err error) {
|
||||
if parityShards < 1 || parityShards > 8 || surplusShards > parityShards {
|
||||
return c, errors.New("Invalid parity shard count/surplus shard count given")
|
||||
}
|
||||
if surplusShards < 0 {
|
||||
return colGrey, err
|
||||
}
|
||||
colRow := hColTable[parityShards]
|
||||
for index, val := range colRow {
|
||||
if val != -1 && surplusShards <= val {
|
||||
return hColOrder[index], err
|
||||
}
|
||||
}
|
||||
return c, errors.New("cannot get a heal color code")
|
||||
}
|
||||
|
||||
type uiData struct {
|
||||
Bucket, Prefix string
|
||||
Client *madmin.AdminClient
|
||||
ClientToken string
|
||||
ForceStart bool
|
||||
HealOpts *madmin.HealOpts
|
||||
LastItem *hri
|
||||
|
||||
// Total time since heal start
|
||||
HealDuration time.Duration
|
||||
|
||||
// Accumulated statistics of heal result records
|
||||
BytesScanned int64
|
||||
|
||||
// Counter for objects, and another counter for all kinds of
|
||||
// items
|
||||
ObjectsScanned, ItemsScanned int64
|
||||
|
||||
// Counters for healed objects and all kinds of healed items
|
||||
ObjectsHealed, ItemsHealed int64
|
||||
|
||||
// Map from online drives to number of objects with that many
|
||||
// online drives.
|
||||
ObjectsByOnlineDrives map[int]int64
|
||||
// Map of health color code to number of objects with that
|
||||
// health color code.
|
||||
HealthCols map[col]int64
|
||||
|
||||
// channel to receive a prompt string to indicate activity on
|
||||
// the terminal
|
||||
CurChan (<-chan string)
|
||||
}
|
||||
|
||||
func (ui *uiData) updateStats(i madmin.HealResultItem) error {
|
||||
if i.Type == madmin.HealItemObject {
|
||||
// Objects whose size could not be found have -1 size
|
||||
// returned.
|
||||
if i.ObjectSize >= 0 {
|
||||
ui.BytesScanned += i.ObjectSize
|
||||
}
|
||||
|
||||
ui.ObjectsScanned++
|
||||
}
|
||||
ui.ItemsScanned++
|
||||
|
||||
beforeUp, afterUp := i.GetOnlineCounts()
|
||||
if afterUp > beforeUp {
|
||||
if i.Type == madmin.HealItemObject {
|
||||
ui.ObjectsHealed++
|
||||
}
|
||||
ui.ItemsHealed++
|
||||
}
|
||||
ui.ObjectsByOnlineDrives[afterUp]++
|
||||
|
||||
// Update health color stats:
|
||||
|
||||
// Fetch health color after heal:
|
||||
var err error
|
||||
var afterCol col
|
||||
h := newHRI(&i)
|
||||
switch h.Type {
|
||||
case madmin.HealItemBucket:
|
||||
_, afterCol, err = h.getBucketHCCChange()
|
||||
case madmin.HealItemMetadata, madmin.HealItemBucketMetadata:
|
||||
_, afterCol, err = h.getReplicatedFileHCCChange()
|
||||
default:
|
||||
_, afterCol, err = h.getObjectHCCChange()
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
ui.HealthCols[afterCol]++
|
||||
return nil
|
||||
}
|
||||
|
||||
func (ui *uiData) updateDuration(s *madmin.HealTaskStatus) {
|
||||
ui.HealDuration = UTCNow().Sub(s.StartTime)
|
||||
}
|
||||
|
||||
func (ui *uiData) getProgress() (oCount, objSize, duration string) {
|
||||
oCount = humanize.Comma(ui.ObjectsScanned)
|
||||
|
||||
duration = ui.HealDuration.Round(time.Second).String()
|
||||
|
||||
bytesScanned := float64(ui.BytesScanned)
|
||||
|
||||
// Compute unit for object size
|
||||
magnitudes := []float64{1 << 10, 1 << 20, 1 << 30, 1 << 40, 1 << 50, 1 << 60}
|
||||
units := []string{"B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB"}
|
||||
var i int
|
||||
for i = 0; i < len(magnitudes); i++ {
|
||||
if bytesScanned <= magnitudes[i] {
|
||||
break
|
||||
}
|
||||
}
|
||||
numUnits := int(bytesScanned * (1 << 10) / magnitudes[i])
|
||||
objSize = fmt.Sprintf("%d %s", numUnits, units[i])
|
||||
return
|
||||
}
|
||||
|
||||
func (ui *uiData) getPercentsNBars() (p map[col]float64, b map[col]string) {
|
||||
// barChar, emptyBarChar := "█", "░"
|
||||
barChar, emptyBarChar := "█", " "
|
||||
barLen := 12
|
||||
sum := float64(ui.ItemsScanned)
|
||||
cols := []col{colGrey, colRed, colYellow, colGreen}
|
||||
|
||||
p = make(map[col]float64, len(cols))
|
||||
b = make(map[col]string, len(cols))
|
||||
var filledLen int
|
||||
for _, col := range cols {
|
||||
v := float64(ui.HealthCols[col])
|
||||
if sum == 0 {
|
||||
p[col] = 0
|
||||
filledLen = 0
|
||||
} else {
|
||||
p[col] = v * 100 / sum
|
||||
// round up the filled part
|
||||
filledLen = int(math.Ceil(float64(barLen) * v / sum))
|
||||
}
|
||||
b[col] = strings.Repeat(barChar, filledLen) +
|
||||
strings.Repeat(emptyBarChar, barLen-filledLen)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (ui *uiData) printItemsQuietly(s *madmin.HealTaskStatus) (err error) {
|
||||
lpad := func(s col) string {
|
||||
return fmt.Sprintf("%-6s", string(s))
|
||||
}
|
||||
rpad := func(s col) string {
|
||||
return fmt.Sprintf("%6s", string(s))
|
||||
}
|
||||
printColStr := func(before, after col) {
|
||||
console.PrintC("[" + lpad(before) + " -> " + rpad(after) + "] ")
|
||||
}
|
||||
|
||||
var b, a col
|
||||
for _, item := range s.Items {
|
||||
h := newHRI(&item)
|
||||
hrStr := h.getHealResultStr()
|
||||
switch h.Type {
|
||||
case madmin.HealItemBucket:
|
||||
b, a, err = h.getBucketHCCChange()
|
||||
case madmin.HealItemMetadata, madmin.HealItemBucketMetadata:
|
||||
b, a, err = h.getReplicatedFileHCCChange()
|
||||
default:
|
||||
b, a, err = h.getObjectHCCChange()
|
||||
}
|
||||
if err != nil {
|
||||
errMsg := err.Error()
|
||||
if h.Detail != "" {
|
||||
errMsg = h.Detail
|
||||
}
|
||||
console.PrintC("[ERROR] ** ", hrStr, " **", ": ", errMsg, "\n")
|
||||
continue
|
||||
}
|
||||
printColStr(b, a)
|
||||
switch h.Type {
|
||||
case madmin.HealItemMetadata, madmin.HealItemBucketMetadata:
|
||||
console.PrintC(fmt.Sprintln("**", hrStr, "**"))
|
||||
default:
|
||||
console.PrintC(hrStr, "\n")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (ui *uiData) printStatsQuietly() {
|
||||
totalObjects, totalSize, totalTime := ui.getProgress()
|
||||
|
||||
healedStr := fmt.Sprintf("Healed:\t%s/%s objects; %s in %s\n",
|
||||
humanize.Comma(ui.ObjectsHealed), totalObjects,
|
||||
totalSize, totalTime)
|
||||
|
||||
console.PrintC(healedStr)
|
||||
}
|
||||
|
||||
func (ui *uiData) printItemsJSON(s *madmin.HealTaskStatus) (err error) {
|
||||
type healRec struct {
|
||||
Status string `json:"status"`
|
||||
Error string `json:"error,omitempty"`
|
||||
Detail string `json:"detail,omitempty"`
|
||||
Type string `json:"type"`
|
||||
Name string `json:"name"`
|
||||
Before struct {
|
||||
Color string `json:"color"`
|
||||
Offline int `json:"offline"`
|
||||
Online int `json:"online"`
|
||||
Missing int `json:"missing"`
|
||||
Corrupted int `json:"corrupted"`
|
||||
Drives []madmin.HealDriveInfo `json:"drives"`
|
||||
} `json:"before"`
|
||||
After struct {
|
||||
Color string `json:"color"`
|
||||
Offline int `json:"offline"`
|
||||
Online int `json:"online"`
|
||||
Missing int `json:"missing"`
|
||||
Corrupted int `json:"corrupted"`
|
||||
Drives []madmin.HealDriveInfo `json:"drives"`
|
||||
} `json:"after"`
|
||||
Size int64 `json:"size"`
|
||||
}
|
||||
makeHR := func(h *hri) (r healRec) {
|
||||
r.Status = "success"
|
||||
r.Type, r.Name = h.getHRTypeAndName()
|
||||
|
||||
var b, a col
|
||||
var err error
|
||||
switch h.Type {
|
||||
case madmin.HealItemBucket:
|
||||
b, a, err = h.getBucketHCCChange()
|
||||
case madmin.HealItemMetadata, madmin.HealItemBucketMetadata:
|
||||
b, a, err = h.getReplicatedFileHCCChange()
|
||||
default:
|
||||
if h.Type == madmin.HealItemObject {
|
||||
r.Size = h.ObjectSize
|
||||
}
|
||||
b, a, err = h.getObjectHCCChange()
|
||||
}
|
||||
if err != nil {
|
||||
r.Error = err.Error()
|
||||
}
|
||||
r.Detail = h.Detail
|
||||
r.Before.Color = strings.ToLower(string(b))
|
||||
r.After.Color = strings.ToLower(string(a))
|
||||
r.Before.Online, r.After.Online = h.GetOnlineCounts()
|
||||
r.Before.Missing, r.After.Missing = h.GetMissingCounts()
|
||||
r.Before.Corrupted, r.After.Corrupted = h.GetCorruptedCounts()
|
||||
r.Before.Offline, r.After.Offline = h.GetOfflineCounts()
|
||||
r.Before.Drives = h.Before.Drives
|
||||
r.After.Drives = h.After.Drives
|
||||
return r
|
||||
}
|
||||
|
||||
for _, item := range s.Items {
|
||||
h := newHRI(&item)
|
||||
jsonBytes, e := json.MarshalIndent(makeHR(h), "", " ")
|
||||
fatalIf(probe.NewError(e), "Unable to marshal to JSON.")
|
||||
console.Println(string(jsonBytes))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (ui *uiData) printStatsJSON(_ *madmin.HealTaskStatus) {
|
||||
var summary struct {
|
||||
Status string `json:"status"`
|
||||
Error string `json:"error,omitempty"`
|
||||
Type string `json:"type"`
|
||||
ObjectsScanned int64 `json:"objects_scanned"`
|
||||
ObjectsHealed int64 `json:"objects_healed"`
|
||||
ItemsScanned int64 `json:"items_scanned"`
|
||||
ItemsHealed int64 `json:"items_healed"`
|
||||
Size int64 `json:"size"`
|
||||
ElapsedTime int64 `json:"duration"`
|
||||
}
|
||||
|
||||
summary.Status = "success"
|
||||
summary.Type = "summary"
|
||||
|
||||
summary.ObjectsScanned = ui.ObjectsScanned
|
||||
summary.ObjectsHealed = ui.ObjectsHealed
|
||||
summary.ItemsScanned = ui.ItemsScanned
|
||||
summary.ItemsHealed = ui.ItemsHealed
|
||||
summary.Size = ui.BytesScanned
|
||||
summary.ElapsedTime = int64(ui.HealDuration.Round(time.Second).Seconds())
|
||||
|
||||
jBytes, e := json.MarshalIndent(summary, "", " ")
|
||||
fatalIf(probe.NewError(e), "Unable to marshal to JSON.")
|
||||
console.Println(string(jBytes))
|
||||
}
|
||||
|
||||
func (ui *uiData) updateUI(s *madmin.HealTaskStatus) (err error) {
|
||||
itemCount := len(s.Items)
|
||||
h := ui.LastItem
|
||||
if itemCount > 0 {
|
||||
item := s.Items[itemCount-1]
|
||||
h = newHRI(&item)
|
||||
ui.LastItem = h
|
||||
}
|
||||
scannedStr := "** waiting for status from server **"
|
||||
if h != nil {
|
||||
scannedStr = lineTrunc(h.makeHealEntityString(), lineWidth-len("Scanned: "))
|
||||
}
|
||||
|
||||
totalObjects, totalSize, totalTime := ui.getProgress()
|
||||
healedStr := fmt.Sprintf("%s/%s objects; %s in %s",
|
||||
humanize.Comma(ui.ObjectsHealed), totalObjects,
|
||||
totalSize, totalTime)
|
||||
|
||||
console.Print(console.Colorize("HealUpdateUI", fmt.Sprintf(" %s", <-ui.CurChan)))
|
||||
console.PrintC(fmt.Sprintf(" %s\n", scannedStr))
|
||||
console.PrintC(fmt.Sprintf(" %s\n", healedStr))
|
||||
|
||||
dspOrder := []col{colGreen, colYellow, colRed, colGrey}
|
||||
printColors := []*color.Color{}
|
||||
for _, c := range dspOrder {
|
||||
printColors = append(printColors, getPrintCol(c))
|
||||
}
|
||||
t := console.NewTable(printColors, []bool{false, true, true}, 4)
|
||||
|
||||
percentMap, barMap := ui.getPercentsNBars()
|
||||
cellText := make([][]string, len(dspOrder))
|
||||
for i := range cellText {
|
||||
cellText[i] = []string{
|
||||
string(dspOrder[i]),
|
||||
fmt.Sprint(humanize.Comma(ui.HealthCols[dspOrder[i]])),
|
||||
fmt.Sprintf("%5.1f%% %s", percentMap[dspOrder[i]], barMap[dspOrder[i]]),
|
||||
}
|
||||
}
|
||||
|
||||
t.DisplayTable(cellText)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (ui *uiData) UpdateDisplay(s *madmin.HealTaskStatus) {
|
||||
// Update state
|
||||
ui.updateDuration(s)
|
||||
for _, i := range s.Items {
|
||||
ui.updateStats(i)
|
||||
}
|
||||
|
||||
// Update display
|
||||
switch {
|
||||
case globalJSON:
|
||||
ui.printItemsJSON(s)
|
||||
case globalQuiet:
|
||||
ui.printItemsQuietly(s)
|
||||
default:
|
||||
ui.updateUI(s)
|
||||
}
|
||||
}
|
||||
|
||||
func (ui *uiData) healResumeMsg(aliasedURL string) string {
|
||||
var flags string
|
||||
if ui.HealOpts.Recursive {
|
||||
flags += "--recursive "
|
||||
}
|
||||
if ui.HealOpts.DryRun {
|
||||
flags += "--dry-run "
|
||||
}
|
||||
return fmt.Sprintf("Healing is backgrounded, to resume watching use `mc admin heal %s %s`", flags, aliasedURL)
|
||||
}
|
||||
|
||||
func (ui *uiData) DisplayAndFollowHealStatus(aliasedURL string) (res madmin.HealTaskStatus, err error) {
|
||||
quitMsg := ui.healResumeMsg(aliasedURL)
|
||||
|
||||
firstIter := true
|
||||
for {
|
||||
select {
|
||||
case <-globalContext.Done():
|
||||
return res, errors.New(quitMsg)
|
||||
default:
|
||||
_, res, err = ui.Client.Heal(globalContext, ui.Bucket, ui.Prefix, *ui.HealOpts,
|
||||
ui.ClientToken, ui.ForceStart, false)
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
if firstIter {
|
||||
firstIter = false
|
||||
} else {
|
||||
if !globalQuiet && !globalJSON {
|
||||
console.RewindLines(8)
|
||||
}
|
||||
}
|
||||
|
||||
ui.UpdateDisplay(&res)
|
||||
|
||||
if res.Summary == "finished" {
|
||||
if globalJSON {
|
||||
ui.printStatsJSON(&res)
|
||||
} else if globalQuiet {
|
||||
ui.printStatsQuietly()
|
||||
}
|
||||
return res, nil
|
||||
}
|
||||
|
||||
if res.Summary == "stopped" {
|
||||
return res, fmt.Errorf("Heal had an error - %s", res.FailureDetail)
|
||||
}
|
||||
|
||||
time.Sleep(time.Second)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,781 +0,0 @@
|
||||
// Copyright (c) 2015-2024 MinIO, Inc.
|
||||
//
|
||||
// This file is part of MinIO Object Storage stack
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"fmt"
|
||||
"math"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/dustin/go-humanize"
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/cli"
|
||||
json "github.com/minio/colorjson"
|
||||
"github.com/minio/madmin-go/v3"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/pkg/v3/console"
|
||||
)
|
||||
|
||||
const (
|
||||
scanNormalMode = "normal"
|
||||
scanDeepMode = "deep"
|
||||
)
|
||||
|
||||
var adminHealFlags = []cli.Flag{
|
||||
cli.IntFlag{
|
||||
Name: "pool",
|
||||
Usage: "heal only the given pool",
|
||||
Hidden: true,
|
||||
},
|
||||
cli.IntFlag{
|
||||
Name: "set",
|
||||
Usage: "heal only the given set",
|
||||
Hidden: true,
|
||||
},
|
||||
cli.StringFlag{
|
||||
Name: "scan",
|
||||
Usage: "select the healing scan mode (normal/deep)",
|
||||
Value: scanNormalMode,
|
||||
Hidden: true,
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "recursive, r",
|
||||
Usage: "heal recursively",
|
||||
Hidden: true,
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "dry-run, n",
|
||||
Usage: "only inspect data, but do not mutate",
|
||||
Hidden: true,
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "force-start, f",
|
||||
Usage: "force start a new heal sequence",
|
||||
Hidden: true,
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "force-stop, s",
|
||||
Usage: "force stop a running heal sequence",
|
||||
Hidden: true,
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "force",
|
||||
Usage: "avoid showing a warning prompt",
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "remove",
|
||||
Usage: "remove dangling objects in heal sequence",
|
||||
Hidden: true,
|
||||
},
|
||||
cli.StringFlag{
|
||||
Name: "storage-class",
|
||||
Usage: "show server/drives failure tolerance with the given storage class",
|
||||
Hidden: true,
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "rewrite",
|
||||
Usage: "rewrite objects from older to newer format",
|
||||
Hidden: true,
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "verbose, v",
|
||||
Usage: "show verbose information",
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "all-drives, a",
|
||||
Usage: "select all drives for verbose printing",
|
||||
},
|
||||
}
|
||||
|
||||
var adminHealCmd = cli.Command{
|
||||
Name: "heal",
|
||||
Usage: "monitor healing for bucket(s) and object(s) on MinIO server",
|
||||
Action: mainAdminHeal,
|
||||
OnUsageError: onUsageError,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: append(adminHealFlags, globalFlags...),
|
||||
HideHelpCommand: true,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
{{.HelpName}} [FLAGS] TARGET
|
||||
|
||||
FLAGS:
|
||||
{{range .VisibleFlags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
1. Monitor healing status on a running server at alias 'myminio':
|
||||
{{.Prompt}} {{.HelpName}} myminio/
|
||||
`,
|
||||
}
|
||||
|
||||
func checkAdminHealSyntax(ctx *cli.Context) {
|
||||
if len(ctx.Args()) != 1 {
|
||||
showCommandHelpAndExit(ctx, 1) // last argument is exit code
|
||||
}
|
||||
|
||||
// Check for scan argument
|
||||
scanArg := ctx.String("scan")
|
||||
scanArg = strings.ToLower(scanArg)
|
||||
if scanArg != scanNormalMode && scanArg != scanDeepMode {
|
||||
showCommandHelpAndExit(ctx, 1) // last argument is exit code
|
||||
}
|
||||
}
|
||||
|
||||
// stopHealMessage is container for stop heal success and failure messages.
|
||||
type stopHealMessage struct {
|
||||
Status string `json:"status"`
|
||||
Alias string `json:"alias"`
|
||||
}
|
||||
|
||||
// String colorized stop heal message.
|
||||
func (s stopHealMessage) String() string {
|
||||
return console.Colorize("HealStopped", "Heal stopped successfully at `"+s.Alias+"`.")
|
||||
}
|
||||
|
||||
// JSON jsonified stop heal message.
|
||||
func (s stopHealMessage) JSON() string {
|
||||
stopHealJSONBytes, e := json.MarshalIndent(s, "", " ")
|
||||
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
|
||||
|
||||
return string(stopHealJSONBytes)
|
||||
}
|
||||
|
||||
type setIndex struct {
|
||||
pool, set int
|
||||
}
|
||||
|
||||
type poolInfo struct {
|
||||
tolerance int
|
||||
endpoints []string
|
||||
}
|
||||
|
||||
type setInfo struct {
|
||||
totalDisks int
|
||||
|
||||
readyDisksCount int // disks online and not in healing state
|
||||
readyDisksUsedSpace uint64 // the total used space of ready disks
|
||||
|
||||
incapableDisks int
|
||||
}
|
||||
|
||||
type serverInfo struct {
|
||||
pool int
|
||||
disks []madmin.Disk
|
||||
}
|
||||
|
||||
func (s serverInfo) onlineDisksForSet(index setIndex) (setFound bool, count int) {
|
||||
for _, disk := range s.disks {
|
||||
if disk.PoolIndex != index.pool || disk.SetIndex != index.set {
|
||||
continue
|
||||
}
|
||||
setFound = true
|
||||
if disk.State == "ok" && !disk.Healing {
|
||||
count++
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// Get all drives from set statuses
|
||||
func getAllDisks(sets []madmin.SetStatus) []madmin.Disk {
|
||||
var disks []madmin.Disk
|
||||
for _, set := range sets {
|
||||
disks = append(disks, set.Disks...)
|
||||
}
|
||||
return disks
|
||||
}
|
||||
|
||||
// Get all pools id from all drives
|
||||
func getPoolsIndexes(disks []madmin.Disk) []int {
|
||||
m := make(map[int]struct{})
|
||||
for _, d := range disks {
|
||||
m[d.PoolIndex] = struct{}{}
|
||||
}
|
||||
var pools []int
|
||||
for pool := range m {
|
||||
pools = append(pools, pool)
|
||||
}
|
||||
sort.Ints(pools)
|
||||
return pools
|
||||
}
|
||||
|
||||
// Generate sets info from disks
|
||||
func generateSetsStatus(disks []madmin.Disk) map[setIndex]setInfo {
|
||||
m := make(map[setIndex]setInfo)
|
||||
for _, d := range disks {
|
||||
idx := setIndex{pool: d.PoolIndex, set: d.SetIndex}
|
||||
setSt, ok := m[idx]
|
||||
if !ok {
|
||||
setSt = setInfo{}
|
||||
}
|
||||
setSt.totalDisks++
|
||||
if d.State != "ok" || d.Healing {
|
||||
setSt.incapableDisks++
|
||||
} else {
|
||||
setSt.readyDisksCount++
|
||||
setSt.readyDisksUsedSpace += d.UsedSpace
|
||||
}
|
||||
m[idx] = setSt
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
// Return a map of server endpoints and the corresponding status
|
||||
func generateServersStatus(disks []madmin.Disk) map[string]serverInfo {
|
||||
m := make(map[string]serverInfo)
|
||||
for _, d := range disks {
|
||||
u, e := url.Parse(d.Endpoint)
|
||||
if e != nil {
|
||||
continue
|
||||
}
|
||||
endpoint := u.Host
|
||||
if endpoint == "" {
|
||||
endpoint = "local-pool" + humanize.Ordinal(d.PoolIndex+1)
|
||||
}
|
||||
serverSt, ok := m[endpoint]
|
||||
if !ok {
|
||||
serverSt = serverInfo{
|
||||
pool: d.PoolIndex,
|
||||
}
|
||||
}
|
||||
serverSt.disks = append(serverSt.disks, d)
|
||||
m[endpoint] = serverSt
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
// Return the list of endpoints of a given pool index
|
||||
func computePoolEndpoints(pool int, serversStatus map[string]serverInfo) []string {
|
||||
var endpoints []string
|
||||
for endpoint, server := range serversStatus {
|
||||
if server.pool != pool {
|
||||
continue
|
||||
}
|
||||
endpoints = append(endpoints, endpoint)
|
||||
}
|
||||
return endpoints
|
||||
}
|
||||
|
||||
// Compute the tolerance of each node in a given pool
|
||||
func computePoolTolerance(pool, parity int, setsStatus map[setIndex]setInfo, serversStatus map[string]serverInfo) int {
|
||||
var (
|
||||
onlineDisksPerSet = make(map[setIndex]int)
|
||||
tolerancePerSet = make(map[setIndex]int)
|
||||
)
|
||||
|
||||
for set, setStatus := range setsStatus {
|
||||
if set.pool != pool {
|
||||
continue
|
||||
}
|
||||
|
||||
onlineDisksPerSet[set] = setStatus.totalDisks - setStatus.incapableDisks
|
||||
tolerancePerSet[set] = 0
|
||||
|
||||
for _, server := range serversStatus {
|
||||
if server.pool != pool {
|
||||
continue
|
||||
}
|
||||
|
||||
canShutdown := true
|
||||
setFound, count := server.onlineDisksForSet(set)
|
||||
if !setFound {
|
||||
continue
|
||||
}
|
||||
minDisks := setStatus.totalDisks - parity
|
||||
if onlineDisksPerSet[set]-count < minDisks {
|
||||
canShutdown = false
|
||||
}
|
||||
if canShutdown {
|
||||
tolerancePerSet[set]++
|
||||
onlineDisksPerSet[set] -= count
|
||||
} else {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
minServerTolerance := len(serversStatus)
|
||||
for _, tolerance := range tolerancePerSet {
|
||||
if tolerance < minServerTolerance {
|
||||
minServerTolerance = tolerance
|
||||
}
|
||||
}
|
||||
|
||||
return minServerTolerance
|
||||
}
|
||||
|
||||
// Extract offline nodes from offline full path endpoints
|
||||
func getOfflineNodes(endpoints []string) map[string]struct{} {
|
||||
offlineNodes := make(map[string]struct{})
|
||||
for _, endpoint := range endpoints {
|
||||
offlineNodes[endpoint] = struct{}{}
|
||||
}
|
||||
return offlineNodes
|
||||
}
|
||||
|
||||
// verboseBackgroundHealStatusMessage is container for stop heal success and failure messages.
|
||||
type verboseBackgroundHealStatusMessage struct {
|
||||
Status string `json:"status"`
|
||||
HealInfo madmin.BgHealState
|
||||
|
||||
allDrives bool
|
||||
|
||||
// Specify storage class to show servers/disks tolerance
|
||||
ToleranceForSC string `json:"-"`
|
||||
}
|
||||
|
||||
// String colorized to show background heal status message.
|
||||
func (s verboseBackgroundHealStatusMessage) String() string {
|
||||
var msg strings.Builder
|
||||
|
||||
parity, showTolerance := s.HealInfo.SCParity[s.ToleranceForSC]
|
||||
offlineEndpoints := getOfflineNodes(s.HealInfo.OfflineEndpoints)
|
||||
allDisks := getAllDisks(s.HealInfo.Sets)
|
||||
pools := getPoolsIndexes(allDisks)
|
||||
setsStatus := generateSetsStatus(allDisks)
|
||||
serversStatus := generateServersStatus(allDisks)
|
||||
|
||||
poolsInfo := make(map[int]poolInfo)
|
||||
for _, pool := range pools {
|
||||
tolerance := computePoolTolerance(pool, parity, setsStatus, serversStatus)
|
||||
endpoints := computePoolEndpoints(pool, serversStatus)
|
||||
poolsInfo[pool] = poolInfo{tolerance: tolerance, endpoints: endpoints}
|
||||
}
|
||||
|
||||
distributed := len(serversStatus) > 1
|
||||
|
||||
plural := ""
|
||||
if distributed {
|
||||
plural = "s"
|
||||
}
|
||||
fmt.Fprintf(&msg, "Server%s status:\n", plural)
|
||||
fmt.Fprintf(&msg, "==============\n")
|
||||
|
||||
for _, pool := range pools {
|
||||
fmt.Fprintf(&msg, "Pool %s:\n", humanize.Ordinal(pool+1))
|
||||
|
||||
// Sort servers in this pool by name
|
||||
orderedEndpoints := make([]string, len(poolsInfo[pool].endpoints))
|
||||
copy(orderedEndpoints, poolsInfo[pool].endpoints)
|
||||
sort.Strings(orderedEndpoints)
|
||||
|
||||
for _, endpoint := range orderedEndpoints {
|
||||
// Print offline status if node is offline
|
||||
_, ok := offlineEndpoints[endpoint]
|
||||
if ok {
|
||||
stateText := console.Colorize("NodeFailed", "OFFLINE")
|
||||
fmt.Fprintf(&msg, " %s: %s\n", endpoint, stateText)
|
||||
continue
|
||||
}
|
||||
var serverHeader strings.Builder
|
||||
var serverHeaderPrinted bool
|
||||
serverStatus := serversStatus[endpoint]
|
||||
switch {
|
||||
case showTolerance:
|
||||
hdr := " %s: (Tolerance: %d server(s))\n"
|
||||
fmt.Fprintf(&serverHeader, hdr, endpoint, poolsInfo[serverStatus.pool].tolerance)
|
||||
default:
|
||||
hdr := " %s:\n"
|
||||
fmt.Fprintf(&serverHeader, hdr, endpoint)
|
||||
}
|
||||
|
||||
for _, d := range serverStatus.disks {
|
||||
if d.PoolIndex != pool {
|
||||
continue
|
||||
}
|
||||
stateText := ""
|
||||
switch {
|
||||
case d.State == "ok" && d.Healing:
|
||||
stateText = console.Colorize("DiskHealing", "HEALING")
|
||||
case d.State == "ok":
|
||||
if !s.allDrives {
|
||||
continue
|
||||
}
|
||||
stateText = console.Colorize("DiskOK", "OK")
|
||||
default:
|
||||
stateText = console.Colorize("DiskFailed", d.State)
|
||||
}
|
||||
if !serverHeaderPrinted {
|
||||
serverHeaderPrinted = true
|
||||
fmt.Fprint(&msg, serverHeader.String())
|
||||
}
|
||||
drivePath := d.DrivePath
|
||||
if drivePath == "" {
|
||||
if u, e := url.Parse(d.Endpoint); e == nil {
|
||||
drivePath = u.Path
|
||||
}
|
||||
}
|
||||
fmt.Fprintf(&msg, " + %s : %s\n", drivePath, stateText)
|
||||
|
||||
thisSet := setsStatus[setIndex{d.PoolIndex, d.SetIndex}]
|
||||
if d.Healing && d.HealInfo != nil && !d.HealInfo.Finished {
|
||||
refUsedSpace := uint64(math.MaxUint64)
|
||||
if thisSet.readyDisksCount > 0 { // to avoid crashing
|
||||
refUsedSpace = thisSet.readyDisksUsedSpace / uint64(thisSet.readyDisksCount)
|
||||
}
|
||||
if refUsedSpace < d.UsedSpace { // normalize
|
||||
refUsedSpace = d.UsedSpace
|
||||
}
|
||||
fmt.Fprintf(&msg, " |__ Progress: %d%%\n", 100*d.UsedSpace/refUsedSpace)
|
||||
fmt.Fprintf(&msg, " |__ Started: %s\n", humanize.Time(d.HealInfo.Started))
|
||||
if d.HealInfo.RetryAttempts > 0 {
|
||||
fmt.Fprintf(&msg, " |__ Retries: %d\n", d.HealInfo.RetryAttempts)
|
||||
}
|
||||
}
|
||||
fmt.Fprintf(&msg, " |__ Capacity: %s/%s\n", humanize.IBytes(d.UsedSpace), humanize.IBytes(d.TotalSpace))
|
||||
if showTolerance {
|
||||
fmt.Fprintf(&msg, " |__ Tolerance: %d drive(s)\n", parity-thisSet.incapableDisks)
|
||||
}
|
||||
}
|
||||
|
||||
if serverHeaderPrinted {
|
||||
fmt.Fprintf(&msg, "\n")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if showTolerance {
|
||||
fmt.Fprintf(&msg, "\n")
|
||||
fmt.Fprintf(&msg, "Server Failure Tolerance:\n")
|
||||
fmt.Fprintf(&msg, "========================\n")
|
||||
for i, pool := range poolsInfo {
|
||||
fmt.Fprintf(&msg, "Pool %s:\n", humanize.Ordinal(i+1))
|
||||
fmt.Fprintf(&msg, " Tolerance : %d server(s)\n", pool.tolerance)
|
||||
fmt.Fprintf(&msg, " Nodes :")
|
||||
for _, endpoint := range pool.endpoints {
|
||||
fmt.Fprintf(&msg, " %s", endpoint)
|
||||
}
|
||||
fmt.Fprintf(&msg, "\n")
|
||||
}
|
||||
}
|
||||
|
||||
summary := shortBackgroundHealStatusMessage{HealInfo: s.HealInfo}
|
||||
|
||||
fmt.Fprint(&msg, "\n")
|
||||
fmt.Fprint(&msg, "Summary:\n")
|
||||
fmt.Fprint(&msg, "=======\n")
|
||||
fmt.Fprint(&msg, summary.String())
|
||||
fmt.Fprint(&msg, "\n")
|
||||
|
||||
return msg.String()
|
||||
}
|
||||
|
||||
// JSON jsonified stop heal message.
|
||||
func (s verboseBackgroundHealStatusMessage) JSON() string {
|
||||
healJSONBytes, e := json.MarshalIndent(s, "", " ")
|
||||
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
|
||||
|
||||
return string(healJSONBytes)
|
||||
}
|
||||
|
||||
// shortBackgroundHealStatusMessage is container for stop heal success and failure messages.
|
||||
type shortBackgroundHealStatusMessage struct {
|
||||
Status string `json:"status"`
|
||||
HealInfo madmin.BgHealState
|
||||
}
|
||||
|
||||
// String colorized to show background heal status message.
|
||||
func (s shortBackgroundHealStatusMessage) String() string {
|
||||
healPrettyMsg := ""
|
||||
var (
|
||||
itemsHealed uint64
|
||||
bytesHealed uint64
|
||||
itemsFailed uint64
|
||||
bytesFailed uint64
|
||||
itemsHealedPerSec float64
|
||||
bytesHealedPerSec float64
|
||||
startedAt time.Time
|
||||
setsExceedsStd int
|
||||
setsExceedsReduced int
|
||||
|
||||
// The addition of Elapsed time of each parallel healing operation
|
||||
// this is needed to calculate the rate of healing
|
||||
accumulatedElapsedTime time.Duration
|
||||
)
|
||||
|
||||
var problematicDisks int
|
||||
leastPct := 100.0
|
||||
|
||||
for _, set := range s.HealInfo.Sets {
|
||||
setsStatus := generateSetsStatus(set.Disks)
|
||||
// Furthest along disk...
|
||||
var furthestHealingDisk *madmin.Disk
|
||||
missingInSet := 0
|
||||
for _, disk := range set.Disks {
|
||||
// Ignore disk with non 'ok' status
|
||||
if disk.State != madmin.DriveStateOk {
|
||||
if disk.State != madmin.DriveStateUnformatted {
|
||||
missingInSet++
|
||||
problematicDisks++
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
if disk.HealInfo != nil && !disk.HealInfo.Finished {
|
||||
missingInSet++
|
||||
|
||||
thisSet := setsStatus[setIndex{pool: disk.PoolIndex, set: disk.SetIndex}]
|
||||
refUsedSpace := uint64(math.MaxUint64)
|
||||
if thisSet.readyDisksCount > 0 {
|
||||
refUsedSpace = thisSet.readyDisksUsedSpace / uint64(thisSet.readyDisksCount)
|
||||
}
|
||||
if refUsedSpace < disk.UsedSpace {
|
||||
refUsedSpace = disk.UsedSpace
|
||||
}
|
||||
if refUsedSpace > 0 {
|
||||
if pct := float64(disk.UsedSpace) / float64(refUsedSpace); pct < leastPct {
|
||||
leastPct = pct
|
||||
}
|
||||
} else {
|
||||
// Unlikely to have max used space in an erasure set to be zero, but still set this to zero
|
||||
leastPct = 0
|
||||
}
|
||||
|
||||
disk := disk
|
||||
if furthestHealingDisk == nil {
|
||||
furthestHealingDisk = &disk
|
||||
continue
|
||||
}
|
||||
if disk.HealInfo.ItemsHealed+disk.HealInfo.ItemsFailed > furthestHealingDisk.HealInfo.ItemsHealed+furthestHealingDisk.HealInfo.ItemsFailed {
|
||||
furthestHealingDisk = &disk
|
||||
continue
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if furthestHealingDisk != nil {
|
||||
disk := furthestHealingDisk
|
||||
|
||||
// Approximate values
|
||||
itemsHealed += disk.HealInfo.ItemsHealed
|
||||
bytesHealed += disk.HealInfo.BytesDone
|
||||
bytesFailed += disk.HealInfo.BytesFailed
|
||||
itemsFailed += disk.HealInfo.ItemsFailed
|
||||
|
||||
if !disk.HealInfo.Started.IsZero() {
|
||||
if !disk.HealInfo.Started.Before(startedAt) {
|
||||
startedAt = disk.HealInfo.Started
|
||||
}
|
||||
|
||||
if !disk.HealInfo.LastUpdate.IsZero() {
|
||||
accumulatedElapsedTime += disk.HealInfo.LastUpdate.Sub(disk.HealInfo.Started)
|
||||
}
|
||||
|
||||
bytesHealedPerSec += float64(time.Second) * float64(disk.HealInfo.BytesDone) / float64(disk.HealInfo.LastUpdate.Sub(disk.HealInfo.Started))
|
||||
itemsHealedPerSec += float64(time.Second) * float64(disk.HealInfo.ItemsHealed+disk.HealInfo.ItemsFailed) / float64(disk.HealInfo.LastUpdate.Sub(disk.HealInfo.Started))
|
||||
|
||||
}
|
||||
if n, ok := s.HealInfo.SCParity["STANDARD"]; ok && missingInSet > n {
|
||||
setsExceedsStd++
|
||||
}
|
||||
if n, ok := s.HealInfo.SCParity["REDUCED_REDUNDANCY"]; ok && missingInSet > n {
|
||||
setsExceedsReduced++
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if startedAt.IsZero() && itemsHealed == 0 {
|
||||
healPrettyMsg += "No active healing is detected for new disks"
|
||||
if problematicDisks > 0 {
|
||||
healPrettyMsg += fmt.Sprintf(", though %d offline disk(s) found.", problematicDisks)
|
||||
} else {
|
||||
healPrettyMsg += "."
|
||||
}
|
||||
return healPrettyMsg
|
||||
}
|
||||
|
||||
// Objects healed information
|
||||
healPrettyMsg += fmt.Sprintf("Objects Healed: %s, %s (%s)\n",
|
||||
humanize.Comma(int64(itemsHealed)), humanize.IBytes(bytesHealed), humanize.CommafWithDigits(leastPct*100, 1)+"%")
|
||||
healPrettyMsg += fmt.Sprintf("Objects Failed: %s\n", humanize.Comma(int64(itemsFailed)))
|
||||
|
||||
if accumulatedElapsedTime > 0 {
|
||||
healPrettyMsg += fmt.Sprintf("Heal rate: %d obj/s, %s/s\n", int64(itemsHealedPerSec), humanize.IBytes(uint64(bytesHealedPerSec)))
|
||||
}
|
||||
|
||||
if problematicDisks > 0 {
|
||||
healPrettyMsg += "\n"
|
||||
healPrettyMsg += fmt.Sprintf("%d offline disk(s) found.", problematicDisks)
|
||||
}
|
||||
if setsExceedsStd > 0 {
|
||||
healPrettyMsg += "\n"
|
||||
healPrettyMsg += fmt.Sprintf("%d of %d sets exceeds standard parity count EC:%d lost/offline disks", setsExceedsStd, len(s.HealInfo.Sets), s.HealInfo.SCParity["STANDARD"])
|
||||
}
|
||||
if setsExceedsReduced > 0 {
|
||||
healPrettyMsg += "\n"
|
||||
healPrettyMsg += fmt.Sprintf("%d of %d sets exceeds reduced parity count EC:%d lost/offline disks", setsExceedsReduced, len(s.HealInfo.Sets), s.HealInfo.SCParity["REDUCED_REDUNDANCY"])
|
||||
}
|
||||
return healPrettyMsg
|
||||
}
|
||||
|
||||
// JSON jsonified stop heal message.
|
||||
func (s shortBackgroundHealStatusMessage) JSON() string {
|
||||
healJSONBytes, e := json.MarshalIndent(s, "", " ")
|
||||
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
|
||||
|
||||
return string(healJSONBytes)
|
||||
}
|
||||
|
||||
func transformScanArg(scanArg string) madmin.HealScanMode {
|
||||
switch scanArg {
|
||||
case "deep":
|
||||
return madmin.HealDeepScan
|
||||
}
|
||||
return madmin.HealNormalScan
|
||||
}
|
||||
|
||||
// mainAdminHeal - the entry function of heal command
|
||||
func mainAdminHeal(ctx *cli.Context) error {
|
||||
// Check for command syntax
|
||||
checkAdminHealSyntax(ctx)
|
||||
|
||||
// Get the alias parameter from cli
|
||||
args := ctx.Args()
|
||||
aliasedURL := args.Get(0)
|
||||
|
||||
console.SetColor("Heal", color.New(color.FgGreen, color.Bold))
|
||||
console.SetColor("Dot", color.New(color.FgGreen, color.Bold))
|
||||
console.SetColor("HealBackgroundTitle", color.New(color.FgGreen, color.Bold))
|
||||
console.SetColor("HealBackground", color.New(color.Bold))
|
||||
console.SetColor("HealUpdateUI", color.New(color.FgYellow, color.Bold))
|
||||
console.SetColor("HealStopped", color.New(color.FgGreen, color.Bold))
|
||||
|
||||
console.SetColor("DiskHealing", color.New(color.FgYellow, color.Bold))
|
||||
console.SetColor("DiskOK", color.New(color.FgGreen, color.Bold))
|
||||
console.SetColor("DiskFailed", color.New(color.FgRed, color.Bold))
|
||||
console.SetColor("NodeFailed", color.New(color.FgRed, color.Bold))
|
||||
|
||||
// Create a new MinIO Admin Client
|
||||
adminClnt, err := newAdminClient(aliasedURL)
|
||||
if err != nil {
|
||||
fatalIf(err.Trace(aliasedURL), "Unable to initialize admin client.")
|
||||
return nil
|
||||
}
|
||||
|
||||
// Compute bucket and object from the aliased URL
|
||||
aliasedURL = filepath.ToSlash(aliasedURL)
|
||||
splits := splitStr(aliasedURL, "/", 3)
|
||||
bucket, prefix := splits[1], splits[2]
|
||||
|
||||
clnt, err := newClient(aliasedURL)
|
||||
if err != nil {
|
||||
fatalIf(err.Trace(clnt.GetURL().String()), "Unable to create client for URL ", aliasedURL)
|
||||
return nil
|
||||
}
|
||||
|
||||
// Return the background heal status when the user
|
||||
// doesn't pass a bucket or --recursive flag.
|
||||
if bucket == "" && !ctx.Bool("recursive") {
|
||||
bgHealStatus, e := adminClnt.BackgroundHealStatus(globalContext)
|
||||
fatalIf(probe.NewError(e), "Unable to get background heal status.")
|
||||
if ctx.Bool("verbose") {
|
||||
printMsg(verboseBackgroundHealStatusMessage{
|
||||
Status: "success",
|
||||
HealInfo: bgHealStatus,
|
||||
allDrives: ctx.Bool("all-drives"),
|
||||
ToleranceForSC: strings.ToUpper(ctx.String("storage-class")),
|
||||
})
|
||||
} else {
|
||||
printMsg(shortBackgroundHealStatusMessage{
|
||||
Status: "success",
|
||||
HealInfo: bgHealStatus,
|
||||
})
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
opts := madmin.HealOpts{
|
||||
ScanMode: transformScanArg(ctx.String("scan")),
|
||||
Remove: ctx.Bool("remove"),
|
||||
Recursive: ctx.Bool("recursive"),
|
||||
DryRun: ctx.Bool("dry-run"),
|
||||
Recreate: ctx.Bool("rewrite"),
|
||||
}
|
||||
|
||||
if ctx.IsSet("pool") {
|
||||
p := ctx.Int("pool")
|
||||
if p < 1 {
|
||||
fatalIf(errInvalidArgument(), "--pool takes a non zero positive number.")
|
||||
}
|
||||
p--
|
||||
opts.Pool = &p
|
||||
}
|
||||
|
||||
if ctx.IsSet("set") {
|
||||
s := ctx.Int("set")
|
||||
if s < 1 {
|
||||
fatalIf(errInvalidArgument(), "--set takes a non zero positive number.")
|
||||
}
|
||||
s--
|
||||
opts.Set = &s
|
||||
}
|
||||
|
||||
forceStart := ctx.Bool("force-start")
|
||||
forceStop := ctx.Bool("force-stop")
|
||||
if forceStop {
|
||||
_, _, e := adminClnt.Heal(globalContext, bucket, prefix, opts, "", forceStart, forceStop)
|
||||
fatalIf(probe.NewError(e), "Unable to stop healing.")
|
||||
printMsg(stopHealMessage{Status: "success", Alias: aliasedURL})
|
||||
return nil
|
||||
}
|
||||
|
||||
if opts.Recursive && opts.Pool == nil && opts.Set == nil && isTerminal() && !ctx.Bool("force") {
|
||||
fmt.Printf("You are about to scan and heal the whole namespace in all pools and sets, please confirm [y/N]: ")
|
||||
answer, e := bufio.NewReader(os.Stdin).ReadString('\n')
|
||||
fatalIf(probe.NewError(e), "Unable to parse user input.")
|
||||
if answer = strings.TrimSpace(strings.ToLower(answer)); answer != "y" && answer != "yes" {
|
||||
fmt.Println("Heal aborted!")
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
healStart, _, e := adminClnt.Heal(globalContext, bucket, prefix, opts, "", forceStart, false)
|
||||
fatalIf(probe.NewError(e), "Unable to start healing.")
|
||||
|
||||
ui := uiData{
|
||||
Bucket: bucket,
|
||||
Prefix: prefix,
|
||||
Client: adminClnt,
|
||||
ClientToken: healStart.ClientToken,
|
||||
ForceStart: forceStart,
|
||||
HealOpts: &opts,
|
||||
ObjectsByOnlineDrives: make(map[int]int64),
|
||||
HealthCols: make(map[col]int64),
|
||||
CurChan: cursorAnimate(),
|
||||
}
|
||||
|
||||
res, e := ui.DisplayAndFollowHealStatus(aliasedURL)
|
||||
if e != nil {
|
||||
if res.FailureDetail != "" {
|
||||
data, _ := json.MarshalIndent(res, "", " ")
|
||||
traceStr := string(data)
|
||||
fatalIf(probe.NewError(e).Trace(aliasedURL, traceStr), "Unable to display heal status.")
|
||||
} else {
|
||||
fatalIf(probe.NewError(e).Trace(aliasedURL), "Unable to display heal status.")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -1,39 +0,0 @@
|
||||
// Copyright (c) 2015-2022 MinIO, Inc.
|
||||
//
|
||||
// This file is part of MinIO Object Storage stack
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package cmd
|
||||
|
||||
import "github.com/minio/cli"
|
||||
|
||||
var adminIDPCmd = cli.Command{
|
||||
Name: "idp",
|
||||
Usage: "manage MinIO IDentity Provider server configuration",
|
||||
Action: mainAdminIDP,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
HideHelpCommand: true,
|
||||
Hidden: true,
|
||||
CustomHelpTemplate: `This command's functionality has moved and this command is DEPRECATED.
|
||||
|
||||
Please use commands under 'mc idp ldap|openid' instead.
|
||||
`,
|
||||
}
|
||||
|
||||
func mainAdminIDP(_ *cli.Context) error {
|
||||
deprecatedError("mc idp ldap|openid")
|
||||
return nil
|
||||
}
|
||||
@@ -1,408 +0,0 @@
|
||||
// Copyright (c) 2015-2024 MinIO, Inc.
|
||||
//
|
||||
// This file is part of MinIO Object Storage stack
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/dustin/go-humanize"
|
||||
"github.com/dustin/go-humanize/english"
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/cli"
|
||||
json "github.com/minio/colorjson"
|
||||
"github.com/minio/madmin-go/v3"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/minio-go/v7/pkg/set"
|
||||
"github.com/minio/pkg/v3/console"
|
||||
)
|
||||
|
||||
var adminInfoFlags = []cli.Flag{
|
||||
cli.BoolFlag{
|
||||
Name: "offline",
|
||||
Usage: "show only offline nodes/drives",
|
||||
},
|
||||
}
|
||||
|
||||
var adminInfoCmd = cli.Command{
|
||||
Name: "info",
|
||||
Usage: "display MinIO server information",
|
||||
Action: mainAdminInfo,
|
||||
OnUsageError: onUsageError,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: append(globalFlags, adminInfoFlags...),
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
{{.HelpName}} TARGET
|
||||
|
||||
FLAGS:
|
||||
{{range .VisibleFlags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
1. Get server information of the 'play' MinIO server.
|
||||
{{.Prompt}} {{.HelpName}} play/
|
||||
`,
|
||||
}
|
||||
|
||||
type poolSummary struct {
|
||||
index int
|
||||
setsCount int
|
||||
drivesPerSet int
|
||||
driveTolerance int
|
||||
drivesTotalFreeSpace uint64
|
||||
drivesTotalUsableSpace uint64
|
||||
endpoints set.StringSet
|
||||
}
|
||||
|
||||
type clusterInfo map[int]*poolSummary
|
||||
|
||||
func clusterSummaryInfo(info madmin.InfoMessage) clusterInfo {
|
||||
summary := make(clusterInfo)
|
||||
|
||||
for _, srv := range info.Servers {
|
||||
for _, disk := range srv.Disks {
|
||||
if disk.PoolIndex < 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
pool := summary[disk.PoolIndex]
|
||||
if pool == nil {
|
||||
pool = &poolSummary{
|
||||
index: disk.PoolIndex,
|
||||
endpoints: set.NewStringSet(),
|
||||
driveTolerance: info.StandardParity(),
|
||||
}
|
||||
}
|
||||
|
||||
if len(info.Backend.DrivesPerSet) > 0 {
|
||||
if disk.DiskIndex < (info.Backend.DrivesPerSet[disk.PoolIndex] - info.Backend.StandardSCParity) {
|
||||
pool.drivesTotalFreeSpace += disk.AvailableSpace
|
||||
pool.drivesTotalUsableSpace += disk.TotalSpace
|
||||
}
|
||||
}
|
||||
|
||||
pool.endpoints.Add(srv.Endpoint)
|
||||
summary[disk.PoolIndex] = pool
|
||||
}
|
||||
}
|
||||
|
||||
for idx := range info.Backend.TotalSets {
|
||||
pool := summary[idx]
|
||||
if pool != nil {
|
||||
pool.setsCount = info.Backend.TotalSets[idx]
|
||||
pool.drivesPerSet = info.Backend.DrivesPerSet[idx]
|
||||
summary[idx] = pool
|
||||
}
|
||||
}
|
||||
|
||||
return summary
|
||||
}
|
||||
|
||||
func endpointToPools(endpoint string, c clusterInfo) (pools []int) {
|
||||
for poolNumber, poolSummary := range c {
|
||||
if poolSummary.endpoints.Contains(endpoint) {
|
||||
pools = append(pools, poolNumber)
|
||||
}
|
||||
}
|
||||
sort.Ints(pools)
|
||||
return
|
||||
}
|
||||
|
||||
// Wrap "Info" message together with fields "Status" and "Error"
|
||||
type clusterStruct struct {
|
||||
Status string `json:"status"`
|
||||
Error string `json:"error,omitempty"`
|
||||
Info madmin.InfoMessage `json:"info,omitempty"`
|
||||
|
||||
onlyOffline bool
|
||||
}
|
||||
|
||||
// String provides colorized info messages
|
||||
func (u clusterStruct) String() (msg string) {
|
||||
// Check cluster level "Status" field for error
|
||||
if u.Status == "error" {
|
||||
fatal(probe.NewError(errors.New(u.Error)), "Unable to get service info")
|
||||
}
|
||||
|
||||
// If nothing has been collected, error out
|
||||
if u.Info.Servers == nil {
|
||||
fatal(probe.NewError(errors.New("Unable to get service info")), "")
|
||||
}
|
||||
|
||||
// Initialization
|
||||
var totalOfflineNodes int
|
||||
|
||||
// Color palette initialization
|
||||
console.SetColor("Info", color.New(color.FgGreen, color.Bold))
|
||||
console.SetColor("InfoFail", color.New(color.FgRed, color.Bold))
|
||||
console.SetColor("InfoWarning", color.New(color.FgYellow, color.Bold))
|
||||
|
||||
backendType := u.Info.BackendType()
|
||||
|
||||
coloredDot := console.Colorize("Info", dot)
|
||||
if madmin.ItemState(u.Info.Mode) == madmin.ItemInitializing {
|
||||
coloredDot = console.Colorize("InfoWarning", dot)
|
||||
}
|
||||
|
||||
sort.Slice(u.Info.Servers, func(i, j int) bool {
|
||||
return u.Info.Servers[i].Endpoint < u.Info.Servers[j].Endpoint
|
||||
})
|
||||
|
||||
clusterSummary := clusterSummaryInfo(u.Info)
|
||||
|
||||
// Loop through each server and put together info for each one
|
||||
for _, srv := range u.Info.Servers {
|
||||
// Check if MinIO server is not online ("Mode" field),
|
||||
if srv.State != string(madmin.ItemOnline) {
|
||||
totalOfflineNodes++
|
||||
// "PrintB" is color blue in console library package
|
||||
msg += fmt.Sprintf("%s %s\n", console.Colorize("InfoFail", dot), console.Colorize("PrintB", srv.Endpoint))
|
||||
msg += fmt.Sprintf(" Uptime: %s\n", console.Colorize("InfoFail", srv.State))
|
||||
|
||||
if backendType == madmin.Erasure {
|
||||
// Info about drives on a server, only available for non-FS types
|
||||
var OffDrives int
|
||||
var OnDrives int
|
||||
var dispNoOfDrives string
|
||||
for _, disk := range srv.Disks {
|
||||
switch disk.State {
|
||||
case madmin.DriveStateOk, madmin.DriveStateUnformatted:
|
||||
OnDrives++
|
||||
default:
|
||||
OffDrives++
|
||||
}
|
||||
}
|
||||
|
||||
totalDrivesPerServer := OnDrives + OffDrives
|
||||
|
||||
dispNoOfDrives = strconv.Itoa(OnDrives) + "/" + strconv.Itoa(totalDrivesPerServer)
|
||||
msg += fmt.Sprintf(" Drives: %s %s\n", dispNoOfDrives, console.Colorize("InfoFail", "OK "))
|
||||
}
|
||||
|
||||
msg += "\n"
|
||||
|
||||
// Continue to the next server
|
||||
continue
|
||||
}
|
||||
|
||||
if u.onlyOffline {
|
||||
continue
|
||||
}
|
||||
|
||||
// Print server title
|
||||
msg += fmt.Sprintf("%s %s\n", coloredDot, console.Colorize("PrintB", srv.Endpoint))
|
||||
|
||||
// Uptime
|
||||
msg += fmt.Sprintf(" Uptime: %s\n", console.Colorize("Info",
|
||||
humanize.RelTime(time.Now(), time.Now().Add(time.Duration(srv.Uptime)*time.Second), "", "")))
|
||||
|
||||
// Version
|
||||
version := srv.Version
|
||||
if strings.Contains(srv.Version, "DEVELOPMENT") {
|
||||
version = "<development>"
|
||||
}
|
||||
msg += fmt.Sprintf(" Version: %s\n", version)
|
||||
// Network info, only available for non-FS types
|
||||
connectionAlive := 0
|
||||
totalNodes := len(srv.Network)
|
||||
if srv.Network != nil && backendType == madmin.Erasure {
|
||||
for _, v := range srv.Network {
|
||||
if v == "online" {
|
||||
connectionAlive++
|
||||
}
|
||||
}
|
||||
clr := "Info"
|
||||
if connectionAlive != totalNodes {
|
||||
clr = "InfoWarning"
|
||||
}
|
||||
displayNwInfo := strconv.Itoa(connectionAlive) + "/" + strconv.Itoa(totalNodes)
|
||||
msg += fmt.Sprintf(" Network: %s %s\n", displayNwInfo, console.Colorize(clr, "OK "))
|
||||
}
|
||||
|
||||
if backendType == madmin.Erasure {
|
||||
// Info about drives on a server, only available for non-FS types
|
||||
var OffDrives int
|
||||
var OnDrives int
|
||||
var dispNoOfDrives string
|
||||
for _, disk := range srv.Disks {
|
||||
switch disk.State {
|
||||
case madmin.DriveStateOk, madmin.DriveStateUnformatted:
|
||||
OnDrives++
|
||||
default:
|
||||
OffDrives++
|
||||
}
|
||||
}
|
||||
|
||||
totalDrivesPerServer := OnDrives + OffDrives
|
||||
clr := "Info"
|
||||
if OnDrives != totalDrivesPerServer {
|
||||
clr = "InfoWarning"
|
||||
}
|
||||
dispNoOfDrives = strconv.Itoa(OnDrives) + "/" + strconv.Itoa(totalDrivesPerServer)
|
||||
msg += fmt.Sprintf(" Drives: %s %s\n", dispNoOfDrives, console.Colorize(clr, "OK "))
|
||||
|
||||
// Print pools belonging to this server
|
||||
var prettyPools []string
|
||||
for _, pool := range endpointToPools(srv.Endpoint, clusterSummary) {
|
||||
prettyPools = append(prettyPools, strconv.Itoa(pool+1))
|
||||
}
|
||||
msg += fmt.Sprintf(" Pool: %s\n", console.Colorize("Info", fmt.Sprintf("%+v", strings.Join(prettyPools, ", "))))
|
||||
}
|
||||
|
||||
msg += "\n"
|
||||
}
|
||||
|
||||
if backendType == madmin.Erasure {
|
||||
dspOrder := []col{colGreen} // Header
|
||||
for i := 0; i < len(clusterSummary); i++ {
|
||||
dspOrder = append(dspOrder, colGrey)
|
||||
}
|
||||
var printColors []*color.Color
|
||||
for _, c := range dspOrder {
|
||||
printColors = append(printColors, getPrintCol(c))
|
||||
}
|
||||
|
||||
tbl := console.NewTable(printColors, []bool{false, false, false, false}, 0)
|
||||
|
||||
var builder strings.Builder
|
||||
cellText := make([][]string, 0, len(clusterSummary)+1)
|
||||
cellText = append(cellText, []string{
|
||||
"Pool",
|
||||
"Drives Usage",
|
||||
"Erasure stripe size",
|
||||
"Erasure sets",
|
||||
})
|
||||
|
||||
var printSummary bool
|
||||
// Keep the pool order while printing the output
|
||||
for poolIdx := 0; poolIdx < len(clusterSummary); poolIdx++ {
|
||||
summary := clusterSummary[poolIdx]
|
||||
if summary == nil {
|
||||
break
|
||||
}
|
||||
totalSize := summary.drivesTotalUsableSpace
|
||||
usedCurrent := summary.drivesTotalUsableSpace - summary.drivesTotalFreeSpace
|
||||
var capacity string
|
||||
if totalSize > 0 {
|
||||
capacity = fmt.Sprintf("%.1f%% (total: %s)", 100*float64(usedCurrent)/float64(totalSize), humanize.IBytes(totalSize))
|
||||
}
|
||||
|
||||
if summary.drivesPerSet > 0 {
|
||||
printSummary = true
|
||||
}
|
||||
|
||||
cellText = append(cellText, []string{
|
||||
humanize.Ordinal(poolIdx + 1),
|
||||
capacity,
|
||||
strconv.Itoa(summary.drivesPerSet),
|
||||
strconv.Itoa(summary.setsCount),
|
||||
})
|
||||
}
|
||||
|
||||
if printSummary {
|
||||
e := tbl.PopulateTable(&builder, cellText)
|
||||
fatalIf(probe.NewError(e), "unable to populate the table")
|
||||
|
||||
msg += builder.String() + "\n"
|
||||
}
|
||||
}
|
||||
|
||||
// Summary on used space, total no of buckets and
|
||||
// total no of objects at the Cluster level
|
||||
usedTotal := humanize.IBytes(u.Info.Usage.Size)
|
||||
if u.Info.Buckets.Count > 0 {
|
||||
msg += fmt.Sprintf("%s Used, %s, %s", usedTotal,
|
||||
english.Plural(int(u.Info.Buckets.Count), "Bucket", ""),
|
||||
english.Plural(int(u.Info.Objects.Count), "Object", ""))
|
||||
if u.Info.Versions.Count > 0 {
|
||||
msg += ", " + english.Plural(int(u.Info.Versions.Count), "Version", "")
|
||||
}
|
||||
if u.Info.DeleteMarkers.Count > 0 {
|
||||
msg += ", " + english.Plural(int(u.Info.DeleteMarkers.Count), "Delete Marker", "")
|
||||
}
|
||||
msg += "\n"
|
||||
}
|
||||
if backendType == madmin.Erasure {
|
||||
if totalOfflineNodes != 0 {
|
||||
msg += fmt.Sprintf("%s offline, ", english.Plural(totalOfflineNodes, "node", ""))
|
||||
}
|
||||
// Summary on total no of online and total
|
||||
// number of offline drives at the Cluster level
|
||||
msg += fmt.Sprintf("%s online, %s offline, EC:%d\n",
|
||||
english.Plural(u.Info.Backend.OnlineDisks, "drive", ""),
|
||||
english.Plural(u.Info.Backend.OfflineDisks, "drive", ""),
|
||||
u.Info.Backend.StandardSCParity)
|
||||
}
|
||||
|
||||
// Remove the last new line if any
|
||||
// since this is a String() function
|
||||
msg = strings.TrimSuffix(msg, "\n")
|
||||
return
|
||||
}
|
||||
|
||||
// JSON jsonifies service status message.
|
||||
func (u clusterStruct) JSON() string {
|
||||
statusJSONBytes, e := json.MarshalIndent(u, "", " ")
|
||||
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
|
||||
|
||||
return string(statusJSONBytes)
|
||||
}
|
||||
|
||||
// checkAdminInfoSyntax - validate arguments passed by a user
|
||||
func checkAdminInfoSyntax(ctx *cli.Context) {
|
||||
if len(ctx.Args()) == 0 || len(ctx.Args()) > 1 {
|
||||
showCommandHelpAndExit(ctx, 1) // last argument is exit code
|
||||
}
|
||||
}
|
||||
|
||||
func mainAdminInfo(ctx *cli.Context) error {
|
||||
checkAdminInfoSyntax(ctx)
|
||||
|
||||
// Get the alias parameter from cli
|
||||
args := ctx.Args()
|
||||
aliasedURL := args.Get(0)
|
||||
|
||||
// Create a new MinIO Admin Client
|
||||
client, err := newAdminClient(aliasedURL)
|
||||
fatalIf(err, "Unable to initialize admin connection.")
|
||||
|
||||
clusterInfo := clusterStruct{
|
||||
onlyOffline: ctx.Bool("offline"),
|
||||
}
|
||||
|
||||
// Fetch info of all servers (cluster or single server)
|
||||
admInfo, e := client.ServerInfo(globalContext)
|
||||
if e != nil {
|
||||
clusterInfo.Status = "error"
|
||||
clusterInfo.Error = e.Error()
|
||||
} else {
|
||||
clusterInfo.Status = "success"
|
||||
clusterInfo.Error = ""
|
||||
}
|
||||
|
||||
clusterInfo.Info = admInfo
|
||||
printMsg(clusterInfo)
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -1,39 +0,0 @@
|
||||
// Copyright (c) 2015-2022 MinIO, Inc.
|
||||
//
|
||||
// This file is part of MinIO Object Storage stack
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"github.com/minio/cli"
|
||||
)
|
||||
|
||||
var adminInspectCmd = cli.Command{
|
||||
Name: "inspect",
|
||||
Usage: "inspect files on MinIO server",
|
||||
Action: mainAdminInspect,
|
||||
OnUsageError: onUsageError,
|
||||
Before: setGlobalsFromContext,
|
||||
HideHelpCommand: true,
|
||||
Hidden: true,
|
||||
CustomHelpTemplate: "Please use 'mc support inspect'",
|
||||
}
|
||||
|
||||
// mainAdminHeal - the entry function of heal command
|
||||
func mainAdminInspect(_ *cli.Context) error {
|
||||
deprecatedError("mc support inspect")
|
||||
return nil
|
||||
}
|
||||
@@ -1,70 +0,0 @@
|
||||
// Copyright (c) 2015-2022 MinIO, Inc.
|
||||
//
|
||||
// This file is part of MinIO Object Storage stack
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/pkg/v3/console"
|
||||
"golang.org/x/term"
|
||||
)
|
||||
|
||||
var adminKMSCreateKeyCmd = cli.Command{
|
||||
Name: "create",
|
||||
Usage: "creates a new master KMS key",
|
||||
Action: mainAdminKMSCreateKey,
|
||||
OnUsageError: onUsageError,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
{{.HelpName}} TARGET [KEY_NAME]
|
||||
|
||||
FLAGS:
|
||||
{{range .VisibleFlags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
1. Create a new master key named 'my-key' default master key.
|
||||
$ {{.HelpName}} play my-key
|
||||
`,
|
||||
}
|
||||
|
||||
// adminKMSCreateKeyCmd is the handler for the "mc admin kms key create" command.
|
||||
func mainAdminKMSCreateKey(ctx *cli.Context) error {
|
||||
if len(ctx.Args()) != 2 {
|
||||
showCommandHelpAndExit(ctx, 1) // last argument is exit code
|
||||
}
|
||||
|
||||
client, err := newAdminClient(ctx.Args().Get(0))
|
||||
fatalIf(err, "Cannot get a configured admin connection.")
|
||||
|
||||
keyID := ctx.Args().Get(1)
|
||||
e := client.CreateKey(globalContext, keyID)
|
||||
fatalIf(probe.NewError(e), "Failed to create master key")
|
||||
|
||||
if term.IsTerminal(int(os.Stdout.Fd())) {
|
||||
console.Println(color.GreenString(fmt.Sprintf("Created master key `%s` successfully", keyID)))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -1,116 +0,0 @@
|
||||
// Copyright (c) 2015-2023 MinIO, Inc.
|
||||
//
|
||||
// This file is part of MinIO Object Storage stack
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
|
||||
"github.com/fatih/color"
|
||||
"github.com/jedib0t/go-pretty/v6/table"
|
||||
"github.com/jedib0t/go-pretty/v6/text"
|
||||
"github.com/minio/cli"
|
||||
json "github.com/minio/colorjson"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/pkg/v3/console"
|
||||
)
|
||||
|
||||
var adminKMSKeyListCmd = cli.Command{
|
||||
Name: "list",
|
||||
Usage: "request list of KMS master keys",
|
||||
Action: mainAdminKMSKeyList,
|
||||
OnUsageError: onUsageError,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
{{.HelpName}} TARGET
|
||||
|
||||
FLAGS:
|
||||
{{range .VisibleFlags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
1. Get list of master keys from a MinIO server/cluster.
|
||||
$ {{.HelpName}} play
|
||||
`,
|
||||
}
|
||||
|
||||
// adminKMSKeyCmd is the handle for the "mc admin kms key" command.
|
||||
func mainAdminKMSKeyList(ctx *cli.Context) error {
|
||||
if len(ctx.Args()) == 0 || len(ctx.Args()) > 1 {
|
||||
showCommandHelpAndExit(ctx, 1) // last argument is exit code
|
||||
}
|
||||
|
||||
console.SetColor("KeyName", color.New(color.FgBlue))
|
||||
|
||||
// Get the alias parameter from cli
|
||||
args := ctx.Args()
|
||||
aliasedURL := args.Get(0)
|
||||
|
||||
// Create a new MinIO Admin Client
|
||||
client, err := newAdminClient(aliasedURL)
|
||||
fatalIf(err, "Unable to initialize admin connection.")
|
||||
|
||||
keys, e := client.ListKeys(globalContext, "*")
|
||||
fatalIf(probe.NewError(e).Trace(args...), "Unable to list KMS keys")
|
||||
|
||||
var rows []table.Row
|
||||
kmsKeys := []string{}
|
||||
for idx, k := range keys {
|
||||
rows = append(rows, table.Row{idx + 1, k.Name})
|
||||
kmsKeys = append(kmsKeys, k.Name)
|
||||
}
|
||||
|
||||
if globalJSON {
|
||||
printMsg(kmsKeysMsg{
|
||||
Status: "success",
|
||||
Target: aliasedURL,
|
||||
Keys: kmsKeys,
|
||||
})
|
||||
return nil
|
||||
}
|
||||
|
||||
t := table.NewWriter()
|
||||
t.SetOutputMirror(os.Stdout)
|
||||
t.SetColumnConfigs([]table.ColumnConfig{{Align: text.AlignCenter}})
|
||||
t.SetTitle("KMS Keys")
|
||||
t.AppendHeader(table.Row{"S N", "Name"})
|
||||
t.AppendRows(rows)
|
||||
t.SetStyle(table.StyleLight)
|
||||
t.Render()
|
||||
return nil
|
||||
}
|
||||
|
||||
type kmsKeysMsg struct {
|
||||
Status string `json:"status"`
|
||||
Target string `json:"target"`
|
||||
Keys []string `json:"keys"`
|
||||
}
|
||||
|
||||
func (k kmsKeysMsg) JSON() string {
|
||||
kmsBytes, e := json.MarshalIndent(k, "", " ")
|
||||
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
|
||||
|
||||
return string(kmsBytes)
|
||||
}
|
||||
|
||||
func (k kmsKeysMsg) String() string {
|
||||
return fmt.Sprintf("Keys: %s\n", k.Keys)
|
||||
}
|
||||
@@ -1,120 +0,0 @@
|
||||
// Copyright (c) 2015-2022 MinIO, Inc.
|
||||
//
|
||||
// This file is part of MinIO Object Storage stack
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/cli"
|
||||
json "github.com/minio/colorjson"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/pkg/v3/console"
|
||||
)
|
||||
|
||||
var adminKMSKeyStatusCmd = cli.Command{
|
||||
Name: "status",
|
||||
Usage: "request status information for a KMS master key",
|
||||
Action: mainAdminKMSKeyStatus,
|
||||
OnUsageError: onUsageError,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
{{.HelpName}} TARGET [KEY_NAME]
|
||||
|
||||
FLAGS:
|
||||
{{range .VisibleFlags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
1. Get default master key and its status from a MinIO server/cluster.
|
||||
$ {{.HelpName}} play
|
||||
2. Get the status of one particular master key from a MinIO server/cluster.
|
||||
$ {{.HelpName}} play my-master-key
|
||||
`,
|
||||
}
|
||||
|
||||
// adminKMSKeyCmd is the handle for the "mc admin kms key" command.
|
||||
func mainAdminKMSKeyStatus(ctx *cli.Context) error {
|
||||
if len(ctx.Args()) == 0 || len(ctx.Args()) > 2 {
|
||||
showCommandHelpAndExit(ctx, 1) // last argument is exit code
|
||||
}
|
||||
|
||||
console.SetColor("StatusSuccess", color.New(color.FgGreen, color.Bold))
|
||||
console.SetColor("StatusError", color.New(color.FgRed, color.Bold))
|
||||
console.SetColor("StatusUnknown", color.New(color.FgYellow, color.Bold))
|
||||
|
||||
client, err := newAdminClient(ctx.Args().Get(0))
|
||||
fatalIf(err, "Unable to get a configured admin connection.")
|
||||
|
||||
var keyID string
|
||||
if len(ctx.Args()) == 2 {
|
||||
keyID = ctx.Args().Get(1)
|
||||
}
|
||||
status, e := client.GetKeyStatus(globalContext, keyID)
|
||||
fatalIf(probe.NewError(e), "Failed to get status information")
|
||||
|
||||
printMsg(kmsKeyStatusMsg{
|
||||
KeyID: status.KeyID,
|
||||
EncryptionErr: status.EncryptionErr,
|
||||
DecryptionErr: status.DecryptionErr,
|
||||
})
|
||||
return nil
|
||||
}
|
||||
|
||||
type kmsKeyStatusMsg struct {
|
||||
KeyID string `json:"keyId"`
|
||||
EncryptionErr string `json:"encryptionError,omitempty"`
|
||||
DecryptionErr string `json:"decryptionError,omitempty"`
|
||||
Status string `json:"status"`
|
||||
}
|
||||
|
||||
func (s kmsKeyStatusMsg) JSON() string {
|
||||
s.Status = "success"
|
||||
kmsBytes, e := json.MarshalIndent(s, "", " ")
|
||||
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
|
||||
|
||||
return string(kmsBytes)
|
||||
}
|
||||
|
||||
func (s kmsKeyStatusMsg) String() string {
|
||||
msg := fmt.Sprintf("Key: %s\n", s.KeyID)
|
||||
|
||||
success := console.Colorize("StatusSuccess", "✔")
|
||||
failure := console.Colorize("StatusError", "✗")
|
||||
dunno := console.Colorize("StatusUnknown", "?")
|
||||
|
||||
formatStatus := func(name string, unknown bool, err string) string {
|
||||
st := ""
|
||||
switch {
|
||||
case !unknown && err == "":
|
||||
st = success
|
||||
case unknown:
|
||||
st = dunno
|
||||
case err != "":
|
||||
st = fmt.Sprintf("%s (%s)", failure, err)
|
||||
}
|
||||
return fmt.Sprintf(" - %s %s\n", name, st)
|
||||
}
|
||||
|
||||
msg += formatStatus("Encryption", false, s.EncryptionErr)
|
||||
msg += formatStatus("Decryption", s.EncryptionErr != "", s.DecryptionErr)
|
||||
return msg
|
||||
}
|
||||
@@ -1,42 +0,0 @@
|
||||
// Copyright (c) 2015-2022 MinIO, Inc.
|
||||
//
|
||||
// This file is part of MinIO Object Storage stack
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package cmd
|
||||
|
||||
import "github.com/minio/cli"
|
||||
|
||||
var adminKMSKeySubcommands = []cli.Command{
|
||||
adminKMSCreateKeyCmd,
|
||||
adminKMSKeyStatusCmd,
|
||||
adminKMSKeyListCmd,
|
||||
}
|
||||
|
||||
var adminKMSKeyCmd = cli.Command{
|
||||
Name: "key",
|
||||
Usage: "manage KMS master keys: Request key status information",
|
||||
Action: mainAdminKMSKey,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
Subcommands: adminKMSKeySubcommands,
|
||||
HideHelpCommand: true,
|
||||
}
|
||||
|
||||
// mainAdminKMSKey is the handle for the "mc admin kms key" command.
|
||||
func mainAdminKMSKey(ctx *cli.Context) error {
|
||||
commandNotFound(ctx, adminKMSKeySubcommands)
|
||||
return nil
|
||||
}
|
||||
@@ -1,40 +0,0 @@
|
||||
// Copyright (c) 2015-2022 MinIO, Inc.
|
||||
//
|
||||
// This file is part of MinIO Object Storage stack
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package cmd
|
||||
|
||||
import "github.com/minio/cli"
|
||||
|
||||
var adminKMSSubcommands = []cli.Command{
|
||||
adminKMSKeyCmd,
|
||||
}
|
||||
|
||||
var adminKMSCmd = cli.Command{
|
||||
Name: "kms",
|
||||
Usage: "perform KMS management operations",
|
||||
Action: mainAdminKMS,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
Subcommands: adminKMSSubcommands,
|
||||
HideHelpCommand: true,
|
||||
}
|
||||
|
||||
// mainAdminKMS is the handle for the "mc admin kms" command.
|
||||
func mainAdminKMS(ctx *cli.Context) error {
|
||||
commandNotFound(ctx, adminKMSSubcommands)
|
||||
return nil
|
||||
}
|
||||
@@ -1,211 +0,0 @@
|
||||
// Copyright (c) 2015-2022 MinIO, Inc.
|
||||
//
|
||||
// This file is part of MinIO Object Storage stack
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/cli"
|
||||
json "github.com/minio/colorjson"
|
||||
"github.com/minio/madmin-go/v3"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/pkg/v3/console"
|
||||
)
|
||||
|
||||
const logTimeFormat string = "15:04:05 MST 01/02/2006"
|
||||
|
||||
var logsShowFlags = []cli.Flag{
|
||||
cli.IntFlag{
|
||||
Name: "last, l",
|
||||
Usage: "show last n log entries",
|
||||
Value: 10,
|
||||
},
|
||||
cli.StringFlag{
|
||||
Name: "type, t",
|
||||
Usage: "list error logs by type. Valid options are '[minio, application, all]'",
|
||||
Value: "all",
|
||||
},
|
||||
}
|
||||
|
||||
var adminLogsCmd = cli.Command{
|
||||
Name: "logs",
|
||||
Usage: "show MinIO logs",
|
||||
OnUsageError: onUsageError,
|
||||
Action: mainAdminLogs,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: append(logsShowFlags, globalFlags...),
|
||||
HideHelpCommand: true,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
USAGE:
|
||||
{{.HelpName}} [FLAGS] TARGET [NODENAME]
|
||||
FLAGS:
|
||||
{{range .VisibleFlags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
1. Show logs for a MinIO server with alias 'myminio'
|
||||
{{.Prompt}} {{.HelpName}} myminio
|
||||
2. Show last 5 log entries for node 'node1' for a MinIO server with alias 'myminio'
|
||||
{{.Prompt}} {{.HelpName}} --last 5 myminio node1
|
||||
3. Show application errors in logs for a MinIO server with alias 'myminio'
|
||||
{{.Prompt}} {{.HelpName}} --type application myminio
|
||||
`,
|
||||
}
|
||||
|
||||
func checkLogsShowSyntax(ctx *cli.Context) {
|
||||
if len(ctx.Args()) == 0 || len(ctx.Args()) > 3 {
|
||||
showCommandHelpAndExit(ctx, 1) // last argument is exit code
|
||||
}
|
||||
}
|
||||
|
||||
// Extend madmin.LogInfo to add String() and JSON() methods
|
||||
type logMessage struct {
|
||||
Status string `json:"status"`
|
||||
madmin.LogInfo
|
||||
}
|
||||
|
||||
// JSON - jsonify loginfo
|
||||
func (l logMessage) JSON() string {
|
||||
l.Status = "success"
|
||||
logJSON, e := json.MarshalIndent(&l, "", " ")
|
||||
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
|
||||
|
||||
return string(logJSON)
|
||||
}
|
||||
|
||||
func getLogTime(lt string) string {
|
||||
tm, e := time.Parse(time.RFC3339Nano, lt)
|
||||
if e != nil {
|
||||
return lt
|
||||
}
|
||||
return tm.Format(logTimeFormat)
|
||||
}
|
||||
|
||||
// String - return colorized loginfo as string.
|
||||
func (l logMessage) String() string {
|
||||
var hostStr string
|
||||
b := &strings.Builder{}
|
||||
if l.NodeName != "" {
|
||||
hostStr = fmt.Sprintf("%s ", colorizedNodeName(l.NodeName))
|
||||
}
|
||||
if l.API != nil {
|
||||
apiString := "API: " + l.API.Name + "("
|
||||
if l.API.Args != nil && l.API.Args.Bucket != "" {
|
||||
apiString = apiString + "bucket=" + l.API.Args.Bucket
|
||||
}
|
||||
if l.API.Args != nil && l.API.Args.Object != "" {
|
||||
apiString = apiString + ", object=" + l.API.Args.Object
|
||||
}
|
||||
apiString += ")"
|
||||
fmt.Fprintf(b, "\n%s %s", hostStr, console.Colorize("API", apiString))
|
||||
}
|
||||
if l.Time != "" {
|
||||
fmt.Fprintf(b, "\n%s Time: %s", hostStr, getLogTime(l.Time))
|
||||
}
|
||||
if l.DeploymentID != "" {
|
||||
fmt.Fprintf(b, "\n%s DeploymentID: %s", hostStr, l.DeploymentID)
|
||||
}
|
||||
if l.RequestID != "" {
|
||||
fmt.Fprintf(b, "\n%s RequestID: %s", hostStr, l.RequestID)
|
||||
}
|
||||
if l.RemoteHost != "" {
|
||||
fmt.Fprintf(b, "\n%s RemoteHost: %s", hostStr, l.RemoteHost)
|
||||
}
|
||||
if l.UserAgent != "" {
|
||||
fmt.Fprintf(b, "\n%s UserAgent: %s", hostStr, l.UserAgent)
|
||||
}
|
||||
if l.Message != "" {
|
||||
fmt.Fprintf(b, "\n%s Message: %s", hostStr, l.Message)
|
||||
}
|
||||
if l.Trace != nil {
|
||||
if l.Trace.Message != "" {
|
||||
fmt.Fprintf(b, "\n%s Error: %s", hostStr, console.Colorize("LogMessage", l.Trace.Message))
|
||||
}
|
||||
if l.Trace.Variables != nil {
|
||||
for key, value := range l.Trace.Variables {
|
||||
if value != "" {
|
||||
fmt.Fprintf(b, "\n%s %s=%s", hostStr, key, value)
|
||||
}
|
||||
}
|
||||
}
|
||||
if l.Trace.Source != nil {
|
||||
traceLength := len(l.Trace.Source)
|
||||
for i, element := range l.Trace.Source {
|
||||
fmt.Fprintf(b, "\n%s %8v: %s", hostStr, traceLength-i, element)
|
||||
}
|
||||
}
|
||||
}
|
||||
logMsg := strings.TrimPrefix(b.String(), "\n")
|
||||
return fmt.Sprintf("%s\n", logMsg)
|
||||
}
|
||||
|
||||
// mainAdminLogs - the entry function of admin logs
|
||||
func mainAdminLogs(ctx *cli.Context) error {
|
||||
// Check for command syntax
|
||||
checkLogsShowSyntax(ctx)
|
||||
console.SetColor("LogMessage", color.New(color.Bold, color.FgRed))
|
||||
console.SetColor("Api", color.New(color.Bold, color.FgWhite))
|
||||
for _, c := range colors {
|
||||
console.SetColor(fmt.Sprintf("Node%d", c), color.New(c))
|
||||
}
|
||||
aliasedURL := ctx.Args().Get(0)
|
||||
var node string
|
||||
if len(ctx.Args()) > 1 {
|
||||
node = ctx.Args().Get(1)
|
||||
}
|
||||
var last int
|
||||
if ctx.IsSet("last") {
|
||||
last = ctx.Int("last")
|
||||
if last <= 0 {
|
||||
fatalIf(errInvalidArgument().Trace(ctx.Args()...), "please set a proper limit, for example: '--last 5' to display last 5 logs, omit this flag to display all available logs")
|
||||
}
|
||||
}
|
||||
logType := strings.ToLower(ctx.String("type"))
|
||||
if logType != "minio" && logType != "application" && logType != "all" {
|
||||
fatalIf(errInvalidArgument().Trace(ctx.Args()...), "Invalid value for --type flag. Valid options are [minio, application, all]")
|
||||
}
|
||||
// Create a new MinIO Admin Client
|
||||
client, err := newAdminClient(aliasedURL)
|
||||
if err != nil {
|
||||
fatalIf(err.Trace(aliasedURL), "Unable to initialize admin client.")
|
||||
return nil
|
||||
}
|
||||
|
||||
ctxt, cancel := context.WithCancel(globalContext)
|
||||
defer cancel()
|
||||
|
||||
// Start listening on all console log activity.
|
||||
logCh := client.GetLogs(ctxt, node, last, logType)
|
||||
for logInfo := range logCh {
|
||||
if logInfo.Err != nil {
|
||||
fatalIf(probe.NewError(logInfo.Err), "Unable to listen to console logs")
|
||||
}
|
||||
// drop nodeName from output if specified as cli arg
|
||||
if node != "" {
|
||||
logInfo.NodeName = ""
|
||||
}
|
||||
if logInfo.DeploymentID != "" {
|
||||
printMsg(logMessage{LogInfo: logInfo})
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -1,79 +0,0 @@
|
||||
// Copyright (c) 2015-2022 MinIO, Inc.
|
||||
//
|
||||
// This file is part of MinIO Object Storage stack
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package cmd
|
||||
|
||||
import "github.com/minio/cli"
|
||||
|
||||
var adminFlags = []cli.Flag{}
|
||||
|
||||
const (
|
||||
// dot represents a list item, for eg. server status - online (green) or offline (red)
|
||||
dot = "●"
|
||||
// check represents successful operation
|
||||
check = "✔"
|
||||
)
|
||||
|
||||
var adminCmdSubcommands = []cli.Command{
|
||||
adminServiceCmd,
|
||||
adminServerUpdateCmd,
|
||||
adminInfoCmd,
|
||||
adminInspectCmd,
|
||||
adminUserCmd,
|
||||
adminGroupCmd,
|
||||
adminPolicyCmd,
|
||||
adminReplicateCmd,
|
||||
adminIDPCmd,
|
||||
adminConfigCmd,
|
||||
adminDecommissionCmd,
|
||||
adminHealCmd,
|
||||
adminPrometheusCmd,
|
||||
adminKMSCmd,
|
||||
adminHealthCmd(),
|
||||
adminSubnetCmd,
|
||||
adminBucketCmd,
|
||||
adminTierCmd,
|
||||
adminSpeedtestCmd,
|
||||
adminProfileCmd,
|
||||
adminScannerCmd,
|
||||
adminTopCmd,
|
||||
adminTraceCmd,
|
||||
adminConsoleCmd,
|
||||
adminClusterCmd,
|
||||
adminRebalanceCmd,
|
||||
adminLogsCmd,
|
||||
adminAccesskeyCmd,
|
||||
}
|
||||
|
||||
var adminCmd = cli.Command{
|
||||
Name: "admin",
|
||||
Usage: "manage MinIO servers",
|
||||
Action: mainAdmin,
|
||||
Subcommands: adminCmdSubcommands,
|
||||
HideHelpCommand: true,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: append(adminFlags, globalFlags...),
|
||||
}
|
||||
|
||||
const dateTimeFormatFilename = "2006-01-02T15-04-05.999999-07-00"
|
||||
|
||||
// mainAdmin is the handle for "mc admin" command.
|
||||
func mainAdmin(ctx *cli.Context) error {
|
||||
commandNotFound(ctx, adminCmdSubcommands)
|
||||
return nil
|
||||
// Sub-commands like "service", "heal", "top" have their own main.
|
||||
}
|
||||
@@ -1,39 +0,0 @@
|
||||
// Copyright (c) 2015-2022 MinIO, Inc.
|
||||
//
|
||||
// This file is part of MinIO Object Storage stack
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"github.com/minio/cli"
|
||||
)
|
||||
|
||||
var adminPolicyAddCmd = cli.Command{
|
||||
Name: "add",
|
||||
Usage: "add an IAM policy",
|
||||
Action: mainAdminPolicyAdd,
|
||||
OnUsageError: onUsageError,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
HideHelpCommand: true,
|
||||
Hidden: true,
|
||||
CustomHelpTemplate: `Please use 'mc admin policy create'`,
|
||||
}
|
||||
|
||||
func mainAdminPolicyAdd(_ *cli.Context) error {
|
||||
deprecatedError("mc admin policy create")
|
||||
return nil
|
||||
}
|
||||
@@ -1,131 +0,0 @@
|
||||
// Copyright (c) 2015-2022 MinIO, Inc.
|
||||
//
|
||||
// This file is part of MinIO Object Storage stack
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/madmin-go/v3"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
)
|
||||
|
||||
const (
|
||||
errCodeChangeAlreadyApplied = "XMinioAdminPolicyChangeAlreadyApplied"
|
||||
)
|
||||
|
||||
var adminAttachPolicyFlags = []cli.Flag{
|
||||
cli.StringFlag{
|
||||
Name: "user, u",
|
||||
Usage: "attach policy to user",
|
||||
},
|
||||
cli.StringFlag{
|
||||
Name: "group, g",
|
||||
Usage: "attach policy to group",
|
||||
},
|
||||
}
|
||||
|
||||
var adminPolicyAttachCmd = cli.Command{
|
||||
Name: "attach",
|
||||
Usage: "attach an IAM policy to a user or group",
|
||||
Action: mainAdminPolicyAttach,
|
||||
OnUsageError: onUsageError,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: append(adminAttachPolicyFlags, globalFlags...),
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
{{.HelpName}} [FLAGS] TARGET POLICY [POLICY...] [--user USER | --group GROUP]
|
||||
|
||||
Exactly one of --user or --group is required.
|
||||
|
||||
POLICY:
|
||||
Name of the policy on the MinIO server.
|
||||
|
||||
FLAGS:
|
||||
{{range .VisibleFlags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
1. Attach the "readonly" policy to user "james".
|
||||
{{.Prompt}} {{.HelpName}} myminio readonly --user james
|
||||
2. Attach the "audit-policy" and "acct-policy" policies to group "legal".
|
||||
{{.Prompt}} {{.HelpName}} myminio audit-policy acct-policy --group legal
|
||||
`,
|
||||
}
|
||||
|
||||
// mainAdminPolicyAttach is the handler for "mc admin policy attach" command.
|
||||
func mainAdminPolicyAttach(ctx *cli.Context) error {
|
||||
return userAttachOrDetachPolicy(ctx, true)
|
||||
}
|
||||
|
||||
func userAttachOrDetachPolicy(ctx *cli.Context, attach bool) error {
|
||||
if len(ctx.Args()) < 2 {
|
||||
showCommandHelpAndExit(ctx, 1) // last argument is exit code
|
||||
}
|
||||
user := ctx.String("user")
|
||||
group := ctx.String("group")
|
||||
|
||||
// Get the alias parameter from cli
|
||||
args := ctx.Args()
|
||||
aliasedURL := args.Get(0)
|
||||
|
||||
policies := args[1:]
|
||||
req := madmin.PolicyAssociationReq{
|
||||
User: user,
|
||||
Group: group,
|
||||
Policies: policies,
|
||||
}
|
||||
|
||||
// Create a new MinIO Admin Client
|
||||
client, err := newAdminClient(aliasedURL)
|
||||
fatalIf(err, "Unable to initialize admin connection.")
|
||||
|
||||
var e error
|
||||
var res madmin.PolicyAssociationResp
|
||||
if attach {
|
||||
res, e = client.AttachPolicy(globalContext, req)
|
||||
} else {
|
||||
res, e = client.DetachPolicy(globalContext, req)
|
||||
}
|
||||
|
||||
if e != nil && madmin.ToErrorResponse(e).Code != errCodeChangeAlreadyApplied {
|
||||
fatalIf(probe.NewError(e), "Unable to make user/group policy association")
|
||||
}
|
||||
|
||||
var emptyResp madmin.PolicyAssociationResp
|
||||
if res.UpdatedAt.Equal(emptyResp.UpdatedAt) {
|
||||
// Older minio does not send a result, so we populate res manually to
|
||||
// simulate a result. TODO(aditya): remove this after newer minio is
|
||||
// released in a few months (Older API Deprecated in Jun 2023)
|
||||
if attach {
|
||||
res.PoliciesAttached = policies
|
||||
} else {
|
||||
res.PoliciesDetached = policies
|
||||
}
|
||||
}
|
||||
|
||||
m := policyAssociationMessage{
|
||||
attach: attach,
|
||||
Status: "success",
|
||||
PoliciesAttached: res.PoliciesAttached,
|
||||
PoliciesDetached: res.PoliciesDetached,
|
||||
User: user,
|
||||
Group: group,
|
||||
}
|
||||
printMsg(m)
|
||||
return nil
|
||||
}
|
||||
@@ -1,144 +0,0 @@
|
||||
// Copyright (c) 2015-2022 MinIO, Inc.
|
||||
//
|
||||
// This file is part of MinIO Object Storage stack
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/cli"
|
||||
json "github.com/minio/colorjson"
|
||||
"github.com/minio/madmin-go/v3"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/pkg/v3/console"
|
||||
)
|
||||
|
||||
var adminPolicyCreateCmd = cli.Command{
|
||||
Name: "create",
|
||||
Usage: "create a new IAM policy",
|
||||
Action: mainAdminPolicyCreate,
|
||||
OnUsageError: onUsageError,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
{{.HelpName}} TARGET POLICYNAME POLICYFILE
|
||||
|
||||
POLICYNAME:
|
||||
Name of the canned policy on MinIO server.
|
||||
|
||||
POLICYFILE:
|
||||
Name of the policy file associated with the policy name.
|
||||
|
||||
FLAGS:
|
||||
{{range .VisibleFlags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
1. Create a new canned policy 'writeonly'.
|
||||
{{.Prompt}} {{.HelpName}} myminio writeonly /tmp/writeonly.json
|
||||
`,
|
||||
}
|
||||
|
||||
// checkAdminPolicyCreateSyntax - validate all the passed arguments
|
||||
func checkAdminPolicyCreateSyntax(ctx *cli.Context) {
|
||||
if len(ctx.Args()) != 3 {
|
||||
showCommandHelpAndExit(ctx, 1) // last argument is exit code
|
||||
}
|
||||
}
|
||||
|
||||
// userPolicyMessage container for content message structure
|
||||
type userPolicyMessage struct {
|
||||
op string
|
||||
Status string `json:"status"`
|
||||
Policy string `json:"policy,omitempty"`
|
||||
PolicyInfo madmin.PolicyInfo `json:"policyInfo,omitempty"`
|
||||
UserOrGroup string `json:"userOrGroup,omitempty"`
|
||||
IsGroup bool `json:"isGroup"`
|
||||
}
|
||||
|
||||
func (u userPolicyMessage) accountType() string {
|
||||
switch u.op {
|
||||
case "attach", "detach":
|
||||
if u.IsGroup {
|
||||
return "group"
|
||||
}
|
||||
return "user"
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (u userPolicyMessage) String() string {
|
||||
switch u.op {
|
||||
case "info":
|
||||
buf, e := json.MarshalIndent(u.PolicyInfo, "", " ")
|
||||
fatalIf(probe.NewError(e), "Unable to marshal to JSON.")
|
||||
return string(buf)
|
||||
case "list":
|
||||
return console.Colorize("PolicyName", u.Policy)
|
||||
case "remove":
|
||||
return console.Colorize("PolicyMessage", "Removed policy `"+u.Policy+"` successfully.")
|
||||
case "create":
|
||||
return console.Colorize("PolicyMessage", "Created policy `"+u.Policy+"` successfully.")
|
||||
case "detach":
|
||||
return console.Colorize("PolicyMessage",
|
||||
fmt.Sprintf("Policy `%s` successfully detached from %s `%s`", u.Policy, u.accountType(), u.UserOrGroup))
|
||||
case "attach":
|
||||
return console.Colorize("PolicyMessage",
|
||||
fmt.Sprintf("Policy `%s` successfully attached to %s `%s`", u.Policy, u.accountType(), u.UserOrGroup))
|
||||
}
|
||||
|
||||
return ""
|
||||
}
|
||||
|
||||
func (u userPolicyMessage) JSON() string {
|
||||
u.Status = "success"
|
||||
jsonMessageBytes, e := json.MarshalIndent(u, "", " ")
|
||||
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
|
||||
|
||||
return string(jsonMessageBytes)
|
||||
}
|
||||
|
||||
// mainAdminPolicyCreate is the handle for "mc admin policy create" command.
|
||||
func mainAdminPolicyCreate(ctx *cli.Context) error {
|
||||
checkAdminPolicyCreateSyntax(ctx)
|
||||
|
||||
console.SetColor("PolicyMessage", color.New(color.FgGreen))
|
||||
|
||||
// Get the alias parameter from cli
|
||||
args := ctx.Args()
|
||||
aliasedURL := args.Get(0)
|
||||
|
||||
policy, e := os.ReadFile(args.Get(2))
|
||||
fatalIf(probe.NewError(e).Trace(args...), "Unable to get policy")
|
||||
|
||||
// Create a new MinIO Admin Client
|
||||
client, err := newAdminClient(aliasedURL)
|
||||
fatalIf(err, "Unable to initialize admin connection.")
|
||||
|
||||
fatalIf(probe.NewError(client.AddCannedPolicy(globalContext, args.Get(1), policy)).Trace(args...), "Unable to create new policy")
|
||||
|
||||
printMsg(userPolicyMessage{
|
||||
op: ctx.Command.Name,
|
||||
Policy: args.Get(1),
|
||||
})
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -1,67 +0,0 @@
|
||||
// Copyright (c) 2015-2022 MinIO, Inc.
|
||||
//
|
||||
// This file is part of MinIO Object Storage stack
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"github.com/minio/cli"
|
||||
)
|
||||
|
||||
var adminDetachPolicyFlags = []cli.Flag{
|
||||
cli.StringFlag{
|
||||
Name: "user, u",
|
||||
Usage: "detach policy from user",
|
||||
},
|
||||
cli.StringFlag{
|
||||
Name: "group, g",
|
||||
Usage: "detach policy from group",
|
||||
},
|
||||
}
|
||||
|
||||
var adminPolicyDetachCmd = cli.Command{
|
||||
Name: "detach",
|
||||
Usage: "detach an IAM policy from a user or group",
|
||||
Action: mainAdminPolicyDetach,
|
||||
OnUsageError: onUsageError,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: append(adminDetachPolicyFlags, globalFlags...),
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
{{.HelpName}} [FLAGS] TARGET POLICY [POLICY...] [--user USER | --group GROUP]
|
||||
|
||||
Exactly one of --user or --group is required.
|
||||
|
||||
POLICY:
|
||||
Name of the policy on the MinIO server.
|
||||
|
||||
FLAGS:
|
||||
{{range .VisibleFlags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
1. Detach the "readonly" policy from user "james".
|
||||
{{.Prompt}} {{.HelpName}} myminio readonly --user james
|
||||
2. Detach the "audit-policy" and "acct-policy" policies from group "legal".
|
||||
{{.Prompt}} {{.HelpName}} myminio audit-policy acct-policy --group legal
|
||||
`,
|
||||
}
|
||||
|
||||
// mainAdmihPolicyDetach is the handler for "mc admin policy detach" command.
|
||||
func mainAdminPolicyDetach(ctx *cli.Context) error {
|
||||
return userAttachOrDetachPolicy(ctx, false)
|
||||
}
|
||||
@@ -1,100 +0,0 @@
|
||||
// Copyright (c) 2015-2022 MinIO, Inc.
|
||||
//
|
||||
// This file is part of MinIO Object Storage stack
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/madmin-go/v3"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
)
|
||||
|
||||
var adminPolicyEntitiesFlags = []cli.Flag{
|
||||
cli.StringSliceFlag{
|
||||
Name: "user, u",
|
||||
Usage: "list policies associated with user(s)",
|
||||
},
|
||||
cli.StringSliceFlag{
|
||||
Name: "group, g",
|
||||
Usage: "list policies associated with group(s)",
|
||||
},
|
||||
cli.StringSliceFlag{
|
||||
Name: "policy, p",
|
||||
Usage: "list users or groups associated with policy",
|
||||
},
|
||||
}
|
||||
|
||||
var adminPolicyEntitiesCmd = cli.Command{
|
||||
Name: "entities",
|
||||
Usage: "list policy association entities",
|
||||
Action: mainAdminPolicyEntities,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: append(adminPolicyEntitiesFlags, globalFlags...),
|
||||
OnUsageError: onUsageError,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
{{.HelpName}} [FLAGS] TARGET
|
||||
|
||||
FLAGS:
|
||||
{{range .VisibleFlags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
1. List all entities associated with all policies
|
||||
{{.Prompt}} {{.HelpName}} play/
|
||||
2. List all entities associated with the policies 'finteam-policy' and 'mlteam-policy'
|
||||
{{.Prompt}} {{.HelpName}} play/ --policy finteam-policy --policy mlteam-policy
|
||||
3. List all policies associated with a pair of user entities
|
||||
{{.Prompt}} {{.HelpName}} play/ --user bob --user james
|
||||
4. List all policies associated with a pair of group entities
|
||||
{{.Prompt}} {{.HelpName}} play/ --group auditors --group accounting
|
||||
5. List all entities associated with a policy, group and user
|
||||
{{.Prompt}} {{.HelpName}} play/ \
|
||||
--policy finteam-policy --user bobfisher --group consulting
|
||||
`,
|
||||
}
|
||||
|
||||
// mainAdminPolicyEntities is the handler for "mc admin policy entities" command.
|
||||
func mainAdminPolicyEntities(ctx *cli.Context) error {
|
||||
if len(ctx.Args()) != 1 {
|
||||
showCommandHelpAndExit(ctx, 1)
|
||||
}
|
||||
|
||||
usersToQuery := ctx.StringSlice("user")
|
||||
groupsToQuery := ctx.StringSlice("group")
|
||||
policiesToQuery := ctx.StringSlice("policy")
|
||||
|
||||
args := ctx.Args()
|
||||
|
||||
aliasedURL := args.Get(0)
|
||||
|
||||
// Create a new MinIO Admin Client
|
||||
client, err := newAdminClient(aliasedURL)
|
||||
fatalIf(err, "Unable to initialize admin connection.")
|
||||
|
||||
res, e := client.GetPolicyEntities(globalContext,
|
||||
madmin.PolicyEntitiesQuery{
|
||||
Users: usersToQuery,
|
||||
Groups: groupsToQuery,
|
||||
Policy: policiesToQuery,
|
||||
})
|
||||
fatalIf(probe.NewError(e), "Unable to fetch policy entities")
|
||||
|
||||
printMsg(policyEntitiesFrom(res))
|
||||
return nil
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user