Compare commits
346
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
77f82e18b5 | ||
|
|
ed0b962588 | ||
|
|
7394ce0dd2 | ||
|
|
b01f0c7371 | ||
|
|
5bb5df85e2 | ||
|
|
ae1eab7d52 | ||
|
|
ee72571936 | ||
|
|
e5d2270535 | ||
|
|
2676e50bc1 | ||
|
|
f72d75db5a | ||
|
|
c305d62fd5 | ||
|
|
4e38f39e25 | ||
|
|
8576e735b1 | ||
|
|
9a180cece7 | ||
|
|
039be57dd2 | ||
|
|
3c9df3f2ea | ||
|
|
00fb114bce | ||
|
|
68f1d43f05 | ||
|
|
f71ad84bcf | ||
|
|
99c1b4365a | ||
|
|
18c1c94d85 | ||
|
|
b9f30231ca | ||
|
|
19d87ba475 | ||
|
|
bbfe579fef | ||
|
|
2c1e058767 | ||
|
|
0a686cf874 | ||
|
|
719f121225 | ||
|
|
b00526b153 | ||
|
|
391616f9cf | ||
|
|
ddda0fce2c | ||
|
|
0b4d69bc57 | ||
|
|
e929f89cee | ||
|
|
56f94fd375 | ||
|
|
2d305ce990 | ||
|
|
3296636c25 | ||
|
|
5349af0082 | ||
|
|
ceb07bee89 | ||
|
|
5ce725ba7d | ||
|
|
c652022dab | ||
|
|
d249b65941 | ||
|
|
b2d265dcc6 | ||
|
|
0f061900ee | ||
|
|
cf909e1063 | ||
|
|
c1d5d4cbb4 | ||
|
|
b3a00e0f8c | ||
|
|
06520070bb | ||
|
|
ce874fdc6a | ||
|
|
1e412f58a5 | ||
|
|
b0f40b4db7 | ||
|
|
10035268c4 | ||
|
|
9eb205cb62 | ||
|
|
0ba848a99e | ||
|
|
28909abaa4 | ||
|
|
383560b1c3 | ||
|
|
8585339d12 | ||
|
|
468ab39f41 | ||
|
|
217d92358b | ||
|
|
c32317ef80 | ||
|
|
089f833ce0 | ||
|
|
42b78ded3a | ||
|
|
147e8f5b3b | ||
|
|
e97f4324d5 | ||
|
|
859c5989a1 | ||
|
|
10c50368c5 | ||
|
|
bd925c01a1 | ||
|
|
030c8125eb | ||
|
|
6376279f15 | ||
|
|
5aee0b1c9e | ||
|
|
8d713ff927 | ||
|
|
318e707071 | ||
|
|
423ef1ba2a | ||
|
|
a4f20fe74c | ||
|
|
5cfac09600 | ||
|
|
b436cd2436 | ||
|
|
0019b7b83c | ||
|
|
cc8758c88d | ||
|
|
95e1f70eb5 | ||
|
|
b1a3941f22 | ||
|
|
147852cb37 | ||
|
|
bf7b5f620e | ||
|
|
f4dd5e4a07 | ||
|
|
19017536cc | ||
|
|
86907df91d | ||
|
|
1681e4497c | ||
|
|
35cb4b8177 | ||
|
|
bb4ff4951a | ||
|
|
308a8ea9d0 | ||
|
|
63eb4a4609 | ||
|
|
6ac18619cf | ||
|
|
95a03f54da | ||
|
|
9f4659884d | ||
|
|
a814b5deaf | ||
|
|
65aa514dfa | ||
|
|
d9b81b2956 | ||
|
|
2c4e3ad46b | ||
|
|
bad9b2c737 | ||
|
|
e20dea646f | ||
|
|
cf128de2cf | ||
|
|
07eeb10c06 | ||
|
|
ce0b434152 | ||
|
|
4616d11c20 | ||
|
|
609f32a4ff | ||
|
|
97fe232a9a | ||
|
|
a5a54b4429 | ||
|
|
be874766a7 | ||
|
|
3dac3d392f | ||
|
|
11ebe952ea | ||
|
|
37095dadcc | ||
|
|
41aca25f6c | ||
|
|
bbfe577d2e | ||
|
|
04c5116c9b | ||
|
|
f2d65b6c18 | ||
|
|
3092b6bf14 | ||
|
|
25ea06308f | ||
|
|
54268c4808 | ||
|
|
ba97441b5e | ||
|
|
efc60a8a90 | ||
|
|
a55d9a8d17 | ||
|
|
6801d70e55 | ||
|
|
2e10255b6d | ||
|
|
efa1b396f2 | ||
|
|
aca5c185fe | ||
|
|
690f3f8bb3 | ||
|
|
2c94b8d039 | ||
|
|
456709a2a4 | ||
|
|
479171e7be | ||
|
|
b34cd742cb | ||
|
|
21ab58a03f | ||
|
|
32b7b72193 | ||
|
|
e7d1e97852 | ||
|
|
d6886b33d2 | ||
|
|
487b874a2e | ||
|
|
58f15fca83 | ||
|
|
a56899e13c | ||
|
|
3cb570ff56 | ||
|
|
28d64f224a | ||
|
|
f0d2ad4708 | ||
|
|
6a06daa1de | ||
|
|
8ad22bb694 | ||
|
|
73e614aee9 | ||
|
|
58c42bc91b | ||
|
|
f6df01d750 | ||
|
|
ded36374e8 | ||
|
|
11034f9de1 | ||
|
|
4d498deb35 | ||
|
|
ddfd44cb35 | ||
|
|
ea33d018ca | ||
|
|
21d3ec0089 | ||
|
|
661e19b3b2 | ||
|
|
d6ff970125 | ||
|
|
26680ab77c | ||
|
|
7e4b64d12a | ||
|
|
74032bc16a | ||
|
|
bbdd9638f2 | ||
|
|
e0d2e95984 | ||
|
|
f5b325d9d3 | ||
|
|
6811427b8b | ||
|
|
3548007d5b | ||
|
|
dda9e96887 | ||
|
|
8876275c07 | ||
|
|
b72bd7992c | ||
|
|
a289dae750 | ||
|
|
adaf70c7eb | ||
|
|
e7c9a733c6 | ||
|
|
a472e3d9ed | ||
|
|
7a0a8f54d9 | ||
|
|
e44a1c612d | ||
|
|
17adf0abbb | ||
|
|
0bd92d778e | ||
|
|
3997483ce7 | ||
|
|
3cfa8642fd | ||
|
|
5040e61400 | ||
|
|
3774027cea | ||
|
|
ac55cd1023 | ||
|
|
a8fdcbe7cb | ||
|
|
d4b7b00d73 | ||
|
|
b46cf3c417 | ||
|
|
900235c14b | ||
|
|
1b890948e8 | ||
|
|
fdb36acbb1 | ||
|
|
0d8c4f8aa8 | ||
|
|
a96123be2e | ||
|
|
5378c957f5 | ||
|
|
45ae31533d | ||
|
|
62b110408f | ||
|
|
2fb9e21122 | ||
|
|
646712d5e5 | ||
|
|
b471de8d18 | ||
|
|
b317d0d63d | ||
|
|
dcb911bed9 | ||
|
|
9fad66d824 | ||
|
|
5b7b222371 | ||
|
|
4a3f5899c6 | ||
|
|
770097b64f | ||
|
|
afd408284e | ||
|
|
5dfaa31d67 | ||
|
|
2ed4cd91a7 | ||
|
|
e59e453a14 | ||
|
|
bc47cebd91 | ||
|
|
3ec030eb26 | ||
|
|
58a9cb37ec | ||
|
|
fe58afcd39 | ||
|
|
e701bce12c | ||
|
|
76c3674200 | ||
|
|
6bac84d281 | ||
|
|
0b13328b3a | ||
|
|
0e3d1d50bf | ||
|
|
9f8147bf0e | ||
|
|
f740a6d40b | ||
|
|
206d017878 | ||
|
|
89d742a76d | ||
|
|
7bac47fe04 | ||
|
|
9043bbf545 | ||
|
|
795ed1eb49 | ||
|
|
2508db9c56 | ||
|
|
53f59667f6 | ||
|
|
1ec55a5178 | ||
|
|
6302f888a5 | ||
|
|
33a43e9c6e | ||
|
|
daf5b18e18 | ||
|
|
98af07b69c | ||
|
|
66daa906eb | ||
|
|
c2bf38f647 | ||
|
|
94cf5edf7a | ||
|
|
f17313e7ab | ||
|
|
744dc910d8 | ||
|
|
403bf6bc3a | ||
|
|
e6288fa5f3 | ||
|
|
5ff2208a2d | ||
|
|
e7ef65e655 | ||
|
|
8156961333 | ||
|
|
1e69c2aadd | ||
|
|
7d5e4ed56d | ||
|
|
6bb045a5e6 | ||
|
|
1466ae7b50 | ||
|
|
669cb0a9a4 | ||
|
|
62b12a2770 | ||
|
|
e21762b5a7 | ||
|
|
1274167567 | ||
|
|
12f446e1de | ||
|
|
ba9fc6a307 | ||
|
|
9a5ef7c56d | ||
|
|
1d42ad0df6 | ||
|
|
ffade16689 | ||
|
|
ffa7a67bcf | ||
|
|
1ff6818938 | ||
|
|
bb25267eaa | ||
|
|
1edb08e74f | ||
|
|
7484802005 | ||
|
|
799ded568d | ||
|
|
2552dbf55e | ||
|
|
bf2d21809a | ||
|
|
d4305a5bf9 | ||
|
|
74e889f95b | ||
|
|
7f1da50991 | ||
|
|
59eca9fea8 | ||
|
|
bad0ad9dfb | ||
|
|
0ffee47910 | ||
|
|
370b7483b1 | ||
|
|
5386533bb9 | ||
|
|
f88eb55911 | ||
|
|
176f657e53 | ||
|
|
c27ddd4adf | ||
|
|
fb5dd2588c | ||
|
|
8e1573ec1b | ||
|
|
60286667cc | ||
|
|
9ad4ee9d08 | ||
|
|
c0462e64b2 | ||
|
|
34be0ed96a | ||
|
|
28f44cb9a0 | ||
|
|
8da737f8fd | ||
|
|
1facc1eef5 | ||
|
|
f78f391f8b | ||
|
|
bb65ba8874 | ||
|
|
1ba9435365 | ||
|
|
1e2c5cec0a | ||
|
|
d920e2b34b | ||
|
|
f5f7147b9e | ||
|
|
b7a7b05395 | ||
|
|
59e0e56b21 | ||
|
|
5e6ae2172e | ||
|
|
2178568417 | ||
|
|
16709e4bbc | ||
|
|
56d84e64b1 | ||
|
|
937b34616f | ||
|
|
d8342b68a0 | ||
|
|
fe05b5bb42 | ||
|
|
4724c024c6 | ||
|
|
6c9cdc27bc | ||
|
|
c3ebf165ee | ||
|
|
5124a01ae7 | ||
|
|
8c8e625217 | ||
|
|
b1d4341fcb | ||
|
|
d3773744a6 | ||
|
|
56803d2167 | ||
|
|
6829c3fabc | ||
|
|
7db80b6ad9 | ||
|
|
a5adf14769 | ||
|
|
011c61b254 | ||
|
|
b7dc9cc724 | ||
|
|
9f2fb2b6a9 | ||
|
|
b82f6c60b2 | ||
|
|
01df0ff497 | ||
|
|
c1f61a1e06 | ||
|
|
dae819544b | ||
|
|
1bcbe9019d | ||
|
|
b798764785 | ||
|
|
75e722216a | ||
|
|
39a57a14b8 | ||
|
|
2678c2c8e5 | ||
|
|
97cc12fdc5 | ||
|
|
0440badc41 | ||
|
|
2c6ae7d1f7 | ||
|
|
eb6f304e2e | ||
|
|
d2a2bdb07b | ||
|
|
903a1f202c | ||
|
|
062f28c9cc | ||
|
|
377b71641b | ||
|
|
fb8a20a780 | ||
|
|
d158b9a478 | ||
|
|
54d12e95bd | ||
|
|
87d6cd2d4f | ||
|
|
32311bb933 | ||
|
|
0793ce767b | ||
|
|
eca8310ac8 | ||
|
|
4be483de6d | ||
|
|
67fa4aa7a3 | ||
|
|
d8ace59107 | ||
|
|
d47a2ba53a | ||
|
|
86d5b64ffa | ||
|
|
1a65176cee | ||
|
|
103272612a | ||
|
|
c3c899c365 | ||
|
|
618512cc92 | ||
|
|
21ee2bd432 | ||
|
|
ae05d45173 | ||
|
|
38b8665e9e | ||
|
|
79df949087 | ||
|
|
f551d4b14d | ||
|
|
3adb6c93fd | ||
|
|
f36429be69 | ||
|
|
e561bc770e | ||
|
|
9dcef8825f | ||
|
|
e088bd45a9 | ||
|
|
e2056fb057 | ||
|
|
5a5a9973c3 |
@@ -1,6 +1,6 @@
|
||||
## 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).
|
||||
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.
|
||||
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
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
|
||||
@@ -3,7 +3,7 @@ name: Go
|
||||
on:
|
||||
pull_request:
|
||||
branches:
|
||||
- master
|
||||
- master
|
||||
|
||||
# This ensures that previous jobs for the PR are canceled when the PR is
|
||||
# updated.
|
||||
@@ -19,17 +19,17 @@ jobs:
|
||||
GO111MODULE: on
|
||||
strategy:
|
||||
matrix:
|
||||
go-version: [1.21.x]
|
||||
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@v1
|
||||
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@v1
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Build on ${{ matrix.os }}
|
||||
if: matrix.os == 'windows-latest'
|
||||
@@ -49,6 +49,9 @@ jobs:
|
||||
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
|
||||
@@ -57,7 +60,7 @@ jobs:
|
||||
make
|
||||
make test-race
|
||||
make verify
|
||||
make crosscompile
|
||||
./functional-tests.sh
|
||||
vetchecks: # Run vet checks against one version.
|
||||
env:
|
||||
CGO_ENABLED: 0
|
||||
@@ -66,7 +69,7 @@ jobs:
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@v2
|
||||
with:
|
||||
go-version: 1.21.x
|
||||
go-version: 1.24.x
|
||||
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v2
|
||||
@@ -74,6 +77,3 @@ jobs:
|
||||
- name: Test 386
|
||||
run: GOOS=linux GOARCH=386 go test -short ./...
|
||||
|
||||
- name: Staticcheck
|
||||
# Run with defaults, but allow errors with other formats ST1005
|
||||
run: go install honnef.co/go/tools/cmd/staticcheck@latest && staticcheck -tests=false -checks="all,-ST1000,-ST1003,-ST1016,-ST1020,-ST1021,-ST1022,-ST1023,-ST1005" ./...
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
# @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 }}
|
||||
@@ -2,25 +2,24 @@ name: VulnCheck
|
||||
on:
|
||||
pull_request:
|
||||
branches:
|
||||
- master
|
||||
- master
|
||||
push:
|
||||
branches:
|
||||
- master
|
||||
- master
|
||||
jobs:
|
||||
vulncheck:
|
||||
name: Analysis
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Check out code into the Go module directory
|
||||
uses: actions/checkout@v3
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@v3
|
||||
with:
|
||||
go-version: 1.21.0
|
||||
check-latest: true
|
||||
- name: Get official govulncheck
|
||||
run: go install golang.org/x/vuln/cmd/govulncheck@latest
|
||||
shell: bash
|
||||
- name: Run govulncheck
|
||||
run: govulncheck ./...
|
||||
shell: bash
|
||||
- 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
-1
@@ -13,4 +13,6 @@ mc
|
||||
.idea/
|
||||
mc.RELEASE*
|
||||
mc.gz
|
||||
.DS_Store
|
||||
.DS_Store
|
||||
.vscode/
|
||||
.bin/
|
||||
|
||||
+37
-32
@@ -1,37 +1,42 @@
|
||||
version: "2"
|
||||
linters:
|
||||
disable-all: true
|
||||
default: none
|
||||
enable:
|
||||
- typecheck
|
||||
- goimports
|
||||
- misspell
|
||||
- govet
|
||||
- revive
|
||||
- ineffassign
|
||||
- gomodguard
|
||||
- gofmt
|
||||
- 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
|
||||
|
||||
linters-settings:
|
||||
golint:
|
||||
min-confidence: 0
|
||||
|
||||
misspell:
|
||||
locale: US
|
||||
|
||||
gofumpt:
|
||||
lang-version: "1.17"
|
||||
|
||||
# Choose whether or not to use the extra rules that are disabled
|
||||
# by default
|
||||
extra-rules: false
|
||||
|
||||
issues:
|
||||
exclude-use-default: false
|
||||
exclude:
|
||||
- instead of using struct literal
|
||||
- should have a package comment
|
||||
- error strings should not be capitalized or end with punctuation or a newline
|
||||
|
||||
service:
|
||||
golangci-lint-version: 1.43.0 # use the fixed version to not introduce new linters unexpectedly
|
||||
- goimports
|
||||
exclusions:
|
||||
generated: lax
|
||||
paths:
|
||||
- third_party$
|
||||
- builtin$
|
||||
- examples$
|
||||
|
||||
+1
-1
@@ -6,7 +6,7 @@ $ cd $GOPATH/src/github.com/minio
|
||||
$ git clone https://github.com/$USER_ID/mc
|
||||
$ cd mc
|
||||
$ make
|
||||
$ mc --help
|
||||
$ ./mc --help
|
||||
```
|
||||
|
||||
### Developer Guidelines
|
||||
|
||||
+11
-16
@@ -1,27 +1,22 @@
|
||||
FROM golang:1.19-alpine as builder
|
||||
FROM golang:1.22-alpine as build
|
||||
|
||||
LABEL maintainer="MinIO Inc <dev@min.io>"
|
||||
|
||||
ENV GOPATH /go
|
||||
ENV CGO_ENABLED 0
|
||||
ENV GO111MODULE on
|
||||
|
||||
RUN \
|
||||
apk add --no-cache git && \
|
||||
git clone https://github.com/minio/mc && cd mc && \
|
||||
go install -v -ldflags "$(go run buildscripts/gen-ldflags.go)"
|
||||
|
||||
FROM registry.access.redhat.com/ubi8/ubi-minimal:8.8
|
||||
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"
|
||||
|
||||
ARG TARGETARCH
|
||||
FROM scratch
|
||||
|
||||
COPY --from=builder /go/bin/mc /usr/bin/mc
|
||||
COPY --from=builder /go/mc/CREDITS /licenses/CREDITS
|
||||
COPY --from=builder /go/mc/LICENSE /licenses/LICENSE
|
||||
|
||||
RUN \
|
||||
microdnf update --nodocs && \
|
||||
microdnf install ca-certificates --nodocs && \
|
||||
microdnf clean all
|
||||
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"]
|
||||
|
||||
+2
-2
@@ -7,8 +7,8 @@ COPY CREDITS /licenses/CREDITS
|
||||
COPY LICENSE /licenses/LICENSE
|
||||
|
||||
RUN \
|
||||
microdnf update --nodocs && \
|
||||
microdnf install ca-certificates --nodocs && \
|
||||
microdnf update --nodocs --assumeyes && \
|
||||
microdnf install ca-certificates --nodocs --assumeyes && \
|
||||
microdnf clean all
|
||||
|
||||
ENTRYPOINT ["mc"]
|
||||
|
||||
+14
-7
@@ -1,17 +1,24 @@
|
||||
FROM registry.access.redhat.com/ubi8/ubi-minimal:8.8
|
||||
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
|
||||
|
||||
RUN \
|
||||
microdnf update --nodocs && \
|
||||
microdnf install curl ca-certificates shadow-utils --nodocs && \
|
||||
microdnf clean all && \
|
||||
curl -s -q https://dl.min.io/client/mc/hotfixes/linux-amd64/archive/mc.${RELEASE} -o /usr/bin/mc && \
|
||||
chmod +x /usr/bin/mc
|
||||
ADD https://dl.min.io/client/mc/hotfixes/linux-${TARGETARCH}/archive/mc.${RELEASE} /usr/bin/mc
|
||||
|
||||
RUN chmod +x /usr/bin/mc
|
||||
|
||||
ENTRYPOINT ["mc"]
|
||||
|
||||
+13
-8
@@ -1,19 +1,24 @@
|
||||
FROM registry.access.redhat.com/ubi8/ubi-minimal:8.8
|
||||
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
|
||||
|
||||
RUN \
|
||||
microdnf update --nodocs && \
|
||||
microdnf install curl ca-certificates shadow-utils util-linux gzip lsof tar net-tools jq --nodocs && \
|
||||
microdnf clean all && \
|
||||
curl -s -q https://dl.minio.io/client/mc/release/linux-${TARGETARCH}/archive/mc.${RELEASE} -o /usr/bin/mc && \
|
||||
chmod +x /usr/bin/mc
|
||||
ADD https://dl.minio.io/client/mc/release/linux-${TARGETARCH}/archive/mc.${RELEASE} /usr/bin/mc
|
||||
|
||||
RUN chmod +x /usr/bin/mc
|
||||
|
||||
ENTRYPOINT ["mc"]
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
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"]
|
||||
@@ -2,12 +2,14 @@ PWD := $(shell pwd)
|
||||
GOPATH := $(shell go env GOPATH)
|
||||
LDFLAGS := $(shell go run buildscripts/gen-ldflags.go)
|
||||
|
||||
GOARCH := $(shell go env GOARCH)
|
||||
GOOS := $(shell go env GOOS)
|
||||
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:
|
||||
@@ -16,9 +18,7 @@ checks:
|
||||
|
||||
getdeps:
|
||||
@mkdir -p ${GOPATH}/bin
|
||||
@echo "Installing golangci-lint" && curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(GOPATH)/bin
|
||||
@echo "Installing stringer" && go install -v golang.org/x/tools/cmd/stringer@latest
|
||||
@echo "Installing staticheck" && go install honnef.co/go/tools/cmd/staticcheck@latest
|
||||
@echo "Installing tools" && go install tool
|
||||
|
||||
crosscompile:
|
||||
@(env bash $(PWD)/buildscripts/cross-compile.sh)
|
||||
@@ -32,10 +32,13 @@ vet:
|
||||
@echo "Running $@"
|
||||
@GO111MODULE=on go vet github.com/minio/mc/...
|
||||
|
||||
lint:
|
||||
lint-fix: getdeps ## runs golangci-lint suite of linters with automatic fixes
|
||||
@echo "Running $@ check"
|
||||
@GO111MODULE=on ${GOPATH}/bin/golangci-lint run --timeout=5m --config ./.golangci.yml
|
||||
@GO111MODULE=on ${GOPATH}/bin/staticcheck -tests=false -checks="all,-ST1000,-ST1003,-ST1016,-ST1020,-ST1021,-ST1022,-ST1023,-ST1005" ./...
|
||||
@$(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
|
||||
@@ -43,7 +46,7 @@ test: verifiers build
|
||||
@echo "Running unit tests"
|
||||
@GO111MODULE=on CGO_ENABLED=0 go test -tags kqueue ./... 1>/dev/null
|
||||
@echo "Running functional tests"
|
||||
@(env bash $(PWD)/functional-tests.sh)
|
||||
@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"
|
||||
@@ -54,12 +57,12 @@ 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"
|
||||
@(env bash $(PWD)/functional-tests.sh)
|
||||
@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 CGO_ENABLED=0 go build -trimpath -tags kqueue --ldflags "$(LDFLAGS)" -o $(PWD)/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 | \
|
||||
@@ -73,9 +76,9 @@ hotfix: hotfix-vars install ## builds mc binary with hotfix tags
|
||||
@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/linux-amd64/archive/
|
||||
@scp -q -r mc.$(VERSION)* minio@dl-1.min.io:~/releases/client/mc/hotfixes/linux-amd64/archive/
|
||||
@echo "Published new hotfix binaries at https://dl.min.io/client/mc/hotfixes/linux-amd64/archive/mc.$(VERSION)"
|
||||
@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)"
|
||||
|
||||
@@ -1,41 +1,53 @@
|
||||
# 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 set, remove and list aliases in configuration file
|
||||
ls list buckets and objects
|
||||
mb make a bucket
|
||||
rb remove a bucket
|
||||
cp copy objects
|
||||
mirror synchronize object(s) to a remote site
|
||||
cat display object contents
|
||||
head display first 'n' lines of an object
|
||||
pipe stream STDIN to an object
|
||||
share generate URL for temporary access to an object
|
||||
find search for objects
|
||||
sql run sql queries on objects
|
||||
stat show object metadata
|
||||
mv move objects
|
||||
tree list buckets and objects in a tree format
|
||||
du summarize disk usage recursively
|
||||
retention set retention for object(s)
|
||||
legalhold set legal hold for object(s)
|
||||
diff list differences in object name, size, and date between two buckets
|
||||
rm remove objects
|
||||
encrypt manage bucket encryption config
|
||||
event manage object notifications
|
||||
watch listen for object notification events
|
||||
undo undo PUT/DELETE operations
|
||||
anonymous manage anonymous access to buckets and objects
|
||||
tag manage tags for bucket(s) and object(s)
|
||||
ilm manage bucket lifecycle
|
||||
version manage bucket versioning
|
||||
replicate configure server side bucket replication
|
||||
admin manage MinIO servers
|
||||
update update mc to latest release
|
||||
ping perform liveness check
|
||||
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
|
||||
@@ -88,7 +100,9 @@ mc --help
|
||||
| Platform | Architecture | URL |
|
||||
| ---------- | -------- |------|
|
||||
|GNU/Linux|64-bit Intel|https://dl.min.io/client/mc/release/linux-amd64/mc |
|
||||
||64-bit PPC|https://dl.min.io/client/mc/release/linux-ppc64le/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
|
||||
@@ -107,7 +121,7 @@ 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.17](https://golang.org/dl/#stable)
|
||||
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
|
||||
@@ -174,9 +188,6 @@ Get your AccessKeyID and SecretAccessKey by following [Google Credentials Guide]
|
||||
mc alias set gcs https://storage.googleapis.com BKIKJAA5BMMU2RHO6IBB V8f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12
|
||||
```
|
||||
|
||||
### Example - IBM Cloud Object Storage
|
||||
See [the complete guide](docs/minio-client-complete-guide.md) for IBM instructions.
|
||||
|
||||
## 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.
|
||||
|
||||
@@ -234,11 +245,6 @@ admin config diff find ls mirror policy session sql
|
||||
cat cp event head mb pipe rm share stat version
|
||||
```
|
||||
|
||||
## Explore Further
|
||||
- [MinIO Client Complete Guide](https://min.io/docs/minio/linux/reference/minio-mc.html?ref=gh)
|
||||
- [MinIO Quickstart Guide](https://min.io/docs/minio/linux/index.html#quickstart-for-linux?ref=gh)
|
||||
- [The MinIO documentation website](https://min.io/docs/minio/linux/index.html?ref=gh)
|
||||
|
||||
## Contribute to MinIO Project
|
||||
Please follow MinIO [Contributor's Guide](https://github.com/minio/mc/blob/master/CONTRIBUTING.md)
|
||||
|
||||
|
||||
+3
-3
@@ -165,9 +165,9 @@ cat cp events mb pipe rm share version
|
||||
```
|
||||
|
||||
## 了解更多
|
||||
- [MinIO Client完全指南](https://min.io/docs/minio/linux/reference/minio-mc.html?ref=gh)
|
||||
- [MinIO快速入门](https://min.io/docs/minio/linux/index.html#quickstart-for-linux?ref=gh)
|
||||
- [MinIO官方文档](https://min.io/docs/minio/linux/index.html?ref=gh)
|
||||
- [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)
|
||||
|
||||
@@ -28,7 +28,7 @@ function _init() {
|
||||
export CGO_ENABLED=0
|
||||
|
||||
## List of architectures and OS to test coss compilation.
|
||||
SUPPORTED_OSARCH="linux/ppc64le linux/mips64 linux/arm64 linux/s390x darwin/arm64 darwin/amd64 freebsd/amd64 windows/amd64 linux/arm linux/386 netbsd/amd64 linux/mips openbsd/amd64"
|
||||
SUPPORTED_OSARCH="linux/ppc64le linux/s390x linux/mips64 linux/amd64 windows/amd64 darwin/amd64 darwin/arm64 linux/arm64 linux/arm"
|
||||
}
|
||||
|
||||
function _build() {
|
||||
|
||||
+31
-2
@@ -17,7 +17,12 @@
|
||||
|
||||
package cmd
|
||||
|
||||
import "path/filepath"
|
||||
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 {
|
||||
@@ -29,7 +34,31 @@ func (b accessPerms) isValidAccessPERM() bool {
|
||||
}
|
||||
|
||||
func (b accessPerms) isValidAccessFile() bool {
|
||||
return filepath.Ext(string(b)) == ".json"
|
||||
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.
|
||||
|
||||
+55
-16
@@ -18,11 +18,14 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"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"
|
||||
@@ -32,7 +35,7 @@ import (
|
||||
type accounter struct {
|
||||
current int64
|
||||
|
||||
Total int64
|
||||
total int64
|
||||
startTime time.Time
|
||||
startValue int64
|
||||
refreshRate time.Duration
|
||||
@@ -44,7 +47,7 @@ type accounter struct {
|
||||
// Instantiate a new accounter.
|
||||
func newAccounter(total int64) *accounter {
|
||||
acct := &accounter{
|
||||
Total: total,
|
||||
total: total,
|
||||
startTime: time.Now(),
|
||||
startValue: 0,
|
||||
refreshRate: time.Millisecond * 200,
|
||||
@@ -56,14 +59,14 @@ func newAccounter(total int64) *accounter {
|
||||
}
|
||||
|
||||
// write calculate the final speed.
|
||||
func (a *accounter) write(current int64) float64 {
|
||||
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
|
||||
return speed, fromStart
|
||||
}
|
||||
return 0.0
|
||||
return 0.0, 0
|
||||
}
|
||||
|
||||
// writer update new accounting data for a specified refreshRate.
|
||||
@@ -81,10 +84,11 @@ func (a *accounter) writer() {
|
||||
|
||||
// accountStat cantainer for current stats captured.
|
||||
type accountStat struct {
|
||||
Status string `json:"status"`
|
||||
Total int64 `json:"total"`
|
||||
Transferred int64 `json:"transferred"`
|
||||
Speed float64 `json:"speed"`
|
||||
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 {
|
||||
@@ -96,15 +100,42 @@ func (c accountStat) JSON() string {
|
||||
}
|
||||
|
||||
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"
|
||||
}
|
||||
message := fmt.Sprintf("Total: %s, Transferred: %s, Speed: %s", pb.Format(c.Total).To(pb.U_BYTES),
|
||||
pb.Format(c.Transferred).To(pb.U_BYTES), speedBox)
|
||||
return message
|
||||
|
||||
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.
|
||||
@@ -112,9 +143,9 @@ func (a *accounter) Stat() accountStat {
|
||||
var acntStat accountStat
|
||||
a.finishOnce.Do(func() {
|
||||
close(a.isFinished)
|
||||
acntStat.Total = a.Total
|
||||
acntStat.Total = a.total
|
||||
acntStat.Transferred = atomic.LoadInt64(&a.current)
|
||||
acntStat.Speed = a.write(atomic.LoadInt64(&a.current))
|
||||
acntStat.Speed, acntStat.Duration = a.write(atomic.LoadInt64(&a.current))
|
||||
})
|
||||
return acntStat
|
||||
}
|
||||
@@ -139,7 +170,8 @@ func (a *accounter) Get() int64 {
|
||||
return atomic.LoadInt64(&a.current)
|
||||
}
|
||||
|
||||
func (a *accounter) SetTotal(int64) {
|
||||
func (a *accounter) SetTotal(n int64) {
|
||||
atomic.StoreInt64(&a.total, n)
|
||||
}
|
||||
|
||||
// Add add to current value atomically.
|
||||
@@ -149,6 +181,13 @@ func (a *accounter) Add(n int64) int64 {
|
||||
|
||||
// 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
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
// 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)
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
// 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)
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
// 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)
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
// 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)
|
||||
}
|
||||
@@ -0,0 +1,202 @@
|
||||
// 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
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
// 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
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
// 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)
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
// 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
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
// 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
|
||||
}
|
||||
@@ -31,7 +31,6 @@ var adminBucketInfoCmd = cli.Command{
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: append(adminBucketInfoFlags, globalFlags...),
|
||||
HideHelpCommand: true,
|
||||
Hidden: true,
|
||||
}
|
||||
|
||||
// mainAdminBucketInfo is the handler for "mc admin bucket info" command.
|
||||
|
||||
@@ -40,7 +40,6 @@ var adminBucketQuotaCmd = cli.Command{
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: append(adminQuotaFlags, globalFlags...),
|
||||
HideHelpCommand: true,
|
||||
Hidden: true,
|
||||
}
|
||||
|
||||
// mainAdminBucketQuota is the handler for "mc admin bucket quota" command.
|
||||
|
||||
@@ -28,7 +28,6 @@ var adminBucketRemoteAddCmd = cli.Command{
|
||||
OnUsageError: onUsageError,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
Hidden: true,
|
||||
HideHelp: true,
|
||||
}
|
||||
|
||||
|
||||
@@ -25,10 +25,10 @@ func TestGetBandwidthInBytes(t *testing.T) {
|
||||
type args struct {
|
||||
bandwidthStr string
|
||||
}
|
||||
f1 := 999.123457 * 1024 * 1024 / 8
|
||||
f2 := 10.123456790 * 1024 * 1024 * 1024 / 8
|
||||
f3 := 10000.123456790 * 1024 * 1024 * 1024 / 8
|
||||
f4 := (0.001*1024*1024*1024 + 1) / 8 // round up
|
||||
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
|
||||
@@ -39,66 +39,66 @@ func TestGetBandwidthInBytes(t *testing.T) {
|
||||
args: args{
|
||||
bandwidthStr: "1Mi",
|
||||
},
|
||||
want: 1024 * 1024 / 8,
|
||||
want: 1024 * 1024,
|
||||
},
|
||||
{
|
||||
name: "1MegaBit",
|
||||
args: args{
|
||||
bandwidthStr: "1M",
|
||||
},
|
||||
want: 1000000 / 8,
|
||||
},
|
||||
{
|
||||
name: "1GigaBit",
|
||||
args: args{
|
||||
bandwidthStr: "1G",
|
||||
},
|
||||
want: 1000000000 / 8,
|
||||
want: 1000000,
|
||||
},
|
||||
{
|
||||
name: "1GigaByte",
|
||||
args: args{
|
||||
bandwidthStr: "1G",
|
||||
},
|
||||
want: 1000000000,
|
||||
},
|
||||
{
|
||||
name: "1GibiByte",
|
||||
args: args{
|
||||
bandwidthStr: "1Gi",
|
||||
},
|
||||
want: 1024 * 1024 * 1024 / 8,
|
||||
},
|
||||
{
|
||||
name: "FractionalMegaBits",
|
||||
args: args{
|
||||
bandwidthStr: "999.123456789123456789M",
|
||||
},
|
||||
want: 999123457 / 8,
|
||||
},
|
||||
{
|
||||
name: "FractionalGigaBits",
|
||||
args: args{
|
||||
bandwidthStr: "10.123456789123456789123456G",
|
||||
},
|
||||
want: 10123456789 / 8,
|
||||
},
|
||||
{
|
||||
name: "FractionalBigGigaBits",
|
||||
args: args{
|
||||
bandwidthStr: "10000.123456789123456789123456G",
|
||||
},
|
||||
want: 10000123456789 / 8,
|
||||
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: "FractionalGigaBytes",
|
||||
name: "FractionalGibiBytes",
|
||||
args: args{
|
||||
bandwidthStr: "10.123456789123456789123456Gi",
|
||||
},
|
||||
want: uint64(f2),
|
||||
},
|
||||
{
|
||||
name: "FractionalBigGigaBytes",
|
||||
name: "FractionalBigGibiBytes",
|
||||
args: args{
|
||||
bandwidthStr: "10000.123456789123456789123456Gi",
|
||||
},
|
||||
@@ -116,12 +116,11 @@ func TestGetBandwidthInBytes(t *testing.T) {
|
||||
args: args{
|
||||
bandwidthStr: "1024Ki",
|
||||
},
|
||||
want: 1024 * 1024 / 8,
|
||||
want: 1024 * 1024,
|
||||
},
|
||||
}
|
||||
t.Parallel()
|
||||
for _, tt := range tests {
|
||||
tt := tt
|
||||
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)
|
||||
|
||||
@@ -29,7 +29,6 @@ var adminBucketRemoteEditCmd = cli.Command{
|
||||
OnUsageError: onUsageError,
|
||||
Flags: globalFlags,
|
||||
HideHelp: true,
|
||||
Hidden: true,
|
||||
}
|
||||
|
||||
// mainAdminBucketRemoteEdit is the handle for "mc admin bucket remote edit" command.
|
||||
|
||||
@@ -30,7 +30,6 @@ var adminBucketRemoteRmCmd = cli.Command{
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
HideHelp: true,
|
||||
Hidden: true,
|
||||
}
|
||||
|
||||
// mainAdminBucketRemoteRemove is the handle for "mc admin bucket remote rm" command.
|
||||
|
||||
@@ -33,6 +33,7 @@ var adminBucketCmd = cli.Command{
|
||||
Flags: globalFlags,
|
||||
Subcommands: adminBucketSubcommands,
|
||||
HideHelpCommand: true,
|
||||
Hidden: true,
|
||||
}
|
||||
|
||||
// mainAdminBucket is the handle for "mc admin bucket" command.
|
||||
|
||||
@@ -30,7 +30,7 @@ import (
|
||||
"github.com/minio/cli"
|
||||
json "github.com/minio/colorjson"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/pkg/console"
|
||||
"github.com/minio/pkg/v3/console"
|
||||
)
|
||||
|
||||
var adminClusterBucketExportCmd = cli.Command{
|
||||
@@ -119,6 +119,11 @@ func mainClusterBucketExport(ctx *cli.Context) error {
|
||||
}
|
||||
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
|
||||
|
||||
@@ -32,7 +32,7 @@ import (
|
||||
json "github.com/minio/colorjson"
|
||||
"github.com/minio/madmin-go/v3"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/pkg/console"
|
||||
"github.com/minio/pkg/v3/console"
|
||||
)
|
||||
|
||||
var adminClusterBucketImportCmd = cli.Command{
|
||||
@@ -96,6 +96,7 @@ func mainClusterBucketImport(ctx *cli.Context) error {
|
||||
|
||||
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)
|
||||
@@ -141,14 +142,15 @@ func statusTick(s madmin.MetaStatus) string {
|
||||
}
|
||||
|
||||
func (i importMetaMsg) String() string {
|
||||
m := i.BucketMetaImportErrs.Buckets
|
||||
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.Policy.Err != "" || st.Notification.Err != "" ||
|
||||
st.Cors.Err != "" || st.Err != "" {
|
||||
totErrs++
|
||||
}
|
||||
}
|
||||
@@ -168,7 +170,8 @@ func (i importMetaMsg) String() string {
|
||||
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.Policy.Err != "" || st.Notification.Err != "" ||
|
||||
st.Cors.Err != "" || st.Err != "" {
|
||||
fmt.Fprintln(&b, printImportErrs(bucket, st))
|
||||
}
|
||||
}
|
||||
@@ -183,7 +186,7 @@ func (i importMetaMsg) JSON() string {
|
||||
// Disable escaping special chars to display XML tags correctly
|
||||
enc.SetEscapeHTML(false)
|
||||
|
||||
fatalIf(probe.NewError(enc.Encode(i.BucketMetaImportErrs.Buckets)), "Unable to marshal into JSON.")
|
||||
fatalIf(probe.NewError(enc.Encode(i.Buckets)), "Unable to marshal into JSON.")
|
||||
return buf.String()
|
||||
}
|
||||
|
||||
@@ -194,6 +197,10 @@ func printImportErrs(bucket string, r madmin.BucketStatus) string {
|
||||
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)
|
||||
@@ -227,5 +234,9 @@ func printImportErrs(bucket string, r madmin.BucketStatus) string {
|
||||
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()
|
||||
}
|
||||
|
||||
@@ -29,7 +29,17 @@ import (
|
||||
"github.com/minio/cli"
|
||||
json "github.com/minio/colorjson"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/pkg/console"
|
||||
"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{
|
||||
@@ -38,7 +48,7 @@ var adminClusterIAMExportCmd = cli.Command{
|
||||
Action: mainClusterIAMExport,
|
||||
OnUsageError: onUsageError,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
Flags: append(iamExportFlags, globalFlags...),
|
||||
HideHelpCommand: true,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
@@ -52,6 +62,9 @@ FLAGS:
|
||||
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
|
||||
`,
|
||||
}
|
||||
|
||||
@@ -97,6 +110,9 @@ func mainClusterIAMExport(ctx *cli.Context) error {
|
||||
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))
|
||||
@@ -109,6 +125,11 @@ func mainClusterIAMExport(ctx *cli.Context) error {
|
||||
|
||||
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
|
||||
|
||||
@@ -23,11 +23,14 @@ import (
|
||||
"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/console"
|
||||
"github.com/minio/pkg/v3/console"
|
||||
)
|
||||
|
||||
var adminClusterIAMImportCmd = cli.Command{
|
||||
@@ -54,6 +57,123 @@ EXAMPLES:
|
||||
`,
|
||||
}
|
||||
|
||||
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
|
||||
@@ -87,6 +207,7 @@ func mainClusterIAMImport(ctx *cli.Context) error {
|
||||
|
||||
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)
|
||||
@@ -95,11 +216,17 @@ func mainClusterIAMImport(ctx *cli.Context) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
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))
|
||||
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
|
||||
}
|
||||
|
||||
@@ -28,7 +28,7 @@ import (
|
||||
"github.com/minio/cli"
|
||||
json "github.com/minio/colorjson"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/pkg/console"
|
||||
"github.com/minio/pkg/v3/console"
|
||||
)
|
||||
|
||||
var adminConfigExportCmd = cli.Command{
|
||||
|
||||
@@ -29,7 +29,7 @@ import (
|
||||
json "github.com/minio/colorjson"
|
||||
"github.com/minio/madmin-go/v3"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/pkg/console"
|
||||
"github.com/minio/pkg/v3/console"
|
||||
)
|
||||
|
||||
var adminConfigGetCmd = cli.Command{
|
||||
|
||||
@@ -26,7 +26,7 @@ import (
|
||||
"github.com/minio/cli"
|
||||
json "github.com/minio/colorjson"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/pkg/console"
|
||||
"github.com/minio/pkg/v3/console"
|
||||
)
|
||||
|
||||
var historyListFlags = []cli.Flag{
|
||||
@@ -127,7 +127,7 @@ func mainAdminConfigHistory(ctx *cli.Context) error {
|
||||
client, err := newAdminClient(aliasedURL)
|
||||
fatalIf(err, "Unable to initialize admin connection.")
|
||||
|
||||
if ctx.IsSet("clear") {
|
||||
if ctx.Bool("clear") {
|
||||
fatalIf(probe.NewError(client.ClearConfigHistoryKV(globalContext, "all")), "Unable to clear server configuration.")
|
||||
|
||||
// Print
|
||||
|
||||
@@ -25,7 +25,7 @@ import (
|
||||
"github.com/minio/cli"
|
||||
json "github.com/minio/colorjson"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/pkg/console"
|
||||
"github.com/minio/pkg/v3/console"
|
||||
)
|
||||
|
||||
var adminConfigImportCmd = cli.Command{
|
||||
|
||||
@@ -25,7 +25,7 @@ import (
|
||||
"github.com/minio/cli"
|
||||
json "github.com/minio/colorjson"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/pkg/console"
|
||||
"github.com/minio/pkg/v3/console"
|
||||
)
|
||||
|
||||
var adminConfigEnvFlags = []cli.Flag{
|
||||
@@ -116,13 +116,13 @@ func mainAdminConfigReset(ctx *cli.Context) error {
|
||||
|
||||
if len(ctx.Args()) == 1 {
|
||||
// Call get config API
|
||||
hr, e := client.HelpConfigKV(globalContext, "", "", ctx.IsSet("env"))
|
||||
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.IsSet("env"),
|
||||
envOnly: ctx.Bool("env"),
|
||||
})
|
||||
|
||||
return nil
|
||||
|
||||
@@ -24,7 +24,7 @@ import (
|
||||
"github.com/minio/cli"
|
||||
json "github.com/minio/colorjson"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/pkg/console"
|
||||
"github.com/minio/pkg/v3/console"
|
||||
)
|
||||
|
||||
var adminConfigRestoreCmd = cli.Command{
|
||||
|
||||
@@ -26,7 +26,7 @@ import (
|
||||
json "github.com/minio/colorjson"
|
||||
"github.com/minio/madmin-go/v3"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/pkg/console"
|
||||
"github.com/minio/pkg/v3/console"
|
||||
)
|
||||
|
||||
var adminConfigSetCmd = cli.Command{
|
||||
@@ -112,13 +112,13 @@ func mainAdminConfigSet(ctx *cli.Context) error {
|
||||
|
||||
if !strings.Contains(input, madmin.KvSeparator) {
|
||||
// Call get config API
|
||||
hr, e := client.HelpConfigKV(globalContext, args.Get(1), args.Get(2), ctx.IsSet("env"))
|
||||
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.IsSet("env"),
|
||||
envOnly: ctx.Bool("env"),
|
||||
})
|
||||
|
||||
return nil
|
||||
|
||||
@@ -25,7 +25,7 @@ import (
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/madmin-go/v3"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/pkg/console"
|
||||
"github.com/minio/pkg/v3/console"
|
||||
)
|
||||
|
||||
var adminDecommissionCancelCmd = cli.Command{
|
||||
|
||||
@@ -24,7 +24,7 @@ import (
|
||||
"github.com/minio/cli"
|
||||
json "github.com/minio/colorjson"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/pkg/console"
|
||||
"github.com/minio/pkg/v3/console"
|
||||
)
|
||||
|
||||
var adminDecommissionStartCmd = cli.Command{
|
||||
|
||||
@@ -27,7 +27,7 @@ import (
|
||||
"github.com/minio/cli"
|
||||
json "github.com/minio/colorjson"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/pkg/console"
|
||||
"github.com/minio/pkg/v3/console"
|
||||
)
|
||||
|
||||
var adminDecommissionStatusCmd = cli.Command{
|
||||
@@ -125,7 +125,7 @@ func mainAdminDecommissionStatus(ctx *cli.Context) error {
|
||||
}
|
||||
|
||||
dspOrder := []col{colGreen} // Header
|
||||
for i := 0; i < len(poolStatuses); i++ {
|
||||
for range poolStatuses {
|
||||
dspOrder = append(dspOrder, colGrey)
|
||||
}
|
||||
var printColors []*color.Color
|
||||
@@ -139,14 +139,19 @@ func mainAdminDecommissionStatus(ctx *cli.Context) error {
|
||||
cellText[0] = []string{
|
||||
"ID",
|
||||
"Pools",
|
||||
"Capacity",
|
||||
"Drives Usage",
|
||||
"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)"
|
||||
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 {
|
||||
|
||||
@@ -26,7 +26,7 @@ import (
|
||||
json "github.com/minio/colorjson"
|
||||
"github.com/minio/madmin-go/v3"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/pkg/console"
|
||||
"github.com/minio/pkg/v3/console"
|
||||
)
|
||||
|
||||
var adminGroupAddCmd = cli.Command{
|
||||
|
||||
@@ -22,7 +22,7 @@ import (
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/madmin-go/v3"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/pkg/console"
|
||||
"github.com/minio/pkg/v3/console"
|
||||
)
|
||||
|
||||
var adminGroupEnableCmd = cli.Command{
|
||||
|
||||
@@ -21,7 +21,7 @@ import (
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/pkg/console"
|
||||
"github.com/minio/pkg/v3/console"
|
||||
)
|
||||
|
||||
var adminGroupInfoCmd = cli.Command{
|
||||
|
||||
@@ -21,7 +21,7 @@ import (
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/pkg/console"
|
||||
"github.com/minio/pkg/v3/console"
|
||||
)
|
||||
|
||||
var adminGroupListCmd = cli.Command{
|
||||
|
||||
@@ -22,7 +22,7 @@ import (
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/madmin-go/v3"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/pkg/console"
|
||||
"github.com/minio/pkg/v3/console"
|
||||
)
|
||||
|
||||
var adminGroupRemoveCmd = cli.Command{
|
||||
|
||||
@@ -18,6 +18,7 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/minio/madmin-go/v3"
|
||||
@@ -49,21 +50,70 @@ func (h hri) getObjectHCCChange() (b, a col, err error) {
|
||||
}
|
||||
a, err = getHColCode(surplusShardsAfterHeal, parityShards)
|
||||
if err != nil {
|
||||
err = fmt.Errorf("%w: surplusShardsBeforeHeal: %d, parityShards: %d",
|
||||
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
|
||||
quorum := h.DiskCount/h.SetCount/2 + 1
|
||||
surplus := numAvail/h.SetCount - quorum
|
||||
parity := h.DiskCount/h.SetCount - quorum
|
||||
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
|
||||
}
|
||||
|
||||
+27
-17
@@ -29,7 +29,7 @@ import (
|
||||
json "github.com/minio/colorjson"
|
||||
"github.com/minio/madmin-go/v3"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/pkg/console"
|
||||
"github.com/minio/pkg/v3/console"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -52,7 +52,7 @@ var (
|
||||
|
||||
func getHColCode(surplusShards, parityShards int) (c col, err error) {
|
||||
if parityShards < 1 || parityShards > 8 || surplusShards > parityShards {
|
||||
return c, fmt.Errorf("Invalid parity shard count/surplus shard count given")
|
||||
return c, errors.New("Invalid parity shard count/surplus shard count given")
|
||||
}
|
||||
if surplusShards < 0 {
|
||||
return colGrey, err
|
||||
@@ -63,7 +63,7 @@ func getHColCode(surplusShards, parityShards int) (c col, err error) {
|
||||
return hColOrder[index], err
|
||||
}
|
||||
}
|
||||
return c, fmt.Errorf("cannot get a heal color code")
|
||||
return c, errors.New("cannot get a heal color code")
|
||||
}
|
||||
|
||||
type uiData struct {
|
||||
@@ -127,7 +127,9 @@ func (ui *uiData) updateStats(i madmin.HealResultItem) error {
|
||||
var afterCol col
|
||||
h := newHRI(&i)
|
||||
switch h.Type {
|
||||
case madmin.HealItemMetadata, madmin.HealItemBucket:
|
||||
case madmin.HealItemBucket:
|
||||
_, afterCol, err = h.getBucketHCCChange()
|
||||
case madmin.HealItemMetadata, madmin.HealItemBucketMetadata:
|
||||
_, afterCol, err = h.getReplicatedFileHCCChange()
|
||||
default:
|
||||
_, afterCol, err = h.getObjectHCCChange()
|
||||
@@ -205,17 +207,24 @@ func (ui *uiData) printItemsQuietly(s *madmin.HealTaskStatus) (err error) {
|
||||
var b, a col
|
||||
for _, item := range s.Items {
|
||||
h := newHRI(&item)
|
||||
hrStr := h.getHealResultStr()
|
||||
switch h.Type {
|
||||
case madmin.HealItemMetadata, madmin.HealItemBucket:
|
||||
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 {
|
||||
return err
|
||||
errMsg := err.Error()
|
||||
if h.Detail != "" {
|
||||
errMsg = h.Detail
|
||||
}
|
||||
console.PrintC("[ERROR] ** ", hrStr, " **", ": ", errMsg, "\n")
|
||||
continue
|
||||
}
|
||||
printColStr(b, a)
|
||||
hrStr := h.getHealResultStr()
|
||||
switch h.Type {
|
||||
case madmin.HealItemMetadata, madmin.HealItemBucketMetadata:
|
||||
console.PrintC(fmt.Sprintln("**", hrStr, "**"))
|
||||
@@ -240,6 +249,7 @@ 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 {
|
||||
@@ -267,7 +277,9 @@ func (ui *uiData) printItemsJSON(s *madmin.HealTaskStatus) (err error) {
|
||||
var b, a col
|
||||
var err error
|
||||
switch h.Type {
|
||||
case madmin.HealItemMetadata, madmin.HealItemBucket:
|
||||
case madmin.HealItemBucket:
|
||||
b, a, err = h.getBucketHCCChange()
|
||||
case madmin.HealItemMetadata, madmin.HealItemBucketMetadata:
|
||||
b, a, err = h.getReplicatedFileHCCChange()
|
||||
default:
|
||||
if h.Type == madmin.HealItemObject {
|
||||
@@ -278,6 +290,7 @@ func (ui *uiData) printItemsJSON(s *madmin.HealTaskStatus) (err error) {
|
||||
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()
|
||||
@@ -369,7 +382,7 @@ func (ui *uiData) updateUI(s *madmin.HealTaskStatus) (err error) {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (ui *uiData) UpdateDisplay(s *madmin.HealTaskStatus) (err error) {
|
||||
func (ui *uiData) UpdateDisplay(s *madmin.HealTaskStatus) {
|
||||
// Update state
|
||||
ui.updateDuration(s)
|
||||
for _, i := range s.Items {
|
||||
@@ -379,13 +392,12 @@ func (ui *uiData) UpdateDisplay(s *madmin.HealTaskStatus) (err error) {
|
||||
// Update display
|
||||
switch {
|
||||
case globalJSON:
|
||||
err = ui.printItemsJSON(s)
|
||||
ui.printItemsJSON(s)
|
||||
case globalQuiet:
|
||||
err = ui.printItemsQuietly(s)
|
||||
ui.printItemsQuietly(s)
|
||||
default:
|
||||
err = ui.updateUI(s)
|
||||
ui.updateUI(s)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (ui *uiData) healResumeMsg(aliasedURL string) string {
|
||||
@@ -420,10 +432,8 @@ func (ui *uiData) DisplayAndFollowHealStatus(aliasedURL string) (res madmin.Heal
|
||||
console.RewindLines(8)
|
||||
}
|
||||
}
|
||||
err = ui.UpdateDisplay(&res)
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
|
||||
ui.UpdateDisplay(&res)
|
||||
|
||||
if res.Summary == "finished" {
|
||||
if globalJSON {
|
||||
|
||||
+149
-73
@@ -1,4 +1,4 @@
|
||||
// Copyright (c) 2015-2022 MinIO, Inc.
|
||||
// Copyright (c) 2015-2024 MinIO, Inc.
|
||||
//
|
||||
// This file is part of MinIO Object Storage stack
|
||||
//
|
||||
@@ -18,8 +18,11 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"fmt"
|
||||
"math"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
@@ -31,7 +34,7 @@ import (
|
||||
json "github.com/minio/colorjson"
|
||||
"github.com/minio/madmin-go/v3"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/pkg/console"
|
||||
"github.com/minio/pkg/v3/console"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -40,48 +43,74 @@ const (
|
||||
)
|
||||
|
||||
var adminHealFlags = []cli.Flag{
|
||||
cli.StringFlag{
|
||||
Name: "scan",
|
||||
Usage: "select the healing scan mode (normal/deep)",
|
||||
Value: scanNormalMode,
|
||||
cli.IntFlag{
|
||||
Name: "pool",
|
||||
Usage: "heal only the given pool",
|
||||
Hidden: true,
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "recursive, r",
|
||||
Usage: "heal recursively",
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "dry-run, n",
|
||||
Usage: "only inspect data, but do not mutate",
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "force-start, f",
|
||||
Usage: "force start a new heal sequence",
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "force-stop, s",
|
||||
Usage: "force stop a running heal sequence",
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "remove",
|
||||
Usage: "remove dangling objects in heal sequence",
|
||||
cli.IntFlag{
|
||||
Name: "set",
|
||||
Usage: "heal only the given set",
|
||||
Hidden: true,
|
||||
},
|
||||
cli.StringFlag{
|
||||
Name: "storage-class",
|
||||
Usage: "show server/drives failure tolerance with the given storage class",
|
||||
Name: "scan",
|
||||
Usage: "select the healing scan mode (normal/deep)",
|
||||
Value: scanNormalMode,
|
||||
Hidden: true,
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "rewrite",
|
||||
Usage: "rewrite objects from older to newer format",
|
||||
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: "heal bucket(s) and object(s) on MinIO server",
|
||||
Usage: "monitor healing for bucket(s) and object(s) on MinIO server",
|
||||
Action: mainAdminHeal,
|
||||
OnUsageError: onUsageError,
|
||||
Before: setGlobalsFromContext,
|
||||
@@ -144,8 +173,11 @@ type poolInfo struct {
|
||||
}
|
||||
|
||||
type setInfo struct {
|
||||
maxUsedSpace uint64
|
||||
totalDisks int
|
||||
totalDisks int
|
||||
|
||||
readyDisksCount int // disks online and not in healing state
|
||||
readyDisksUsedSpace uint64 // the total used space of ready disks
|
||||
|
||||
incapableDisks int
|
||||
}
|
||||
|
||||
@@ -200,11 +232,11 @@ func generateSetsStatus(disks []madmin.Disk) map[setIndex]setInfo {
|
||||
setSt = setInfo{}
|
||||
}
|
||||
setSt.totalDisks++
|
||||
if d.UsedSpace > setSt.maxUsedSpace {
|
||||
setSt.maxUsedSpace = d.UsedSpace
|
||||
}
|
||||
if d.State != "ok" || d.Healing {
|
||||
setSt.incapableDisks++
|
||||
} else {
|
||||
setSt.readyDisksCount++
|
||||
setSt.readyDisksUsedSpace += d.UsedSpace
|
||||
}
|
||||
m[idx] = setSt
|
||||
}
|
||||
@@ -309,6 +341,8 @@ type verboseBackgroundHealStatusMessage struct {
|
||||
Status string `json:"status"`
|
||||
HealInfo madmin.BgHealState
|
||||
|
||||
allDrives bool
|
||||
|
||||
// Specify storage class to show servers/disks tolerance
|
||||
ToleranceForSC string `json:"-"`
|
||||
}
|
||||
@@ -356,14 +390,16 @@ func (s verboseBackgroundHealStatusMessage) String() string {
|
||||
fmt.Fprintf(&msg, " %s: %s\n", endpoint, stateText)
|
||||
continue
|
||||
}
|
||||
var serverHeader strings.Builder
|
||||
var serverHeaderPrinted bool
|
||||
serverStatus := serversStatus[endpoint]
|
||||
switch {
|
||||
case showTolerance:
|
||||
serverHeader := " %s: (Tolerance: %d server(s))\n"
|
||||
fmt.Fprintf(&msg, serverHeader, endpoint, poolsInfo[serverStatus.pool].tolerance)
|
||||
hdr := " %s: (Tolerance: %d server(s))\n"
|
||||
fmt.Fprintf(&serverHeader, hdr, endpoint, poolsInfo[serverStatus.pool].tolerance)
|
||||
default:
|
||||
serverHeader := " %s:\n"
|
||||
fmt.Fprintf(&msg, serverHeader, endpoint)
|
||||
hdr := " %s:\n"
|
||||
fmt.Fprintf(&serverHeader, hdr, endpoint)
|
||||
}
|
||||
|
||||
for _, d := range serverStatus.disks {
|
||||
@@ -375,25 +411,49 @@ func (s verboseBackgroundHealStatusMessage) String() string {
|
||||
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)
|
||||
}
|
||||
fmt.Fprintf(&msg, " + %s : %s\n", d.DrivePath, stateText)
|
||||
if d.Healing && d.HealInfo != nil {
|
||||
now := time.Now().UTC()
|
||||
scanSpeed := float64(d.UsedSpace) / float64(now.Sub(d.HealInfo.Started))
|
||||
remainingTime := time.Duration(float64(setsStatus[setIndex{d.PoolIndex, d.SetIndex}].maxUsedSpace-d.UsedSpace) / scanSpeed)
|
||||
estimationText := humanize.RelTime(now, now.Add(remainingTime), "", "")
|
||||
fmt.Fprintf(&msg, " |__ Estimated: %s\n", estimationText)
|
||||
if !serverHeaderPrinted {
|
||||
serverHeaderPrinted = true
|
||||
fmt.Fprint(&msg, serverHeader.String())
|
||||
}
|
||||
fmt.Fprintf(&msg, " |__ Capacity: %s/%s\n", humanize.IBytes(d.UsedSpace), humanize.IBytes(d.TotalSpace))
|
||||
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-setsStatus[setIndex{d.PoolIndex, d.SetIndex}].incapableDisks)
|
||||
fmt.Fprintf(&msg, " |__ Tolerance: %d drive(s)\n", parity-thisSet.incapableDisks)
|
||||
}
|
||||
}
|
||||
|
||||
fmt.Fprintf(&msg, "\n")
|
||||
if serverHeaderPrinted {
|
||||
fmt.Fprintf(&msg, "\n")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -454,9 +514,6 @@ func (s shortBackgroundHealStatusMessage) String() string {
|
||||
// The addition of Elapsed time of each parallel healing operation
|
||||
// this is needed to calculate the rate of healing
|
||||
accumulatedElapsedTime time.Duration
|
||||
|
||||
// ETA of healing - it is the latest ETA of all drives currently healing
|
||||
healingRemaining time.Duration
|
||||
)
|
||||
|
||||
var problematicDisks int
|
||||
@@ -477,12 +534,19 @@ func (s shortBackgroundHealStatusMessage) String() string {
|
||||
continue
|
||||
}
|
||||
|
||||
if disk.HealInfo != nil {
|
||||
if disk.HealInfo != nil && !disk.HealInfo.Finished {
|
||||
missingInSet++
|
||||
|
||||
diskSet := setIndex{pool: disk.PoolIndex, set: disk.SetIndex}
|
||||
if maxUsedSpace := setsStatus[diskSet].maxUsedSpace; maxUsedSpace > 0 {
|
||||
if pct := float64(disk.UsedSpace) / float64(maxUsedSpace); pct < leastPct {
|
||||
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 {
|
||||
@@ -490,12 +554,6 @@ func (s shortBackgroundHealStatusMessage) String() string {
|
||||
leastPct = 0
|
||||
}
|
||||
|
||||
scanSpeed := float64(disk.UsedSpace) / float64(time.Since(disk.HealInfo.Started))
|
||||
remainingTime := time.Duration(float64(setsStatus[diskSet].maxUsedSpace-disk.UsedSpace) / scanSpeed)
|
||||
if remainingTime > healingRemaining {
|
||||
healingRemaining = remainingTime
|
||||
}
|
||||
|
||||
disk := disk
|
||||
if furthestHealingDisk == nil {
|
||||
furthestHealingDisk = &disk
|
||||
@@ -558,10 +616,6 @@ func (s shortBackgroundHealStatusMessage) String() string {
|
||||
healPrettyMsg += fmt.Sprintf("Heal rate: %d obj/s, %s/s\n", int64(itemsHealedPerSec), humanize.IBytes(uint64(bytesHealedPerSec)))
|
||||
}
|
||||
|
||||
// Estimation completion
|
||||
now := time.Now()
|
||||
healPrettyMsg += fmt.Sprintf("Estimated Completion: %s\n", humanize.RelTime(now, now.Add(healingRemaining), "", ""))
|
||||
|
||||
if problematicDisks > 0 {
|
||||
healPrettyMsg += "\n"
|
||||
healPrettyMsg += fmt.Sprintf("%d offline disk(s) found.", problematicDisks)
|
||||
@@ -641,6 +695,7 @@ func mainAdminHeal(ctx *cli.Context) error {
|
||||
printMsg(verboseBackgroundHealStatusMessage{
|
||||
Status: "success",
|
||||
HealInfo: bgHealStatus,
|
||||
allDrives: ctx.Bool("all-drives"),
|
||||
ToleranceForSC: strings.ToUpper(ctx.String("storage-class")),
|
||||
})
|
||||
} else {
|
||||
@@ -652,13 +707,6 @@ func mainAdminHeal(ctx *cli.Context) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
for content := range clnt.List(globalContext, ListOptions{Recursive: false, ShowDir: DirNone}) {
|
||||
if content.Err != nil {
|
||||
fatalIf(content.Err.Trace(clnt.GetURL().String()), "Unable to heal bucket `"+bucket+"`.")
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
opts := madmin.HealOpts{
|
||||
ScanMode: transformScanArg(ctx.String("scan")),
|
||||
Remove: ctx.Bool("remove"),
|
||||
@@ -667,6 +715,24 @@ func mainAdminHeal(ctx *cli.Context) error {
|
||||
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 {
|
||||
@@ -676,6 +742,16 @@ func mainAdminHeal(ctx *cli.Context) error {
|
||||
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.")
|
||||
|
||||
|
||||
+104
-46
@@ -1,4 +1,4 @@
|
||||
// Copyright (c) 2015-2023 MinIO, Inc.
|
||||
// Copyright (c) 2015-2024 MinIO, Inc.
|
||||
//
|
||||
// This file is part of MinIO Object Storage stack
|
||||
//
|
||||
@@ -33,16 +33,23 @@ import (
|
||||
"github.com/minio/madmin-go/v3"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/minio-go/v7/pkg/set"
|
||||
"github.com/minio/pkg/console"
|
||||
"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: globalFlags,
|
||||
Flags: append(globalFlags, adminInfoFlags...),
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
@@ -59,11 +66,13 @@ EXAMPLES:
|
||||
}
|
||||
|
||||
type poolSummary struct {
|
||||
index int
|
||||
setsCount int
|
||||
drivesPerSet int
|
||||
driveTolerance int
|
||||
endpoints set.StringSet
|
||||
index int
|
||||
setsCount int
|
||||
drivesPerSet int
|
||||
driveTolerance int
|
||||
drivesTotalFreeSpace uint64
|
||||
drivesTotalUsableSpace uint64
|
||||
endpoints set.StringSet
|
||||
}
|
||||
|
||||
type clusterInfo map[int]*poolSummary
|
||||
@@ -73,6 +82,10 @@ func clusterSummaryInfo(info madmin.InfoMessage) 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{
|
||||
@@ -81,25 +94,28 @@ func clusterSummaryInfo(info madmin.InfoMessage) clusterInfo {
|
||||
driveTolerance: info.StandardParity(),
|
||||
}
|
||||
}
|
||||
// Deprecated calculation based on disk location
|
||||
if disk.SetIndex+1 > pool.setsCount {
|
||||
pool.setsCount = disk.SetIndex + 1
|
||||
}
|
||||
// Deprecated calculation based on disk location
|
||||
if disk.DiskIndex+1 > pool.drivesPerSet {
|
||||
pool.drivesPerSet = disk.DiskIndex + 1
|
||||
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
if len(info.Backend.TotalSets) > 0 { // Check if this is a recent enough MinIO version
|
||||
for _, pool := range summary {
|
||||
pool.setsCount = info.Backend.TotalSets[pool.index]
|
||||
pool.drivesPerSet = info.Backend.DrivesPerSet[pool.index]
|
||||
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
|
||||
}
|
||||
|
||||
@@ -118,32 +134,20 @@ 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 depending on the type of a server
|
||||
//
|
||||
// FS server non-FS server
|
||||
//
|
||||
// ============================== ===================================
|
||||
// ● <ip>:<port> ● <ip>:<port>
|
||||
//
|
||||
// Uptime: xxx Uptime: xxx
|
||||
// Version: xxx Version: xxx
|
||||
// Network: X/Y OK Network: X/Y OK
|
||||
//
|
||||
// U Used, B Buckets, O Objects Drives: N/N OK
|
||||
//
|
||||
// U Used, B Buckets, O Objects
|
||||
// N drives online, K drives offline
|
||||
// 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 status")
|
||||
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 status")), "")
|
||||
fatal(probe.NewError(errors.New("Unable to get service info")), "")
|
||||
}
|
||||
|
||||
// Initialization
|
||||
@@ -202,6 +206,10 @@ func (u clusterStruct) String() (msg string) {
|
||||
continue
|
||||
}
|
||||
|
||||
if u.onlyOffline {
|
||||
continue
|
||||
}
|
||||
|
||||
// Print server title
|
||||
msg += fmt.Sprintf("%s %s\n", coloredDot, console.Colorize("PrintB", srv.Endpoint))
|
||||
|
||||
@@ -211,7 +219,7 @@ func (u clusterStruct) String() (msg string) {
|
||||
|
||||
// Version
|
||||
version := srv.Version
|
||||
if srv.Version == "DEVELOPMENT.GOGET" {
|
||||
if strings.Contains(srv.Version, "DEVELOPMENT") {
|
||||
version = "<development>"
|
||||
}
|
||||
msg += fmt.Sprintf(" Version: %s\n", version)
|
||||
@@ -266,15 +274,60 @@ func (u clusterStruct) String() (msg string) {
|
||||
}
|
||||
|
||||
if backendType == madmin.Erasure {
|
||||
msg += "Pools:\n"
|
||||
for pool, summary := range clusterSummary {
|
||||
msg += fmt.Sprintf(" %s, Erasure sets: %d, Drives per erasure set: %d\n",
|
||||
console.Colorize("Info", humanize.Ordinal(pool+1)), summary.setsCount, summary.drivesPerSet)
|
||||
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"
|
||||
}
|
||||
}
|
||||
|
||||
msg += "\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)
|
||||
@@ -296,9 +349,10 @@ func (u clusterStruct) String() (msg string) {
|
||||
}
|
||||
// Summary on total no of online and total
|
||||
// number of offline drives at the Cluster level
|
||||
msg += fmt.Sprintf("%s online, %s offline\n",
|
||||
msg += fmt.Sprintf("%s online, %s offline, EC:%d\n",
|
||||
english.Plural(u.Info.Backend.OnlineDisks, "drive", ""),
|
||||
english.Plural(u.Info.Backend.OfflineDisks, "drive", ""))
|
||||
english.Plural(u.Info.Backend.OfflineDisks, "drive", ""),
|
||||
u.Info.Backend.StandardSCParity)
|
||||
}
|
||||
|
||||
// Remove the last new line if any
|
||||
@@ -333,7 +387,10 @@ func mainAdminInfo(ctx *cli.Context) error {
|
||||
client, err := newAdminClient(aliasedURL)
|
||||
fatalIf(err, "Unable to initialize admin connection.")
|
||||
|
||||
var clusterInfo clusterStruct
|
||||
clusterInfo := clusterStruct{
|
||||
onlyOffline: ctx.Bool("offline"),
|
||||
}
|
||||
|
||||
// Fetch info of all servers (cluster or single server)
|
||||
admInfo, e := client.ServerInfo(globalContext)
|
||||
if e != nil {
|
||||
@@ -343,6 +400,7 @@ func mainAdminInfo(ctx *cli.Context) error {
|
||||
clusterInfo.Status = "success"
|
||||
clusterInfo.Error = ""
|
||||
}
|
||||
|
||||
clusterInfo.Info = admInfo
|
||||
printMsg(clusterInfo)
|
||||
|
||||
|
||||
@@ -24,13 +24,13 @@ import (
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/pkg/console"
|
||||
"github.com/minio/pkg/v3/console"
|
||||
"golang.org/x/term"
|
||||
)
|
||||
|
||||
var adminKMSCreateKeyCmd = cli.Command{
|
||||
Name: "create",
|
||||
Usage: "creates a new master key at the KMS",
|
||||
Usage: "creates a new master KMS key",
|
||||
Action: mainAdminKMSCreateKey,
|
||||
OnUsageError: onUsageError,
|
||||
Before: setGlobalsFromContext,
|
||||
|
||||
@@ -27,7 +27,7 @@ import (
|
||||
"github.com/minio/cli"
|
||||
json "github.com/minio/colorjson"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/pkg/console"
|
||||
"github.com/minio/pkg/v3/console"
|
||||
)
|
||||
|
||||
var adminKMSKeyListCmd = cli.Command{
|
||||
|
||||
@@ -24,7 +24,7 @@ import (
|
||||
"github.com/minio/cli"
|
||||
json "github.com/minio/colorjson"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/pkg/console"
|
||||
"github.com/minio/pkg/v3/console"
|
||||
)
|
||||
|
||||
var adminKMSKeyStatusCmd = cli.Command{
|
||||
|
||||
+4
-10
@@ -28,7 +28,7 @@ import (
|
||||
json "github.com/minio/colorjson"
|
||||
"github.com/minio/madmin-go/v3"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/pkg/console"
|
||||
"github.com/minio/pkg/v3/console"
|
||||
)
|
||||
|
||||
const logTimeFormat string = "15:04:05 MST 01/02/2006"
|
||||
@@ -107,15 +107,6 @@ func (l logMessage) String() string {
|
||||
if l.NodeName != "" {
|
||||
hostStr = fmt.Sprintf("%s ", colorizedNodeName(l.NodeName))
|
||||
}
|
||||
log := l.LogInfo
|
||||
if log.ConsoleMsg != "" {
|
||||
if strings.HasPrefix(log.ConsoleMsg, "\n") {
|
||||
fmt.Fprintf(b, "%s\n", hostStr)
|
||||
log.ConsoleMsg = strings.TrimPrefix(log.ConsoleMsg, "\n")
|
||||
}
|
||||
fmt.Fprintf(b, "%s %s", hostStr, log.ConsoleMsg)
|
||||
return b.String()
|
||||
}
|
||||
if l.API != nil {
|
||||
apiString := "API: " + l.API.Name + "("
|
||||
if l.API.Args != nil && l.API.Args.Bucket != "" {
|
||||
@@ -142,6 +133,9 @@ func (l logMessage) String() string {
|
||||
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))
|
||||
|
||||
@@ -56,6 +56,7 @@ var adminCmdSubcommands = []cli.Command{
|
||||
adminClusterCmd,
|
||||
adminRebalanceCmd,
|
||||
adminLogsCmd,
|
||||
adminAccesskeyCmd,
|
||||
}
|
||||
|
||||
var adminCmd = cli.Command{
|
||||
|
||||
@@ -23,6 +23,10 @@ import (
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
)
|
||||
|
||||
const (
|
||||
errCodeChangeAlreadyApplied = "XMinioAdminPolicyChangeAlreadyApplied"
|
||||
)
|
||||
|
||||
var adminAttachPolicyFlags = []cli.Flag{
|
||||
cli.StringFlag{
|
||||
Name: "user, u",
|
||||
@@ -97,10 +101,13 @@ func userAttachOrDetachPolicy(ctx *cli.Context, attach bool) error {
|
||||
} else {
|
||||
res, e = client.DetachPolicy(globalContext, req)
|
||||
}
|
||||
fatalIf(probe.NewError(e), "Unable to make user/group policy association")
|
||||
|
||||
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 == emptyResp.UpdatedAt {
|
||||
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)
|
||||
|
||||
@@ -26,7 +26,7 @@ import (
|
||||
json "github.com/minio/colorjson"
|
||||
"github.com/minio/madmin-go/v3"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/pkg/console"
|
||||
"github.com/minio/pkg/v3/console"
|
||||
)
|
||||
|
||||
var adminPolicyCreateCmd = cli.Command{
|
||||
|
||||
@@ -24,7 +24,7 @@ import (
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/madmin-go/v3"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/pkg/console"
|
||||
"github.com/minio/pkg/v3/console"
|
||||
)
|
||||
|
||||
var policyInfoFlags = []cli.Flag{
|
||||
@@ -77,6 +77,7 @@ func getPolicyInfo(client *madmin.AdminClient, policyName string) (*madmin.Polic
|
||||
|
||||
if pinfo.PolicyName == "" {
|
||||
// Likely server only supports the older version.
|
||||
// nolint:staticcheck
|
||||
pinfo.Policy, e = client.InfoCannedPolicy(globalContext, policyName)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
|
||||
@@ -21,7 +21,7 @@ import (
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/pkg/console"
|
||||
"github.com/minio/pkg/v3/console"
|
||||
)
|
||||
|
||||
var adminPolicyListCmd = cli.Command{
|
||||
|
||||
@@ -21,7 +21,7 @@ import (
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/pkg/console"
|
||||
"github.com/minio/pkg/v3/console"
|
||||
)
|
||||
|
||||
var adminPolicyRemoveCmd = cli.Command{
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// Copyright (c) 2015-2022 MinIO, Inc.
|
||||
// Copyright (c) 2015-2024 MinIO, Inc.
|
||||
//
|
||||
// This file is part of MinIO Object Storage stack
|
||||
//
|
||||
@@ -24,27 +24,22 @@ import (
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/pkg/console"
|
||||
"github.com/minio/pkg/v3/console"
|
||||
|
||||
json "github.com/minio/colorjson"
|
||||
yaml "gopkg.in/yaml.v2"
|
||||
)
|
||||
|
||||
const (
|
||||
defaultJobName = "minio-job"
|
||||
nodeJobName = "minio-job-node"
|
||||
bucketJobName = "minio-job-bucket"
|
||||
defaultMetricsPath = "/minio/v2/metrics/cluster"
|
||||
nodeMetricsPath = "/minio/v2/metrics/node"
|
||||
bucketMetricsPath = "/minio/v2/metrics/bucket"
|
||||
defaultJobName = "minio-job"
|
||||
metricsV2BasePath = "/minio/v2/metrics"
|
||||
)
|
||||
|
||||
var prometheusFlags = []cli.Flag{
|
||||
var prometheusFlags = append(metricsFlags,
|
||||
cli.BoolFlag{
|
||||
Name: "public",
|
||||
Usage: "disable bearer token generation for scrape_configs",
|
||||
},
|
||||
}
|
||||
})
|
||||
|
||||
var adminPrometheusGenerateCmd = cli.Command{
|
||||
Name: "generate",
|
||||
@@ -61,20 +56,68 @@ USAGE:
|
||||
{{.HelpName}} TARGET [METRIC-TYPE]
|
||||
|
||||
METRIC-TYPE:
|
||||
valid values are ['cluster', 'node', 'bucket']. Defaults to 'cluster' if not specified.
|
||||
valid values are
|
||||
api-version v2 ['cluster', 'node', 'bucket', 'resource']. defaults to 'cluster' if not specified.
|
||||
api-version v3 ["api", "system", "debug", "cluster", "ilm", "audit", "logger", "replication", "notification", "scanner"]. defaults to all if not specified.
|
||||
|
||||
FLAGS:
|
||||
{{range .VisibleFlags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
EXAMPLES (v3):
|
||||
1. Generate a default prometheus config.
|
||||
{{.Prompt}} {{.HelpName}} myminio
|
||||
{{.Prompt}} {{.HelpName}} play --api-version v3
|
||||
|
||||
2. Generate prometheus config for api metrics.
|
||||
{{.Prompt}} {{.HelpName}} play api --api-version v3
|
||||
|
||||
3. Generate prometheus config for api metrics of bucket 'mybucket'.
|
||||
{{.Prompt}} {{.HelpName}} play api --bucket mybucket --api-version v3
|
||||
|
||||
4. Generate prometheus config for system metrics.
|
||||
{{.Prompt}} {{.HelpName}} play system --api-version v3
|
||||
|
||||
5. Generate prometheus config for debug metrics.
|
||||
{{.Prompt}} {{.HelpName}} play debug --api-version v3
|
||||
|
||||
6. Generate prometheus config for cluster metrics.
|
||||
{{.Prompt}} {{.HelpName}} play cluster --api-version v3
|
||||
|
||||
7. Generate prometheus config for ilm metrics.
|
||||
{{.Prompt}} {{.HelpName}} play ilm --api-version v3
|
||||
|
||||
8. Generate prometheus config for audit metrics.
|
||||
{{.Prompt}} {{.HelpName}} play audit --api-version v3
|
||||
|
||||
9. Generate prometheus config for logger metrics.
|
||||
{{.Prompt}} {{.HelpName}} play logger --api-version v3
|
||||
|
||||
10. Generate prometheus config for replication metrics.
|
||||
{{.Prompt}} {{.HelpName}} play replication --api-version v3
|
||||
|
||||
11. Generate prometheus config for replication metrics of bucket 'mybucket'.
|
||||
{{.Prompt}} {{.HelpName}} play replication --bucket mybucket --api-version v3
|
||||
|
||||
12. Generate prometheus config for notification metrics.
|
||||
{{.Prompt}} {{.HelpName}} play notification --api-version v3
|
||||
|
||||
13. Generate prometheus config for scanner metrics.
|
||||
{{.Prompt}} {{.HelpName}} play scanner --api-version v3
|
||||
|
||||
EXAMPLES (v2):
|
||||
1. Generate a default prometheus config.
|
||||
{{.Prompt}} {{.HelpName}} play
|
||||
|
||||
2. Generate prometheus config for node metrics.
|
||||
{{.Prompt}} {{.HelpName}} play node
|
||||
|
||||
3. Generate prometheus config for bucket metrics.
|
||||
{{.Prompt}} {{.HelpName}} play bucket
|
||||
|
||||
4. Generate prometheus config for resource metrics.
|
||||
{{.Prompt}} {{.HelpName}} play resource
|
||||
|
||||
5. Generate prometheus config for cluster metrics.
|
||||
{{.Prompt}} {{.HelpName}} play cluster
|
||||
`,
|
||||
}
|
||||
|
||||
@@ -159,52 +202,43 @@ func generatePrometheusConfig(ctx *cli.Context) error {
|
||||
}
|
||||
|
||||
metricsSubSystem := args.Get(1)
|
||||
var config PrometheusConfig
|
||||
switch metricsSubSystem {
|
||||
case "node":
|
||||
config = PrometheusConfig{
|
||||
ScrapeConfigs: []ScrapeConfig{
|
||||
{
|
||||
JobName: nodeJobName,
|
||||
MetricsPath: nodeMetricsPath,
|
||||
StaticConfigs: []StatConfig{
|
||||
{
|
||||
Targets: []string{""},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
apiVer := ctx.String("api-version")
|
||||
jobName := defaultJobName
|
||||
metricsPath := ""
|
||||
|
||||
switch apiVer {
|
||||
case "v2":
|
||||
if metricsSubSystem == "" {
|
||||
metricsSubSystem = "cluster"
|
||||
}
|
||||
case "bucket":
|
||||
config = PrometheusConfig{
|
||||
ScrapeConfigs: []ScrapeConfig{
|
||||
{
|
||||
JobName: bucketJobName,
|
||||
MetricsPath: bucketMetricsPath,
|
||||
StaticConfigs: []StatConfig{
|
||||
{
|
||||
Targets: []string{""},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
validateV2Args(ctx, metricsSubSystem)
|
||||
if metricsSubSystem != "cluster" {
|
||||
jobName = defaultJobName + "-" + metricsSubSystem
|
||||
}
|
||||
case "", "cluster":
|
||||
config = PrometheusConfig{
|
||||
ScrapeConfigs: []ScrapeConfig{
|
||||
{
|
||||
JobName: defaultJobName,
|
||||
MetricsPath: defaultMetricsPath,
|
||||
StaticConfigs: []StatConfig{
|
||||
{
|
||||
Targets: []string{""},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
metricsPath = metricsV2BasePath + "/" + metricsSubSystem
|
||||
case "v3":
|
||||
bucket := ctx.String("bucket")
|
||||
validateV3Args(metricsSubSystem, bucket)
|
||||
metricsPath = getMetricsV3Path(metricsSubSystem, bucket)
|
||||
if metricsSubSystem != "" {
|
||||
jobName = defaultJobName + "-" + metricsSubSystem
|
||||
}
|
||||
default:
|
||||
fatalIf(errInvalidArgument().Trace(), "invalid metric type '%v'", metricsSubSystem)
|
||||
fatalIf(errInvalidArgument().Trace(), "Invalid api version `"+apiVer+"`")
|
||||
}
|
||||
|
||||
config := PrometheusConfig{
|
||||
ScrapeConfigs: []ScrapeConfig{
|
||||
{
|
||||
JobName: jobName,
|
||||
MetricsPath: metricsPath,
|
||||
StaticConfigs: []StatConfig{
|
||||
{
|
||||
Targets: []string{""},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
if !ctx.Bool("public") {
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
// 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"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/minio-go/v7/pkg/set"
|
||||
)
|
||||
|
||||
var (
|
||||
metricsV3Flags = []cli.Flag{
|
||||
cli.StringFlag{
|
||||
Name: "bucket",
|
||||
Usage: "bucket name to list metrics for. only applicable with api version v3 for metric type 'api, replication'",
|
||||
},
|
||||
}
|
||||
|
||||
metricsV3SubSystems = set.CreateStringSet("api", "system", "debug", "cluster",
|
||||
"ilm", "audit", "logger", "replication", "notification", "scanner")
|
||||
|
||||
bucketMetricsSubSystems = set.CreateStringSet("api", "replication")
|
||||
)
|
||||
|
||||
const metricsV3EndPointRoot = "/minio/metrics/v3"
|
||||
|
||||
func getMetricsV3Path(subsys string, bucket string) string {
|
||||
params := url.Values{}
|
||||
|
||||
metricsPath := metricsV3EndPointRoot
|
||||
if len(bucket) > 0 {
|
||||
metricsPath += "/bucket"
|
||||
}
|
||||
|
||||
if len(subsys) > 0 {
|
||||
metricsPath += "/" + subsys
|
||||
}
|
||||
|
||||
if len(bucket) > 0 {
|
||||
// bucket specific metrics endpoints have '/bucket' prefix and bucket name as suffix.
|
||||
// e.g. bucket api metrics: /bucket/api/mybucket
|
||||
metricsPath += "/" + bucket
|
||||
}
|
||||
|
||||
qparams := params.Encode()
|
||||
if len(qparams) > 0 {
|
||||
metricsPath += "?" + qparams
|
||||
}
|
||||
return metricsPath
|
||||
}
|
||||
|
||||
func validateV3Args(subsys string, bucket string) {
|
||||
if subsys != "" && !metricsV3SubSystems.Contains(subsys) {
|
||||
fatalIf(errInvalidArgument().Trace(),
|
||||
"invalid metric type `"+subsys+"`. valid values are `"+
|
||||
strings.Join(metricsV3SubSystems.ToSlice(), ", ")+"`")
|
||||
}
|
||||
|
||||
if len(bucket) > 0 {
|
||||
bms := strings.Join(bucketMetricsSubSystems.ToSlice(), ", ")
|
||||
if len(subsys) == 0 {
|
||||
fatalIf(errInvalidArgument().Trace(), fmt.Sprintf("metric type must be passed with --bucket. valid values are `%s`", bms))
|
||||
}
|
||||
|
||||
if !bucketMetricsSubSystems.Contains(subsys) {
|
||||
fatalIf(errInvalidArgument().Trace(), fmt.Sprintf("--bucket is applicable only for metric types `%s`", bms))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func printPrometheusMetricsV3(ctx *cli.Context, req prometheusMetricsReq) error {
|
||||
bucket := ctx.String("bucket")
|
||||
validateV3Args(req.subsystem, bucket)
|
||||
|
||||
metricsURL := req.aliasURL + getMetricsV3Path(req.subsystem, bucket)
|
||||
|
||||
resp, e := fetchMetrics(metricsURL, req.token)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode == http.StatusOK {
|
||||
printMsg(prometheusMetricsReader{Reader: resp.Body})
|
||||
return nil
|
||||
}
|
||||
|
||||
return errors.New(resp.Status)
|
||||
}
|
||||
+151
-57
@@ -1,4 +1,4 @@
|
||||
// Copyright (c) 2015-2022 MinIO, Inc.
|
||||
// Copyright (c) 2015-2024 MinIO, Inc.
|
||||
//
|
||||
// This file is part of MinIO Object Storage stack
|
||||
//
|
||||
@@ -18,51 +18,108 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/minio/cli"
|
||||
json "github.com/minio/colorjson"
|
||||
"github.com/minio/madmin-go/v3"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
dto "github.com/prometheus/client_model/go"
|
||||
"github.com/prometheus/prom2json"
|
||||
"github.com/minio/minio-go/v7/pkg/set"
|
||||
)
|
||||
|
||||
var metricsFlags = append(metricsV3Flags,
|
||||
cli.StringFlag{
|
||||
Name: "api-version",
|
||||
Usage: "version of metrics api to use. valid values are ['v2', 'v3']. defaults to 'v2' if not specified.",
|
||||
Value: "v2",
|
||||
})
|
||||
|
||||
var metricsV2SubSystems = set.CreateStringSet("node", "bucket", "cluster", "resource")
|
||||
|
||||
var adminPrometheusMetricsCmd = cli.Command{
|
||||
Name: "metrics",
|
||||
Usage: "print cluster wide prometheus metrics",
|
||||
Usage: "print prometheus metrics",
|
||||
OnUsageError: onUsageError,
|
||||
Action: mainSupportMetrics,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
Flags: append(globalFlags, metricsFlags...),
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
USAGE:
|
||||
{{.HelpName}} TARGET [METRIC-TYPE]
|
||||
|
||||
METRIC-TYPE:
|
||||
valid values are ['cluster', 'node', 'bucket']. Defaults to 'cluster' if not specified.
|
||||
valid values are
|
||||
api-version v2 ['cluster', 'node', 'bucket', 'resource']. defaults to 'cluster' if not specified.
|
||||
api-version v3 ["api", "system", "debug", "cluster", "ilm", "audit", "logger", "replication", "notification", "scanner"]. defaults to all if not specified.
|
||||
|
||||
FLAGS:
|
||||
{{range .VisibleFlags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
1. List of metrics reported cluster wide.
|
||||
EXAMPLES (v3):
|
||||
1. API metrics
|
||||
{{.Prompt}} {{.HelpName}} play api --api-version v3
|
||||
|
||||
2. API metrics for the bucket 'mybucket'
|
||||
{{.Prompt}} {{.HelpName}} play api --bucket mybucket --api-version v3
|
||||
|
||||
3. System metrics
|
||||
{{.Prompt}} {{.HelpName}} play system --api-version v3
|
||||
|
||||
4. Debug metrics
|
||||
{{.Prompt}} {{.HelpName}} play debug --api-version v3
|
||||
|
||||
5. Cluster metrics
|
||||
{{.Prompt}} {{.HelpName}} play cluster --api-version v3
|
||||
|
||||
6. ILM metrics
|
||||
{{.Prompt}} {{.HelpName}} play ilm --api-version v3
|
||||
|
||||
7. Audit metrics
|
||||
{{.Prompt}} {{.HelpName}} play audit --api-version v3
|
||||
|
||||
8. Logger metrics
|
||||
{{.Prompt}} {{.HelpName}} play logger --api-version v3
|
||||
|
||||
9. Replication metrics
|
||||
{{.Prompt}} {{.HelpName}} play replication --api-version v3
|
||||
|
||||
10. Replication metrics for the bucket 'mybucket'
|
||||
{{.Prompt}} {{.HelpName}} play replication --bucket mybucket --api-version v3
|
||||
|
||||
11. Notification metrics
|
||||
{{.Prompt}} {{.HelpName}} play notification --api-version v3
|
||||
|
||||
12. Scanner metrics
|
||||
{{.Prompt}} {{.HelpName}} play scanner --api-version v3
|
||||
|
||||
EXAMPLES (v2):
|
||||
1. Metrics reported cluster wide.
|
||||
{{.Prompt}} {{.HelpName}} play
|
||||
|
||||
2. List of metrics reported at node level.
|
||||
2. Metrics reported at node level.
|
||||
{{.Prompt}} {{.HelpName}} play node
|
||||
|
||||
3. List of metrics reported at bucket level.
|
||||
3. Metrics reported at bucket level.
|
||||
{{.Prompt}} {{.HelpName}} play bucket
|
||||
|
||||
4. Resource metrics.
|
||||
{{.Prompt}} {{.HelpName}} play resource
|
||||
`,
|
||||
}
|
||||
|
||||
const (
|
||||
metricsRespBodyLimit = 10 << 20 // 10 MiB
|
||||
metricsEndPointRoot = "/minio/v2/metrics/"
|
||||
)
|
||||
const metricsEndPointRoot = "/minio/v2/metrics/"
|
||||
|
||||
type prometheusMetricsReq struct {
|
||||
aliasURL string
|
||||
token string
|
||||
subsystem string
|
||||
}
|
||||
|
||||
// checkSupportMetricsSyntax - validate arguments passed by a user
|
||||
func checkSupportMetricsSyntax(ctx *cli.Context) {
|
||||
@@ -71,40 +128,42 @@ func checkSupportMetricsSyntax(ctx *cli.Context) {
|
||||
}
|
||||
}
|
||||
|
||||
func printPrometheusMetrics(ctx *cli.Context) error {
|
||||
// Get the alias parameter from cli
|
||||
args := ctx.Args()
|
||||
alias := cleanAlias(args.Get(0))
|
||||
|
||||
if !isValidAlias(alias) {
|
||||
fatalIf(errInvalidAlias(alias), "Invalid alias.")
|
||||
}
|
||||
hostConfig := mustGetHostConfig(alias)
|
||||
if hostConfig == nil {
|
||||
fatalIf(errInvalidAliasedURL(alias), "No such alias `"+alias+"` found.")
|
||||
return nil
|
||||
}
|
||||
|
||||
token, e := getPrometheusToken(hostConfig)
|
||||
func fetchMetrics(metricsURL string, token string) (*http.Response, error) {
|
||||
req, e := http.NewRequest(http.MethodGet, metricsURL, nil)
|
||||
if e != nil {
|
||||
return e
|
||||
return nil, e
|
||||
}
|
||||
metricsSubSystem := args.Get(1)
|
||||
switch metricsSubSystem {
|
||||
case "node", "bucket", "cluster":
|
||||
case "":
|
||||
metricsSubSystem = "cluster"
|
||||
default:
|
||||
fatalIf(errInvalidArgument().Trace(), "invalid metric type '%v'", metricsSubSystem)
|
||||
if token != "" {
|
||||
req.Header.Add("Authorization", "Bearer "+token)
|
||||
}
|
||||
|
||||
req, e := http.NewRequest(http.MethodGet, hostConfig.URL+metricsEndPointRoot+metricsSubSystem, nil)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
req.Header.Add("Authorization", "Bearer "+token)
|
||||
client := httpClient(60 * time.Second)
|
||||
resp, e := client.Do(req)
|
||||
return client.Do(req)
|
||||
}
|
||||
|
||||
func validateV2Args(ctx *cli.Context, subsys string) {
|
||||
for _, flag := range metricsV3Flags {
|
||||
flagName := flag.GetName()
|
||||
if ctx.IsSet(flagName) {
|
||||
fatalIf(errInvalidArgument().Trace(), "Flag `"+flagName+"` is not supported with v2 metrics")
|
||||
}
|
||||
}
|
||||
|
||||
if !metricsV2SubSystems.Contains(subsys) {
|
||||
fatalIf(errInvalidArgument().Trace(),
|
||||
"invalid metric type `"+subsys+"`. valid values are `"+
|
||||
strings.Join(metricsV2SubSystems.ToSlice(), ", ")+"`")
|
||||
}
|
||||
}
|
||||
|
||||
func printPrometheusMetricsV2(ctx *cli.Context, req prometheusMetricsReq) error {
|
||||
subsys := req.subsystem
|
||||
if subsys == "" {
|
||||
subsys = "cluster"
|
||||
}
|
||||
validateV2Args(ctx, subsys)
|
||||
|
||||
resp, e := fetchMetrics(req.aliasURL+metricsEndPointRoot+subsys, req.token)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
@@ -112,32 +171,30 @@ func printPrometheusMetrics(ctx *cli.Context) error {
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode == http.StatusOK {
|
||||
printMsg(prometheusMetricsReader{Reader: io.LimitReader(resp.Body, metricsRespBodyLimit)})
|
||||
printMsg(prometheusMetricsReader{Reader: resp.Body})
|
||||
return nil
|
||||
}
|
||||
return nil
|
||||
|
||||
return errors.New(resp.Status)
|
||||
}
|
||||
|
||||
// JSON returns jsonified message
|
||||
func (pm prometheusMetricsReader) JSON() string {
|
||||
mfChan := make(chan *dto.MetricFamily)
|
||||
go func() {
|
||||
fatalIf(probe.NewError(prom2json.ParseReader(pm.Reader, mfChan)), "Unable to parse Prometheus metrics.")
|
||||
}()
|
||||
result := []*prom2json.Family{}
|
||||
for mf := range mfChan {
|
||||
result = append(result, prom2json.NewFamily(mf))
|
||||
}
|
||||
jsonMessageBytes, e := json.MarshalIndent(result, "", " ")
|
||||
results, e := madmin.ParsePrometheusResults(pm.Reader)
|
||||
fatalIf(probe.NewError(e), "Unable to parse Prometheus metrics.")
|
||||
|
||||
jsonMessageBytes, e := json.MarshalIndent(results, "", " ")
|
||||
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
|
||||
return string(jsonMessageBytes)
|
||||
}
|
||||
|
||||
// String - returns the string representation of the prometheus metrics
|
||||
func (pm prometheusMetricsReader) String() string {
|
||||
respBytes, e := io.ReadAll(pm.Reader)
|
||||
_, e := io.Copy(os.Stdout, pm.Reader)
|
||||
|
||||
fatalIf(probe.NewError(e), "Unable to read Prometheus metrics.")
|
||||
|
||||
return string(respBytes)
|
||||
return ""
|
||||
}
|
||||
|
||||
// prometheusMetricsReader mirrors the MetricFamily proto message.
|
||||
@@ -148,7 +205,44 @@ type prometheusMetricsReader struct {
|
||||
func mainSupportMetrics(ctx *cli.Context) error {
|
||||
checkSupportMetricsSyntax(ctx)
|
||||
|
||||
fatalIf(probe.NewError(printPrometheusMetrics(ctx)), "Unable to list prometheus metrics.")
|
||||
// Get the alias parameter from cli
|
||||
args := ctx.Args()
|
||||
alias := cleanAlias(args.Get(0))
|
||||
|
||||
if !isValidAlias(alias) {
|
||||
fatalIf(errInvalidAlias(alias), "Invalid alias.")
|
||||
}
|
||||
|
||||
hostConfig := mustGetHostConfig(alias)
|
||||
if hostConfig == nil {
|
||||
fatalIf(errInvalidAliasedURL(alias), "No such alias `"+alias+"` found.")
|
||||
return nil
|
||||
}
|
||||
|
||||
token, e := getPrometheusToken(hostConfig)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
|
||||
metricsSubSystem := args.Get(1)
|
||||
apiVer := ctx.String("api-version")
|
||||
|
||||
metricsReq := prometheusMetricsReq{
|
||||
aliasURL: hostConfig.URL,
|
||||
token: token,
|
||||
subsystem: metricsSubSystem,
|
||||
}
|
||||
|
||||
switch apiVer {
|
||||
case "v2":
|
||||
err := printPrometheusMetricsV2(ctx, metricsReq)
|
||||
fatalIf(probe.NewError(err), "Unable to list prometheus metrics with api-version v2.")
|
||||
case "v3":
|
||||
err := printPrometheusMetricsV3(ctx, metricsReq)
|
||||
fatalIf(probe.NewError(err), "Unable to list prometheus metrics with api-version v3.")
|
||||
default:
|
||||
fatalIf(errInvalidArgument().Trace(), "Invalid api version `"+apiVer+"`")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -24,7 +24,7 @@ import (
|
||||
"github.com/minio/cli"
|
||||
json "github.com/minio/colorjson"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/pkg/console"
|
||||
"github.com/minio/pkg/v3/console"
|
||||
)
|
||||
|
||||
var adminRebalanceStartCmd = cli.Command{
|
||||
|
||||
@@ -27,7 +27,7 @@ import (
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/pkg/console"
|
||||
"github.com/minio/pkg/v3/console"
|
||||
)
|
||||
|
||||
var adminRebalanceStatusCmd = cli.Command{
|
||||
@@ -88,7 +88,7 @@ func mainAdminRebalanceStatus(ctx *cli.Context) error {
|
||||
)
|
||||
row := make([]string, len(rInfo.Pools))
|
||||
for idx, pool := range rInfo.Pools {
|
||||
statusStr := fmt.Sprintf("%.2f%%", pool.Used)
|
||||
statusStr := fmt.Sprintf("%.2f%%", pool.Used*100)
|
||||
if pool.Status == "Started" {
|
||||
statusStr += " *" // indicating rebalance is in progress in this pool
|
||||
}
|
||||
|
||||
@@ -24,7 +24,7 @@ import (
|
||||
"github.com/minio/cli"
|
||||
json "github.com/minio/colorjson"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/pkg/console"
|
||||
"github.com/minio/pkg/v3/console"
|
||||
)
|
||||
|
||||
var adminRebalanceStopCmd = cli.Command{
|
||||
|
||||
@@ -25,16 +25,23 @@ import (
|
||||
json "github.com/minio/colorjson"
|
||||
"github.com/minio/madmin-go/v3"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/pkg/console"
|
||||
"github.com/minio/pkg/v3/console"
|
||||
)
|
||||
|
||||
var adminReplicateAddFlags = []cli.Flag{
|
||||
cli.BoolFlag{
|
||||
Name: "replicate-ilm-expiry",
|
||||
Usage: "replicate ILM expiry rules",
|
||||
},
|
||||
}
|
||||
|
||||
var adminReplicateAddCmd = cli.Command{
|
||||
Name: "add",
|
||||
Usage: "add one or more sites for replication",
|
||||
Action: mainAdminReplicateAdd,
|
||||
OnUsageError: onUsageError,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
Flags: append(globalFlags, adminReplicateAddFlags...),
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
@@ -48,6 +55,9 @@ FLAGS:
|
||||
EXAMPLES:
|
||||
1. Add a site for cluster-level replication:
|
||||
{{.Prompt}} {{.HelpName}} minio1 minio2
|
||||
|
||||
2. Add a site for cluster-level replication with replication of ILM expiry rules:
|
||||
{{.Prompt}} {{.HelpName}} minio1 minio2 --replicate-ilm-expiry
|
||||
`,
|
||||
}
|
||||
|
||||
@@ -106,7 +116,9 @@ func mainAdminReplicateAdd(ctx *cli.Context) error {
|
||||
})
|
||||
}
|
||||
|
||||
res, e := client.SiteReplicationAdd(globalContext, ps)
|
||||
var opts madmin.SRAddOptions
|
||||
opts.ReplicateILMExpiry = ctx.Bool("replicate-ilm-expiry")
|
||||
res, e := client.SiteReplicationAdd(globalContext, ps, opts)
|
||||
fatalIf(probe.NewError(e).Trace(args...), "Unable to add sites for replication")
|
||||
|
||||
printMsg(successMessage(res))
|
||||
|
||||
@@ -18,14 +18,17 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
humanize "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/console"
|
||||
"github.com/minio/pkg/v3/console"
|
||||
)
|
||||
|
||||
var adminReplicateInfoCmd = cli.Command{
|
||||
@@ -72,19 +75,39 @@ func (i srInfo) String() string {
|
||||
Field{"Name", 15},
|
||||
Field{"Endpoint", 46},
|
||||
Field{"Sync", 4},
|
||||
).buildRow("Deployment ID", "Site Name", "Endpoint", "Sync"))
|
||||
Field{"Bandwidth", 10},
|
||||
Field{"ILM Expiry Replication", 25},
|
||||
).buildRow("Deployment ID", "Site Name", "Endpoint", "Sync", "Bandwidth", "ILM Expiry Replication"))
|
||||
messages = append(messages, r)
|
||||
|
||||
r = console.Colorize("THeaders", newPrettyTable(" | ",
|
||||
Field{"Deployment ID", 36},
|
||||
|
||||
Field{"Name", 15},
|
||||
Field{"Endpoint", 46},
|
||||
Field{"Sync", 4},
|
||||
Field{"Bandwidth", 10},
|
||||
Field{"ILM Expiry Replication", 25},
|
||||
).buildRow("", "", "", "", "Per Bucket", ""))
|
||||
messages = append(messages, r)
|
||||
for _, peer := range info.Sites {
|
||||
var chk string
|
||||
if peer.SyncState == madmin.SyncEnabled {
|
||||
chk = check
|
||||
}
|
||||
limit := "N/A" // N/A means cluster bandwidth is not configured
|
||||
if peer.DefaultBandwidth.Limit > 0 {
|
||||
limit = humanize.Bytes(uint64(peer.DefaultBandwidth.Limit))
|
||||
limit = fmt.Sprintf("%s/s", limit)
|
||||
}
|
||||
r := console.Colorize("TDetail", newPrettyTable(" | ",
|
||||
Field{"Deployment ID", 36},
|
||||
Field{"Name", 15},
|
||||
Field{"Endpoint", 46},
|
||||
Field{"Sync", 4},
|
||||
).buildRow(peer.DeploymentID, peer.Name, peer.Endpoint, chk))
|
||||
Field{"Bandwidth", 10},
|
||||
Field{"ILM Expiry Replication", 25},
|
||||
).buildRow(peer.DeploymentID, peer.Name, peer.Endpoint, chk, limit, strconv.FormatBool(peer.ReplicateILMExpiry)))
|
||||
messages = append(messages, r)
|
||||
}
|
||||
} else {
|
||||
|
||||
@@ -25,7 +25,7 @@ import (
|
||||
json "github.com/minio/colorjson"
|
||||
"github.com/minio/madmin-go/v3"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/pkg/console"
|
||||
"github.com/minio/pkg/v3/console"
|
||||
)
|
||||
|
||||
var adminReplicateRemoveFlags = []cli.Flag{
|
||||
@@ -83,27 +83,27 @@ func (i srRemoveStatus) String() string {
|
||||
if i.RemoveAll {
|
||||
return console.Colorize("UserMessage", "All site(s) were removed successfully")
|
||||
}
|
||||
if i.ReplicateRemoveStatus.Status == madmin.ReplicateRemoveStatusSuccess {
|
||||
if i.Status == madmin.ReplicateRemoveStatusSuccess {
|
||||
return console.Colorize("UserMessage", fmt.Sprintf("Following site(s) %s were removed successfully", i.sites))
|
||||
}
|
||||
if len(i.sites) == 1 {
|
||||
return console.Colorize("UserMessage", fmt.Sprintf("Following site %s was removed partially, some operations failed:\nERROR: '%s'", i.sites, i.ReplicateRemoveStatus.ErrDetail))
|
||||
return console.Colorize("UserMessage", fmt.Sprintf("Following site %s was removed partially, some operations failed:\nERROR: '%s'", i.sites, i.ErrDetail))
|
||||
}
|
||||
return console.Colorize("UserMessage", fmt.Sprintf("Following site(s) %s were removed partially, some operations failed: \nERROR: '%s'", i.sites, i.ReplicateRemoveStatus.ErrDetail))
|
||||
return console.Colorize("UserMessage", fmt.Sprintf("Following site(s) %s were removed partially, some operations failed: \nERROR: '%s'", i.sites, i.ErrDetail))
|
||||
}
|
||||
|
||||
func checkAdminReplicateRemoveSyntax(ctx *cli.Context) {
|
||||
// Check argument count
|
||||
argsNr := len(ctx.Args())
|
||||
if ctx.IsSet("all") && argsNr > 1 {
|
||||
if ctx.Bool("all") && argsNr > 1 {
|
||||
fatalIf(errInvalidArgument().Trace(ctx.Args().Tail()...),
|
||||
"")
|
||||
}
|
||||
if argsNr < 2 && !ctx.IsSet("all") {
|
||||
if argsNr < 2 && !ctx.Bool("all") {
|
||||
fatalIf(errInvalidArgument().Trace(ctx.Args().Tail()...),
|
||||
"Need at least two arguments to remove command.")
|
||||
}
|
||||
if !ctx.IsSet("force") {
|
||||
if !ctx.Bool("force") {
|
||||
fatalIf(errDummy().Trace(),
|
||||
"Site removal requires --force flag. This operation is *IRREVERSIBLE*. Please review carefully before performing this *DANGEROUS* operation.")
|
||||
}
|
||||
|
||||
@@ -26,7 +26,7 @@ import (
|
||||
json "github.com/minio/colorjson"
|
||||
"github.com/minio/madmin-go/v3"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/pkg/console"
|
||||
"github.com/minio/pkg/v3/console"
|
||||
)
|
||||
|
||||
var adminReplicateResyncCancelCmd = cli.Command{
|
||||
@@ -74,13 +74,12 @@ func (m resyncCancelMessage) String() string {
|
||||
}
|
||||
|
||||
func mainAdminReplicateResyncCancel(ctx *cli.Context) error {
|
||||
{
|
||||
// Check argument count
|
||||
argsNr := len(ctx.Args())
|
||||
if argsNr != 2 {
|
||||
cli.ShowCommandHelpAndExit(ctx, "cancel", 1) // last argument is exit code
|
||||
}
|
||||
// Check argument count
|
||||
argsNr := len(ctx.Args())
|
||||
if argsNr != 2 {
|
||||
showCommandHelpAndExit(ctx, 1) // last argument is exit code
|
||||
}
|
||||
|
||||
console.SetColor("ResyncMessage", color.New(color.FgGreen))
|
||||
|
||||
// Get the alias parameter from cli
|
||||
@@ -92,9 +91,14 @@ func mainAdminReplicateResyncCancel(ctx *cli.Context) error {
|
||||
fatalIf(err, "Unable to initialize admin connection.")
|
||||
info, e := client.SiteReplicationInfo(globalContext)
|
||||
fatalIf(probe.NewError(e), "Unable to fetch site replication info.")
|
||||
|
||||
peerClient := getClient(args.Get(1))
|
||||
peerAdmInfo, e := peerClient.ServerInfo(globalContext)
|
||||
fatalIf(probe.NewError(e), "Unable to fetch server info of the peer.")
|
||||
|
||||
var peer madmin.PeerInfo
|
||||
for _, site := range info.Sites {
|
||||
if args[1] == site.Name {
|
||||
if peerAdmInfo.DeploymentID == site.DeploymentID {
|
||||
peer = site
|
||||
}
|
||||
}
|
||||
|
||||
@@ -21,12 +21,13 @@ import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/minio/madmin-go/v3"
|
||||
|
||||
"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/console"
|
||||
"github.com/minio/pkg/v3/console"
|
||||
)
|
||||
|
||||
var adminReplicateResyncStartCmd = cli.Command{
|
||||
@@ -74,12 +75,10 @@ func (m resyncMessage) String() string {
|
||||
}
|
||||
|
||||
func mainAdminReplicateResyncStart(ctx *cli.Context) error {
|
||||
{
|
||||
// Check argument count
|
||||
argsNr := len(ctx.Args())
|
||||
if argsNr != 2 {
|
||||
cli.ShowCommandHelpAndExit(ctx, "start", 1) // last argument is exit code
|
||||
}
|
||||
// Check argument count
|
||||
argsNr := len(ctx.Args())
|
||||
if argsNr != 2 {
|
||||
showCommandHelpAndExit(ctx, 1) // last argument is exit code
|
||||
}
|
||||
|
||||
console.SetColor("ResyncMessage", color.New(color.FgGreen))
|
||||
@@ -87,15 +86,20 @@ func mainAdminReplicateResyncStart(ctx *cli.Context) error {
|
||||
|
||||
// Get the alias parameter from cli
|
||||
args := ctx.Args()
|
||||
aliasedURL := args.Get(0)
|
||||
|
||||
// Create a new MinIO Admin Client
|
||||
client, err := newAdminClient(aliasedURL)
|
||||
client, err := newAdminClient(args.Get(0))
|
||||
fatalIf(err, "Unable to initialize admin connection.")
|
||||
info, e := client.SiteReplicationInfo(globalContext)
|
||||
fatalIf(probe.NewError(e), "Unable to fetch site replication info.")
|
||||
|
||||
peerClient := getClient(args.Get(1))
|
||||
peerAdmInfo, e := peerClient.ServerInfo(globalContext)
|
||||
fatalIf(probe.NewError(e), "Unable to fetch server info of the peer.")
|
||||
|
||||
var peer madmin.PeerInfo
|
||||
for _, site := range info.Sites {
|
||||
if args[1] == site.Name {
|
||||
if peerAdmInfo.DeploymentID == site.DeploymentID {
|
||||
peer = site
|
||||
}
|
||||
}
|
||||
|
||||
@@ -32,7 +32,7 @@ import (
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/madmin-go/v3"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/pkg/console"
|
||||
"github.com/minio/pkg/v3/console"
|
||||
"github.com/olekukonko/tablewriter"
|
||||
)
|
||||
|
||||
@@ -60,12 +60,10 @@ EXAMPLES:
|
||||
}
|
||||
|
||||
func mainAdminReplicationResyncStatus(ctx *cli.Context) error {
|
||||
{
|
||||
// Check argument count
|
||||
argsNr := len(ctx.Args())
|
||||
if argsNr != 2 {
|
||||
cli.ShowCommandHelpAndExit(ctx, "status", 1) // last argument is exit code
|
||||
}
|
||||
// Check argument count
|
||||
argsNr := len(ctx.Args())
|
||||
if argsNr != 2 {
|
||||
showCommandHelpAndExit(ctx, 1) // last argument is exit code
|
||||
}
|
||||
|
||||
console.SetColor("ResyncMessage", color.New(color.FgGreen))
|
||||
@@ -86,9 +84,14 @@ func mainAdminReplicationResyncStatus(ctx *cli.Context) error {
|
||||
console.Colorize("ResyncMessage", "SiteReplication is not enabled")
|
||||
return nil
|
||||
}
|
||||
|
||||
peerClient := getClient(args.Get(1))
|
||||
peerAdmInfo, e := peerClient.ServerInfo(globalContext)
|
||||
fatalIf(probe.NewError(e), "Unable to fetch server info of the peer.")
|
||||
|
||||
var peer madmin.PeerInfo
|
||||
for _, site := range info.Sites {
|
||||
if args[1] == site.Name {
|
||||
if peerAdmInfo.DeploymentID == site.DeploymentID {
|
||||
peer = site
|
||||
}
|
||||
}
|
||||
@@ -203,7 +206,7 @@ func (m *resyncMetricsUI) View() string {
|
||||
table.SetNoWhiteSpace(true)
|
||||
|
||||
var data [][]string
|
||||
addLine := func(prefix string, value interface{}) {
|
||||
addLine := func(prefix string, value any) {
|
||||
data = append(data, []string{
|
||||
prefix,
|
||||
whiteStyle.Render(fmt.Sprint(value)),
|
||||
|
||||
+229
-36
@@ -21,13 +21,16 @@ import (
|
||||
"fmt"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
humanize "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/console"
|
||||
"github.com/minio/minio-go/v7/pkg/replication"
|
||||
"github.com/minio/pkg/v3/console"
|
||||
)
|
||||
|
||||
var adminReplicateStatusFlags = []cli.Flag{
|
||||
@@ -47,6 +50,10 @@ var adminReplicateStatusFlags = []cli.Flag{
|
||||
Name: "groups",
|
||||
Usage: "display only groups",
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "ilm-expiry-rules",
|
||||
Usage: "display only ilm expiry rules",
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "all",
|
||||
Usage: "display all available site replication status",
|
||||
@@ -67,6 +74,10 @@ var adminReplicateStatusFlags = []cli.Flag{
|
||||
Name: "group",
|
||||
Usage: "display group sync status",
|
||||
},
|
||||
cli.StringFlag{
|
||||
Name: "ilm-expiry-rule",
|
||||
Usage: "display ILM expiry rule sync status",
|
||||
},
|
||||
}
|
||||
|
||||
// Some cell values
|
||||
@@ -122,7 +133,9 @@ func (i srStatus) JSON() string {
|
||||
|
||||
func (i srStatus) String() string {
|
||||
var messages []string
|
||||
|
||||
ms := i.Metrics
|
||||
q := i.Metrics.Queued
|
||||
w := i.Metrics.ActiveWorkers
|
||||
// Color palette initialization
|
||||
console.SetColor("Summary", color.New(color.FgWhite, color.Bold))
|
||||
console.SetColor("SummaryHdr", color.New(color.FgCyan, color.Bold))
|
||||
@@ -154,8 +167,8 @@ func (i srStatus) String() string {
|
||||
if i.opts.Buckets {
|
||||
messages = append(messages,
|
||||
console.Colorize("SummaryHdr", "Bucket replication status:"))
|
||||
switch {
|
||||
case i.MaxBuckets == 0:
|
||||
switch i.MaxBuckets {
|
||||
case 0:
|
||||
messages = append(messages, console.Colorize("Summary", "No Buckets present\n"))
|
||||
default:
|
||||
msg := console.Colorize(i.getTheme(len(info.BucketStats) == 0), fmt.Sprintf("%d/%d Buckets in sync", info.MaxBuckets-len(info.BucketStats), info.MaxBuckets)) + "\n"
|
||||
@@ -174,7 +187,7 @@ func (i srStatus) String() string {
|
||||
ss := ssMap[dID]
|
||||
switch {
|
||||
case !ss.HasBucket:
|
||||
details = append(details, fmt.Sprintf("%s Bucket", blankCell))
|
||||
details = append(details, fmt.Sprintf("%s ", blankCell))
|
||||
case ss.OLockConfigMismatch, ss.PolicyMismatch, ss.QuotaCfgMismatch, ss.ReplicationCfgMismatch, ss.TagMismatch:
|
||||
details = append(details, fmt.Sprintf("%s in-sync", crossTickCell))
|
||||
default:
|
||||
@@ -191,8 +204,8 @@ func (i srStatus) String() string {
|
||||
if i.opts.Policies {
|
||||
messages = append(messages,
|
||||
console.Colorize("SummaryHdr", "Policy replication status:"))
|
||||
switch {
|
||||
case i.MaxPolicies == 0:
|
||||
switch i.MaxPolicies {
|
||||
case 0:
|
||||
messages = append(messages, console.Colorize("Summary", "No Policies present\n"))
|
||||
default:
|
||||
msg := console.Colorize(i.getTheme(len(i.PolicyStats) == 0), fmt.Sprintf("%d/%d Policies in sync", info.MaxPolicies-len(info.PolicyStats), info.MaxPolicies)) + "\n"
|
||||
@@ -212,7 +225,7 @@ func (i srStatus) String() string {
|
||||
ss := ssMap[dID]
|
||||
switch {
|
||||
case !ss.HasPolicy:
|
||||
details = append(details, fmt.Sprintf("%s Policy", blankCell))
|
||||
details = append(details, blankCell)
|
||||
case ss.PolicyMismatch:
|
||||
details = append(details, fmt.Sprintf("%s in-sync", crossTickCell))
|
||||
default:
|
||||
@@ -230,8 +243,8 @@ func (i srStatus) String() string {
|
||||
if i.opts.Users {
|
||||
messages = append(messages,
|
||||
console.Colorize("SummaryHdr", "User replication status:"))
|
||||
switch {
|
||||
case i.MaxUsers == 0:
|
||||
switch i.MaxUsers {
|
||||
case 0:
|
||||
messages = append(messages, console.Colorize("Summary", "No Users present\n"))
|
||||
default:
|
||||
msg := console.Colorize(i.getTheme(len(i.UserStats) == 0), fmt.Sprintf("%d/%d Users in sync", info.MaxUsers-len(i.UserStats), info.MaxUsers)) + "\n"
|
||||
@@ -271,8 +284,8 @@ func (i srStatus) String() string {
|
||||
if i.opts.Groups {
|
||||
messages = append(messages,
|
||||
console.Colorize("SummaryHdr", "Group replication status:"))
|
||||
switch {
|
||||
case i.MaxGroups == 0:
|
||||
switch i.MaxGroups {
|
||||
case 0:
|
||||
messages = append(messages, console.Colorize("Summary", "No Groups present\n"))
|
||||
default:
|
||||
msg := console.Colorize(i.getTheme(len(i.GroupStats) == 0), fmt.Sprintf("%d/%d Groups in sync", i.MaxGroups-len(i.GroupStats), i.MaxGroups)) + "\n"
|
||||
@@ -307,6 +320,44 @@ func (i srStatus) String() string {
|
||||
}
|
||||
}
|
||||
}
|
||||
if i.opts.ILMExpiryRules {
|
||||
messages = append(messages,
|
||||
console.Colorize("SummaryHdr", "ILM Expiry Rules replication status:"))
|
||||
switch {
|
||||
case i.MaxILMExpiryRules == 0:
|
||||
messages = append(messages, console.Colorize("Summary", "No ILM Expiry Rules present\n"))
|
||||
case i.ILMExpiryStats == nil:
|
||||
messages = append(messages, console.Colorize("Summary", "Replication of ILM Expiry is not enabled\n"))
|
||||
default:
|
||||
msg := console.Colorize(i.getTheme(len(info.ILMExpiryStats) == 0), fmt.Sprintf("%d/%d ILM Expiry Rules in sync", info.MaxILMExpiryRules-len(info.ILMExpiryStats), info.MaxILMExpiryRules)) + "\n"
|
||||
messages = append(messages, fmt.Sprintf("%s %s", coloredDot, msg))
|
||||
if len(i.ILMExpiryStats) > 0 {
|
||||
messages = append(messages, i.siteHeader(siteNames, "ILM Expiry Rules"))
|
||||
}
|
||||
var detailFields []Field
|
||||
for b, ssMap := range i.ILMExpiryStats {
|
||||
var details []string
|
||||
details = append(details, b)
|
||||
detailFields = append(detailFields, legendFields[0])
|
||||
for _, sname := range siteNames {
|
||||
detailFields = append(detailFields, legendFields[0])
|
||||
dID := nameIDMap[sname]
|
||||
ss := ssMap[dID]
|
||||
switch {
|
||||
case !ss.HasILMExpiryRules:
|
||||
details = append(details, blankCell)
|
||||
case ss.ILMExpiryRuleMismatch:
|
||||
details = append(details, fmt.Sprintf("%s in-sync", crossTickCell))
|
||||
default:
|
||||
details = append(details, fmt.Sprintf("%s in-sync", tickCell))
|
||||
}
|
||||
}
|
||||
messages = append(messages, newPrettyTable(" | ",
|
||||
detailFields...).buildRow(details...))
|
||||
messages = append(messages, "")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
switch i.opts.Entity {
|
||||
case madmin.SRBucketEntity:
|
||||
@@ -317,9 +368,86 @@ func (i srStatus) String() string {
|
||||
messages = append(messages, i.getUserStatusSummary(siteNames, nameIDMap, "User")...)
|
||||
case madmin.SRGroupEntity:
|
||||
messages = append(messages, i.getGroupStatusSummary(siteNames, nameIDMap, "Group")...)
|
||||
|
||||
case madmin.SRILMExpiryRuleEntity:
|
||||
messages = append(messages, i.getILMExpiryStatusSummary(siteNames, nameIDMap, "ILMExpiryRule")...)
|
||||
}
|
||||
if i.opts.Metrics {
|
||||
uiFn := func(theme string) func(string) string {
|
||||
return func(s string) string {
|
||||
return console.Colorize(theme, s)
|
||||
}
|
||||
}
|
||||
singleTgt := len(ms.Metrics) == 1
|
||||
maxui := uiFn("Peak")
|
||||
avgui := uiFn("Avg")
|
||||
valueui := uiFn("Value")
|
||||
messages = append(messages,
|
||||
console.Colorize("SummaryHdr", "Object replication status:"))
|
||||
|
||||
messages = append(messages, console.Colorize("UptimeStr", fmt.Sprintf("Replication status since %s", uiFn("Uptime")(humanize.RelTime(time.Now(), time.Now().Add(time.Duration(ms.Uptime)*time.Second), "", "ago")))))
|
||||
// for queue stats
|
||||
coloredDot := console.Colorize("qStatusOK", dot)
|
||||
if q.Curr.Count > q.Avg.Count {
|
||||
coloredDot = console.Colorize("qStatusWarn", dot)
|
||||
}
|
||||
|
||||
var replicatedCount, replicatedSize int64
|
||||
for _, m := range ms.Metrics {
|
||||
nodeName := m.Endpoint
|
||||
nodeui := uiFn(getNodeTheme(nodeName))
|
||||
messages = append(messages, nodeui(nodeName))
|
||||
messages = append(messages, fmt.Sprintf("Replicated: %s objects (%s)", humanize.Comma(int64(m.ReplicatedCount)), valueui(humanize.IBytes(uint64(m.ReplicatedSize)))))
|
||||
|
||||
if singleTgt { // for single target - combine summary section into the target section
|
||||
messages = append(messages, fmt.Sprintf("Received: %s objects (%s)", humanize.Comma(int64(ms.ReplicaCount)), humanize.IBytes(uint64(ms.ReplicaSize))))
|
||||
messages = append(messages, fmt.Sprintf("Queued: %s %s objects, (%s) (%s: %s objects, %s; %s: %s objects, %s)", coloredDot, humanize.Comma(int64(q.Curr.Count)), valueui(humanize.IBytes(uint64(q.Curr.Bytes))), avgui("avg"),
|
||||
humanize.Comma(int64(q.Avg.Count)), valueui(humanize.IBytes(uint64(q.Avg.Bytes))), maxui("max"),
|
||||
humanize.Comma(int64(q.Max.Count)), valueui(humanize.IBytes(uint64(q.Max.Bytes)))))
|
||||
messages = append(messages, fmt.Sprintf("Workers: %s (%s: %s; %s %s) ", humanize.Comma(int64(w.Curr)), avgui("avg"), humanize.Comma(int64(w.Avg)), maxui("max"), humanize.Comma(int64(w.Max))))
|
||||
} else {
|
||||
replicatedCount += m.ReplicatedCount
|
||||
replicatedSize += m.ReplicatedSize
|
||||
}
|
||||
|
||||
if m.XferStats != nil {
|
||||
tgtXfer, ok := m.XferStats[replication.Total]
|
||||
if ok {
|
||||
messages = append(messages, fmt.Sprintf("Transfer Rate: %s/s (avg: %s/s; max %s/s)", valueui(humanize.Bytes(uint64(tgtXfer.CurrRate))), valueui(humanize.Bytes(uint64(tgtXfer.AvgRate))), valueui(humanize.Bytes(uint64(tgtXfer.PeakRate)))))
|
||||
messages = append(messages, fmt.Sprintf("Latency: %s (avg: %s; max %s)", valueui(m.Latency.Curr.Round(time.Millisecond).String()), valueui(m.Latency.Avg.Round(time.Millisecond).String()), valueui(m.Latency.Max.Round(time.Millisecond).String())))
|
||||
}
|
||||
}
|
||||
|
||||
healthDot := console.Colorize("online", dot)
|
||||
if !m.Online {
|
||||
healthDot = console.Colorize("offline", dot)
|
||||
}
|
||||
currDowntime := time.Duration(0)
|
||||
if !m.Online && !m.LastOnline.IsZero() {
|
||||
currDowntime = UTCNow().Sub(m.LastOnline)
|
||||
}
|
||||
// normalize because total downtime is calculated at server side at heartbeat interval, may be slightly behind
|
||||
totalDowntime := max(currDowntime, m.TotalDowntime)
|
||||
var linkStatus string
|
||||
if m.Online {
|
||||
linkStatus = healthDot + fmt.Sprintf(" online (total downtime: %s)", timeDurationToHumanizedDuration(totalDowntime).String())
|
||||
} else {
|
||||
linkStatus = healthDot + fmt.Sprintf(" offline %s (total downtime: %s)", timeDurationToHumanizedDuration(currDowntime).String(), valueui(timeDurationToHumanizedDuration(totalDowntime).String()))
|
||||
}
|
||||
messages = append(messages, fmt.Sprintf("Link: %s", linkStatus))
|
||||
messages = append(messages, fmt.Sprintf("Errors: %s in last 1 minute; %s in last 1hr; %s since uptime", valueui(humanize.Comma(int64(m.Failed.LastMinute.Count))), valueui(humanize.Comma(int64(m.Failed.LastHour.Count))), valueui(humanize.Comma(int64(m.Failed.Totals.Count)))))
|
||||
messages = append(messages, "")
|
||||
}
|
||||
if !singleTgt {
|
||||
messages = append(messages,
|
||||
console.Colorize("SummaryHdr", "Summary:"))
|
||||
messages = append(messages, fmt.Sprintf("Replicated: %s objects (%s)", humanize.Comma(int64(replicatedCount)), valueui(humanize.IBytes(uint64(replicatedSize)))))
|
||||
messages = append(messages, fmt.Sprintf("Queued: %s %s objects, (%s) (%s: %s objects, %s; %s: %s objects, %s)", coloredDot, humanize.Comma(int64(q.Curr.Count)), valueui(humanize.IBytes(uint64(q.Curr.Bytes))), avgui("avg"),
|
||||
humanize.Comma(int64(q.Avg.Count)), valueui(humanize.IBytes(uint64(q.Avg.Bytes))), maxui("max"),
|
||||
humanize.Comma(int64(q.Max.Count)), valueui(humanize.IBytes(uint64(q.Max.Bytes)))))
|
||||
|
||||
messages = append(messages, fmt.Sprintf("Received: %s objects (%s)", humanize.Comma(int64(ms.ReplicaCount)), humanize.IBytes(uint64(ms.ReplicaSize))))
|
||||
}
|
||||
}
|
||||
return console.Colorize("UserMessage", strings.Join(messages, "\n"))
|
||||
}
|
||||
|
||||
@@ -347,7 +475,7 @@ func (i srStatus) getBucketStatusSummary(siteNames []string, nameIDMap map[strin
|
||||
var messages []string
|
||||
coloredDot := console.Colorize("Status", dot)
|
||||
var found bool
|
||||
for _, st := range i.SRStatusInfo.BucketStats[i.opts.EntityValue] {
|
||||
for _, st := range i.BucketStats[i.opts.EntityValue] {
|
||||
if st.HasBucket {
|
||||
found = true
|
||||
break
|
||||
@@ -387,7 +515,7 @@ func (i srStatus) getBucketStatusSummary(siteNames []string, nameIDMap map[strin
|
||||
rows := make([]string, len(rowLegend))
|
||||
for j, sname := range siteNames {
|
||||
dID := nameIDMap[sname]
|
||||
ss := i.SRStatusInfo.BucketStats[i.opts.EntityValue][dID]
|
||||
ss := i.BucketStats[i.opts.EntityValue][dID]
|
||||
var theme, msgStr string
|
||||
for r := range rowLegend {
|
||||
switch r {
|
||||
@@ -443,6 +571,7 @@ func (i srStatus) getBucketStatusSummary(siteNames []string, nameIDMap map[strin
|
||||
}
|
||||
}
|
||||
messages = append(messages, rows...)
|
||||
|
||||
return messages
|
||||
}
|
||||
|
||||
@@ -450,7 +579,7 @@ func (i srStatus) getPolicyStatusSummary(siteNames []string, nameIDMap map[strin
|
||||
var messages []string
|
||||
coloredDot := console.Colorize("Status", dot)
|
||||
var found bool
|
||||
for _, st := range i.SRStatusInfo.PolicyStats[i.opts.EntityValue] {
|
||||
for _, st := range i.PolicyStats[i.opts.EntityValue] {
|
||||
if st.HasPolicy {
|
||||
found = true
|
||||
break
|
||||
@@ -471,7 +600,7 @@ func (i srStatus) getPolicyStatusSummary(siteNames []string, nameIDMap map[strin
|
||||
rows := make([]string, len(rowLegend))
|
||||
for j, sname := range siteNames {
|
||||
dID := nameIDMap[sname]
|
||||
ss := i.SRStatusInfo.PolicyStats[i.opts.EntityValue][dID]
|
||||
ss := i.PolicyStats[i.opts.EntityValue][dID]
|
||||
var theme, msgStr string
|
||||
for r := range rowLegend {
|
||||
switch r {
|
||||
@@ -502,7 +631,7 @@ func (i srStatus) getUserStatusSummary(siteNames []string, nameIDMap map[string]
|
||||
var messages []string
|
||||
coloredDot := console.Colorize("Status", dot)
|
||||
var found bool
|
||||
for _, st := range i.SRStatusInfo.UserStats[i.opts.EntityValue] {
|
||||
for _, st := range i.UserStats[i.opts.EntityValue] {
|
||||
if st.HasUser {
|
||||
found = true
|
||||
break
|
||||
@@ -530,7 +659,7 @@ func (i srStatus) getUserStatusSummary(siteNames []string, nameIDMap map[string]
|
||||
rows := make([]string, len(rowLegend))
|
||||
for j, sname := range siteNames {
|
||||
dID := nameIDMap[sname]
|
||||
ss := i.SRStatusInfo.UserStats[i.opts.EntityValue][dID]
|
||||
ss := i.UserStats[i.opts.EntityValue][dID]
|
||||
var theme, msgStr string
|
||||
for r := range rowLegend {
|
||||
switch r {
|
||||
@@ -570,7 +699,7 @@ func (i srStatus) getGroupStatusSummary(siteNames []string, nameIDMap map[string
|
||||
rowLegend := []string{"Info", "Policy mapping"}
|
||||
detailFields := make([][]Field, len(rowLegend))
|
||||
var found bool
|
||||
for _, st := range i.SRStatusInfo.GroupStats[i.opts.EntityValue] {
|
||||
for _, st := range i.GroupStats[i.opts.EntityValue] {
|
||||
if st.HasGroup {
|
||||
found = true
|
||||
break
|
||||
@@ -596,7 +725,7 @@ func (i srStatus) getGroupStatusSummary(siteNames []string, nameIDMap map[string
|
||||
// b := i.opts.EntityValue
|
||||
for j, sname := range siteNames {
|
||||
dID := nameIDMap[sname]
|
||||
ss := i.SRStatusInfo.GroupStats[i.opts.EntityValue][dID]
|
||||
ss := i.GroupStats[i.opts.EntityValue][dID]
|
||||
// sm := i.SRStatusInfo.StatsSummary
|
||||
var theme, msgStr string
|
||||
for r := range rowLegend {
|
||||
@@ -631,28 +760,75 @@ func (i srStatus) getGroupStatusSummary(siteNames []string, nameIDMap map[string
|
||||
return messages
|
||||
}
|
||||
|
||||
func (i srStatus) getILMExpiryStatusSummary(siteNames []string, nameIDMap map[string]string, legend string) []string {
|
||||
var messages []string
|
||||
coloredDot := console.Colorize("Status", dot)
|
||||
var found bool
|
||||
for _, st := range i.ILMExpiryStats[i.opts.EntityValue] {
|
||||
if st.HasILMExpiryRules {
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
messages = append(messages, console.Colorize("Summary", fmt.Sprintf("ILM Expiry Rule %s not found\n", i.opts.EntityValue)))
|
||||
return messages
|
||||
}
|
||||
|
||||
rowLegend := []string{"ILM Expiry Rule"}
|
||||
detailFields := make([][]Field, len(rowLegend))
|
||||
|
||||
var rules []string
|
||||
detailFields[0] = make([]Field, len(siteNames)+1)
|
||||
detailFields[0][0] = Field{"Entity", 15}
|
||||
rules = append(rules, "ILM Expiry Rule")
|
||||
rows := make([]string, len(rowLegend))
|
||||
for j, sname := range siteNames {
|
||||
dID := nameIDMap[sname]
|
||||
ss := i.ILMExpiryStats[i.opts.EntityValue][dID]
|
||||
var theme, msgStr string
|
||||
for r := range rowLegend {
|
||||
switch r {
|
||||
case 0:
|
||||
theme, msgStr = syncStatus(ss.ILMExpiryRuleMismatch, ss.HasILMExpiryRules)
|
||||
rules = append(rules, msgStr)
|
||||
detailFields[r][j+1] = Field{theme, fieldLen}
|
||||
}
|
||||
}
|
||||
}
|
||||
for r := range rowLegend {
|
||||
switch r {
|
||||
case 0:
|
||||
rows[r] = newPrettyTable(" | ",
|
||||
detailFields[r]...).buildRow(rules...)
|
||||
}
|
||||
}
|
||||
messages = append(messages,
|
||||
console.Colorize("SummaryHdr", fmt.Sprintf("%s %s\n", coloredDot, console.Colorize("Summary", "ILM Expiry Rule replication summary for: ")+console.Colorize("UserMessage", i.opts.EntityValue))))
|
||||
siteHdr := i.siteHeader(siteNames, legend)
|
||||
messages = append(messages, siteHdr)
|
||||
|
||||
messages = append(messages, rows...)
|
||||
return messages
|
||||
}
|
||||
|
||||
// Calculate srstatus options for command line flags
|
||||
func srStatusOpts(ctx *cli.Context) (opts madmin.SRStatusOptions) {
|
||||
if !(ctx.IsSet("buckets") ||
|
||||
ctx.IsSet("users") ||
|
||||
ctx.IsSet("groups") ||
|
||||
ctx.IsSet("policies") ||
|
||||
ctx.IsSet("bucket") ||
|
||||
ctx.IsSet("user") ||
|
||||
ctx.IsSet("group") ||
|
||||
ctx.IsSet("policy") ||
|
||||
ctx.IsSet("all")) || ctx.IsSet("all") {
|
||||
if (!ctx.IsSet("buckets") && !ctx.IsSet("users") && !ctx.IsSet("groups") && !ctx.IsSet("policies") && !ctx.IsSet("ilm-expiry-rules") && !ctx.IsSet("bucket") && !ctx.IsSet("user") && !ctx.IsSet("group") && !ctx.IsSet("policy") && !ctx.IsSet("ilm-expiry-rule") && !ctx.IsSet("all")) || ctx.IsSet("all") {
|
||||
opts.Buckets = true
|
||||
opts.Users = true
|
||||
opts.Groups = true
|
||||
opts.Policies = true
|
||||
opts.Metrics = true
|
||||
opts.ILMExpiryRules = true
|
||||
return
|
||||
}
|
||||
opts.Buckets = ctx.Bool("buckets")
|
||||
opts.Policies = ctx.Bool("policies")
|
||||
opts.Users = ctx.Bool("users")
|
||||
opts.Groups = ctx.Bool("groups")
|
||||
for _, name := range []string{"bucket", "user", "group", "policy"} {
|
||||
opts.ILMExpiryRules = ctx.Bool("ilm-expiry-rules")
|
||||
for _, name := range []string{"bucket", "user", "group", "policy", "ilm-expiry-rule"} {
|
||||
if ctx.IsSet(name) {
|
||||
opts.Entity = madmin.GetSREntityType(name)
|
||||
opts.EntityValue = ctx.String(name)
|
||||
@@ -670,13 +846,13 @@ func mainAdminReplicationStatus(ctx *cli.Context) error {
|
||||
fatalIf(errInvalidArgument().Trace(ctx.Args().Tail()...),
|
||||
"Need exactly one alias argument.")
|
||||
}
|
||||
groupStatus := ctx.IsSet("buckets") || ctx.IsSet("groups") || ctx.IsSet("users") || ctx.IsSet("policies")
|
||||
indivStatus := ctx.IsSet("bucket") || ctx.IsSet("group") || ctx.IsSet("user") || ctx.IsSet("policy")
|
||||
groupStatus := ctx.IsSet("buckets") || ctx.IsSet("groups") || ctx.IsSet("users") || ctx.IsSet("policies") || ctx.IsSet("ilm-expiry-rules")
|
||||
indivStatus := ctx.IsSet("bucket") || ctx.IsSet("group") || ctx.IsSet("user") || ctx.IsSet("policy") || ctx.IsSet("ilm-expiry-rule")
|
||||
if groupStatus && indivStatus {
|
||||
fatalIf(errInvalidArgument().Trace(ctx.Args().Tail()...),
|
||||
"Cannot specify both (bucket|group|policy|user) flag and one or more of buckets|groups|policies|users) flag(s)")
|
||||
"Cannot specify both (bucket|group|policy|user|ilm-expiry-rule) flag and one or more of buckets|groups|policies|users|ilm-expiry-rules) flag(s)")
|
||||
}
|
||||
setSlc := []bool{ctx.IsSet("bucket"), ctx.IsSet("user"), ctx.IsSet("group"), ctx.IsSet("policy")}
|
||||
setSlc := []bool{ctx.IsSet("bucket"), ctx.IsSet("user"), ctx.IsSet("group"), ctx.IsSet("policy"), ctx.IsSet("ilm-expiry-rule")}
|
||||
count := 0
|
||||
for _, s := range setSlc {
|
||||
if s {
|
||||
@@ -685,12 +861,29 @@ func mainAdminReplicationStatus(ctx *cli.Context) error {
|
||||
}
|
||||
if count > 1 {
|
||||
fatalIf(errInvalidArgument().Trace(ctx.Args().Tail()...),
|
||||
"Cannot specify more than one of --bucket, --policy, --user, --group flags at the same time")
|
||||
"Cannot specify more than one of --bucket, --policy, --user, --group, --ilm-expiry-rule flags at the same time")
|
||||
}
|
||||
}
|
||||
|
||||
console.SetColor("UserMessage", color.New(color.FgGreen))
|
||||
console.SetColor("WarningMessage", color.New(color.FgYellow))
|
||||
for _, c := range colors {
|
||||
console.SetColor(fmt.Sprintf("Node%d", c), color.New(c, color.Bold))
|
||||
}
|
||||
console.SetColor("Replicated", color.New(color.FgCyan))
|
||||
console.SetColor("In-Queue", color.New(color.Bold, color.FgYellow))
|
||||
console.SetColor("Avg", color.New(color.FgCyan))
|
||||
console.SetColor("Peak", color.New(color.FgYellow))
|
||||
console.SetColor("Value", color.New(color.FgWhite, color.Bold))
|
||||
|
||||
console.SetColor("Current", color.New(color.FgCyan))
|
||||
console.SetColor("Uptime", color.New(color.Bold, color.FgWhite))
|
||||
console.SetColor("UptimeStr", color.New(color.FgHiWhite))
|
||||
|
||||
console.SetColor("qStatusWarn", color.New(color.FgYellow, color.Bold))
|
||||
console.SetColor("qStatusOK", color.New(color.FgGreen, color.Bold))
|
||||
console.SetColor("online", color.New(color.FgGreen, color.Bold))
|
||||
console.SetColor("offline", color.New(color.FgRed, color.Bold))
|
||||
|
||||
// Get the alias parameter from cli
|
||||
args := ctx.Args()
|
||||
|
||||
@@ -26,7 +26,7 @@ import (
|
||||
json "github.com/minio/colorjson"
|
||||
"github.com/minio/madmin-go/v3"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/pkg/console"
|
||||
"github.com/minio/pkg/v3/console"
|
||||
)
|
||||
|
||||
var adminReplicateUpdateFlags = []cli.Flag{
|
||||
@@ -48,7 +48,18 @@ var adminReplicateUpdateFlags = []cli.Flag{
|
||||
Usage: "enable synchronous replication for this target, valid values are ['enable', 'disable'].",
|
||||
Value: "disable",
|
||||
Hidden: true, // deprecated Jul 2023
|
||||
|
||||
},
|
||||
cli.StringFlag{
|
||||
Name: "bucket-bandwidth",
|
||||
Usage: "Set default bandwidth limit for bucket in bytes per second (K,B,G,T for metric and Ki,Bi,Gi,Ti for IEC units)",
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "disable-ilm-expiry-replication",
|
||||
Usage: "disable ILM expiry rules replication",
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "enable-ilm-expiry-replication",
|
||||
Usage: "enable ILM expiry rules replication",
|
||||
},
|
||||
}
|
||||
|
||||
@@ -74,6 +85,15 @@ FLAGS:
|
||||
EXAMPLES:
|
||||
1. Edit a site endpoint participating in cluster-level replication:
|
||||
{{.Prompt}} {{.HelpName}} myminio --deployment-id c1758167-4426-454f-9aae-5c3dfdf6df64 --endpoint https://minio2:9000
|
||||
|
||||
2. Set default bucket bandwidth limit for replication from myminio to the peer cluster with deployment-id c1758167-4426-454f-9aae-5c3dfdf6df64
|
||||
{{.Prompt}} {{.HelpName}} myminio --deployment-id c1758167-4426-454f-9aae-5c3dfdf6df64 --bucket-bandwidth "2G"
|
||||
|
||||
3. Disable replication of ILM expiry in cluster-level replication:
|
||||
{{.Prompt}} {{.HelpName}} myminio --disable-ilm-expiry-replication
|
||||
|
||||
4. Enable replication of ILM expiry in cluster-level replication:
|
||||
{{.Prompt}} {{.HelpName}} myminio --enable-ilm-expiry-replication
|
||||
`,
|
||||
}
|
||||
|
||||
@@ -119,15 +139,21 @@ func mainAdminReplicateUpdate(ctx *cli.Context) error {
|
||||
client, err := newAdminClient(aliasedURL)
|
||||
fatalIf(err, "Unable to initialize admin connection.")
|
||||
|
||||
if !ctx.IsSet("deployment-id") {
|
||||
if !ctx.IsSet("deployment-id") && !ctx.IsSet("disable-ilm-expiry-replication") && !ctx.IsSet("enable-ilm-expiry-replication") {
|
||||
fatalIf(errInvalidArgument(), "--deployment-id is a required flag")
|
||||
}
|
||||
if !ctx.IsSet("endpoint") && !ctx.IsSet("mode") && !ctx.IsSet("sync") {
|
||||
fatalIf(errInvalidArgument(), "--endpoint or --mode is a required flag")
|
||||
if !ctx.IsSet("endpoint") && !ctx.IsSet("mode") && !ctx.IsSet("sync") && !ctx.IsSet("bucket-bandwidth") && !ctx.IsSet("disable-ilm-expiry-replication") && !ctx.IsSet("enable-ilm-expiry-replication") {
|
||||
fatalIf(errInvalidArgument(), "--endpoint, --mode, --bucket-bandwidth, --disable-ilm-expiry-replication or --enable-ilm-expiry-replication is a required flag")
|
||||
}
|
||||
if ctx.IsSet("mode") && ctx.IsSet("sync") {
|
||||
fatalIf(errInvalidArgument(), "either --sync or --mode flag should be specified")
|
||||
}
|
||||
if ctx.IsSet("disable-ilm-expiry-replication") && ctx.IsSet("enable-ilm-expiry-replication") {
|
||||
fatalIf(errInvalidArgument(), "either --disable-ilm-expiry-replication or --enable-ilm-expiry-replication flag should be specified")
|
||||
}
|
||||
if (ctx.IsSet("disable-ilm-expiry-replication") || ctx.IsSet("enable-ilm-expiry-replication")) && ctx.IsSet("deployment-id") {
|
||||
fatalIf(errInvalidArgument(), "--deployment-id should not be set with --disable-ilm-expiry-replication or --enable-ilm-expiry-replication")
|
||||
}
|
||||
|
||||
var syncState string
|
||||
if ctx.IsSet("sync") { // for backward compatibility - deprecated Jul 2023
|
||||
@@ -150,6 +176,16 @@ func mainAdminReplicateUpdate(ctx *cli.Context) error {
|
||||
fatalIf(errInvalidArgument().Trace(args...), "--mode can be either [sync|async]")
|
||||
}
|
||||
}
|
||||
|
||||
var bwDefaults madmin.BucketBandwidth
|
||||
if ctx.IsSet("bucket-bandwidth") {
|
||||
bandwidthStr := ctx.String("bucket-bandwidth")
|
||||
bandwidth, e := getBandwidthInBytes(bandwidthStr)
|
||||
fatalIf(probe.NewError(e).Trace(bandwidthStr), "invalid bandwidth value")
|
||||
|
||||
bwDefaults.Limit = bandwidth
|
||||
bwDefaults.IsSet = true
|
||||
}
|
||||
var ep string
|
||||
if ctx.IsSet("endpoint") {
|
||||
parsedURL := ctx.String("endpoint")
|
||||
@@ -159,11 +195,15 @@ func mainAdminReplicateUpdate(ctx *cli.Context) error {
|
||||
}
|
||||
ep = u.String()
|
||||
}
|
||||
var opts madmin.SREditOptions
|
||||
opts.DisableILMExpiryReplication = ctx.Bool("disable-ilm-expiry-replication")
|
||||
opts.EnableILMExpiryReplication = ctx.Bool("enable-ilm-expiry-replication")
|
||||
res, e := client.SiteReplicationEdit(globalContext, madmin.PeerInfo{
|
||||
DeploymentID: ctx.String("deployment-id"),
|
||||
Endpoint: ep,
|
||||
SyncState: madmin.SyncStatus(syncState),
|
||||
})
|
||||
DeploymentID: ctx.String("deployment-id"),
|
||||
Endpoint: ep,
|
||||
SyncState: madmin.SyncStatus(syncState),
|
||||
DefaultBandwidth: bwDefaults,
|
||||
}, opts)
|
||||
fatalIf(probe.NewError(e).Trace(args...), "Unable to edit cluster replication site endpoint")
|
||||
|
||||
printMsg(updateSuccessMessage(res))
|
||||
|
||||
+244
-53
@@ -18,23 +18,29 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/charmbracelet/bubbles/spinner"
|
||||
tea "github.com/charmbracelet/bubbletea"
|
||||
"github.com/charmbracelet/lipgloss"
|
||||
"github.com/dustin/go-humanize"
|
||||
"github.com/fatih/color"
|
||||
"github.com/klauspost/compress/zstd"
|
||||
"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/console"
|
||||
"github.com/minio/pkg/v3/console"
|
||||
"github.com/olekukonko/tablewriter"
|
||||
)
|
||||
|
||||
@@ -58,6 +64,14 @@ var adminScannerInfoFlags = []cli.Flag{
|
||||
Usage: "maximum number of active paths to show. -1 for unlimited",
|
||||
Value: -1,
|
||||
},
|
||||
cli.StringFlag{
|
||||
Name: "in",
|
||||
Usage: "read previously saved json from file and replay",
|
||||
},
|
||||
cli.StringFlag{
|
||||
Name: "bucket",
|
||||
Usage: "show scan stats about a given bucket",
|
||||
},
|
||||
}
|
||||
|
||||
var adminScannerInfo = cli.Command{
|
||||
@@ -87,22 +101,161 @@ EXAMPLES:
|
||||
|
||||
// checkAdminTopAPISyntax - validate all the passed arguments
|
||||
func checkAdminScannerInfoSyntax(ctx *cli.Context) {
|
||||
if ctx.String("in") != "" {
|
||||
return
|
||||
}
|
||||
if len(ctx.Args()) == 0 || len(ctx.Args()) > 1 {
|
||||
showCommandHelpAndExit(ctx, 1) // last argument is exit code
|
||||
}
|
||||
}
|
||||
|
||||
// bucketScanMsg container for content message structure
|
||||
type bucketScanMsg struct {
|
||||
Status string `json:"status"`
|
||||
Stats []madmin.BucketScanInfo `json:"stats"`
|
||||
}
|
||||
|
||||
func (b bucketScanMsg) String() string {
|
||||
var sb strings.Builder
|
||||
sb.WriteString("\n")
|
||||
|
||||
sort.Slice(b.Stats, func(i, j int) bool { return b.Stats[i].LastUpdate.Before(b.Stats[j].LastUpdate) })
|
||||
|
||||
pt := newPrettyTable(" | ",
|
||||
Field{"Pool", 5},
|
||||
Field{"Set", 5},
|
||||
Field{"LastUpdate", timeFieldMaxLen},
|
||||
)
|
||||
|
||||
sb.WriteString(console.Colorize("Headers", pt.buildRow("Pool", "Set", "Last Update")) + "\n")
|
||||
|
||||
now := time.Now().UTC()
|
||||
for i := range b.Stats {
|
||||
sb.WriteString(
|
||||
pt.buildRow(
|
||||
strconv.Itoa(b.Stats[i].Pool+1),
|
||||
strconv.Itoa(b.Stats[i].Set+1),
|
||||
humanize.RelTime(now, b.Stats[i].LastUpdate, "", "ago"),
|
||||
) + "\n")
|
||||
}
|
||||
|
||||
var (
|
||||
earliestESScan time.Time // the earliest ES that completed a bucket scan
|
||||
latestESScan time.Time // the last ES that completed a bucket scan
|
||||
fullScan = true
|
||||
)
|
||||
|
||||
// Look for a bucket full scan inforation only if all
|
||||
// erasure sets completed at least 16 cycles
|
||||
for _, st := range b.Stats {
|
||||
if len(st.Completed) < 16 {
|
||||
fullScan = false
|
||||
break
|
||||
}
|
||||
if earliestESScan.IsZero() {
|
||||
// First stats
|
||||
earliestESScan = st.Completed[0]
|
||||
latestESScan = st.Completed[len(st.Completed)-1]
|
||||
continue
|
||||
}
|
||||
if earliestESScan.Before(st.Completed[0]) {
|
||||
earliestESScan = st.Completed[0]
|
||||
}
|
||||
if latestESScan.After(st.Completed[len(st.Completed)-1]) {
|
||||
latestESScan = st.Completed[len(st.Completed)-1]
|
||||
}
|
||||
}
|
||||
|
||||
sb.WriteString("\n")
|
||||
|
||||
if fullScan {
|
||||
took := latestESScan.Sub(earliestESScan)
|
||||
sb.WriteString(
|
||||
fmt.Sprintf(
|
||||
"%s %s (took %s)\n",
|
||||
console.Colorize("FullScan", "Full bucket scan: "),
|
||||
humanize.RelTime(now, latestESScan, "", "ago"),
|
||||
fmt.Sprintf("%dd%dh%dm", int(took.Hours()/24), int(took.Hours())%24, int(took.Minutes())%60)),
|
||||
)
|
||||
}
|
||||
|
||||
sb.WriteString("\n")
|
||||
|
||||
return sb.String()
|
||||
}
|
||||
|
||||
func (b bucketScanMsg) JSON() string {
|
||||
b.Status = "success"
|
||||
jsonMessageBytes, e := json.MarshalIndent(b, "", " ")
|
||||
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
|
||||
|
||||
return string(jsonMessageBytes)
|
||||
}
|
||||
|
||||
func mainAdminScannerInfo(ctx *cli.Context) error {
|
||||
console.SetColor("Headers", color.New(color.Bold, color.FgHiGreen))
|
||||
console.SetColor("FullScan", color.New(color.Bold, color.FgHiGreen))
|
||||
|
||||
checkAdminScannerInfoSyntax(ctx)
|
||||
|
||||
aliasedURL := ctx.Args().Get(0)
|
||||
ui := tea.NewProgram(initScannerMetricsUI(ctx.Int("max-paths")))
|
||||
ctxt, cancel := context.WithCancel(globalContext)
|
||||
defer cancel()
|
||||
|
||||
// Replay from file
|
||||
if inFile := ctx.String("in"); inFile != "" {
|
||||
go func() {
|
||||
if _, e := ui.Run(); e != nil {
|
||||
cancel()
|
||||
fatalIf(probe.NewError(e), "Unable to fetch scanner metrics")
|
||||
}
|
||||
}()
|
||||
f, e := os.Open(inFile)
|
||||
fatalIf(probe.NewError(e), "Unable to open input")
|
||||
defer f.Close()
|
||||
in := io.Reader(f)
|
||||
if strings.HasSuffix(inFile, ".zst") {
|
||||
zr, e := zstd.NewReader(in)
|
||||
fatalIf(probe.NewError(e), "Unable to open input")
|
||||
defer zr.Close()
|
||||
in = zr
|
||||
}
|
||||
sc := bufio.NewReader(in)
|
||||
var lastTime time.Time
|
||||
for {
|
||||
b, e := sc.ReadBytes('\n')
|
||||
if e == io.EOF {
|
||||
break
|
||||
}
|
||||
var metrics madmin.RealtimeMetrics
|
||||
e = json.Unmarshal(b, &metrics)
|
||||
if e != nil || metrics.Aggregated.Scanner == nil {
|
||||
continue
|
||||
}
|
||||
delay := metrics.Aggregated.Scanner.CollectedAt.Sub(lastTime)
|
||||
if !lastTime.IsZero() && delay > 0 {
|
||||
if delay > 3*time.Second {
|
||||
delay = 3 * time.Second
|
||||
}
|
||||
time.Sleep(delay)
|
||||
}
|
||||
ui.Send(metrics)
|
||||
lastTime = metrics.Aggregated.Scanner.CollectedAt
|
||||
}
|
||||
os.Exit(0)
|
||||
}
|
||||
|
||||
// Create a new MinIO Admin Client
|
||||
aliasedURL := ctx.Args().Get(0)
|
||||
client, err := newAdminClient(aliasedURL)
|
||||
fatalIf(err.Trace(aliasedURL), "Unable to initialize admin client.")
|
||||
|
||||
ctxt, cancel := context.WithCancel(globalContext)
|
||||
defer cancel()
|
||||
if bucket := ctx.String("bucket"); bucket != "" {
|
||||
bucketStats, err := client.BucketScanInfo(globalContext, bucket)
|
||||
fatalIf(probe.NewError(err).Trace(aliasedURL), "Unable to get bucket stats.")
|
||||
printMsg(bucketScanMsg{Stats: bucketStats})
|
||||
return nil
|
||||
}
|
||||
|
||||
opts := madmin.MetricsOptions{
|
||||
Type: madmin.MetricsScanner,
|
||||
@@ -111,7 +264,6 @@ func mainAdminScannerInfo(ctx *cli.Context) error {
|
||||
Hosts: strings.Split(ctx.String("nodes"), ","),
|
||||
ByHost: false,
|
||||
}
|
||||
ui := tea.NewProgram(initScannerMetricsUI(ctx.Int("max-paths")))
|
||||
if globalJSON {
|
||||
e := client.Metrics(ctxt, opts, func(metrics madmin.RealtimeMetrics) {
|
||||
printMsg(metricsMessage{RealtimeMetrics: metrics})
|
||||
@@ -208,11 +360,13 @@ func (m *scannerMetricsUI) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
||||
return m, tea.Quit
|
||||
}
|
||||
return m, nil
|
||||
case spinner.TickMsg:
|
||||
var cmd tea.Cmd
|
||||
m.spinner, cmd = m.spinner.Update(msg)
|
||||
return m, cmd
|
||||
}
|
||||
|
||||
var cmd tea.Cmd
|
||||
m.spinner, cmd = m.spinner.Update(msg)
|
||||
return m, cmd
|
||||
return m, nil
|
||||
}
|
||||
|
||||
func (m *scannerMetricsUI) View() string {
|
||||
@@ -222,21 +376,33 @@ func (m *scannerMetricsUI) View() string {
|
||||
s.WriteString(fmt.Sprintf("%s %s\n", console.Colorize("metrics-top-title", "Scanner Activity:"), m.spinner.View()))
|
||||
}
|
||||
|
||||
// Set table header
|
||||
// Set table header - akin to k8s style
|
||||
// https://github.com/olekukonko/tablewriter#example-10---set-nowhitespace-and-tablepadding-option
|
||||
table := tablewriter.NewWriter(&s)
|
||||
table.SetAutoWrapText(false)
|
||||
table.SetAutoFormatHeaders(true)
|
||||
table.SetHeaderAlignment(tablewriter.ALIGN_LEFT)
|
||||
table.SetAlignment(tablewriter.ALIGN_LEFT)
|
||||
table.SetBorder(true)
|
||||
table.SetRowLine(false)
|
||||
table.SetCenterSeparator("")
|
||||
table.SetColumnSeparator("")
|
||||
table.SetRowSeparator("")
|
||||
table.SetHeaderLine(false)
|
||||
table.SetBorder(false)
|
||||
table.SetTablePadding("\t") // pad with tabs
|
||||
table.SetNoWhiteSpace(true)
|
||||
|
||||
writtenRows := 0
|
||||
addRow := func(s string) {
|
||||
table.Append([]string{s})
|
||||
writtenRows++
|
||||
}
|
||||
_ = addRow
|
||||
addRowF := func(format string, vals ...interface{}) {
|
||||
addRowF := func(format string, vals ...any) {
|
||||
s := fmt.Sprintf(format, vals...)
|
||||
table.Append([]string{s})
|
||||
writtenRows++
|
||||
}
|
||||
|
||||
sc := m.current.Aggregated.Scanner
|
||||
if sc == nil {
|
||||
s.WriteString("(waiting for data)")
|
||||
@@ -245,54 +411,63 @@ func (m *scannerMetricsUI) View() string {
|
||||
|
||||
title := metricsTitle
|
||||
ui := metricsUint64
|
||||
const wantCycles = 16
|
||||
if len(sc.CyclesCompletedAt) < 2 {
|
||||
addRow("Scan time: Unknown (not enough data)")
|
||||
addRow("")
|
||||
|
||||
if sc.CurrentCycle == 0 && sc.CurrentStarted.IsZero() && sc.CyclesCompletedAt == nil {
|
||||
addRowF(" "+title("Scanning:")+" %d bucket(s)", sc.OngoingBuckets)
|
||||
} else {
|
||||
sort.Slice(sc.CyclesCompletedAt, func(i, j int) bool {
|
||||
return sc.CyclesCompletedAt[i].After(sc.CyclesCompletedAt[j])
|
||||
})
|
||||
if len(sc.CyclesCompletedAt) >= wantCycles {
|
||||
sinceLast := sc.CyclesCompletedAt[0].Sub(sc.CyclesCompletedAt[wantCycles-1])
|
||||
perMonth := float64(30*24*time.Hour) / float64(sinceLast)
|
||||
cycleTime := console.Colorize("metrics-number", fmt.Sprintf("%dd%dh%dm", int(sinceLast.Hours()/24), int(sinceLast.Hours())%24, int(sinceLast.Minutes())%60))
|
||||
perms := console.Colorize("metrics-number", fmt.Sprintf("%.02f", perMonth))
|
||||
addRowF(title("Last full scan time:")+" %s; Estimated %s/month", cycleTime, perms)
|
||||
const wantCycles = 16
|
||||
if len(sc.CyclesCompletedAt) < 2 {
|
||||
addRow("Last full scan time: Unknown (not enough data)")
|
||||
} else {
|
||||
sinceLast := sc.CyclesCompletedAt[0].Sub(sc.CyclesCompletedAt[1]) * time.Duration(wantCycles)
|
||||
perMonth := float64(30*24*time.Hour) / float64(sinceLast)
|
||||
cycleTime := console.Colorize("metrics-number", fmt.Sprintf("%dd%dh%dm", int(sinceLast.Hours()/24), int(sinceLast.Hours())%24, int(sinceLast.Minutes())%60))
|
||||
perms := console.Colorize("metrics-number", fmt.Sprintf("%.02f", perMonth))
|
||||
addRowF(title("Est. full scan time:")+" %s; Estimated %s/month", cycleTime, perms)
|
||||
addRow("Overall Statistics")
|
||||
addRow("------------------")
|
||||
sort.Slice(sc.CyclesCompletedAt, func(i, j int) bool {
|
||||
return sc.CyclesCompletedAt[i].After(sc.CyclesCompletedAt[j])
|
||||
})
|
||||
if len(sc.CyclesCompletedAt) >= wantCycles {
|
||||
sinceLast := sc.CyclesCompletedAt[0].Sub(sc.CyclesCompletedAt[wantCycles-1])
|
||||
perMonth := float64(30*24*time.Hour) / float64(sinceLast)
|
||||
cycleTime := console.Colorize("metrics-number", fmt.Sprintf("%dd%dh%dm", int(sinceLast.Hours()/24), int(sinceLast.Hours())%24, int(sinceLast.Minutes())%60))
|
||||
perms := console.Colorize("metrics-number", fmt.Sprintf("%.02f", perMonth))
|
||||
addRowF(title("Last full scan time:")+" %s; Estimated %s/month", cycleTime, perms)
|
||||
} else {
|
||||
sinceLast := sc.CyclesCompletedAt[0].Sub(sc.CyclesCompletedAt[1]) * time.Duration(wantCycles)
|
||||
perMonth := float64(30*24*time.Hour) / float64(sinceLast)
|
||||
cycleTime := console.Colorize("metrics-number", fmt.Sprintf("%dd%dh%dm", int(sinceLast.Hours()/24), int(sinceLast.Hours())%24, int(sinceLast.Minutes())%60))
|
||||
perms := console.Colorize("metrics-number", fmt.Sprintf("%.02f", perMonth))
|
||||
addRowF(title("Est. full scan time:")+" %s; Estimated %s/month", cycleTime, perms)
|
||||
}
|
||||
}
|
||||
if sc.CurrentCycle > 0 {
|
||||
addRowF(title("Current cycle:")+" %s; Started: %v", ui(sc.CurrentCycle), console.Colorize("metrics-date", sc.CurrentStarted))
|
||||
} else {
|
||||
addRowF("%s", title("Current cycle:")+" (between cycles)")
|
||||
}
|
||||
}
|
||||
if sc.CurrentCycle > 0 {
|
||||
addRowF(title("Current cycle:")+" %s; Started: %v", ui(sc.CurrentCycle), console.Colorize("metrics-date", sc.CurrentStarted))
|
||||
addRowF(title("Active drives:")+" %s", ui(uint64(len(sc.ActivePaths))))
|
||||
} else {
|
||||
addRowF(title("Current cycle:") + " (between cycles)")
|
||||
addRowF(title("Active drives:")+" %s", ui(uint64(len(sc.ActivePaths))))
|
||||
|
||||
addRowF(title("Active drives:")+" %s", ui(uint64(len(sc.ActivePaths))))
|
||||
|
||||
getRate := func(x madmin.TimedAction) string {
|
||||
if x.AccTime > 0 {
|
||||
return fmt.Sprintf("; Rate: %v/day", ui(uint64(float64(24*time.Hour)/(float64(time.Minute)/float64(x.Count)))))
|
||||
}
|
||||
return ""
|
||||
}
|
||||
addRow("-------------------------------------- Last Minute Statistics ---------------------------------------")
|
||||
addRow("")
|
||||
addRow("Last Minute Statistics")
|
||||
addRow("----------------------")
|
||||
objs := uint64(0)
|
||||
x := sc.LastMinute.Actions["ScanObject"]
|
||||
{
|
||||
avg := x.Avg()
|
||||
rate := ""
|
||||
if x.AccTime > 0 {
|
||||
rate = fmt.Sprintf("; Rate: %v/day", ui(uint64(float64(24*time.Hour)/(float64(time.Minute)/float64(x.Count)))))
|
||||
}
|
||||
addRowF(title("Objects Scanned:")+" %s objects; Avg: %v%s", ui(x.Count), metricsDuration(avg), rate)
|
||||
addRowF(title("Objects Scanned:")+" %s objects; Avg: %v%s", ui(x.Count), metricsDuration(avg), getRate(x))
|
||||
objs = x.Count
|
||||
}
|
||||
x = sc.LastMinute.Actions["ApplyVersion"]
|
||||
{
|
||||
avg := x.Avg()
|
||||
rate := ""
|
||||
if x.AccTime > 0 {
|
||||
rate = fmt.Sprintf("; Rate: %s/day", ui(uint64(float64(24*time.Hour)/(float64(time.Minute)/float64(x.Count)))))
|
||||
}
|
||||
addRowF(title("Versions Scanned:")+" %s versions; Avg: %v%s", ui(x.Count), metricsDuration(avg), rate)
|
||||
addRowF(title("Versions Scanned:")+" %s versions; Avg: %v%s", ui(x.Count), metricsDuration(avg), getRate(x))
|
||||
}
|
||||
x = sc.LastMinute.Actions["HealCheck"]
|
||||
{
|
||||
@@ -315,6 +490,15 @@ func (m *scannerMetricsUI) View() string {
|
||||
}
|
||||
x = sc.LastMinute.Actions["CheckMissing"]
|
||||
addRowF(title("Verify Deleted:")+" %s folders; Avg: %v", ui(x.Count), metricsDuration(x.Avg()))
|
||||
x = sc.LastMinute.Actions["HealAbandonedObject"]
|
||||
if x.Count > 0 {
|
||||
addRowF(title(" Missing Objects:")+" %s objects healed; Avg: %v%s", ui(x.Count), metricsDuration(x.Avg()), getRate(x))
|
||||
}
|
||||
x = sc.LastMinute.Actions["HealAbandonedVersion"]
|
||||
if x.Count > 0 {
|
||||
addRowF(title(" Missing Versions:")+" %s versions healed; Avg: %v%s; %v bytes/v", ui(x.Count), metricsDuration(x.Avg()), getRate(x), ui(x.AvgBytes()))
|
||||
}
|
||||
|
||||
for k, x := range sc.LastMinute.ILM {
|
||||
const length = 17
|
||||
k += ":"
|
||||
@@ -331,14 +515,27 @@ func (m *scannerMetricsUI) View() string {
|
||||
}
|
||||
addRowF(title("Yield:")+" %v total; Avg: %s", metricsDuration(time.Duration(x.AccTime)), avg)
|
||||
}
|
||||
if errs := m.current.Errors; len(errs) > 0 {
|
||||
addRow("------------------------------------------- Errors --------------------------------------------------")
|
||||
for _, s := range errs {
|
||||
addRow(console.Colorize("metrics-error", s))
|
||||
}
|
||||
}
|
||||
|
||||
if m.maxPaths != 0 && len(sc.ActivePaths) > 0 {
|
||||
addRow("------------------------------------- Currently Scanning Paths --------------------------------------")
|
||||
const length = 100
|
||||
length := 100
|
||||
if globalTermWidth > 5 {
|
||||
length = globalTermWidth
|
||||
}
|
||||
for i, s := range sc.ActivePaths {
|
||||
if i == m.maxPaths {
|
||||
break
|
||||
}
|
||||
if globalTermHeight > 5 && writtenRows >= globalTermHeight-5 {
|
||||
addRow(console.Colorize("metrics-path", fmt.Sprintf("( ... hiding %d more disk(s) .. )", len(sc.ActivePaths)-i)))
|
||||
break
|
||||
}
|
||||
if len(s) > length {
|
||||
s = s[:length-3] + "..."
|
||||
}
|
||||
@@ -346,12 +543,6 @@ func (m *scannerMetricsUI) View() string {
|
||||
addRow(console.Colorize("metrics-path", s))
|
||||
}
|
||||
}
|
||||
if errs := m.current.Errors; len(errs) > 0 {
|
||||
addRow("------------------------------------------- Errors --------------------------------------------------")
|
||||
for _, s := range errs {
|
||||
addRow(console.Colorize("metrics-error", s))
|
||||
}
|
||||
}
|
||||
table.Render()
|
||||
return s.String()
|
||||
}
|
||||
|
||||
@@ -24,7 +24,7 @@ import (
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/pkg/console"
|
||||
"github.com/minio/pkg/v3/console"
|
||||
)
|
||||
|
||||
var adminScannerTraceFlags = []cli.Flag{
|
||||
@@ -169,7 +169,7 @@ func mainAdminScannerTrace(ctx *cli.Context) error {
|
||||
if traceInfo.Err != nil {
|
||||
fatalIf(probe.NewError(traceInfo.Err), "Unable to listen to http trace")
|
||||
}
|
||||
if matchTrace(mopts, traceInfo) {
|
||||
if mopts.matches(traceInfo) {
|
||||
printTrace(verbose, traceInfo)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -22,7 +22,7 @@ import (
|
||||
"github.com/minio/cli"
|
||||
json "github.com/minio/colorjson"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/pkg/console"
|
||||
"github.com/minio/pkg/v3/console"
|
||||
)
|
||||
|
||||
var adminServiceFreezeCmd = cli.Command{
|
||||
@@ -90,7 +90,7 @@ func mainAdminServiceFreeze(ctx *cli.Context) error {
|
||||
fatalIf(err, "Unable to initialize admin connection.")
|
||||
|
||||
// Freeze the specified MinIO server
|
||||
fatalIf(probe.NewError(client.ServiceFreeze(globalContext)), "Unable to freeze the server.")
|
||||
fatalIf(probe.NewError(client.ServiceFreezeV2(globalContext)), "Unable to freeze the server.")
|
||||
|
||||
// Success..
|
||||
printMsg(serviceFreezeCommand{Status: "success", ServerURL: aliasedURL})
|
||||
|
||||
+262
-84
@@ -1,4 +1,4 @@
|
||||
// Copyright (c) 2015-2022 MinIO, Inc.
|
||||
// Copyright (c) 2015-2024 MinIO, Inc.
|
||||
//
|
||||
// This file is part of MinIO Object Storage stack
|
||||
//
|
||||
@@ -20,23 +20,39 @@ package cmd
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/charmbracelet/bubbles/spinner"
|
||||
tea "github.com/charmbracelet/bubbletea"
|
||||
"github.com/charmbracelet/lipgloss"
|
||||
"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/console"
|
||||
"github.com/minio/pkg/v3/console"
|
||||
)
|
||||
|
||||
var serviceRestartFlag = []cli.Flag{
|
||||
cli.BoolFlag{
|
||||
Name: "dry-run",
|
||||
Usage: "do not attempt a restart, however verify the peer status",
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "wait, w",
|
||||
Usage: "wait for background initializations to complete",
|
||||
},
|
||||
}
|
||||
|
||||
var adminServiceRestartCmd = cli.Command{
|
||||
Name: "restart",
|
||||
Usage: "restart a MinIO cluster",
|
||||
Action: mainAdminServiceRestart,
|
||||
OnUsageError: onUsageError,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
Flags: append(serviceRestartFlag, globalFlags...),
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
@@ -52,42 +68,154 @@ EXAMPLES:
|
||||
`,
|
||||
}
|
||||
|
||||
// serviceRestartCommand is container for service restart command success and failure messages.
|
||||
type serviceRestartCommand struct {
|
||||
Status string `json:"status"`
|
||||
ServerURL string `json:"serverURL"`
|
||||
type serviceRestartUI struct {
|
||||
current atomic.Value
|
||||
tbl *console.Table
|
||||
meter spinner.Model
|
||||
quitting bool
|
||||
}
|
||||
|
||||
// String colorized service restart command message.
|
||||
func (s serviceRestartCommand) String() string {
|
||||
return console.Colorize("ServiceRestart", "Restart command successfully sent to `"+s.ServerURL+"`. Type Ctrl-C to quit or wait to follow the status of the restart process.")
|
||||
func (m *serviceRestartUI) add(msg serviceRestartMessage) {
|
||||
m.current.Store(msg)
|
||||
}
|
||||
|
||||
func (m *serviceRestartUI) Init() tea.Cmd {
|
||||
return m.meter.Tick
|
||||
}
|
||||
|
||||
func (m *serviceRestartUI) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
||||
if m.quitting {
|
||||
return m, tea.Quit
|
||||
}
|
||||
switch msg := msg.(type) {
|
||||
case tea.KeyMsg:
|
||||
switch msg.String() {
|
||||
case "q", "esc", "ctrl+c":
|
||||
m.quitting = true
|
||||
return m, tea.Quit
|
||||
default:
|
||||
return m, nil
|
||||
}
|
||||
case spinner.TickMsg:
|
||||
var cmd tea.Cmd
|
||||
m.meter, cmd = m.meter.Update(msg)
|
||||
return m, cmd
|
||||
}
|
||||
return m, nil
|
||||
}
|
||||
|
||||
func (m *serviceRestartUI) View() string {
|
||||
var s strings.Builder
|
||||
|
||||
msgI := m.current.Load()
|
||||
if msgI == nil {
|
||||
s.WriteString("(waiting for data)")
|
||||
return s.String()
|
||||
}
|
||||
|
||||
s.WriteString(fmt.Sprintf("Service status: %s ", m.meter.View()))
|
||||
|
||||
msg := msgI.(serviceRestartMessage)
|
||||
state := msg.State
|
||||
switch state {
|
||||
case restarting:
|
||||
// Actually still restarting, no response yet from the server.
|
||||
s.WriteString("[RESTARTING]\n")
|
||||
case waiting:
|
||||
// Waiting on background initializations such as IAM and bucket metadata
|
||||
s.WriteString(console.Colorize("ServiceInitializing", "[WAITING]"))
|
||||
s.WriteString("\n")
|
||||
case done:
|
||||
m.quitting = true
|
||||
|
||||
// Finished restarting and optionally waiting for the background initializations to complete.
|
||||
s.WriteString(console.Colorize("ServiceRestarted", "[DONE]"))
|
||||
s.WriteString("\n")
|
||||
var (
|
||||
totalNodes = len(msg.Result.Results)
|
||||
totalOfflineNodes int
|
||||
totalHungNodes int
|
||||
)
|
||||
|
||||
for _, peerRes := range msg.Result.Results {
|
||||
if peerRes.Err != "" {
|
||||
totalOfflineNodes++
|
||||
} else if len(peerRes.WaitingDrives) > 0 {
|
||||
totalHungNodes++
|
||||
}
|
||||
}
|
||||
|
||||
s.WriteString("Summary:\n")
|
||||
|
||||
var cellText [][]string
|
||||
cellText = append(cellText, []string{
|
||||
"Servers:",
|
||||
fmt.Sprintf("%d online, %d offline, %d hung", totalNodes-(totalOfflineNodes+totalHungNodes), totalOfflineNodes, totalHungNodes),
|
||||
})
|
||||
|
||||
cellText = append(cellText, []string{
|
||||
"Restart Time:",
|
||||
msg.RestartDuration.String(),
|
||||
})
|
||||
|
||||
if msg.WaitingDuration > 0 {
|
||||
cellText = append(cellText, []string{
|
||||
"Background Init Time:",
|
||||
msg.WaitingDuration.String(),
|
||||
})
|
||||
}
|
||||
|
||||
fatalIf(probe.NewError(m.tbl.PopulateTable(&s, cellText)), "unable to populate the table")
|
||||
}
|
||||
|
||||
return s.String()
|
||||
}
|
||||
|
||||
func initServiceRestartUI(rowCount int, currentCh chan serviceRestartMessage) *serviceRestartUI {
|
||||
var printColors []*color.Color
|
||||
for range rowCount {
|
||||
printColors = append(printColors, getPrintCol(colGreen))
|
||||
}
|
||||
|
||||
tbl := console.NewTable(printColors, []bool{false, false}, 4)
|
||||
|
||||
meter := spinner.New()
|
||||
meter.Spinner = spinner.Meter
|
||||
meter.Style = lipgloss.NewStyle().Foreground(lipgloss.Color("205"))
|
||||
|
||||
svcUI := &serviceRestartUI{tbl: tbl, meter: meter}
|
||||
go func() {
|
||||
for msg := range currentCh {
|
||||
if msg.Status != "" {
|
||||
svcUI.add(msg)
|
||||
}
|
||||
}
|
||||
}()
|
||||
return svcUI
|
||||
}
|
||||
|
||||
const (
|
||||
restarting = iota
|
||||
waiting
|
||||
done
|
||||
)
|
||||
|
||||
// serviceRestartMessage is container for service restart command success and failure messages.
|
||||
type serviceRestartMessage struct {
|
||||
Status string `json:"status"`
|
||||
ServerURL string `json:"serverURL"`
|
||||
Result madmin.ServiceActionResult `json:"result"`
|
||||
RestartDuration time.Duration `json:"restartDuration"`
|
||||
WaitingDuration time.Duration `json:"waitingDuration"`
|
||||
TimeTaken time.Duration `json:"timeTaken"` // deprecated use "restartDuration" instead.
|
||||
State int `json:"state"`
|
||||
}
|
||||
|
||||
func (s serviceRestartMessage) String() string {
|
||||
return s.JSON()
|
||||
}
|
||||
|
||||
// JSON jsonified service restart command message.
|
||||
func (s serviceRestartCommand) JSON() string {
|
||||
serviceRestartJSONBytes, e := json.MarshalIndent(s, "", " ")
|
||||
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
|
||||
|
||||
return string(serviceRestartJSONBytes)
|
||||
}
|
||||
|
||||
// serviceRestartMessage is container for service restart success and failure messages.
|
||||
type serviceRestartMessage struct {
|
||||
Status string `json:"status"`
|
||||
ServerURL string `json:"serverURL"`
|
||||
TimeTaken time.Duration `json:"timeTaken"`
|
||||
Err error `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
// String colorized service restart message.
|
||||
func (s serviceRestartMessage) String() string {
|
||||
if s.Err == nil {
|
||||
return console.Colorize("ServiceRestart", fmt.Sprintf("\nRestarted `%s` successfully in %s", s.ServerURL, timeDurationToHumanizedDuration(s.TimeTaken).StringShort()))
|
||||
}
|
||||
return console.Colorize("FailedServiceRestart", "Failed to restart `"+s.ServerURL+"`. error: "+s.Err.Error())
|
||||
}
|
||||
|
||||
// JSON jsonified service restart message.
|
||||
func (s serviceRestartMessage) JSON() string {
|
||||
serviceRestartJSONBytes, e := json.MarshalIndent(s, "", " ")
|
||||
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
|
||||
@@ -112,7 +240,7 @@ func mainAdminServiceRestart(ctx *cli.Context) error {
|
||||
// Set color.
|
||||
console.SetColor("ServiceOffline", color.New(color.FgRed, color.Bold))
|
||||
console.SetColor("ServiceInitializing", color.New(color.FgYellow, color.Bold))
|
||||
console.SetColor("ServiceRestart", color.New(color.FgGreen, color.Bold))
|
||||
console.SetColor("ServiceRestarted", color.New(color.FgGreen, color.Bold))
|
||||
console.SetColor("FailedServiceRestart", color.New(color.FgRed, color.Bold))
|
||||
|
||||
// Get the alias parameter from cli
|
||||
@@ -122,60 +250,110 @@ func mainAdminServiceRestart(ctx *cli.Context) error {
|
||||
client, err := newAdminClient(aliasedURL)
|
||||
fatalIf(err, "Unable to initialize admin connection.")
|
||||
|
||||
// Restart the specified MinIO server
|
||||
fatalIf(probe.NewError(client.ServiceRestart(ctxt)), "Unable to restart the server.")
|
||||
|
||||
// Success..
|
||||
printMsg(serviceRestartCommand{Status: "success", ServerURL: aliasedURL})
|
||||
|
||||
// Start pinging the service until it is ready
|
||||
|
||||
anonClient, err := newAnonymousClient(aliasedURL)
|
||||
fatalIf(err.Trace(aliasedURL), "Could not ping `"+aliasedURL+"`.")
|
||||
|
||||
coloring := color.New(color.FgRed)
|
||||
mark := "..."
|
||||
|
||||
// Print restart progress
|
||||
printProgress := func() {
|
||||
if !globalQuiet && !globalJSON {
|
||||
coloring.Printf(mark)
|
||||
}
|
||||
rowCount := 2
|
||||
toWait := ctx.Bool("wait")
|
||||
if toWait {
|
||||
rowCount = 3
|
||||
}
|
||||
|
||||
printProgress()
|
||||
mark = "."
|
||||
ch := make(chan serviceRestartMessage, 1)
|
||||
|
||||
timer := time.NewTimer(time.Second)
|
||||
defer timer.Stop()
|
||||
svcUI := initServiceRestartUI(rowCount, ch)
|
||||
go func() {
|
||||
t := time.Now()
|
||||
|
||||
t := time.Now()
|
||||
for {
|
||||
select {
|
||||
case <-ctxt.Done():
|
||||
return ctxt.Err()
|
||||
case <-timer.C:
|
||||
healthCtx, healthCancel := context.WithTimeout(ctxt, 3*time.Second)
|
||||
// Fetch the health status of the specified MinIO server
|
||||
healthResult, healthErr := anonClient.Healthy(healthCtx, madmin.HealthOpts{})
|
||||
healthCancel()
|
||||
switch {
|
||||
case healthErr == nil && healthResult.Healthy:
|
||||
printMsg(serviceRestartMessage{
|
||||
Status: "success",
|
||||
ServerURL: aliasedURL,
|
||||
TimeTaken: time.Since(t),
|
||||
})
|
||||
return nil
|
||||
case healthErr == nil && !healthResult.Healthy:
|
||||
coloring = color.New(color.FgYellow)
|
||||
mark = "!"
|
||||
fallthrough
|
||||
default:
|
||||
printProgress()
|
||||
// Restart the specified MinIO server
|
||||
result, e := client.ServiceAction(ctxt, madmin.ServiceActionOpts{
|
||||
Action: madmin.ServiceActionRestart,
|
||||
DryRun: ctx.Bool("dry-run"),
|
||||
})
|
||||
if e != nil {
|
||||
// Attempt an older API server might be old
|
||||
// nolint:staticcheck
|
||||
// we need this fallback
|
||||
e = client.ServiceRestart(ctxt)
|
||||
}
|
||||
fatalIf(probe.NewError(e), "Unable to restart the server.")
|
||||
|
||||
timeTaken := time.Since(t)
|
||||
restart := restarting
|
||||
if !toWait {
|
||||
restart = done
|
||||
}
|
||||
|
||||
ch <- serviceRestartMessage{
|
||||
Status: "success",
|
||||
ServerURL: aliasedURL,
|
||||
Result: result,
|
||||
RestartDuration: timeTaken,
|
||||
TimeTaken: timeTaken,
|
||||
State: restart,
|
||||
}
|
||||
|
||||
if toWait {
|
||||
sleepInterval := 500 * time.Millisecond
|
||||
go func() {
|
||||
defer close(ch)
|
||||
|
||||
wt := time.Now()
|
||||
|
||||
// Start pinging the service until it is ready
|
||||
anonClient, err := newAnonymousClient(aliasedURL)
|
||||
fatalIf(err.Trace(aliasedURL), "unable to initialize anonymous client for`"+aliasedURL+"`.")
|
||||
|
||||
for {
|
||||
healthCtx, healthCancel := context.WithTimeout(ctxt, 2*time.Second)
|
||||
|
||||
// Fetch the health status of the specified MinIO server
|
||||
healthResult, healthErr := anonClient.Healthy(healthCtx, madmin.HealthOpts{})
|
||||
healthCancel()
|
||||
|
||||
switch {
|
||||
case healthErr == nil && healthResult.Healthy:
|
||||
ch <- serviceRestartMessage{
|
||||
Status: "success",
|
||||
ServerURL: aliasedURL,
|
||||
Result: result,
|
||||
RestartDuration: timeTaken,
|
||||
TimeTaken: timeTaken,
|
||||
WaitingDuration: time.Since(wt),
|
||||
State: done,
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
ch <- serviceRestartMessage{
|
||||
Status: "success",
|
||||
ServerURL: aliasedURL,
|
||||
Result: result,
|
||||
WaitingDuration: time.Since(wt),
|
||||
RestartDuration: timeTaken,
|
||||
TimeTaken: timeTaken,
|
||||
State: waiting,
|
||||
}
|
||||
|
||||
time.Sleep(sleepInterval)
|
||||
}
|
||||
}()
|
||||
} else {
|
||||
close(ch)
|
||||
}
|
||||
}()
|
||||
|
||||
if !globalJSON {
|
||||
ui := tea.NewProgram(svcUI)
|
||||
if _, e := ui.Run(); e != nil {
|
||||
cancel()
|
||||
fatalIf(probe.NewError(e).Trace(aliasedURL), "Unable to initialize service restart UI")
|
||||
}
|
||||
} else {
|
||||
for msg := range ch {
|
||||
printMsg(msg)
|
||||
if msg.State == done {
|
||||
break
|
||||
}
|
||||
|
||||
timer.Reset(time.Second)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -22,7 +22,7 @@ import (
|
||||
"github.com/minio/cli"
|
||||
json "github.com/minio/colorjson"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/pkg/console"
|
||||
"github.com/minio/pkg/v3/console"
|
||||
)
|
||||
|
||||
var adminServiceStopCmd = cli.Command{
|
||||
@@ -32,6 +32,7 @@ var adminServiceStopCmd = cli.Command{
|
||||
OnUsageError: onUsageError,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
Hidden: true, // this command is hidden on purpose, please do not enable it.
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
@@ -88,7 +89,7 @@ func mainAdminServiceStop(ctx *cli.Context) error {
|
||||
fatalIf(err, "Unable to initialize admin connection.")
|
||||
|
||||
// Stop the specified MinIO server
|
||||
fatalIf(probe.NewError(client.ServiceStop(globalContext)), "Unable to stop the server.")
|
||||
fatalIf(probe.NewError(client.ServiceStopV2(globalContext)), "Unable to stop the server.")
|
||||
|
||||
// Success..
|
||||
printMsg(serviceStopMessage{Status: "success", ServerURL: aliasedURL})
|
||||
|
||||
@@ -18,11 +18,13 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/cli"
|
||||
json "github.com/minio/colorjson"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/pkg/console"
|
||||
"github.com/minio/pkg/v3/console"
|
||||
)
|
||||
|
||||
var adminServiceUnfreezeCmd = cli.Command{
|
||||
@@ -74,7 +76,7 @@ func checkAdminServiceUnfreezeSyntax(ctx *cli.Context) {
|
||||
}
|
||||
|
||||
func mainAdminServiceUnfreeze(ctx *cli.Context) error {
|
||||
// Validate serivce unfreeze syntax.
|
||||
// Validate service unfreeze syntax.
|
||||
checkAdminServiceUnfreezeSyntax(ctx)
|
||||
|
||||
// Set color.
|
||||
@@ -88,8 +90,19 @@ func mainAdminServiceUnfreeze(ctx *cli.Context) error {
|
||||
client, err := newAdminClient(aliasedURL)
|
||||
fatalIf(err, "Unable to initialize admin connection.")
|
||||
|
||||
ctxt, cancel := context.WithCancel(globalContext)
|
||||
defer cancel()
|
||||
|
||||
// Unfreeze the specified MinIO server
|
||||
fatalIf(probe.NewError(client.ServiceUnfreeze(globalContext)), "Unable to unfreeze the server.")
|
||||
e := client.ServiceUnfreezeV2(ctxt)
|
||||
if e != nil {
|
||||
// Attempt an older API server might be old
|
||||
// nolint:staticcheck
|
||||
// we need this fallback
|
||||
e = client.ServiceUnfreeze(ctxt)
|
||||
}
|
||||
// Unfreeze the specified MinIO server
|
||||
fatalIf(probe.NewError(e), "Unable to unfreeze the server.")
|
||||
|
||||
// Success..
|
||||
printMsg(serviceUnfreezeCommand{Status: "success", ServerURL: aliasedURL})
|
||||
|
||||
@@ -28,7 +28,7 @@ var adminServiceSubcommands = []cli.Command{
|
||||
|
||||
var adminServiceCmd = cli.Command{
|
||||
Name: "service",
|
||||
Usage: "restart, stop and unfreeze a MinIO cluster",
|
||||
Usage: "restart or unfreeze a MinIO cluster",
|
||||
Action: mainAdminService,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
|
||||
@@ -32,7 +32,7 @@ var adminSubnetHealthCmd = cli.Command{
|
||||
Action: mainSubnetHealth,
|
||||
Before: setGlobalsFromContext,
|
||||
Hidden: true,
|
||||
Flags: append(supportDiagFlags, globalFlags...),
|
||||
Flags: supportDiagFlags, // No need to append globalFlags as top level command would add them
|
||||
CustomHelpTemplate: "This command is deprecated and will be removed in a future release. Use 'mc support diag' instead.\n",
|
||||
}
|
||||
|
||||
|
||||
+281
-38
@@ -18,23 +18,30 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"hash/fnv"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"path"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
tea "github.com/charmbracelet/bubbletea"
|
||||
"github.com/dustin/go-humanize"
|
||||
"github.com/fatih/color"
|
||||
"github.com/klauspost/compress/zstd"
|
||||
"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/console"
|
||||
"github.com/minio/pkg/v3/console"
|
||||
)
|
||||
|
||||
var adminTraceFlags = []cli.Flag{
|
||||
@@ -74,10 +81,24 @@ var adminTraceFlags = []cli.Flag{
|
||||
Name: "request-header",
|
||||
Usage: "trace only matching request headers",
|
||||
},
|
||||
cli.StringSliceFlag{
|
||||
Name: "request-query",
|
||||
Usage: "trace only matching request queries",
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "errors, e",
|
||||
Usage: "trace only failed requests",
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "stats",
|
||||
Usage: "print statistical summary of all the traced calls",
|
||||
},
|
||||
cli.IntFlag{
|
||||
Name: "stats-n",
|
||||
Usage: "maximum number of stat entries",
|
||||
Value: 20,
|
||||
Hidden: true,
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "filter-request",
|
||||
Usage: "trace calls only with request bytes greater than this threshold, use with filter-size",
|
||||
@@ -94,6 +115,10 @@ var adminTraceFlags = []cli.Flag{
|
||||
Name: "filter-size",
|
||||
Usage: "filter size, use with filter (see UNITS)",
|
||||
},
|
||||
cli.StringFlag{
|
||||
Name: "in",
|
||||
Usage: "read previously saved json from file and replay",
|
||||
},
|
||||
}
|
||||
|
||||
// traceCallTypes contains all call types and flags to apply when selected.
|
||||
@@ -119,6 +144,11 @@ var traceCallTypes = map[string]func(o *madmin.ServiceTraceOpts) (help string){
|
||||
o.BatchKeyRotation = true
|
||||
return "Trace Batch KeyRotation (alias: brot)"
|
||||
},
|
||||
"batch-expiration": func(o *madmin.ServiceTraceOpts) string {
|
||||
o.BatchExpire = true
|
||||
return "Trace Batch Expiration (alias: bexp)"
|
||||
},
|
||||
|
||||
"decommission": func(o *madmin.ServiceTraceOpts) string {
|
||||
o.Decommission = true
|
||||
return "Trace Decommission operations (alias: decom)"
|
||||
@@ -140,6 +170,7 @@ var traceCallTypeAliases = map[string]func(o *madmin.ServiceTraceOpts) string{
|
||||
"resync": traceCallTypes["replication-resync"],
|
||||
"brep": traceCallTypes["batch-replication"],
|
||||
"brot": traceCallTypes["batch-keyrotation"],
|
||||
"bexp": traceCallTypes["batch-expiration"],
|
||||
}
|
||||
|
||||
func traceCallsHelp() string {
|
||||
@@ -159,7 +190,7 @@ func traceCallsHelp() string {
|
||||
|
||||
var adminTraceCmd = cli.Command{
|
||||
Name: "trace",
|
||||
Usage: "show http trace for MinIO server",
|
||||
Usage: "Show HTTP call trace for all incoming and internode on MinIO",
|
||||
Action: mainAdminTrace,
|
||||
OnUsageError: onUsageError,
|
||||
Before: setGlobalsFromContext,
|
||||
@@ -174,7 +205,6 @@ USAGE:
|
||||
FLAGS:
|
||||
{{range .VisibleFlags}}{{.}}
|
||||
{{end}}
|
||||
|
||||
CALL TYPES:
|
||||
` + traceCallsHelp() + `
|
||||
|
||||
@@ -217,7 +247,7 @@ const traceTimeFormat = "2006-01-02T15:04:05.000"
|
||||
var colors = []color.Attribute{color.FgCyan, color.FgWhite, color.FgYellow, color.FgGreen}
|
||||
|
||||
func checkAdminTraceSyntax(ctx *cli.Context) {
|
||||
if len(ctx.Args()) != 1 {
|
||||
if len(ctx.Args()) != 1 && len(ctx.String("in")) == 0 {
|
||||
showCommandHelpAndExit(ctx, 1) // last argument is exit code
|
||||
}
|
||||
filterFlag := ctx.Bool("filter-request") || ctx.Bool("filter-response")
|
||||
@@ -251,11 +281,12 @@ type matchOpts struct {
|
||||
apiPaths []string
|
||||
nodes []string
|
||||
reqHeaders []matchString
|
||||
reqQueries []matchString
|
||||
requestSize uint64
|
||||
responseSize uint64
|
||||
}
|
||||
|
||||
func matchTrace(opts matchOpts, traceInfo madmin.ServiceTraceInfo) bool {
|
||||
func (opts matchOpts) matches(traceInfo madmin.ServiceTraceInfo) bool {
|
||||
// Filter request path if passed by the user
|
||||
if len(opts.apiPaths) > 0 {
|
||||
matched := false
|
||||
@@ -334,7 +365,7 @@ func matchTrace(opts matchOpts, traceInfo madmin.ServiceTraceInfo) bool {
|
||||
headerFound := false
|
||||
for traceHdr, traceVals := range traceInfo.Trace.HTTP.ReqInfo.Headers {
|
||||
for _, traceVal := range traceVals {
|
||||
if headerMatch(hdr.val, traceHdr+": "+traceVal) {
|
||||
if patternMatch(hdr.val, traceHdr+": "+traceVal) {
|
||||
headerFound = true
|
||||
goto exitFindingHeader
|
||||
}
|
||||
@@ -352,12 +383,38 @@ func matchTrace(opts matchOpts, traceInfo madmin.ServiceTraceInfo) bool {
|
||||
}
|
||||
}
|
||||
|
||||
if opts.requestSize > 0 && traceInfo.Trace.HTTP.CallStats.InputBytes < int(opts.requestSize) {
|
||||
return false
|
||||
if len(opts.reqQueries) > 0 && traceInfo.Trace.HTTP != nil {
|
||||
matched := false
|
||||
for _, qry := range opts.reqQueries {
|
||||
queryFound := false
|
||||
v, err := url.ParseQuery(traceInfo.Trace.HTTP.ReqInfo.RawQuery)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
for traceQuery, traceVals := range v {
|
||||
for _, traceVal := range traceVals {
|
||||
if patternMatch(qry.val, traceQuery+"="+traceVal) {
|
||||
queryFound = true
|
||||
goto exitFindingQuery
|
||||
}
|
||||
}
|
||||
}
|
||||
exitFindingQuery:
|
||||
if !qry.reverse && queryFound || qry.reverse && !queryFound {
|
||||
matched = true
|
||||
goto exitMatchingQuery
|
||||
}
|
||||
}
|
||||
exitMatchingQuery:
|
||||
if !matched {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
if opts.responseSize > 0 && traceInfo.Trace.HTTP.CallStats.OutputBytes < int(opts.responseSize) {
|
||||
return false
|
||||
if traceInfo.Trace.HTTP != nil {
|
||||
if (opts.requestSize > 0 && traceInfo.Trace.HTTP.CallStats.InputBytes < int(opts.requestSize)) || (opts.responseSize > 0 && traceInfo.Trace.HTTP.CallStats.OutputBytes < int(opts.responseSize)) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
return true
|
||||
@@ -370,11 +427,18 @@ func matchingOpts(ctx *cli.Context) (opts matchOpts) {
|
||||
opts.apiPaths = ctx.StringSlice("path")
|
||||
opts.nodes = ctx.StringSlice("node")
|
||||
for _, s := range ctx.StringSlice("request-header") {
|
||||
ms := matchString{}
|
||||
ms.reverse = strings.HasPrefix(s, "!")
|
||||
ms.val = strings.TrimPrefix(s, "!")
|
||||
opts.reqHeaders = append(opts.reqHeaders, ms)
|
||||
opts.reqHeaders = append(opts.reqHeaders, matchString{
|
||||
reverse: strings.HasPrefix(s, "!"),
|
||||
val: strings.TrimPrefix(s, "!"),
|
||||
})
|
||||
}
|
||||
for _, s := range ctx.StringSlice("request-query") {
|
||||
opts.reqQueries = append(opts.reqQueries, matchString{
|
||||
reverse: strings.HasPrefix(s, "!"),
|
||||
val: strings.TrimPrefix(s, "!"),
|
||||
})
|
||||
}
|
||||
|
||||
var e error
|
||||
var requestSize, responseSize uint64
|
||||
if ctx.Bool("filter-request") && ctx.String("filter-size") != "" {
|
||||
@@ -410,14 +474,16 @@ func tracingOpts(ctx *cli.Context, apis []string) (opts madmin.ServiceTraceOpts,
|
||||
}
|
||||
|
||||
for _, api := range apis {
|
||||
fn, ok := traceCallTypes[api]
|
||||
if !ok {
|
||||
fn, ok = traceCallTypeAliases[api]
|
||||
for _, api := range strings.Split(api, ",") {
|
||||
fn, ok := traceCallTypes[api]
|
||||
if !ok {
|
||||
fn, ok = traceCallTypeAliases[api]
|
||||
}
|
||||
if !ok {
|
||||
return madmin.ServiceTraceOpts{}, fmt.Errorf("unknown call name: `%s`", api)
|
||||
}
|
||||
fn(&opts)
|
||||
}
|
||||
if !ok {
|
||||
return madmin.ServiceTraceOpts{}, fmt.Errorf("unknown call name: `%s`", api)
|
||||
}
|
||||
fn(&opts)
|
||||
}
|
||||
return
|
||||
}
|
||||
@@ -428,7 +494,7 @@ func mainAdminTrace(ctx *cli.Context) error {
|
||||
checkAdminTraceSyntax(ctx)
|
||||
|
||||
verbose := ctx.Bool("verbose")
|
||||
aliasedURL := ctx.Args().Get(0)
|
||||
stats := ctx.Bool("stats")
|
||||
|
||||
console.SetColor("Stat", color.New(color.FgYellow))
|
||||
|
||||
@@ -449,28 +515,110 @@ func mainAdminTrace(ctx *cli.Context) error {
|
||||
for _, c := range colors {
|
||||
console.SetColor(fmt.Sprintf("Node%d", c), color.New(c))
|
||||
}
|
||||
// Create a new MinIO Admin Client
|
||||
client, err := newAdminClient(aliasedURL)
|
||||
if err != nil {
|
||||
fatalIf(err.Trace(aliasedURL), "Unable to initialize admin client.")
|
||||
return nil
|
||||
}
|
||||
|
||||
var traceCh <-chan madmin.ServiceTraceInfo
|
||||
|
||||
ctxt, cancel := context.WithCancel(globalContext)
|
||||
defer cancel()
|
||||
|
||||
opts, e := tracingOpts(ctx, ctx.StringSlice("call"))
|
||||
fatalIf(probe.NewError(e), "Unable to start tracing")
|
||||
if inFile := ctx.String("in"); inFile != "" {
|
||||
stats = true
|
||||
ch := make(chan madmin.ServiceTraceInfo, 1000)
|
||||
traceCh = ch
|
||||
go func() {
|
||||
f, e := os.Open(inFile)
|
||||
fatalIf(probe.NewError(e), "Unable to open input")
|
||||
defer f.Close()
|
||||
in := io.Reader(f)
|
||||
if strings.HasSuffix(inFile, ".zst") {
|
||||
zr, e := zstd.NewReader(in)
|
||||
fatalIf(probe.NewError(e), "Unable to open input")
|
||||
defer zr.Close()
|
||||
in = zr
|
||||
}
|
||||
sc := bufio.NewReader(in)
|
||||
for ctxt.Err() == nil {
|
||||
b, e := sc.ReadBytes('\n')
|
||||
if e == io.EOF {
|
||||
break
|
||||
}
|
||||
var t shortTraceMsg
|
||||
e = json.Unmarshal(b, &t)
|
||||
if e != nil || t.Type == "Bootstrap" {
|
||||
// Ignore bootstrap, since their times skews averages.
|
||||
continue
|
||||
}
|
||||
ch <- madmin.ServiceTraceInfo{
|
||||
Trace: madmin.TraceInfo{
|
||||
TraceType: t.trcType, // TODO: Grab from string, once we can.
|
||||
NodeName: t.Host,
|
||||
FuncName: t.FuncName,
|
||||
Time: t.Time,
|
||||
Path: t.Path,
|
||||
Duration: t.Duration,
|
||||
Bytes: t.Size,
|
||||
Message: t.StatusMsg,
|
||||
Error: t.Error,
|
||||
Custom: t.Extra,
|
||||
HTTP: nil,
|
||||
HealResult: nil,
|
||||
},
|
||||
Err: nil,
|
||||
}
|
||||
}
|
||||
close(ch)
|
||||
select {}
|
||||
}()
|
||||
} else {
|
||||
// Create a new MinIO Admin Client
|
||||
aliasedURL := ctx.Args().Get(0)
|
||||
|
||||
client, err := newAdminClient(aliasedURL)
|
||||
if err != nil {
|
||||
fatalIf(err.Trace(aliasedURL), "Unable to initialize admin client.")
|
||||
return nil
|
||||
}
|
||||
|
||||
opts, e := tracingOpts(ctx, ctx.StringSlice("call"))
|
||||
fatalIf(probe.NewError(e), "Unable to start tracing")
|
||||
|
||||
// Start listening on all trace activity.
|
||||
traceCh = client.ServiceTrace(ctxt, opts)
|
||||
}
|
||||
|
||||
mopts := matchingOpts(ctx)
|
||||
|
||||
// Start listening on all trace activity.
|
||||
traceCh := client.ServiceTrace(ctxt, opts)
|
||||
if stats {
|
||||
filteredTraces := make(chan madmin.ServiceTraceInfo, 1)
|
||||
ui := tea.NewProgram(initTraceStatsUI(ctx.Bool("all"), ctx.Int("stats-n"), filteredTraces))
|
||||
var te error
|
||||
go func() {
|
||||
for t := range traceCh {
|
||||
if t.Err != nil {
|
||||
te = t.Err
|
||||
ui.Kill()
|
||||
return
|
||||
}
|
||||
if mopts.matches(t) {
|
||||
filteredTraces <- t
|
||||
}
|
||||
}
|
||||
ui.Send(tea.Quit())
|
||||
}()
|
||||
if _, e := ui.Run(); e != nil {
|
||||
cancel()
|
||||
if te != nil {
|
||||
e = te
|
||||
}
|
||||
aliasedURL := ctx.Args().Get(0)
|
||||
fatalIf(probe.NewError(e).Trace(aliasedURL), "Unable to fetch http trace statistics")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
for traceInfo := range traceCh {
|
||||
if traceInfo.Err != nil {
|
||||
fatalIf(probe.NewError(traceInfo.Err), "Unable to listen to http trace")
|
||||
}
|
||||
if matchTrace(mopts, traceInfo) {
|
||||
if mopts.matches(traceInfo) {
|
||||
printTrace(verbose, traceInfo)
|
||||
}
|
||||
}
|
||||
@@ -493,6 +641,7 @@ type shortTraceMsg struct {
|
||||
StatusCode int `json:"statusCode"`
|
||||
StatusMsg string `json:"statusMsg"`
|
||||
Type string `json:"type"`
|
||||
Size int64 `json:"size,omitempty"`
|
||||
Error string `json:"error"`
|
||||
Extra map[string]string `json:"extra"`
|
||||
trcType madmin.TraceType
|
||||
@@ -561,6 +710,7 @@ func shortTrace(ti madmin.ServiceTraceInfo) shortTraceMsg {
|
||||
s.Duration = t.Duration
|
||||
s.StatusMsg = t.Message
|
||||
s.Extra = t.Custom
|
||||
s.Size = t.Bytes
|
||||
|
||||
switch t.TraceType {
|
||||
case madmin.TraceS3, madmin.TraceInternal:
|
||||
@@ -614,10 +764,15 @@ func (s shortTraceMsg) String() string {
|
||||
console.Colorize("ErrStatus", s.Error),
|
||||
console.Colorize("HeaderValue", s.Duration))
|
||||
} else {
|
||||
fmt.Fprintf(b, "[%s] %s %s %s %2s", console.Colorize("RespStatus", strings.ToUpper(s.trcType.String())), console.Colorize("FuncName", s.FuncName),
|
||||
sz := ""
|
||||
if s.Size != 0 {
|
||||
sz = fmt.Sprintf(" %s", humanize.IBytes(uint64(s.Size)))
|
||||
}
|
||||
fmt.Fprintf(b, "[%s] %s %s %s %2s%s", console.Colorize("RespStatus", strings.ToUpper(s.trcType.String())), console.Colorize("FuncName", s.FuncName),
|
||||
hostStr,
|
||||
s.Path,
|
||||
console.Colorize("HeaderValue", s.Duration))
|
||||
console.Colorize("HeaderValue", s.Duration),
|
||||
sz)
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
@@ -750,10 +905,14 @@ func (t traceMessage) String() string {
|
||||
fmt.Fprintf(b, "%s %s [%s] %s%s", nodeNameStr, console.Colorize("Request", fmt.Sprintf("[%s %s]", strings.ToUpper(trc.TraceType.String()), trc.FuncName)), trc.Time.Local().Format(traceTimeFormat), trc.Message, extra)
|
||||
return b.String()
|
||||
default:
|
||||
sz := ""
|
||||
if trc.Bytes != 0 {
|
||||
sz = fmt.Sprintf(" %s", humanize.IBytes(uint64(trc.Bytes)))
|
||||
}
|
||||
if trc.Error != "" {
|
||||
fmt.Fprintf(b, "%s %s [%s] %s%s err='%s' %s", nodeNameStr, console.Colorize("Request", fmt.Sprintf("[%s %s]", strings.ToUpper(trc.TraceType.String()), trc.FuncName)), trc.Time.Local().Format(traceTimeFormat), trc.Path, extra, console.Colorize("ErrStatus", trc.Error), trc.Duration)
|
||||
fmt.Fprintf(b, "%s %s [%s] %s%s err='%s' %s%s", nodeNameStr, console.Colorize("Request", fmt.Sprintf("[%s %s]", strings.ToUpper(trc.TraceType.String()), trc.FuncName)), trc.Time.Local().Format(traceTimeFormat), trc.Path, extra, console.Colorize("ErrStatus", trc.Error), trc.Duration, sz)
|
||||
} else {
|
||||
fmt.Fprintf(b, "%s %s [%s] %s%s %s", nodeNameStr, console.Colorize("Request", fmt.Sprintf("[%s %s]", strings.ToUpper(trc.TraceType.String()), trc.FuncName)), trc.Time.Local().Format(traceTimeFormat), trc.Path, extra, trc.Duration)
|
||||
fmt.Fprintf(b, "%s %s [%s] %s%s %s%s", nodeNameStr, console.Colorize("Request", fmt.Sprintf("[%s %s]", strings.ToUpper(trc.TraceType.String()), trc.FuncName)), trc.Time.Local().Format(traceTimeFormat), trc.Path, extra, trc.Duration, sz)
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
@@ -802,3 +961,87 @@ func (t traceMessage) String() string {
|
||||
fmt.Fprint(b, nodeNameStr)
|
||||
return b.String()
|
||||
}
|
||||
|
||||
type statItem struct {
|
||||
Name string
|
||||
Count int `json:"count"`
|
||||
Duration time.Duration `json:"duration"`
|
||||
Errors int `json:"errors,omitempty"`
|
||||
CallStatsCount int `json:"callStatsCount,omitempty"`
|
||||
CallStats callStats `json:"callStats,omitempty"`
|
||||
TTFB time.Duration `json:"ttfb,omitempty"`
|
||||
MaxTTFB time.Duration `json:"maxTTFB,omitempty"`
|
||||
MaxDur time.Duration `json:"maxDuration"`
|
||||
MinDur time.Duration `json:"minDuration"`
|
||||
Size int64 `json:"size"`
|
||||
}
|
||||
|
||||
type statTrace struct {
|
||||
Calls map[string]statItem `json:"calls"`
|
||||
Oldest time.Time
|
||||
Latest time.Time
|
||||
mu sync.Mutex
|
||||
}
|
||||
|
||||
func (s *statTrace) JSON() string {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
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(s)), "Unable to marshal into JSON.")
|
||||
|
||||
// strip off extra newline added by json encoder
|
||||
return strings.TrimSuffix(buf.String(), "\n")
|
||||
}
|
||||
|
||||
func (s *statTrace) String() string {
|
||||
return ""
|
||||
}
|
||||
|
||||
func (s *statTrace) add(t madmin.ServiceTraceInfo) {
|
||||
id := t.Trace.FuncName
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if t.Trace.TraceType != madmin.TraceBootstrap {
|
||||
// We can't use bootstrap to find start/end
|
||||
ended := t.Trace.Time.Add(t.Trace.Duration)
|
||||
if s.Oldest.IsZero() {
|
||||
s.Oldest = ended
|
||||
}
|
||||
if ended.After(s.Latest) {
|
||||
s.Latest = ended
|
||||
}
|
||||
}
|
||||
got := s.Calls[id]
|
||||
if got.Name == "" {
|
||||
got.Name = id
|
||||
}
|
||||
if got.MaxDur < t.Trace.Duration {
|
||||
got.MaxDur = t.Trace.Duration
|
||||
}
|
||||
if got.MinDur <= 0 {
|
||||
got.MinDur = t.Trace.Duration
|
||||
}
|
||||
if got.MinDur > t.Trace.Duration {
|
||||
got.MinDur = t.Trace.Duration
|
||||
}
|
||||
got.Count++
|
||||
got.Duration += t.Trace.Duration
|
||||
if t.Trace.Error != "" {
|
||||
got.Errors++
|
||||
}
|
||||
got.Size += t.Trace.Bytes
|
||||
if t.Trace.HTTP != nil {
|
||||
got.CallStatsCount++
|
||||
got.CallStats.Rx += t.Trace.HTTP.CallStats.InputBytes
|
||||
got.CallStats.Tx += t.Trace.HTTP.CallStats.OutputBytes
|
||||
got.TTFB += t.Trace.HTTP.CallStats.TimeToFirstByte
|
||||
if got.MaxTTFB < t.Trace.HTTP.CallStats.TimeToFirstByte {
|
||||
got.MaxTTFB = t.Trace.HTTP.CallStats.TimeToFirstByte
|
||||
}
|
||||
}
|
||||
s.Calls[id] = got
|
||||
}
|
||||
|
||||
+37
-17
@@ -24,10 +24,13 @@ import (
|
||||
"strings"
|
||||
|
||||
"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/madmin-go/v3"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/pkg/console"
|
||||
"github.com/minio/pkg/v3/console"
|
||||
)
|
||||
|
||||
var adminUpdateFlags = []cli.Flag{
|
||||
@@ -64,22 +67,37 @@ EXAMPLES:
|
||||
|
||||
// serverUpdateMessage is container for ServerUpdate success and failure messages.
|
||||
type serverUpdateMessage struct {
|
||||
Status string `json:"status"`
|
||||
ServerURL string `json:"serverURL"`
|
||||
CurrentVersion string `json:"currentVersion"`
|
||||
UpdatedVersion string `json:"updatedVersion"`
|
||||
Status string `json:"status"`
|
||||
ServerURL string `json:"serverURL"`
|
||||
ServerUpdateStatus madmin.ServerUpdateStatusV2 `json:"serverUpdateStatus"`
|
||||
}
|
||||
|
||||
// String colorized serverUpdate message.
|
||||
func (s serverUpdateMessage) String() string {
|
||||
if s.CurrentVersion != s.UpdatedVersion {
|
||||
return console.Colorize("ServerUpdate",
|
||||
fmt.Sprintf("Server `%s` updated successfully from %s to %s",
|
||||
s.ServerURL, s.CurrentVersion, s.UpdatedVersion))
|
||||
var rows []table.Row
|
||||
for _, peerRes := range s.ServerUpdateStatus.Results {
|
||||
errStr := fmt.Sprintf("upgraded server from %s to %s: %s", peerRes.CurrentVersion, peerRes.UpdatedVersion, tickCell)
|
||||
if peerRes.Err != "" {
|
||||
errStr = peerRes.Err
|
||||
} else if len(peerRes.WaitingDrives) > 0 {
|
||||
errStr = fmt.Sprintf("%d drives are hung, process was upgraded. However OS reboot is recommended.", len(peerRes.WaitingDrives))
|
||||
}
|
||||
rows = append(rows, table.Row{peerRes.Host, errStr})
|
||||
}
|
||||
return console.Colorize("ServerUpdate",
|
||||
fmt.Sprintf("Server `%s` already running the most recent version %s of MinIO",
|
||||
s.ServerURL, s.CurrentVersion))
|
||||
|
||||
t := table.NewWriter()
|
||||
var s1 strings.Builder
|
||||
s1.WriteString("Server update request sent successfully `" + s.ServerURL + "`\n")
|
||||
|
||||
t.SetOutputMirror(&s1)
|
||||
t.SetColumnConfigs([]table.ColumnConfig{{Align: text.AlignCenter}})
|
||||
|
||||
t.AppendHeader(table.Row{"Host", "Status"})
|
||||
t.AppendRows(rows)
|
||||
t.SetStyle(table.StyleLight)
|
||||
t.Render()
|
||||
|
||||
return console.Colorize("ServiceRestart", s1.String())
|
||||
}
|
||||
|
||||
// JSON jsonified server update message.
|
||||
@@ -128,15 +146,17 @@ func mainAdminServerUpdate(ctx *cli.Context) error {
|
||||
|
||||
// Update the specified MinIO server, optionally also
|
||||
// with the provided update URL.
|
||||
us, e := client.ServerUpdate(globalContext, updateURL)
|
||||
us, e := client.ServerUpdateV2(globalContext, madmin.ServerUpdateOpts{
|
||||
DryRun: ctx.Bool("dry-run"),
|
||||
UpdateURL: updateURL,
|
||||
})
|
||||
fatalIf(probe.NewError(e), "Unable to update the server.")
|
||||
|
||||
// Success..
|
||||
printMsg(serverUpdateMessage{
|
||||
Status: "success",
|
||||
ServerURL: aliasedURL,
|
||||
CurrentVersion: us.CurrentVersion,
|
||||
UpdatedVersion: us.UpdatedVersion,
|
||||
Status: "success",
|
||||
ServerURL: aliasedURL,
|
||||
ServerUpdateStatus: us,
|
||||
})
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -27,7 +27,7 @@ import (
|
||||
"github.com/minio/cli"
|
||||
json "github.com/minio/colorjson"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/pkg/console"
|
||||
"github.com/minio/pkg/v3/console"
|
||||
"golang.org/x/term"
|
||||
)
|
||||
|
||||
|
||||
@@ -22,7 +22,7 @@ import (
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/madmin-go/v3"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/pkg/console"
|
||||
"github.com/minio/pkg/v3/console"
|
||||
)
|
||||
|
||||
var adminUserDisableCmd = cli.Command{
|
||||
|
||||
@@ -22,7 +22,7 @@ import (
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/madmin-go/v3"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/pkg/console"
|
||||
"github.com/minio/pkg/v3/console"
|
||||
)
|
||||
|
||||
var adminUserEnableCmd = cli.Command{
|
||||
|
||||
@@ -25,7 +25,7 @@ import (
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/madmin-go/v3"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/pkg/console"
|
||||
"github.com/minio/pkg/v3/console"
|
||||
)
|
||||
|
||||
var adminUserInfoCmd = cli.Command{
|
||||
|
||||
@@ -23,7 +23,7 @@ import (
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/pkg/console"
|
||||
"github.com/minio/pkg/v3/console"
|
||||
)
|
||||
|
||||
var adminUserListCmd = cli.Command{
|
||||
|
||||
@@ -19,11 +19,15 @@ package cmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/cli"
|
||||
json "github.com/minio/colorjson"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/pkg/console"
|
||||
"github.com/minio/pkg/v3/console"
|
||||
"github.com/minio/pkg/v3/policy"
|
||||
)
|
||||
|
||||
var adminUserPolicyCmd = cli.Command{
|
||||
@@ -70,13 +74,29 @@ func mainAdminUserPolicy(ctx *cli.Context) error {
|
||||
user, e := client.GetUserInfo(globalContext, args.Get(1))
|
||||
fatalIf(probe.NewError(e).Trace(args...), "Unable to get user info")
|
||||
|
||||
pinfo, e := getPolicyInfo(client, user.PolicyName)
|
||||
if user.PolicyName == "" {
|
||||
e = fmt.Errorf("Policy not found for user %s", args.Get(1))
|
||||
e = fmt.Errorf("policy not found for user %s", args.Get(1))
|
||||
fatalIf(probe.NewError(e).Trace(args...), "Unable to fetch user policy document")
|
||||
}
|
||||
fatalIf(probe.NewError(e).Trace(args...), "Unable to fetch user policy document")
|
||||
|
||||
fmt.Println(string(pinfo.Policy))
|
||||
policyNames := strings.Split(user.PolicyName, ",")
|
||||
|
||||
var policies []policy.Policy
|
||||
for _, policyName := range policyNames {
|
||||
if policyName == "" {
|
||||
continue
|
||||
}
|
||||
policyInfo, e := getPolicyInfo(client, policyName)
|
||||
fatalIf(probe.NewError(e).Trace(), "Unable to fetch user policy document for policy "+policyName)
|
||||
|
||||
var policyObj policy.Policy
|
||||
if e := json.Unmarshal(policyInfo.Policy, &policyObj); e != nil {
|
||||
fatalIf(probe.NewError(e).Trace(), "Unable to unmarshal policy")
|
||||
}
|
||||
policies = append(policies, policyObj)
|
||||
}
|
||||
|
||||
mergedPolicy := policy.MergePolicies(policies...)
|
||||
json.NewEncoder(os.Stdout).Encode(mergedPolicy)
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -21,7 +21,7 @@ import (
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/pkg/console"
|
||||
"github.com/minio/pkg/v3/console"
|
||||
)
|
||||
|
||||
var adminUserRemoveCmd = cli.Command{
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user