Compare commits

...
Author SHA1 Message Date
Payton Ward 77f82e18b5 Add --ldap-username and --ldap-password flags to mc idp ldap accesskey create-with-login (#5258)
Add ldap-username and ldap-password flags to "idp ldap accesskey create-with-login"
2025-11-06 08:25:29 -08:00
Klaus Post ed0b962588 Modernize + Go version bump + Pin linter (#5256)
* Upgrade go version in CI.
* Add toolchain to pin version.
* Add linter/fumpt as pinned version in tools.
* Run `go run golang.org/x/tools/gopls/internal/analysis/modernize/cmd/modernize@latest -fix -test ./...`
2025-11-05 04:20:36 -08:00
dorman 7394ce0dd2 feat: beautify output for the ping command (#5237) 2025-08-13 01:35:41 -07:00
Daryl White b01f0c7371 Update links to new docs site (#5242) 2025-08-13 01:35:23 -07:00
dorman 5bb5df85e2 Fix the abnormal exit of the ping command (#5233)
The ping command abnormally exits after being executed more than 1000 times.
2025-07-23 13:36:38 -07:00
M Alvee ae1eab7d52 chore: clear error message with unauthorized credentials (#5236) 2025-07-23 13:36:17 -07:00
Yashwanth Krishnan ee72571936 update dependencies to fix dependent library CVEs: CVE-2025-22874, CVE-2025-4673 (#5235) 2025-07-20 22:28:08 -07:00
Shreyas Mali e5d2270535 fix: mirror active-active and race condition (#5234) 2025-07-19 07:45:24 -07:00
M Alvee 2676e50bc1 fix: redact sse key in debug logs (#5231) 2025-07-16 08:35:03 -07:00
dorman f72d75db5a mv:support set tag and checksum (#5133) 2025-07-13 11:52:53 -07:00
dorman c305d62fd5 ping: support ping a specified node and remove duplicate port printing (#5132) 2025-07-13 11:48:37 -07:00
Matthieu OLIVIER 4e38f39e25 feat: add --storage-class option to mc put subcommand (#5228)
feat: add --storage-class option to mc put
2025-07-13 11:46:49 -07:00
dorman 8576e735b1 mirror and cp support set the maximum number of threads (#5220) 2025-07-02 09:49:52 -07:00
Klaus Post 9a180cece7 Some paths like url2Stat will send resource with backslashes on windows (#5226)
This will cause key paths to mismatch and not be sent.

Example:

```
λ go build&&mc stat -enc-c="play/testbucket/=MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTIzNDU2Nzg5MDA" play/testbucket/mc
Name      : mc
Date      : 2025-07-02 17:52:42 CEST
Size      : 43 MiB
ETag      : 398345f23dc2ad4dd277e437e6ca7a1d-3
Type      : file
Encryption: SSE-C
Metadata  :
  Content-Type: application/x-msdownload
```
2025-07-02 09:49:02 -07:00
Menno Finlay-Smits 039be57dd2 Include ARN in "replicate list" output (#5215)
The "replicate resync start" command requires the remote bucket ARN.
This is currently difficult to obtain and requires picking through the
output of "replicate list --json". Worse still, the JSON output doesn't
contain the human-readable host for the bucket, making it difficult to
know that you've got the correct one.

This change solves the issue by including the ARN in the default list
output.
2025-06-25 08:26:44 -07:00
Klaus Post 3c9df3f2ea Update build version (#5218)
Fixes #5217
2025-06-24 02:41:42 -07:00
Burkov Egor 00fb114bce fix: add checks for nil HTTP in admin-trace matches func (#5216) 2025-06-23 08:14:30 -07:00
Harshavardhana 68f1d43f05 remove fips 'mc' container Dockerfile 2025-05-24 22:02:12 -07:00
Krutika Dhananjay f71ad84bcf Fix deletion of previously sync'd buckets and objects during mc-mirror (#5205) 2025-05-20 18:59:54 -07:00
angry-garden-salad 99c1b4365a Add STATUS column to batch job list table output (#5202) 2025-05-19 14:17:46 -07:00
jiuker 18c1c94d85 fix: remove check if lock config exists before set (#5203) 2025-05-19 01:05:02 -07:00
Shreyas Mali b9f30231ca removing config cmd (#5201) 2025-05-19 00:46:25 -07:00
Shreyas Mali 19d87ba475 fix: support chained mirror properly for delete propagation #4558 (#5197) 2025-05-06 09:41:33 -07:00
Klaus Post bbfe579fef Change support profile defaults (#5198)
* Remove block and mutex as they are rather intensive and provide little information.
* Add 'runtime'. Small, not intensive and possibly useful. Ignored by non-AIStor.
* Do 15 seconds for better data.
2025-05-06 08:10:18 -07:00
angry-garden-salad 2c1e058767 Explicitly set file permissions for admin-cluster-{bucket,iam}-export… (#5194)
Explicitly set file permissions for admin-cluster-{bucket,iam}-export.go to 600 regardless of umask
2025-05-02 09:34:41 -07:00
Aditya Manthramurthy 0a686cf874 Add support for catalog batch job type (#5150)
- During batch yaml generation, we check if the server supports the kind
of batch job requested.
- Shows catalog job status
2025-05-02 09:33:45 -07:00
Taran Pelkey 719f121225 Add idp openid accesskey commands (#5182) 2025-05-02 09:33:10 -07:00
jiuker b00526b153 feat: add deletemarker info for batch status (#5191) 2025-04-16 11:13:26 -07:00
Olli Janatuinen 391616f9cf mirror: skip status message from excluded buckets (#5190) 2025-04-10 08:51:27 -07:00
Burkov Egor ddda0fce2c typo: fix typo in tracing error for path (#5189) 2025-04-10 08:51:05 -07:00
Burkov Egor 0b4d69bc57 fix: update better error handling (#5188) 2025-04-10 08:50:18 -07:00
Mark Theunissen e929f89cee ConsoleMsg is not set by open source or AIStor, we should remove this an… (#5186)
ConsoleMsg is not set by open source or eos, we should remove this and correctly show Message only
2025-04-08 08:39:49 -07:00
dorman 56f94fd375 fix the terminal is damaged when parameters are missing (#5175) 2025-04-03 10:07:56 -07:00
jiuker 2d305ce990 fix: error out when the source and destination might be subdirectories of each other (#5173) 2025-04-01 22:51:22 -07:00
Harshavardhana 3296636c25 fix: replace tag and point to relevant release 2025-03-31 15:31:04 -07:00
Taran Pelkey 5349af0082 Add admin accesskey sts-revoke and idp ldap accesskey sts-revoke (#5160) 2025-03-31 13:55:31 -07:00
dorman ceb07bee89 fix return EOF failure on lines with trailing empty lines (#5176) 2025-03-28 02:05:40 -07:00
jiuker 5ce725ba7d fix: no data transition will show error for when mc ilm info not found (#5177) 2025-03-28 01:26:11 -07:00
Harshavardhana c652022dab upgrade golang-lint to v2 (#5178) 2025-03-28 01:05:40 -07:00
Harshavardhana d249b65941 pre-emptively disable sha256 payload if checksum is set (#5167) 2025-03-27 12:54:23 -07:00
dependabot[bot] b2d265dcc6 build(deps): bump github.com/golang-jwt/jwt/v4 from 4.5.1 to 4.5.2 (#5169)
Bumps [github.com/golang-jwt/jwt/v4](https://github.com/golang-jwt/jwt) from 4.5.1 to 4.5.2.
- [Release notes](https://github.com/golang-jwt/jwt/releases)
- [Changelog](https://github.com/golang-jwt/jwt/blob/main/VERSION_HISTORY.md)
- [Commits](https://github.com/golang-jwt/jwt/compare/v4.5.1...v4.5.2)

---
updated-dependencies:
- dependency-name: github.com/golang-jwt/jwt/v4
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-03-24 08:40:50 -07:00
Aditya Manthramurthy 0f061900ee batch: use server's generate API when available (#5166)
Uses the new GenerateBatchJobV2 API to request server to list supported
batch jobs and to request job templates in `mc batch generate`
2025-03-14 10:29:01 -07:00
Klaus Post cf909e1063 Add ping sort to mc support top rpc (#5158)
Use key 'p' to sort by ping.
2025-03-13 01:02:18 -07:00
Aditya Manthramurthy c1d5d4cbb4 Update all deps (#5165) 2025-03-12 10:29:24 -07:00
Shireesh Anjal b3a00e0f8c Update madmin-go to latest version (#5161)
and clear reference to the removed variable madmin.HealthDataTypeSysLoad
2025-03-11 10:47:28 -07:00
Aditya Manthramurthy 06520070bb Update ssh and jws libs for fixed CVEs (#5164)
-   https://pkg.go.dev/vuln/GO-2025-3488
-   https://pkg.go.dev/vuln/GO-2025-3487
2025-03-11 09:36:39 -07:00
Harshavardhana ce874fdc6a rename rcp -> rpc 2025-03-07 15:46:22 -08:00
Shireesh Anjal 1e412f58a5 Remove logs feature from 'mc support callhome' (#5157)
Both the flags --logs and --diag are removed, and the command supports
only diagnostics callhome.
2025-03-06 08:30:58 -08:00
jinapurapu b0f40b4db7 Reject add ILM rule with both day and date parameters (#5155) 2025-03-06 05:05:05 -08:00
jinapurapu 10035268c4 Fix transition days calculation (#5154) 2025-03-05 13:23:17 -08:00
Klaus Post 9eb205cb62 Mirror should delete on delete marker creation + ILM (#5148)
Fixes #5147
2025-02-21 08:00:46 -08:00
jiuker 0ba848a99e fix: use tags package instead of s3utils (#5146) 2025-02-20 00:54:15 -08:00
Grahit 28909abaa4 fix empty ilm tier list output (#5145) 2025-02-19 20:27:26 -08:00
Harshavardhana 383560b1c3 update all dependencies (#5143) 2025-02-15 02:36:16 -08:00
Anis Eleuch 8585339d12 More fixes to custom arch hotfix building (#5135)
Set TARGET_GOOS and TARGET_GOARCH to specify the target architecture of
the built binary.
2025-02-14 08:49:56 -08:00
jiuker 468ab39f41 test: add tags copy test for mirror (#5141) 2025-02-14 08:49:41 -08:00
Klaus Post 217d92358b Add CRC64NVME checksum type. (#5142)
Also adds `CRC32-FO` and `CRC32C-FO` for complete object checksums.

```
λ mc cp -checksum=crc64nvme mc.exe myminio/testbucket
...com\minio\mc\mc.exe: 41.95 MiB / 41.95 MiB

λ mc stat myminio/testbucket/mc.exe
Name      : mc.exe
Date      : 2025-02-14 13:59:05 CET
Size      : 42 MiB
ETag      : 7f130846cec6e6ece750565b1f3d9518-3
VersionID : f4daeb78-9eaf-4da9-b9ca-d8b65fbc69e3
Type      : file
Checksum  : CRC64NVME:TOfg0RHhpZk=
Metadata  :
  Content-Type: application/x-msdownload

λ mc cp -checksum=crc32-fo mc.exe myminio/testbucket
...com\minio\mc\mc.exe: 41.95 MiB / 41.95 MiB

λ mc stat myminio/testbucket/mc.exe
Name      : mc.exe
Date      : 2025-02-14 13:58:52 CET
Size      : 42 MiB
ETag      : 7f130846cec6e6ece750565b1f3d9518-3
VersionID : 1ec587dd-9127-42ee-ad82-58b48f9676d5
Type      : file
Checksum  : CRC32:3Dt3fQ==
Metadata  :
  Content-Type: application/x-msdownload

λ _
```
2025-02-14 08:13:46 -08:00
Mark Theunissen c32317ef80 Improve docs to hint to the user that MD5 is not stored (#5138)
Improve docs to hint to the user that MD5 is the odd one out in this list
2025-02-13 10:19:41 -08:00
jiuker 089f833ce0 feat: support --custom-header flags (#5127) 2025-02-13 10:18:53 -08:00
Burkov Egor 42b78ded3a fix: explicit fd close fix (#5129) 2025-02-13 02:41:18 -08:00
jiuker 147e8f5b3b feat: add tags copy for mirror (#5137) 2025-02-13 02:39:59 -08:00
Klaus Post e97f4324d5 Fix vet check (#5134)
... and pin toolchain.
2025-02-12 08:36:32 -08:00
Harshavardhana 859c5989a1 make custom ARCH based hotfixes 2025-02-11 15:37:45 -08:00
Harshavardhana 10c50368c5 remove fips build 2025-02-08 13:06:32 -08:00
dorman bd925c01a1 mirror: add the duration time and beautify the output (#5125)
add the duration time and beautify the output
2025-02-08 11:14:21 -08:00
Burkov Egor 030c8125eb fix: urls equals nil deref (#5126)
Now in checks we can get nil dereference while both struct has Content
field of nil. But in code we cheching for nil, and I believe that
testcase can be real:
```go
urls1 := URLs{};
urls2 := URLs{};
urls1.Equal(urls2);
```
2025-02-07 02:46:26 -08:00
Harshavardhana 6376279f15 add support for pre-2023 minio deployments (#5122) 2025-02-04 14:18:02 -08:00
Taran Pelkey 5aee0b1c9e Change enable to "enable=" (#5104) 2025-02-04 12:34:19 -08:00
Sveinn ( keyb1nd ) 8d713ff927 Giving mirror the option to exit early when --remove is not set (#5116)
* Giving mirror the option to exit early when --remove is not set
* Making sure always to cancel the context on exit
* Adding an internal flag to enable local listing only based on active/active and remove flags
* Renaming localListingOnly to sourceListingOnly
2025-02-04 12:32:54 -08:00
Klaus Post 318e707071 Add "mc support upload" encryption (#5113)
* Add `--enc` parameter to `mc support upload` to encrypt the file content.
* Add file size as zstd frame content size.
* Test opening the file before doing more.
* Uses same key as "mc support inspect".
2025-02-03 20:57:50 -08:00
Harshavardhana 423ef1ba2a update go deps 2025-01-22 23:47:51 -08:00
Shubhendu a4f20fe74c Use latest madmin-go for policy content check (#5109)
Signed-off-by: Shubhendu Ram Tripathi <shubhendu@minio.io>
2025-01-22 23:41:01 -08:00
Mark Theunissen 5cfac09600 Improve the error message when trying to add multiple expiry options (#5117) 2025-01-22 22:51:38 -08:00
Klaus Post b436cd2436 mc find - allow absolute times (#5118)
For `--newer-than` and `--older-than`, allow using absolute times.

Example:

```
λ mc ls play/testbucket
[2025-01-22 09:57:12 CET] 676KiB STANDARD Daily checks Procedure for Portainer.docx
[2025-01-22 16:40:07 CET]  22KiB STANDARD dovrennost_mobilizaciya_0-2.docx

λ mc find -newer-than="2025-01-22 09:57:00 CET" play/testbucket
play/testbucket/Daily checks Procedure for Portainer.docx
play/testbucket/dovrennost_mobilizaciya_0-2.docx

λ mc find -newer-than="2025-01-22 09:57:13 CET" play/testbucket
play/testbucket/dovrennost_mobilizaciya_0-2.docx
```

We allow the same timestamp types as `--rewind` and add the printed type for easy copy+paste.
2025-01-22 22:51:15 -08:00
dorman 0019b7b83c fix: cp and mirror commands fail to be executed when the file length is 255 characters (#5114) 2025-01-21 02:19:00 -08:00
Harshavardhana cc8758c88d chore: update deps 2025-01-17 15:25:50 -08:00
qinyuren 95e1f70eb5 The version-id in the get command does not work (#5110) 2025-01-16 01:52:17 -08:00
Harshavardhana b1a3941f22 chore: update deps (#5102) 2025-01-02 05:11:34 -08:00
Klaus Post 147852cb37 Add go runtime profile type (#5098)
Available on AIStor.

Requires https://github.com/minio/madmin-go/pull/322

Lower minimum duration to 1 second. Useful (pretty much required) for traces.
2025-01-02 04:55:34 -08:00
Poorna bf7b5f620e fix ilm rule edit for --expire-all-object-versions (#5101)
Editing a rule with --expire-all-object-versions should be applied
to existing rule properly
2025-01-02 04:10:56 -08:00
Harshavardhana f4dd5e4a07 update all deps and update CREDITS (#5097) 2024-12-16 04:20:40 +05:30
Klaus Post 19017536cc Add support top rpc ui nicities (#5087)
* Split to/from. t/f keys to go directly. <tab> to switch.
* Sort by queue size (q)
* Filter/Sort by reconnects (r)
* Add PgUp+PgDn
* Pause with <space>
2024-12-15 01:26:01 -08:00
Klaus Post 86907df91d Improve trace stats (#5095)
Allows traces to be replayed in stats mode from `mc admin trace -json ALIAS >trace.json`, using `mc admin trace -in=trace.json`. `.zst` are automatically decompressed.

This is replayed at full speed, since I don't really see any value in keeping original speed.

Add scrolling to stats. Up+Down+Home+End

Add 'r' to reset min/max stats.
2024-12-15 01:25:34 -08:00
Anis Eleuch 1681e4497c heal: Do not print a cryptic msg when scanning a dangling object (#5084)
Healing in server side will list with quorum 1, so it will pick stale
objects as well. This is currently not rendered well in mc that shows
this cryptic message:
	Invalid parity shard count/surplus shard count given

Print the text sent by the server instead.
2024-11-21 09:21:54 -08:00
Allan Roger Reid 35cb4b8177 Return delete markers in mc find (#5083)
* Default to list delete flags if they are part of the result set, so that they are not hidden from the find function

* Add --with-delete-marker flag to toggle the listing of delete markers. Defaults to false

* List delete markers as well when using the --versions flag
2024-11-20 10:10:21 -08:00
Harshavardhana bb4ff4951a when --no-list is specified avoid every List() call (#5082) 2024-11-17 11:35:25 -08:00
Anis Eleuch 308a8ea9d0 heal: Simplify bucket healing status (#5079)
Avoid using the drive count concept to pick a color for a bucket healing
result. This was straightforward when we were healing a bucket per erasure 
set, but now it becomes more complex to show a result.

Pick green if everything is okay, yellow if a bucket is missing in a
drive, red for any other drive state (unformatted, offline, ..), and
grey for any weird situation.
2024-11-13 08:33:49 -08:00
Anis Eleuch 63eb4a4609 lint: Fix new detected lint complaints (#5080) 2024-11-13 05:46:18 -08:00
Klaus Post 6ac18619cf Only warn if less than 28 days to cert expires (#5077)
Fixes #5076 as much as reasonable.
2024-11-05 03:29:45 -08:00
dependabot[bot] 95a03f54da Bump github.com/golang-jwt/jwt/v4 from 4.5.0 to 4.5.1 (#5074)
Bumps [github.com/golang-jwt/jwt/v4](https://github.com/golang-jwt/jwt) from 4.5.0 to 4.5.1.
- [Release notes](https://github.com/golang-jwt/jwt/releases)
- [Changelog](https://github.com/golang-jwt/jwt/blob/main/VERSION_HISTORY.md)
- [Commits](https://github.com/golang-jwt/jwt/compare/v4.5.0...v4.5.1)

---
updated-dependencies:
- dependency-name: github.com/golang-jwt/jwt/v4
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-11-05 02:22:23 -08:00
dorman 9f4659884d Make the profiler easier to use (#5068) 2024-10-29 08:34:59 -07:00
Shubhendu a814b5deaf Mark batch job status properly (#5066)
Client side overall status was always shown as `in-progress` even if
job was successful or failed.

Signed-off-by: Shubhendu Ram Tripathi <shubhendu@minio.io>
2024-10-21 01:51:15 -07:00
Michael Fenn 65aa514dfa Add string/json output string mc pipe (#5065)
This commit adds a string message and json output to mc pipe.  The
implementation is heavily inspired by the one in mc cp, just adapted to
the different semantics of pipe.
2024-10-20 06:55:58 -07:00
Klaus Post d9b81b2956 Add support rpc JSON replay. (#5064)
Add realtime replay of captured JSON data.

Example:
```
λ mc support top rpc --json myminio >rpc.json

λ mc support top rpc -in=rpc.json
```
2024-10-18 14:18:41 -07:00
Klaus Post 2c4e3ad46b Report errors and better file names for mc support inspect (#5062)
Check the returned stream for errors and show them. Don't upload/keep pointless data

Use the request alias to create a better file name...

Example:

```
λ mc support inspect play/testbucket/testdat/**
mc: <ERROR> Unable to download file data. GetRawData: No files matched the given pattern.
```

Previously the error would just be ignored.

```
λ mc support inspect --airgap play/testbucket/testdata/**
File data successfully downloaded as inspect-play_testbucket_testdata.enc
```

Previously all files would be called `inspect-data.enc`, which would just be difficult to distinguish.
2024-10-15 08:15:39 -07:00
Klaus Post bad9b2c737 Add basic RPC metrics via mc support top rpc (#5060)
Example:
```
λ mc support top rpc myminio
      SERVER            CONCTD  PING    OUT Q   RECONNS STR IN  STR OUT MSG IN  MSG OUT
 To  127.0.0.1:9001       5     0.5ms     0        0    -> 20    0 ->   60007    60089
From 127.0.0.1:9001       5     0.5ms     0        0     -> 0    20 ->  60089    60002
 To  127.0.0.1:9002       5     0.0ms     0        0     -> 0    4 ->   34209    33937
From 127.0.0.1:9002       5     0.5ms     0        0     -> 4    0 ->   33938    34209
 To  127.0.0.1:9003       5     0.0ms     0        0     -> 0    4 ->   99379   101165
From 127.0.0.1:9003       5     0.0ms     0        0     -> 4    0 ->   101166   99379
 To  127.0.0.1:9004       5     0.5ms     0        0     -> 0    4 ->   33784    33029
From 127.0.0.1:9004       5     0.0ms     0        0     -> 4    0 ->   33030    33784
 To  127.0.0.1:9005       5     0.0ms     0        0     -> 0    4 ->   33515    33135
From 127.0.0.1:9005       5     0.5ms     0        0     -> 4    0 ->   33136    33515
 To  127.0.0.1:9006       5     0.0ms     0        0     -> 0    4 ->   33627    33161
From 127.0.0.1:9006       5     0.0ms     0        0     -> 4    0 ->   33162    33627
```

There is already server support for metrics.
2024-10-14 13:50:20 -07:00
Harshavardhana e20dea646f remove s390x support 2024-10-13 06:54:36 -07:00
Krutika Dhananjay cf128de2cf Do not fail mc-admin-policy-attach if policy already attached/detached (#5058)
Currently, attempts to attach a policy to a user who already has
the policy attached to them results in a 400.

This change handles cases where policy attach/detach operations
are automated using scripts/jobs. A re-run of the attach/detach
step should not fail the entire job.
2024-10-08 02:37:26 -07:00
Taran Pelkey 07eeb10c06 Add mc admin accesskey commands (#5038) 2024-10-04 04:29:36 -07:00
Harshavardhana ce0b434152 upgrade dependencies (#5053) 2024-10-02 01:27:28 -07:00
Anis Eleuch 4616d11c20 heal: More UX changes (#5052)
- Do not show healing ETA anymore; there are some scenarios where the
  ETA can be wrong. Show when healing is started and the progress of the
  healing drive usage compared to nonhealing drives in the same erasure set.
- `--verbose` prints only offline/faulty and healing drives
- `--all-drives` to show information about all drives
- Add yes/no prompt when a user wants to heal the whole namespace
2024-10-01 15:14:33 -07:00
Harshavardhana 609f32a4ff cleanup use of os.Environ() re-use env.List(prefix) (#5048) 2024-09-27 05:08:56 -07:00
Harshavardhana 97fe232a9a add alias name to 'mc ready' (#5044) 2024-09-25 02:56:38 -07:00
llchry a5a54b4429 put: Add --disable-multipart to make it easier to use. (#5041) 2024-09-24 10:47:33 -07:00
Klaus Post be874766a7 Add --checksum param to pipe, put, cp, mirror (#5043)
Add checksums to pipe, cp, mirror commands.

> Add checksum to uploaded object. Values: MD5, CRC32, CRC32C, SHA1 or SHA256. Requires server trailing headers support like AWS, MinIO and possibly others.

`--md5` is hidden, but still applied.

Uploads to buckets with object locking will still use MD5.

Bonus: `mc stat` shows checksum information.
2024-09-24 08:25:16 -07:00
Poorna 3dac3d392f fix quota info (#5040) 2024-09-20 05:49:53 -07:00
11ebe952ea iam export:designate zip file name (#4995)
Co-authored-by: Harshavardhana <harsha@minio.io>


---------

Co-authored-by: Harshavardhana <harsha@minio.io>
Co-authored-by: Klaus Post <klauspost@gmail.com>
Co-authored-by: Aditya Manthramurthy <donatello@users.noreply.github.com>
2024-09-16 10:43:14 -07:00
dormanandKlaus Post 37095dadcc mirror:Add the printing of event time (#4953)
* Add the printing of event time

* Update mirror-main.go

---------

Co-authored-by: Klaus Post <klauspost@gmail.com>
2024-09-16 10:30:02 -07:00
dorman 41aca25f6c alias: mc alias list command outputs the alias information specified by MC_CONFIG_ENV_FILE (#5028)
* Update alias-list.go
2024-09-16 10:23:10 -07:00
Anis EleuchandAnis Eleuch bbfe577d2e idp-ldap: Fix create-with-login command (#5036)
Currently, LDAP create-with-login command is not working properly when
the LDAP user does not have admin:CreateServiceAccount permission.

The permission is normally not needed since a user is allowed
to create a service account for itself. In that case, a temporary
account should be created and a new service account should be issued to
the temporary account access key, and not to the LDAP username as what
the code currently does.

This commit will send the correct target user in that case to make
create-with-login always successful.

Co-authored-by: Anis Eleuch <anis@min.io>
2024-09-14 20:56:26 -07:00
Shubhendu 04c5116c9b Fix regression (#5034)
A regression was introduced by https://github.com/minio/mc/pull/5032
where new `mc` with old MinIO wont import the IAM configs properly.

Signed-off-by: Shubhendu Ram Tripathi <shubhendu@minio.io>
2024-09-09 00:53:10 -07:00
Anis Eleuch f2d65b6c18 scanner-status: Support both old & new scanner metrics (#4683)
When the scanner uses parallel erasure sets scanning, the cycle concept
for the whole scan is no longer relevant. This PR will show the number
of ongoing bucket scans. 

```
mc admin scanner status --bucket <bucket-name> ALIAS
```

Will print a detailed report of a particular bucket scan.

Like, when the last scan progress was saved for that bucket for all
erasure sets. Also it will print when a full scan of a bucket finished.

(A full bucket scan means the last time frame that was needed for each
of erasure sets to do sixteen cycles)
2024-09-08 01:15:30 -07:00
Anis Eleuch 3092b6bf14 tier: Add hidden --force to remove tiering command (#5031)
To ensure that the server can remove an internal tier configuration
when the tiering is unreachable or other corner cases where it is not
possible for the server to determine if the tier contains some data
or fully empty.
2024-09-06 11:28:18 -07:00
Shubhendu 25ea06308f Update to print skipped entities during IAM import (#5032)
Signed-off-by: Shubhendu Ram Tripathi <shubhendu@minio.io>
2024-09-05 08:31:14 -07:00
Taran Pelkey 54268c4808 Add edit, enable, and disable to mc idp ldap accesskey (#5033) 2024-09-05 04:03:52 -07:00
Anis Eleuch ba97441b5e mirror: Print errors in --json format when --skip-errs is provided (#5030) 2024-08-29 19:25:07 -07:00
Harshavardhana efc60a8a90 fix: docker buildx warnings 2024-08-26 09:48:09 -07:00
Harshavardhana a55d9a8d17 upgrade pkg/v3, minio-go/v7 deps (#5027) 2024-08-26 03:49:58 -07:00
Anis Eleuch 6801d70e55 heal: Do not show heal ETA when there is a retry attempt (#5025)
There is no suitable mechanism to estimate the ETA of healing when it is
retrying, although in most cases, it is just a listing that should be
quick enough. Hide the ETA anyway for now.
2024-08-26 01:50:57 -07:00
Harshavardhana 2e10255b6d allow cat to take part by part numbers (#5026) 2024-08-26 01:48:58 -07:00
Mark Theunissen efa1b396f2 Add commands for managing Bucket CORS (#5019) 2024-08-22 08:46:05 -07:00
Anis Eleuch aca5c185fe heal: Adapt the status based on a new Finished flag (#5017)
In a new MinIO version, Healing can be set to false while HealInfo is
not nil. This indicates that the drive was healed and the healing is
finished. This commit adapts the code with the new concept. This will
not break with older MinIO versions since those versions will already
remove .healing.bin, in that case Healing will be false, HealInfo will
be nil.
2024-08-21 05:20:43 -07:00
jiuker 690f3f8bb3 fix: Use TLS for STS endpoint when STS endpoint uses https scheme. (#5022) 2024-08-17 15:15:59 -07:00
Taran Pelkey 2c94b8d039 policy entities now print group memberships per user (#4961) 2024-08-17 04:33:50 -07:00
Harshavardhana 456709a2a4 combine STS, SVC accounts into access keys with or without expiration (#5004) 2024-08-17 04:11:58 -07:00
Ramon de Klein 479171e7be Fix warnings (#5023) 2024-08-15 08:50:11 -07:00
Harshavardhana b34cd742cb chore: update all deps (#5018) 2024-08-12 22:33:17 -07:00
Mark Theunissen 21ab58a03f Import bucket metadata must show CORS and general errors if any are found (#5001) 2024-08-12 20:08:58 -07:00
Harshavardhana 32b7b72193 conditionally disallow list() when object does not exist (#5016)
allow users to avoid list() call when an object does not
exist when following flags are used with `mc stat`

```
--no-list (HEAD the latest version)
--version-id <vid>
```

Also avoid superflous url2Stat() calls while processing
the args, there is no real reason to do that.
2024-08-12 01:52:27 -07:00
dorman e7d1e97852 stat: print information about all buckets when only alias are set (#5002) 2024-08-08 19:04:42 -07:00
Ravind Kumar d6886b33d2 Update admin-service.go (#5010)
`mc admin service stop` is hidden as it is a dangerous/one-way command.

No need to reference it in the description
2024-08-08 17:46:32 -07:00
Sveinn 487b874a2e Fixing invalid help menu for s3 type encryption (#5008)
* Fixing invalid help menu for s3 type encryption

* removing random comment
2024-08-08 17:46:22 -07:00
Andreas Auernhammer 58f15fca83 add global --resolve HOST[:PORT]=IP flag (#5013)
add global `--resolve HOST[:PORT]:IP` flag

This commit adds support for custom DNS overwrites via one or multiple
`--resolve` flags. It allows `mc` users to define custom DNS mappings
from a HOST (and optional port) to an IP address.

For example:
```
mc --resolve foo.com:9000=10.1.2.3 ls myminio/mybucket
```
The `--resolve` syntax is taken from cURL. Ref. `curl --help dns`

Use cases:

  1. DNS overwrites. If there are no DNS resolvers available, e.g.
     due to a temp. outage, this allows `mc` to connect to a defined
     alias as long as the IP of the one or multiple cluster nodes are
     known. It also allows `mc` to overwrite the current DNS responses.
     This is useful for various tests in dev and staging environments.
  2. TLS certificate verification. Often TLS certificates are issued
     for some DNS names (via SAN) but not for IP addresses. IP addresses
     are usually not static and might change anytime. Accessing a MinIO
     cluster that serves a certificate containing only DNS SANs via an
     IP address results in a TLS certificate verification error - even
     if the certificate is issued by a trusted CA. The current workaround
     is the `--insecure` flag which disables TLS certification completely.

Example for TLS verification:

```
$ mc alias set 'myminio' 'https://192.168.188.118:9000' 'minioadmin' 'minioadmin'
mc: <ERROR> Unable to initialize new alias from the provided credentials.
Get "https://192.168.188.118:9000": tls: failed to verify certificate:
x509: cannot validate certificate for 192.168.188.118 because it doesn't contain any IP SANs.
```

```
mc alias set --resolve foo.com:9000=192.168.188.118 'myminio' 'https://foo.com:9000' 'minioadmin' 'minioadmin'
Added `myminio` successfully.
```

Signed-off-by: Andreas Auernhammer <github@aead.dev>
2024-08-08 17:46:03 -07:00
Andrea Longo a56899e13c docs: explain scanner bucket quota check process (#5011) 2024-08-07 03:27:15 -07:00
Klaus Post 3cb570ff56 Normalize metadata values for compare (#5006)
Possible fix for https://github.com/minio/mc/issues/4997
2024-08-05 18:45:27 -07:00
Shireesh Anjal 28d64f224a Fix wrong message shown when upload to SUBNET fails (#5005)
When upload of the inspect file to SUBNET fails, following wrong message
was getting printed:

`Object inspection data for '' uploaded to SUBNET successfully`

Fixed the if condition to ensure that following correct message is
printed:

`File data successfully downloaded as <filename>`
2024-08-05 01:06:03 -07:00
Taran Pelkey f0d2ad4708 Rework mc idp ldap accesskey list to use new API endpoint (#4946) 2024-07-31 08:58:33 -07:00
Roman Chechyotkin 6a06daa1de #4988 fixed prometheus metrics usage message (#5000) 2024-07-31 08:47:42 -07:00
Harshavardhana 8ad22bb694 trace: avoid aggregate statistics TX/RX with --all (#4998) 2024-07-26 06:08:44 -07:00
Klaus Post 73e614aee9 Make trace stats more compact (#4999)
Make `mc admin trace -stats` more compact, and hopefully more readable.

* Truncates durations more reasonably
* Use `-` for 0 TTFB.
* Use `↑151B ↓12K` instead of `↑ 151 B ↓ 12 KiB/m`
* Reduce FPS from 7 to 3 for less flickering.
2024-07-26 05:50:54 -07:00
Anis Eleuch 58c42bc91b Allow STANDARD_IA as a AWS tier storage class (#4994) 2024-07-22 13:02:49 -07:00
Klaus Post f6df01d750 Fix incorrect bool parsing (#4991)
For example `--json=false` would still print JSON.

Went through all usage, and I think I covered them all.
2024-07-18 09:08:30 -07:00
Anis Eleuch ded36374e8 Show a warning when the server certificate duration is expiring soon (#4989)
When 90% of the validity time of a server is elapsed, print a warning
reminding the user to change the certificate.
2024-07-18 09:08:07 -07:00
mchtech 11034f9de1 mirror: let user decide whether to skip errors if client runs in watch / active-active mode (#4986)
Signed-off-by: mchtech <michu_an@126.com>
2024-07-15 10:46:06 -07:00
Klaus Post 4d498deb35 Fix non-recursive compares against alias+key on Windows (#4983)
Many listings would stop after the first version had been processed on Windows, since

For example, `mytls/testbucket/trace.json` != `mytls\testbucket\trace.json` would cause `mc undo` to only see one version since this would fail.

Use `getStandardizedURL` for both sides of these compares.
2024-07-11 11:01:28 -07:00
Shireesh Anjal ddfd44cb35 Support metrics-v3 api in admin prometheus generate (#4985)
Add a flag --api-version with possible values of v2 and v3, with default
being v2.

So when this flag is not passed, the command will work exactly as it did
before.

When using v3, there is a different set of metric types supported. It
also supports a new flag:

bucket: the bucket for which the metrics are to be fetched. it is
applicable only for the metric types that are available at bucket level,
which currently are 'api' and 'replication'
2024-07-11 11:00:59 -07:00
Shireesh Anjal ea33d018ca Support metrics-v3 api in admin prometheus metrics (#4982)
Add a flag --api-version with possible values of v2 and v3, with the default
being v2. So when this flag is not passed, the command will work exactly
as before.

When using v3, a different set of metric types is supported. It
also supports two additional flags:

Bucket: the bucket for which the metrics are to be fetched. it is
applicable only for the metric types that are available at the bucket level,
which currently are 'api' and 'replication'
2024-07-11 01:33:12 -07:00
Harshavardhana 21d3ec0089 improve 'admin service restart' UI (#4979)
```
mc admin service restart local -w
Service status: ▰▱▱ [DONE]
Summary:
    ┌───────────────────────┬─────────────────────────────┐
    │ Servers:              │ 4 online, 0 offline, 0 hung │
    │ Restart Time:         │ 3.949842ms                  │
    │ Background Init Time: │ 1.503707801s                │
    └───────────────────────┴─────────────────────────────┘
```

Existing UI didn't scale well for 100+ nodes, this
UI change is also made to provide clear guidance on
how soon the service is available v/s background
initialization time.
2024-07-08 13:59:24 -07:00
Harshavardhana 661e19b3b2 update deps (#4978) 2024-07-04 07:29:35 -07:00
Harshavardhana d6ff970125 honor bucket-key S3 feature (#4976)
fixes #4973
2024-07-03 13:17:25 -07:00
Mark Theunissen 26680ab77c Add ability to update tier credentials for Azure svc principal accounts (#4975) 2024-07-03 12:14:48 -07:00
Klaus Post 7e4b64d12a Simplify go.mod (#4977)
Combine into direct and indirect sections. See https://github.com/golang/go/issues/67948 for why this is a mess.

Enables running `go mod tidy` without blowing up things.
2024-07-03 11:49:12 -07:00
Harshavardhana 74032bc16a update govulncheck 1.22.5 2024-07-02 14:39:05 -07:00
Shubhendu bbdd9638f2 Use new batch status api /status-job (#4930)
Signed-off-by: Shubhendu Ram Tripathi <shubhendu@minio.io>
2024-07-02 08:29:37 -07:00
Anis Eleuch e0d2e95984 heal: Add hidden --pool and --set to heal a particular ES (#4971)
--pool and --set are hidden flags. They could be used to heal a
particular erasure set. --pool and --set start with 1 (not indexes)
2024-07-02 02:28:07 -07:00
Harshavardhana f5b325d9d3 remove unused code 2024-06-29 12:08:46 -07:00
Harshavardhana 6811427b8b provide a overall summary along with call-wise (#4970)
```
Duration: 1m3s ▱▱▱
RPM    :  1168103.3
RX Rate:↑ 2.5 TiB/m
TX Rate:↓ 2.4 TiB/m
-------------
...
```
2024-06-28 16:17:44 -07:00
Harshavardhana 3548007d5b fix: make sure to set the right sse-kms key (#4967) 2024-06-24 12:40:33 -07:00
Harshavardhana dda9e96887 make 'mc admin service restart' more descriptive of what it does (#4965) 2024-06-20 07:50:54 -07:00
Harshavardhana 8876275c07 list versions including DEL marker when figuring out Stat() (#4951)
this is needed to avoid an inconsistent behavior when an
object exists v/s DEL marker or FreeVersion exists.
2024-06-19 22:57:53 -07:00
Prakash Senthil Vel b72bd7992c enable batch expiry option in trace (#4964)
add batch expiry option in trace
2024-06-19 22:17:42 -07:00
Harshavardhana a289dae750 fix: support 'mc put --if-not-exists' (#4963)
Also allow 'mc get --version-id'
2024-06-18 14:15:26 -07:00
Sveinn adaf70c7eb Adding support for Hex keys (#4962) 2024-06-18 07:51:58 -07:00
Poorna e7c9a733c6 fix replicate status display for older replication config (#4957)
that specified ARN in the Role field. This has since moved to
Destination.Bucket
2024-06-12 07:34:03 -07:00
Harshavardhana a472e3d9ed switch RX and TX arrow marks correctly
the arrow marks must be from server perpective
not `mc` perspective.
2024-06-11 12:50:18 -07:00
Anis Eleuch 7a0a8f54d9 info: Add --offline flag to show only offline nodes (#4955) 2024-06-10 09:44:15 -07:00
jiuker e44a1c612d fix: mc mirror got zero exit code when access denied (#4952) 2024-06-07 08:48:20 -07:00
Harshavardhana 17adf0abbb add vulncheck with go upgrade 2024-06-05 11:13:30 -07:00
Harshavardhana 0bd92d778e add space between upload/download indicators 2024-06-05 11:12:13 -07:00
Klaus Post 3997483ce7 Add sizes to mc admin trace (#4949)
```
Regular trace:

2024-06-03T14:18:37.303 [STORAGE] storage.ReadXL 127.0.0.1:9001 e:\data\distxl\s1\d3 warp-benchmark-bucket pz9WSPPj/4.TnpU8KEot9t4zl66.rnd 538.3µs 1003 B

With -v:

127.0.0.1:9001  [STORAGE storage.ReadXL] [2024-06-03T14:14:51.680] e:\data\distxl\s1\d3 warp-benchmark-bucket yvhiOPYp/117.hjDOOH6KmAhtC0Ty.rnd total-errs-availability=0 total-errs-timeout=0 0s 1003 B

With -stats

Duration: 21s ∙∙●
Call                            Count           RPM     Avg Time        Min Time        Max Time        Avg TTFB        Max TTFB        Avg Size        Errors
storage.ReadXL                  15808 (67.2%)   44344.8 429µs           0s              69.9984ms       0s              0s              1.2 KiB         0
storage.Delete                  3088 (13.1%)    8662.5  2.056ms         9.7075ms        305.0662ms      0s              0s              -               3

http stats:

Duration: 14s ∙∙●
Call                            Count           RPM     Avg Time        Min Time        Max Time        Avg TTFB        Max TTFB        Avg Size        Errors
s3.GetObject                    4532 (44.1%)    19502.8 1.121ms         267.5µs         67.9369ms       1.098ms         67.9369ms       ↓77 B ↑1000 B   0
s3.HeadObject                   3028 (29.4%)    13030.6 1.031ms         506.8µs         62.9893ms       0s              0s              ↓77 B           0
s3.PutObject                    1711 (16.6%)    7363.1  21.109ms        2.5496ms        181.8214ms      9µs             10.6771ms       ↓1.3 KiB ↑0 B   0
s3.DeleteObject                 1008 (9.8%)     4337.8  56.204ms        1.5859ms        411.1034ms      1.185ms         175.1619ms      ↓77 B ↑4 B      0
s3.DeleteMultipleObjects        1 (0.0%)        4.3     316.358ms       316.3584ms      316.3584ms      315.306ms       315.3055ms      ↓23 KiB ↑24 KiB 0

```

Backwards compatible, but will start displaying non-zero after: https://github.com/minio/minio/pull/19851 and  https://github.com/minio/minio/pull/19864
2024-06-05 00:50:20 -07:00
voldikss 3cfa8642fd fix: rm command with --newer-than not working (#4944) 2024-06-01 08:03:35 -07:00
Klaus Post 5040e61400 Fix support top net JSON (#4948)
JSON output was completely mangled.
Add switch to limit the number of responses.
2024-05-31 07:59:52 -07:00
jiuker 3774027cea fix: avoid HeadObject call for mc get (#4947) 2024-05-31 07:53:51 -07:00
Harshavardhana ac55cd1023 remote flaky bucket_replication test for now 2024-05-30 10:00:02 -07:00
Harshavardhana a8fdcbe7cb restructure credential creation with simplified expectations (#4939)
avoid weird coding style, simplify by using relatively
less number of variables and move things around to make
code more readable.

Improve HELP output readability.
2024-05-24 02:08:49 -07:00
Aditya Manthramurthy d4b7b00d73 Bump up minio/pkg to v3 (#4940) 2024-05-23 00:59:47 -07:00
Harshavardhana b46cf3c417 simplify histograms, make it based on the server return (#4935) 2024-05-13 09:31:11 -07:00
Harshavardhana 900235c14b keep pool display order and also pretty it (#4931)
```
mc admin info play/
●  play.min.io
   Uptime: 4 minutes
   Version: 2024-05-10T08:24:14Z
   Network: 1/1 OK
   Drives: 4/4 OK
   Pool: 1

┌──────┬───────────────────────┬─────────────────────┬──────────────┐
│ Pool │ Raw Usage             │ Erasure stripe size │ Erasure sets │
│ 1st  │ 8.5% (total: 120 GiB) │ 4                   │ 1            │
└──────┴───────────────────────┴─────────────────────┴──────────────┘

8.4 GiB Used, 479 Buckets, 3,585 Objects, 210 Versions, 27 Delete Markers
4 drives online, 0 drives offline, EC:1
```
2024-05-10 11:56:40 -07:00
jiuker 1b890948e8 fix: mirror --summary should work like -q (#4923) 2024-05-10 11:47:20 -07:00
Harshavardhana fdb36acbb1 fix: test regression since #4920 (#4928)
use mc_cmd always inside `functional-tests.sh`

Bonus: run shell formatting
2024-05-09 10:04:24 -07:00
jiuker 0d8c4f8aa8 fix: mc find --metadata work without prefix (#4926) 2024-05-09 07:13:21 -07:00
Sveinn a96123be2e showing disable-pager flag as an option (#4929) 2024-05-09 07:13:07 -07:00
jiuker 5378c957f5 fix: mc rb --force return ok with bucketNotExists (#4927) 2024-05-09 03:32:30 -07:00
Kanagaraj M 45ae31533d fix replication bandwidth unit conversion (#4922) 2024-05-09 03:04:18 -07:00
Shubhendu 62b110408f Correct spelling in message (#4924)
Signed-off-by: Shubhendu Ram Tripathi <shubhendu@minio.io>
2024-05-09 01:41:56 -07:00
Shubhendu 2fb9e21122 Added test for bucket replication (#4920)
Make sure proxying of DEL markers doesnt happen to remote site
while stat calls.

Signed-off-by: Shubhendu Ram Tripathi <shubhendu@minio.io>
2024-05-09 01:40:35 -07:00
Shubhendu 646712d5e5 Fix panic in mc admin health command (#4921)
The globalFlags were getting added twice and so causing duplicate
error andso a panic.

Signed-off-by: Shubhendu Ram Tripathi <shubhendu@minio.io>
2024-05-07 08:20:21 -07:00
Klaus Post b471de8d18 Add standard EC setting to admin info (#4918)
Discretely adds the standard EC setting to regular `mc admin info`.

```
λ mc admin info play
●  play.min.io
   Uptime: 1 hour
   Version: 2024-04-15T10:03:01Z
   Network: 1/1 OK
   Drives: 4/4 OK
   Pool: 1

Pools:
   1st, Erasure sets: 1, Drives per erasure set: 4

945 MiB Used, 409 Buckets, 5,498 Objects, 52 Versions, 4 Delete Markers
4 drives online, 0 drives offline, EC:2
```

Will save many deep dives into JSON.
2024-05-03 04:21:07 -07:00
Harshavardhana b317d0d63d fix: honor S3v2 if configured (#4917)
fixes #4915

A regression was introduced in #4755, we hardly test
with v2 anymore so this has never been covered.
2024-05-03 04:17:42 -07:00
Harshavardhana dcb911bed9 make s3Config Transport a roundTripper (#4914) 2024-04-30 10:44:48 -07:00
Sveinn 9fad66d824 updating prefix validation and adding some tests (#4907) 2024-04-30 10:29:33 -07:00
jiuker 5b7b222371 fix: divde by zero for decom status (#4908) 2024-04-29 02:56:05 -07:00
Sveinn 4a3f5899c6 enabling MC_DISABLE_PAGER and --dp (#4909) 2024-04-29 02:55:40 -07:00
Ziyi Fan 770097b64f Fix the percent of pool used (#4910)
Fix a the percent of pool used in rebalance status
2024-04-29 02:55:22 -07:00
Harshavardhana afd408284e scanner token buffer can overflow use bufio.NewReader() (#4912)
To avoid the following error on binary objects

```
bufio.Scanner: token too long.
```
2024-04-29 02:48:39 -07:00
Harshavardhana 5dfaa31d67 move to crypto/sha256 instead of sha256-simd (#4911) 2024-04-25 15:35:12 -07:00
Harshavardhana 2ed4cd91a7 fix: docker hotfix binaries 2024-04-19 09:41:02 -07:00
Harshavardhana e59e453a14 fix: docker hotfix container builds 2024-04-19 09:33:18 -07:00
Shubhendu bc47cebd91 Show ILM Expiry Replication status only if enabled (#4900)
In case Replication of ILM Expiry rules is disabled, mention the same
in `mc admin replicate status ALIAS` output.

Signed-off-by: Shubhendu Ram Tripathi <shubhendu@minio.io>
2024-04-19 01:52:20 -07:00
Anis Eleuch 3ec030eb26 cosmetic: Hide mc admin bucket and its subcommands visible (#4905)
Current mc admin bucket is visible under 'mc admin' however, mc admin
bucket will not show sub-commands, which is confusing.

Hide mc admin bucket and make mc admin bucket subcommands visible for
now, until removed later.
2024-04-18 09:45:29 -07:00
Harshavardhana 58a9cb37ec upgrade deps to latest releases (#4904) 2024-04-18 07:46:46 -07:00
Sveinn fe58afcd39 Large MC Update (new encryption flags, functional test suite, removal of session code, minor cleanup, vuln. updates ) (#4882) 2024-04-15 08:10:25 -07:00
Taran Pelkey e701bce12c Move mc idp ldap accesskey create --login to mc idp ldap accesskey create-with-login (#4894) 2024-04-12 00:00:53 -07:00
Aditya Manthramurthy 76c3674200 fix: build on linux/mips64 (#4899)
Also, add cross-compilation to CI. This includes all the archs we intend
to publish production binaries for.

`linux/mips64` was broken previously, and this is fixed by updating
github.com/shirou/gopsutil/v3 to the latest version.
2024-04-11 17:36:42 -07:00
Aditya Manthramurthy 6bac84d281 Update version for govulncheck (#4898) 2024-04-11 16:47:52 -07:00
Krishnan Parthasarathi 0b13328b3a Move ilm-tier-info to use lipgloss/table (#4892) 2024-04-02 15:58:53 -07:00
Krishnan Parthasarathi 0e3d1d50bf Use lipgloss's table package for ilm-tier-ls (#4890) 2024-04-02 02:14:13 -07:00
dorman 9f8147bf0e doc update (#4867) 2024-03-30 08:29:52 -07:00
David Legrand f740a6d40b Functional tests: add a parameter for the full site cleaning test (#4877)
fixes #4876 

The latest `mc rb` test cleans all the site data, and on the demo site, 
there are sometimes WORM files put in by some users, which leads to 
a failure. This test should only be run on sites where the user knows he can
clean everything without errors.
2024-03-30 08:29:28 -07:00
Shireesh Anjal 206d017878 Expose health diagnostics related functions (#4885)
So that dependent projects (e.g. console) can make use of them instead
of duplicating the logic.
2024-03-30 08:28:09 -07:00
Klaus Post 89d742a76d Update madmin to existing master (#4888)
Proposed branch no longer exists.
2024-03-28 08:12:19 -07:00
Praveen raj Mani 7bac47fe04 fix resync to find peers by deployment ID instead of site names (#4884)
The site names may vary if configured on UI. The Deployment ID
is immutable and can be used instead in replicate resync commands.
2024-03-25 09:41:14 -07:00
Shireesh Anjal 9043bbf545 Expose getClusterRegInfo (#4881)
so that it can be used by other projects (e.g. console) instead of
duplicating the logic.
2024-03-20 14:07:29 -07:00
David Legrand 795ed1eb49 Fix functional-tests.sh file generation under macOS (#4875)
Fixes #4874 

`head -c 0` leads to an `head: illegal byte count -- 0` error under macOS. We should also provide the input with `-i` parameter (it's ok under GNU/Linux too)
2024-03-16 03:01:31 -07:00
dependabot[bot] 2508db9c56 Bump google.golang.org/protobuf from 1.31.0 to 1.33.0 (#4872)
Bumps google.golang.org/protobuf from 1.31.0 to 1.33.0.

---
updated-dependencies:
- dependency-name: google.golang.org/protobuf
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-03-13 16:51:57 -07:00
Harshavardhana 53f59667f6 support node being part of multiple pools pick the actual number (#4870) 2024-03-13 12:22:53 -07:00
Harshavardhana 1ec55a5178 avoid stat and listing with --purge (#4869) 2024-03-08 22:43:06 -08:00
dependabot[bot] 6302f888a5 Bump github.com/lestrrat-go/jwx from 1.2.28 to 1.2.29 (#4868)
Bumps [github.com/lestrrat-go/jwx](https://github.com/lestrrat-go/jwx) from 1.2.28 to 1.2.29.
- [Release notes](https://github.com/lestrrat-go/jwx/releases)
- [Changelog](https://github.com/lestrrat-go/jwx/blob/v1.2.29/Changes)
- [Commits](https://github.com/lestrrat-go/jwx/compare/v1.2.28...v1.2.29)

---
updated-dependencies:
- dependency-name: github.com/lestrrat-go/jwx
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-03-08 14:29:25 -08:00
Harshavardhana 33a43e9c6e update go to v1.21.8 for vulncheck 2024-03-06 16:31:49 -08:00
Shireesh Anjal daf5b18e18 Add command for uploading file to SUBNET issue (#4854)
mc support upload --issue <issueNum> --comment <msg> <alias> </path/to/file>

Will upload the given file to the given SUBNET issue
2024-03-06 16:29:26 -08:00
Harshavardhana 98af07b69c bring back the original progress bar (#4866)
also cleanup 'mc put/get' behavior
2024-03-02 16:13:08 -08:00
Shireesh Anjal 66daa906eb mc support commands: allow --json in online mode (#4859)
There was a validation that said `--json` is supported only when
`--airgap` is also passed for SUBNET related `mc support` commands.

Remove this validation to allow `--json` to be passed even in online
mode. In this scenario, print a status JSON after upload to SUBNET.
2024-03-02 11:55:14 -08:00
dorman c2bf38f647 mirror: add bucket exclusions (#4861) 2024-03-02 11:54:51 -08:00
dorman 94cf5edf7a replicate: support alias (#4864) 2024-03-02 01:24:46 -08:00
jiuker f17313e7ab fix: emtpy progrese_bar and add change the color style white into green after upload success. (#4857) 2024-02-23 17:33:20 -08:00
Shireesh Anjal 744dc910d8 Do not validate deployment id from license if nil uuid (#4856)
In some very rare cases the license can contain a nil uuid
(00000000-0000-0000-0000-000000000000). Do not validate it against the
cluster's deployment id during registration.
2024-02-23 16:44:28 -08:00
jiuker 403bf6bc3a fix: add showLastProgressBar (#4855) 2024-02-22 04:23:55 -08:00
Sveinn e6288fa5f3 add help menu to put command when no parameters are present (#4852) 2024-02-21 18:35:53 -08:00
jiuker 5ff2208a2d add mc get (#4847) 2024-02-21 18:34:48 -08:00
jiuker e7ef65e655 fix: add error message to mc put (#4849) 2024-02-21 10:10:34 -08:00
Shubhendu 8156961333 Enable --expire-all-object-versions (#4840) 2024-02-20 06:47:42 -08:00
jiuker 1e69c2aadd feat: add put action (#4839) 2024-02-19 22:36:31 -08:00
Poorna 7d5e4ed56d fix example in admin replicate update (#4846) 2024-02-16 03:05:48 -08:00
dorman 6bb045a5e6 mirror: copy events also can mirror (#4842) 2024-02-14 13:19:52 -08:00
Harshavardhana 1466ae7b50 fix missing space while printing profile success message (#4845) 2024-02-14 13:18:56 -08:00
Sveinn 669cb0a9a4 Removing terminal whitelist for pager mechanism (#4843) 2024-02-09 14:18:24 -08:00
jiuker 62b12a2770 fix: mirror with local path (#4825) 2024-01-31 00:59:40 -08:00
Fexiven e21762b5a7 Fix syntax in examples (#4834) 2024-01-31 00:58:34 -08:00
Poorna 1274167567 fix validation in replicate rm to allow stale target cleanup (#4838)
when --all --force is specified, send request to server even if
replication config is not found to allow stale target cleanup
2024-01-31 00:58:18 -08:00
Poorna 12f446e1de fix prometheus metrics response on success (#4835) 2024-01-29 11:40:12 -08:00
Harshavardhana ba9fc6a307 fix: remove prometheus metrics arbitrary body limit (#4832) 2024-01-28 08:23:14 -08:00
Harshavardhana 9a5ef7c56d feat: service restart/update provides now per node status (#4827) 2024-01-26 12:32:20 -08:00
dependabot[bot] 1d42ad0df6 Bump github.com/lestrrat-go/jwx from 1.2.27 to 1.2.28 (#4830)
Bumps [github.com/lestrrat-go/jwx](https://github.com/lestrrat-go/jwx) from 1.2.27 to 1.2.28.
- [Release notes](https://github.com/lestrrat-go/jwx/releases)
- [Changelog](https://github.com/lestrrat-go/jwx/blob/v1.2.28/Changes)
- [Commits](https://github.com/lestrrat-go/jwx/compare/v1.2.27...v1.2.28)

---
updated-dependencies:
- dependency-name: github.com/lestrrat-go/jwx
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-01-25 15:59:36 -08:00
jiuker ffade16689 feat: add skip-errors to mc mirror (#4831) 2024-01-25 15:10:12 -08:00
jiuker ffa7a67bcf fix: allow -q by turning of pipe progress bar (#4828) 2024-01-22 21:02:19 -08:00
Sveinn 1ff6818938 Adding screen-256color to pager enabled terms (#4829) 2024-01-22 21:01:39 -08:00
jiuker bb25267eaa feat: add action for mc undo recursive (#4822) 2024-01-17 23:03:39 -08:00
Klaus Post 1edb08e74f Add ability to replay JSON file in scanner info (#4824)
Add (for now hidden) `-in` switch that opens a file that was output from `-json` and replays it.

```
λ go build&&mc admin scanner info -in=scanner-status.json
Scanner Activity: ∙∙●

Overall Statistics
------------------
Est. full scan time:   148d18h50m; Estimated 0.20/month
Current cycle:         5618; Started: 2024-01-06 14:14:39.745238158 +0000 UTC
Active drives:         2

Last Minute Statistics
----------------------
Objects Scanned:       402 objects; Avg: 91.974ms; Rate: 578880/day
Versions Scanned:      402 versions; Avg: 66.892µs; Rate: 578880/day
Versions Heal Checked: 0 versions; Avg: 0ms
Read Metadata:         402 objects; Avg: 91.74ms, Size: 649 bytes/obj
ILM checks:            402 versions; Avg: 1.909µs
Check Replication:     402 versions; Avg: 63.641µs
Verify Deleted:        0 folders; Avg: 0ms
Yield:                 1m13.7s total; Avg: 183.311ms/obj
------------------------------------------- Errors --------------------------------------------------
peer is not reachable
peer is not reachable
------------------------------------- Currently Scanning Paths --------------------------------------
...
```
2024-01-17 09:02:52 -08:00
Sveinn 7484802005 Making cli pager optional + better visual indicators for scrolling (#4819) 2024-01-16 08:06:34 -08:00
Anis Eleuch 799ded568d mirror: --preserve should not activate --overwrite (#4821)
Users would expect the mirror will not override anything unless --overwrite
flag is specified. However, currently --preserve will activate
--overwrite, which is not needed. This commit will fix this behavior.
2024-01-13 00:44:48 -08:00
Sveinn 2552dbf55e Fixing PR template format (#4820) 2024-01-12 11:02:16 -08:00
Sveinn bf2d21809a Arranging command help menu alphabetically (#4817)
arranging commands alphabetically
2024-01-11 22:49:15 -08:00
Shubhendu d4305a5bf9 Added option --exclude-folders (#4566)
This flag works in conjunction with `--recursive` and sets tags for all
the bucket objects minus the subdirs.

Signed-off-by: Shubhendu Ram Tripathi <shubhendu@minio.io>
2024-01-10 21:49:32 -08:00
Daniel Valdivia 74e889f95b Workflow to add issues to tracking project (#4815)
Signed-off-by: Daniel Valdivia <hola@danielvaldivia.com>
2024-01-10 15:21:17 -08:00
Shubhendu 7f1da50991 allow aliases with single character strings (#4812)
Signed-off-by: Shubhendu Ram Tripathi <shubhendu@minio.io>
2024-01-08 11:17:23 -08:00
Krishnan Parthasarathi 59eca9fea8 ILM rule type filter flags should work with --json (#4814) 2024-01-04 21:04:32 -08:00
Shireesh Anjal bad0ad9dfb Add missing space between 'at' and filename (#4813)
When the report is generated in airgap mode, mc shows a message

MinIO diagnostics report saved at<filename>

Here a space is missing between 'at' and the filename. Add the same.
2024-01-03 08:51:10 -08:00
jiuker 0ffee47910 honor correct content-type for any files when passed via SQL query (#4809)
fixes #4518
2024-01-03 01:02:08 -08:00
jiuker 370b7483b1 feat: support summary for mc mirror (#4811) 2024-01-02 10:12:43 -08:00
Shubhendu 5386533bb9 Use correct target path during mirroring objects (#4807)
Currently if we don't use absolute paths in mirror command, absolute path of
source gets appended to the target path and so in destination object gets
mirrored to wrong prefix / path.

For example say source object path is `/tmp/source/prefix/a.txt` and mirror
command executed from `/tmp` dir as `mc mirror --json --watch source xyz`,
the object in target gets mirrored to location `xyz/tmp/source/prefix/a.txt`.
Also any new file created gets copied properly though.

```
mc mirror --json --watch source/ xyz/
{
 "status": "success",
 "source": "/tmp/source/prefix/a.txt",
 "target": "xyz/tmp/source/prefix/a.txt",
 "size": 0,
 "totalCount": 1,
 "totalSize": 0
}
{
 "status": "success",
 "source": "/tmp/source/b.txt",
 "target": "xyz/b.txt",
 "size": 0,
 "totalCount": 2,
 "totalSize": 0
}

```

With the fix now after running the command `mc mirror --json --watch source xyz`
the object would correctly get copied to location `/tmp/xyz/prefix/a.txt` as below

```
{
 "status": "success",
 "source": "/tmp/source/prefix/a.txt",
 "target": "xyz/prefix/a.txt",
 "size": 0,
 "totalCount": 2,
 "totalSize": 0
}
{
 "status": "success",
 "source": "/tmp/source/b.txt",
 "target": "xyz/b.txt",
 "size": 0,
 "totalCount": 1,
 "totalSize": 0
}
{
 "status": "success",
 "source": "/tmp/source/c.txt",
 "target": "xyz/c.txt",
 "size": 0,
 "totalCount": 3,
 "totalSize": 0
}
```

Signed-off-by: Shubhendu Ram Tripathi <shubhendu@minio.io>
2023-12-29 12:15:29 -08:00
jiuker f88eb55911 fix: tree traversal issue with empty folders (#4810)
fixes #4794
2023-12-29 09:16:55 -08:00
Harshavardhana 176f657e53 properly ignore permission denied error with mirror (#4803) 2023-12-26 10:07:28 -08:00
Taran Pelkey c27ddd4adf Add ldap accesskey create, update accesskey list with new endpoint (#4760) 2023-12-23 00:47:21 -08:00
Shireesh Anjal fb5dd2588c Accept --license flag in mc license register (#4795)
If passed,

- validate and save it immediately in the subnet config
- extract API key from it and use it for online registration with SUBNET
  (if `--airgap` is not passed)
- in case online registration with SUBNET fails for any reason, fallback
  to airgap mode (show URL to be visited on SUBNET)
2023-12-20 00:45:13 -08:00
Klaus Post 8e1573ec1b Set exitcode on copy/mirror source failure (#4798)
Also fixes errors potentially being swallowed by filtering.

Fixes #4773

```
λ go build&&mc cp s3/default/1.mp4 1.mp4
mc: <ERROR> Unable to prepare URL for copying. Unable to guess the type of copy operation.

λ echo %errorlevel%
1

λ _
```
2023-12-19 23:14:22 -08:00
Harshavardhana 60286667cc update dependencies to address new CVE (#4799) 2023-12-19 23:13:54 -08:00
Anis Eleuch 9ad4ee9d08 tier: Support AWS web identity token file for MinIO EKS pods (#4789)
Add --aws-role-arn and --aws-web-identity-file to allow MinIO EKS pods
to use web identity token auth style to tier data to a AWS S3 bucket.
2023-12-15 13:36:29 -08:00
asce c0462e64b2 use explicit operation handling for anonymous operations to prevent undesirable checks (#4791) 2023-12-15 13:36:12 -08:00
Anis Eleuch 34be0ed96a decom: status clearly shows that the it is about raw disk usage (#4792)
Some users are confused about the 'Capacity' wording and think this is
about the objects usage, not disk usage; Change the wording to make this
is more clear.
2023-12-14 19:00:20 -08:00
Shireesh Anjal 28f44cb9a0 Read new key license_v2 from SUBNET response (#4788)
SUBNET now has a v2 license that is returned in the new key
`license_v2`. mc will start reading and storing the same.
2023-12-13 20:46:56 -08:00
Anis Eleuch 8da737f8fd tier: Add support of service principal auth for Azure (#4787)
Add new flags to `mc ilm tier add` command to support Azure storage
authentication using a service principal account:
 
 --az-sp-tenant-id
 --az-sp-client-id
 --az-sp-client-secret
2023-12-13 16:37:41 -08:00
Anis Eleuch 1facc1eef5 support: --debug flag will print http requests for easier debugging (#4776) 2023-12-13 15:31:01 -08:00
Harshavardhana f78f391f8b fix: broken 'anonymous get-json' 2023-12-13 15:29:52 -08:00
Shireesh Anjal bb65ba8874 Use subnet package in pkg for license validation (#4784)
Most of the code related to license validation is now available in
`minio/pkg`. So remove it from mc and use the function(s) from `pkg`.
2023-12-11 09:06:09 -08:00
Shubhendu 1ba9435365 Fix a panic for bucket heal (#4781)
Signed-off-by: Shubhendu Ram Tripathi <shubhendu@minio.io>
2023-12-07 14:13:17 -08:00
Anis Eleuch 1e2c5cec0a ready: Do not quit when the target server is offline or any other error (#4783)
Ready makes sense to not quit in any case, until the target server is
fully initialized
2023-12-07 14:13:04 -08:00
Krishnan Parthasarathi d920e2b34b Add support to batch-expire jobs (#4677) 2023-12-02 03:24:10 -08:00
Harshavardhana f5f7147b9e do not auto-decompress objects with content-encoding (#4777)
fixes #4769
2023-12-01 18:03:28 -08:00
Krishnan Parthasarathi b7a7b05395 Update minio-go to incl ilm fix (#4779) 2023-11-30 10:39:50 -08:00
Harshavardhana 59e0e56b21 chore update minio/pkg and madmin-go (#4774) 2023-11-28 09:29:57 -08:00
r-sc 5e6ae2172e set-json to fail on custom policies without .json (#4745) 2023-11-27 03:26:13 -08:00
Harshavardhana 2178568417 make STS support for 'mc' alias specific (#4771)
currently STS specific behavior is global,
`mc` however supports multiple aliases - we
need to make sure that `mc` treats this ENV
specific to an alias.
2023-11-26 01:35:13 -08:00
Krishnan Parthasarathi 16709e4bbc ilm: Add support for size based filters (#4770) 2023-11-22 23:59:19 -08:00
Shubhendu 56d84e64b1 Option to enable disable ILM expiry for site replication (#4698)
Added options `replicate-ilm-expiry` and `disable-ilm-expiry-replication`
for `mc admin replicate add` and `mc admin replicate update` commands
respectively.

Signed-off-by: Shubhendu Ram Tripathi <shubhendu@minio.io>
2023-11-21 22:17:38 -08:00
Shireesh Anjal 937b34616f Do not fail if deployment id not found in license (#4767)
SUBNET is being enhanced to generate account-level licenses instead of
deployment-level. So newer licenses may not contain the deployment id.

So validate the deployment id against the cluster only if present in the
license.
2023-11-20 08:30:59 -08:00
Harshavardhana d8342b68a0 fix: docker container builds with proper container name 2023-11-16 19:34:18 -08:00
Harshavardhana fe05b5bb42 fix: avoid crash with --stats -a (#4765) 2023-11-16 16:43:30 -08:00
Harshavardhana 4724c024c6 support missing role-arn and role-session-name (#4763) 2023-11-15 14:45:58 -08:00
Pedro Juarez 6c9cdc27bc Refactor methods that initialize client to reuse code blocks (#4755) 2023-11-15 13:20:52 -08:00
jiuker c3ebf165ee fix: Incorrect batch status Throughput entry (#4758)
fixes https://github.com/minio/mc/issues/4756
2023-11-13 10:10:39 -08:00
Harshavardhana 5124a01ae7 add 'alias export' command (#4759) 2023-11-13 03:20:16 -08:00
Harshavardhana 8c8e625217 trace statistics add MaxTTFB column (#4757) 2023-11-13 02:26:37 -08:00
Pedro Juarez b1d4341fcb add STS support for mc admin command (#4754) 2023-11-11 23:08:33 -08:00
Krishnan Parthasarathi d3773744a6 Transition doesn't support NewerNoncurrentVersions (#4750)
hiding --noncurrent-transition-newer flag to avoid confusion to MinIO
users.
2023-11-11 12:58:33 -08:00
Daryl White 56803d2167 Updating example with correct flag (#4751) 2023-11-10 13:37:17 -08:00
Shubhendu 6829c3fabc Change go version to 1.21.4 to fix vulncheck failures (#4749)
Signed-off-by: Shubhendu Ram Tripathi <shubhendu@minio.io>
2023-11-09 14:43:59 -08:00
Harshavardhana 7db80b6ad9 fix: broken docker builds for microdnf command (#4746) 2023-11-08 13:00:21 -08:00
Shireesh Anjal a5adf14769 Add anonymize flag to support-diag (#4742) 2023-11-08 01:36:09 -08:00
Daniel Valdivia 011c61b254 Add support for STS credentials (#4744) 2023-11-05 20:19:23 -08:00
Shireesh Anjal b7dc9cc724 Show net info spinner in health diagnostics (#4741) 2023-11-02 09:52:34 -07:00
Harshavardhana 9f2fb2b6a9 upgrade madmin-go/v3 (#4738) 2023-10-30 11:43:32 -07:00
Sveinn b82f6c60b2 Removing un-used variables and fixing an error condition (#4737) 2023-10-30 08:43:44 -07:00
Harshavardhana 01df0ff497 upgrade madmin-go/v3 (#4735) 2023-10-28 14:24:39 -07:00
Taran Pelkey c1f61a1e06 Add idp ldap accesskey (#4686) 2023-10-26 14:23:45 -07:00
dependabot[bot] dae819544b Bump google.golang.org/grpc from 1.58.0 to 1.58.3 (#4731)
Bumps [google.golang.org/grpc](https://github.com/grpc/grpc-go) from 1.58.0 to 1.58.3.
- [Release notes](https://github.com/grpc/grpc-go/releases)
- [Commits](https://github.com/grpc/grpc-go/compare/v1.58.0...v1.58.3)

---
updated-dependencies:
- dependency-name: google.golang.org/grpc
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-10-26 10:53:29 -07:00
Harshavardhana 1bcbe9019d add top locks owner as well (#4733)
```
Since                 Type    Owner                 Resource
13 hours ago          WRITE   10.68.100.18:9000     .minio.sys/leader.lock
13 hours ago          WRITE   10.68.100.18:9000     .minio.sys/callhome/runCallhome.lock
13 hours ago          WRITE   10.68.100.23:9000     .minio.sys/new-drive-healing/0/0
...
...
```
2023-10-26 07:52:18 -07:00
Andreas Auernhammer b798764785 update container base image to ubi9 (#4730)
This commit updates the container base image
to ubi9/ubi-9.2. It is ~4 MB smaller than ubi-8.

Signed-off-by: Andreas Auernhammer <github@aead.dev>
2023-10-25 08:31:38 -07:00
r-sc 75e722216a fix: print updates/merge multiple policy for a user (#4691) 2023-10-24 14:42:22 -07:00
Shireesh Anjal 39a57a14b8 revamp spinner in mc support diag (#4727)
The current spinner mechanism looks for the data categories (CPU,
drives, memory, etc) sequentially. If any of the category's data is not
received, it gets stuck there.

If a new data category is introduced without changing the version of the
HealthInfo struct, then `mc support diag` can get stuck for the new
category when talking to an older version of minio.

So instead of looking for the categories one by one, start a spinner for
each category at the beginning, and mark it as done as soon as the
corresponding data is received. When the last category (admin info) is
received, mark any pending category as done so that the command
continues with the rest of the processing.
2023-10-24 00:17:17 -07:00
Harshavardhana 2678c2c8e5 use Dockerfile ADD feature deprecate curl (#4728) 2023-10-23 23:32:21 -07:00
Harshavardhana 97cc12fdc5 Add average TTFB for statistics (#4726) 2023-10-23 22:18:28 -07:00
Andreas Auernhammer 0440badc41 use ubi-micro instead of ubi-minimal (#4725)
This commit replaces the UBI minimal with the
small and less bloated UBI micro image.

This reduces noise from security scanners flagging
components not used by mc and reduces the overall
size of the container.

Signed-off-by: Andreas Auernhammer <github@aead.dev>
2023-10-23 21:51:09 -07:00
Poorna 2c6ae7d1f7 Add --bucket-bandwidth flag to mc admin replicate update (#4687)
to allow default bucket bandwidth to be set in site replication
2023-10-23 15:46:02 -07:00
Sveinn eb6f304e2e Created a retry mechanism and added a --retry flag to mc mirror (#4715) 2023-10-20 02:03:26 -07:00
Klaus Post d2a2bdb07b Fix missing colours on windows (#4721) 2023-10-19 11:31:34 -07:00
Harshavardhana 903a1f202c add support for min/max time in 'trace --stats' (#4723)
also change the UI to match a k8s'isk style
output.

```
mc admin trace play/ --stats
Duration: 12s ●∙∙
Call                    Count           RPM     Avg Time        Min Time        Max Time        Errors  RX Avg  TX Avg
s3.GetBucketLocation    22 (48.9%)      107.8   431µs           205.196µs       1.360389ms      0       135 B   137 B
s3.ListObjectsV2        22 (48.9%)      107.8   1.615ms         520.96µs        6.821432ms      0       135 B   2.3 KiB
s3.ListBuckets          1 (2.2%)        4.9     2.302ms         2.301694ms      2.301694ms      0       135 B   29 KiB
```
2023-10-18 11:09:29 -07:00
Harshavardhana 062f28c9cc allow 'mc' flags to have ENV equivalent (#4720)
it simplifies the codebase a bit and also
allows for `mc` to easily be configured in
containerized environments.
2023-10-16 22:51:25 -07:00
Sveinn 377b71641b Preventing duplicate transfers during cp and mv when prefixes overlap (#4719) 2023-10-16 09:56:30 -07:00
Shubham Vernekar fb8a20a780 chore: update docs to indicate where is present (#4718) 2023-10-16 08:44:12 -07:00
Anis Eleuch d158b9a478 prom: Allow insecure TLS connections if --insecure is provided (#4716) 2023-10-13 18:57:03 -07:00
dependabot[bot]andHarshavardhana 54d12e95bd Bump golang.org/x/net from 0.15.0 to 0.17.0 (#4713)
Bumps [golang.org/x/net](https://github.com/golang/net) from 0.15.0 to 0.17.0.
- [Commits](https://github.com/golang/net/compare/v0.15.0...v0.17.0)

---
updated-dependencies:
- dependency-name: golang.org/x/net
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Harshavardhana <harsha@minio.io>
2023-10-12 12:06:14 -07:00
Sveinn 87d6cd2d4f Validation optimization - reduce HEAD calls during cp and mv operations (#4710) 2023-10-12 11:30:11 -07:00
Shubhendu 32311bb933 Use the new golang version 1.21.3 (#4714)
Signed-off-by: Shubhendu Ram Tripathi <shubhendu@minio.io>
2023-10-12 06:14:15 -07:00
Klaus Post 0793ce767b Add --stats to traces (#4669)
Allows collecting live stats of all traced subsystems.

Examples:

```
λ mc admin trace --stats play
+----------------------------+-------------+------+-----------+--------+---------+---------+
| Call                       | Count       | RPM  | Avg Time  | Errors | RX Avg  | TX Avg  |
| s3.GetObject               | 247 (63.3%) | 82.5 | 2.391ms   | 0      | 133 B   | 179 KiB |
| s3.HeadBucket              | 102 (26.2%) | 34.1 | 1.114ms   | 0      | 147 B   | 0 B     |
| s3.GetBucketLocation       | 18 (4.6%)   | 6.0  | 1.942ms   | 0      | 147 B   | 149 B   |
| s3.PutBucket               | 6 (1.5%)    | 2.0  | 4.146ms   | 0      | 151 B   | 0 B     |
| s3.ListObjectsV1           | 4 (1.0%)    | 1.3  | 4.276ms   | 0      | 124 B   | 577 B   |
| s3.ListBuckets             | 3 (0.8%)    | 1.0  | 15.312ms  | 0      | 135 B   | 82 KiB  |
| s3.PutObject               | 3 (0.8%)    | 1.0  | 4.304ms   | 0      | 14 KiB  | 0 B     |
| s3.DeleteObject            | 2 (0.5%)    | 0.7  | 407µs     | 0      | 88 B    | 0 B     |
| s3.HeadObject              | 2 (0.5%)    | 0.7  | 1.36ms    | 0      | 108 B   | 0 B     |
| s3.CompleteMultipartUpload | 1 (0.3%)    | 0.3  | 7.943ms   | 0      | 301 B   | 449 B   |
| s3.NewMultipartUpload      | 1 (0.3%)    | 0.3  | 4.895ms   | 0      | 160 B   | 383 B   |
| s3.PutObjectPart           | 1 (0.3%)    | 0.3  | 103.782ms | 0      | 8.8 MiB | 0 B     |
+----------------------------+-------------+------+-----------+--------+---------+---------+

λ mc admin trace --stats -call=storage play
+------------------------------+---------------+----------+----------+--------+--------+--------+
| Call                         | Count         | RPM      | Avg Time | Errors | RX Avg | TX Avg |
| storage.ReadXL               | 70780 (33.3%) | 174700.3 | 43µs     | 200    | -      | -      |
| storage.RenameData           | 70633 (33.2%) | 174337.5 | 1.165ms  | 0      | -      | -      |
| storage.DiskInfo             | 70540 (33.1%) | 174107.9 | 1µs      | 0      | -      | -      |
| storage.ReadVersion          | 280 (0.1%)    | 691.1    | 70µs     | 0      | -      | -      |
| storage.StatVol              | 236 (0.1%)    | 582.5    | 13µs     | 0      | -      | -      |
| storage.DeleteAbandonedParts | 140 (0.1%)    | 345.6    | 149µs    | 0      | -      | -      |
| storage.CreateFile           | 88 (0.0%)     | 217.2    | 4.169ms  | 0      | -      | -      |
| storage.ListVols             | 88 (0.0%)     | 217.2    | 426µs    | 0      | -      | -      |
| storage.ReadFileStream       | 18 (0.0%)     | 44.4     | 28µs     | 0      | -      | -      |
| storage.VerifyFile           | 16 (0.0%)     | 39.5     | 2.166ms  | 0      | -      | -      |
+------------------------------+---------------+----------+----------+--------+--------+--------+
```
2023-10-10 10:12:06 -07:00
Shireesh Anjal eca8310ac8 Add support for resource metrics (#4689) 2023-10-03 23:52:56 -07:00
Anis Eleuch 4be483de6d scanner: Limit the active disks if no enough term space (#4705)
If the terminal height is not enough to show the number of active disks,
which is likely the case in a large deployment, print only a few entries
until the number of lines reaches the terminal height.
2023-10-03 08:31:31 -07:00
Anis Eleuch 67fa4aa7a3 Fix mirror stats with --quiet flag (#4703) 2023-10-02 08:03:54 -06:00
Harshavardhana d8ace59107 add 'mc admin trace' filtering based on request queries (#4704) 2023-10-02 00:40:19 -07:00
Armin Weißer d47a2ba53a Add min, max and total request time to top api command (#4702)
Add min and max request time to top api command
2023-09-29 09:41:22 -07:00
Shireesh Anjal 86d5b64ffa Use latest madmin-go (v3.0.21) (#4701)
This ensures that drive model is included in the partition data inside
the health diagnostics report.
2023-09-29 01:07:54 -07:00
Anis Eleuch 1a65176cee perf net: Do not show Err: tag if there is no error (#4700) 2023-09-28 15:59:55 -07:00
Harshavardhana 103272612a change 6->3 decimal resolution, to conserve terminal realestate 2023-09-28 10:48:30 -07:00
Armin Weißer c3c899c365 Add ART and ATP to 'support top api' command (#4699)
Average Request Time (ART) = Total Duration / Calls
Average Throughput (ATP) = (RX+TX) / Total Duration
2023-09-28 08:33:49 -07:00
Taran Pelkey 618512cc92 broaden reach of --no-color flag (#4697) 2023-09-25 23:10:43 -07:00
Klaus Post 21ee2bd432 Show heal checks performed on missing (#4692)
Add stats for objects missing on current disk, but healed.

Visualizes stats for https://github.com/minio/minio/pull/18076
2023-09-25 10:32:06 -07:00
Harshavardhana ae05d45173 upgrade minio/pkg v2.0.2 (#4694) 2023-09-21 22:07:46 -07:00
Anis Eleuch 38b8665e9e perf net: Show the error with the bandwidth results (#4688)
An error in the result does not mean that the whole perf net test
failed, we can still show some results, with an error as well, to be
less confusing to the user.
2023-09-20 08:22:31 -07:00
Harshavardhana 79df949087 add exclude-storageclass flag for mirror (#4684)
this option exists to skip tiered objects such as

- "GLACIER"
- "DEEP_ARCHIVE"

users can use this option when migrating awss3 -> minio

```
mc mirror --exclude-storageclass GLACIER \
   --exclude-storageclass DEEP_ARCHIVE s3/bucket minio/bucket
```
2023-09-19 22:47:55 -07:00
r-sc f551d4b14d Support multiple policies in 'mc admin user policy' command (#4685) 2023-09-19 09:27:38 -07:00
Harshavardhana 3adb6c93fd hide all old deprecate heal options (#4682) 2023-09-18 23:02:58 -07:00
Klaus Post f36429be69 Add download links (#4681)
Update README.md

Add more archs.
2023-09-18 10:00:11 -07:00
Harshavardhana e561bc770e update all dependencies (#4679) 2023-09-13 16:08:58 -07:00
Harshavardhana 9dcef8825f fix: alignment issues in help for svacct sub-commands (#4676) 2023-09-07 15:48:55 -07:00
Harshavardhana e088bd45a9 fix: alignment in 'replicate status' help (#4675) 2023-09-07 01:01:36 -07:00
Aditya Manthramurthy e2056fb057 Update to minio/pkg v2 (#4674) 2023-09-02 14:28:03 -07:00
Poorna 5a5a9973c3 Change replicate status metrics to show additional info (#4582)
in `mc replicate status` for bucket replication
and `mc admin replicate status` for site replication.
2023-08-30 01:02:26 -07:00
Harshavardhana 9da0b405db support all scanner events to be reported for excessive versions (#4672) 2023-08-29 15:55:06 -07:00
Shubhendu 38d4108458 Added mc admin kms key list ALIAS command (#4663)
Signed-off-by: Shubhendu Ram Tripathi <shubhendu@minio.io>
2023-08-29 15:36:30 -07:00
Harshavardhana d973c0a9bb update contribution license PR template 2023-08-29 09:39:46 -07:00
Poorna acc25b8c50 fix: bandwidth displayed in mc replicate status (#4664) 2023-08-18 14:57:55 -07:00
Harshavardhana df68f5cf89 add new PR template license terms and go1.21.x build (#4662) 2023-08-15 16:03:09 -07:00
Harshavardhana f198b23e1a fix: batch status responsiveness (#4661) 2023-08-15 14:15:45 -07:00
Anis Eleuch 469f770fe6 kms-status: Show unknown for decryption when encryption fails (#4659)
mc admin kms key status shows success for decryption when encryption is
failed, though the server does not test the decryption processs when the
encryption is failed. In such cases, this commit will show decryption with a
question mark instead of OK mark
2023-08-14 13:04:49 -07:00
Anis Eleuch 9d99cfbb7e mv: Do not error out when a bucket has an object lock config (#4654)
It appears that this code is coming from the old days when locking was
implemented before versioning; It does not make sense now to make mv
errors out when a bucket has a locking configuration.
2023-08-14 13:04:26 -07:00
Shireesh Anjal e112429e81 fix license register error in airgap mode (#4653) 2023-08-10 10:12:21 -07:00
jiuker 44ca181a93 feat: support perf client to show TX from client to server (#4645) 2023-08-10 07:16:40 -07:00
Shubhendu 01fb7c5a96 fix: provide an option for Prometheus config for node and bucket endpoints (#4652)
Earlier the command `mc admin prometheus generate ALIAS` used to
display only the scrape configuration for cluster metrics endpoint.
This change enables optionally to display scrape configuration for
node / bucket metrics endpoints.

Signed-off-by: Shubhendu Ram Tripathi <shubhendu@minio.io>
2023-08-08 10:23:59 -07:00
Harshavardhana b8d6623a3d update go1.20.7 for vulncheck 2023-08-08 09:44:00 -07:00
Harshavardhana 0a529d5e64 update deps to latest packages and update CREDITS (#4649) 2023-08-01 16:30:57 -07:00
Harshavardhana 3cf3095253 add TTFB as part of 'mc admin trace' in pretty form (#4648) 2023-07-31 20:31:06 -07:00
Shireesh Anjal 6b8680a2f7 Do not allow registration of play cluster (#4647)
Since play is a public demo cluster, it should not be allowed to
register with subnet.
2023-07-25 20:51:50 -07:00
Shubhendu 1c17ff4c99 Enabled option to show node and bucket metrics (#4632)
Earlier the command `mc admin prometheus metrics ALIAS` used to
display only the cluster-level metrics. This change enables
optionally to list node/bucket-specific metrics.

Signed-off-by: Shubhendu Ram Tripathi <shubhendu@minio.io>
2023-07-21 13:44:27 -07:00
Krishnan Parthasarathi 057470183f admin-info: Include delete markers count (#4642) 2023-07-19 15:54:09 -07:00
Poorna c04a480dd3 fix replicate update to check for older role ARN (#4640) 2023-07-19 13:11:09 -07:00
Harshavardhana c5ea09b74d properly report bandwidth if not configured (#4641)
report bandwidth if not configured
2023-07-19 12:42:18 -07:00
jiuker 493cd196b7 fix: remove count flag and show the byteRate for support top net (#4639) 2023-07-19 08:34:35 -07:00
jiuker dd6e9c7fcd fix: Enable byHost filtering by supplying server host list (#4637) 2023-07-19 00:45:16 -07:00
Harshavardhana 216aae32b9 fix: with --purge flag ignore path validation errors (#4636) 2023-07-18 14:05:38 -07:00
jiuker 48dd25742a Support mc top net (#4626) 2023-07-18 13:11:00 -07:00
Sergey c78ff23e77 Fixing misleading usage help for mc anonymous set-json (#4621) 2023-07-18 01:07:38 -07:00
Harshavardhana 1fbd97aa04 run gofumpt -extra on all source files (#4634) 2023-07-17 13:10:20 -07:00
Shireesh Anjal e8f049cbb1 Ensure --airgap is available on all support commands (#4633)
- remove deprecated and unused flags from `support diag`
- add missing registration check-in
  - call home status
  - proxy set|show|remove
2023-07-17 09:02:50 -07:00
Shubhendu 15ea1125e3 Added endpoint and version attributes to KMS details (#4591)
Added endpoint and version attributes to KMS details

Now it would list details of all KMS instances with additional attributes
endpoint and version. In case of k8s based deployment the list would consist
a single entry.

Signed-off-by: Shubhendu Ram Tripathi <shubhendu@minio.io>
2023-07-13 09:10:43 -07:00
Poorna 09a06e2a75 Rename mc replicate diff as mc replicate backlog (#4568)
Rename `mc replicate diff` as `mc replicate backlog`

By default `mc replicate backlog` shows the most recent failures with additional
--nodes flag to filter output by node and --arn flag to filter by remote target.
This is a fast operation and provides a quick snapshot of backlog currently in failed
status.

`mc replicate backlog --full` does a full listing and reports all object versions in
 pending or failed replication status.
2023-07-13 09:06:12 -07:00
Harshavardhana 355150151f allow purge to happen on quorum lost objects (#4629) 2023-07-13 00:11:43 -07:00
Harshavardhana c1193fc29d add update UBI image to 8.8 (#4625) 2023-07-11 16:30:44 -07:00
Aditya Manthramurthy 1b992864ee Enhance user info output with authentication info (#4613) 2023-07-06 22:25:51 -07:00
Poorna a2c253c43b admin replicate update: rename --sync flag to --mode (#4623) 2023-07-06 22:25:27 -07:00
jiuker 72958227ad fix: miss count for 'mc support top drive' (#4624) 2023-07-06 08:46:12 -07:00
jiuker 00b68bfa16 support site perf replication (#4608) 2023-07-06 01:07:41 -07:00
Shireesh Anjal eebdcdf365 Upgrade madmin-go/v3 to 3.0.4 (#4618)
Capture realtime metrics in health report
2023-06-28 14:54:17 -07:00
Kaan Kabalak c96b42c8f2 Fix issues related to 'mc admin svcacct list --json' cmd (#4619)
- Fix table header being printed when the '--json' flag is present for
the 'mc admin svcacct list' command
- Fix sentinel date being marshaled when the '--json' flag is present
for the 'mc admin svcacct list' command
2023-06-27 22:52:26 -07:00
Harshavardhana 0ed2956757 improve user messaging in 'support perf' and 'mc rm --dry-run' (#4617)
- terminal messaging for 'mc rm --dry-run' was completely
  wrong, it was using `fmt.Println` which shouldn't be done.

- mc support perf - printing was using a mix of color.New()
  and console.Infoln() (use one)

- mc support profile - printing was using a mix of color.New()
  and console.Info() (use one)

- mc support inspect - printing was using a mix of color.New()
  and consoleInfo() (use one)
2023-06-26 09:20:51 -07:00
r-sc f8f565c2b6 fix: allow cluster bucket export to export single bucket (#4614) 2023-06-24 01:38:52 -07:00
r-sc dea3058aa1 Improve consistency in mc cmds (#4609) 2023-06-23 11:12:07 -07:00
Aditya Manthramurthy 4b06db8e17 Update minio dependencies (#4610) 2023-06-20 14:00:40 -07:00
Aditya Manthramurthy 5f39522e69 Add response details for policy attach/detach cmd (#4602)
For internal IDP.

Also updates madmin-go to v3 as part of this change

- Temporarily disable test_admin_users until minio side fix is merged
2023-06-19 12:31:19 -07:00
Poorna bf3924b583 resync status: show current status (#4604)
Also exit tea.Program when resync is canceled.
2023-06-15 08:08:26 -07:00
dependabot[bot] 84f5724459 Bump github.com/lestrrat-go/jwx from 1.2.25 to 1.2.26 (#4601)
Bumps [github.com/lestrrat-go/jwx](https://github.com/lestrrat-go/jwx) from 1.2.25 to 1.2.26.
- [Release notes](https://github.com/lestrrat-go/jwx/releases)
- [Changelog](https://github.com/lestrrat-go/jwx/blob/v1.2.26/Changes)
- [Commits](https://github.com/lestrrat-go/jwx/compare/v1.2.25...v1.2.26)

---
updated-dependencies:
- dependency-name: github.com/lestrrat-go/jwx
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-06-14 12:40:22 -07:00
r-sc 2c67a3aaa7 Improve output readability for mc stat command (#4597) 2023-06-14 07:44:46 -07:00
Aditya Manthramurthy 916e05bc24 Fix unconfigured IDP output in idp info command (#4600) 2023-06-13 13:49:33 -07:00
Shubhendu 41926421f9 Set theme color for mc admin user svcacct set output (#4599)
Align with output theme for other commands like `enable`,
`disable` etc.

Signed-off-by: Shubhendu Ram Tripathi <shubhendu@minio.io>
2023-06-13 11:19:50 -07:00
Harshavardhana f148db7ae0 remove unnecessary newline and contextualize the success (#4598) 2023-06-13 08:44:46 -07:00
Klaus Post 2ecd33086f fix: copy progress crash (#4596)
Fix naked type assertion crash on `mc cp` with no output.

Fixes #4595
2023-06-12 13:48:33 -07:00
Harshavardhana 5e4ab1ec48 add ftp trace support (#4590) 2023-06-06 06:48:56 -07:00
Harshavardhana 04407b4199 print in tabular form for callhome status (#4588) 2023-06-03 08:09:50 -07:00
Kaan Kabalak ca1d00741b Implement '--expiry' flag for 'mc admin user svcacct add & edit' (#4570) 2023-05-30 15:41:38 -07:00
Klaus Post c6d4b63785 Make mc ping useful for startup checks (#4584) 2023-05-29 20:36:19 -07:00
Shireesh Anjal 298dbc50ca fix proxy not being used to test connectivity (#4583) 2023-05-28 11:02:33 -07:00
Shubhendu 9cb069e7af Corrected message to align with other messages (#4577)
Signed-off-by: Shubhendu Ram Tripathi <shubhendu@minio.io>
2023-05-26 16:31:54 -07:00
Kaan Kabalak 0fac0e006e List expiration dates for 'mc admin user svcacct list' command (#4576) 2023-05-26 10:55:37 -07:00
Krishnan Parthasarathi 68a3d5adec Add updatedAt for ilm-rule-ls (#4579) 2023-05-26 09:37:48 -07:00
Klaus Post 96cb5cfc44 fix: limit manual GC to bigger objects (#4581) 2023-05-26 08:12:10 -07:00
Shubhendu 7415469c72 Show groups with their policy details while listing users (#4578)
Signed-off-by: Shubhendu Ram Tripathi <shubhendu@minio.io>
2023-05-23 10:15:19 -07:00
Aditya Manthramurthy 8c06f54d8b Move mc admin idp to mc idp (#4574) 2023-05-19 15:10:28 -07:00
Anis Eleuch 7259e23679 Add sorting order to top drive command (#4575) 2023-05-19 08:41:17 -07:00
Aditya Manthramurthy 43745a9a59 Deprecate older idp commands (#4572) 2023-05-18 09:59:00 -07:00
Aditya Manthramurthy 052cf01a96 Add name and description for service accounts (#4569) 2023-05-17 11:46:09 -07:00
Thierry FOURNIER c767a3705f bug: panic on nil pointer dereference for "mc admin heal" when disk i… (#4571) 2023-05-17 10:03:17 -07:00
Anis Eleuch aefb1db4db Load Subnet proxy and API key from the env if found (#4557) 2023-05-09 10:11:27 -07:00
dorman ada4096d0b randomly generate AK and SK on mc client (#4565) 2023-05-09 09:14:34 -07:00
Anis Eleuch 6050568e66 info: Correctly show pool config with offline node(s) (#4567) 2023-05-09 08:13:26 -07:00
Shireesh Anjal af0e241883 Support setting subnet url via env var in dev mode (#4564) 2023-05-07 23:34:22 -07:00
Anis Eleuch 5a0d5116f4 mirror: Fix removal of FS target without a trailing slash (#4560) 2023-05-04 11:10:16 -07:00
Shubhendu b005b9a94d Remove tags for object versions (#4563)
Signed-off-by: Shubhendu Ram Tripathi <shubhendu@minio.io>
2023-05-01 08:04:31 -07:00
Anis EleuchandAnis Elleuch a7e729fd38 mirror: Honor --fake for target bucket removal (#4561)
Co-authored-by: Anis Elleuch <anis@min.io>
2023-04-27 19:52:06 -07:00
Shireesh Anjal 36e26c448f Ensure perf results file has an extension (#4551) 2023-04-25 11:41:52 -07:00
Anis Eleuch 7130c92043 info: Show nodes in initializing state (#4556) 2023-04-25 11:41:24 -07:00
Harshavardhana 0da22db3af allow aliases to be / at the end and handle such cases (#4554) 2023-04-21 11:30:52 -07:00
Daniel Valdivia 6833118338 Consistent subcommand naming for list and remove with shortname (#4548)
Signed-off-by: Daniel Valdivia <hola@danielvaldivia.com>
2023-04-16 23:07:14 -07:00
Klaus Post 2ff87d64dc Fix dry run message crash (#4546) 2023-04-16 23:04:51 -07:00
dorman 4bc0aa730d doc: Update mc admin doc (#4529) 2023-04-16 23:04:33 -07:00
吴小白 b088b02adc build: support loong64 (#4549) 2023-04-13 11:09:41 -07:00
Anis Eleuch 1843717c57 Remove diskInfo structure in heal report (#4545) 2023-04-11 19:21:51 -07:00
Anis Eleuch 83336dfab3 heal: Fix summary ETA with multiple disks healing in one set (#4543) 2023-04-11 10:03:28 -07:00
Harshavardhana e668f4ad69 update minio-go/v7 -> v7.0.52 (#4544) 2023-04-11 10:03:12 -07:00
Anis Eleuch 50f11d8248 stat: fix printing bucket usage info (#4542) 2023-04-10 09:32:41 -07:00
Harshavardhana a06e46677a fix: remove replace directive merged incorrectly 2023-04-09 19:08:14 -07:00
Anis Eleuch 456c6fde8b perf: Add --noclear flag to avoid doing cleanup (#4473) 2023-04-08 23:10:28 -07:00
Poorna e94ce35608 Add trace for ilm call type (#4538) 2023-04-08 11:37:17 -07:00
Harshavardhana c6db258e7d do not crash on zero values (#4536) 2023-04-08 11:36:50 -07:00
Klaus Post 36aa65b791 Add metadata and tags to mc find (#4531) 2023-04-08 09:43:27 -07:00
Poorna 2c3f0e8ccf Add flag to admin replicate update to toggle synchronous replication (#4514) 2023-04-08 08:54:39 -07:00
jinapurapu a9fb9426f1 Improve errInvalidAlias (#4532) 2023-04-08 08:20:20 -07:00
Shubhendu 2d12a0a310 Dont send blank perf report to SUBNET (#4533)
Signed-off-by: Shubhendu Ram Tripathi <shubhendu@minio.io>
2023-04-08 08:04:27 -07:00
tomaszduda23 d385122bef print RestoreInfo to check status of restored objects (#4534) 2023-04-08 08:03:46 -07:00
Taran Pelkey 1c6f4f48ab Add errors for deprecated commands (#4498) 2023-04-06 09:51:10 -07:00
Poorna b5768efc96 Add trace options for batch key rotation (#4507) 2023-04-04 14:00:02 -07:00
Shireesh Anjal a9cf9103ef Upgrade madmin-go to 2.0.18 (#4535) 2023-04-04 11:33:01 -07:00
Allan Roger Reid ada99298b2 fix: redact secretKey from printed on screen (#4526) 2023-03-28 12:50:57 -07:00
Anis Eleuch 81453d7c8f stat: Fix output when stat a prefix which has other prefixes (#4501) 2023-03-23 13:03:04 -07:00
Harshavardhana 8d6afee8fc honor context cancellation on long-running lists (#4519) 2023-03-23 12:44:45 -07:00
Shubhendu f3ff8b1556 Revert query parameter src while diag upload to SUBNET (#4516) 2023-03-23 12:36:06 -07:00
Anis Eleuch 8a67c25f53 cp: Descriptive error about why unable to locate the source (#4517) 2023-03-23 08:00:24 -07:00
Harshavardhana 381f016f61 add Expiration: info if present for sts/svc accounts (#4515) 2023-03-23 07:59:46 -07:00
Krishnan Parthasarathi 88896ae495 Incl. rules with NewerNoncurrentVersions > 0 (#4505) 2023-03-20 10:17:53 -07:00
Poorna 292f2dd960 Add batch cancel command (#4506) 2023-03-20 10:17:32 -07:00
Klaus Post 2e9b7e5ddc Fix decommission status crash (#4510) 2023-03-20 10:17:00 -07:00
Harshavardhana 252421354c update functional tests for admin_users with 'policy commands' (#4508) 2023-03-19 20:49:16 -07:00
Anis Eleuch e290a426a1 heal: Summary output based on disks utilization (#4474) 2023-03-18 16:43:18 -07:00
Taran Pelkey 9401450402 Restructure adding and removing policies from users and groups (#4428) 2023-03-18 16:41:57 -07:00
Anis Eleuch 07fb372398 rm: --dry-run with --versions to print versions modtime (#4495) 2023-03-18 16:39:26 -07:00
Aditya Manthramurthy 0e97683460 fix: ldap commands don't accept config name (#4499) 2023-03-18 16:38:27 -07:00
Klaus Post 5d334f4960 fix: windows stat command (#4503) 2023-03-18 16:37:13 -07:00
Shubhendu 045430905a Added query parameter src while diag upload to SUBNET (#4504)
Signed-off-by: Shubhendu Ram Tripathi <shubhendu@minio.io>
2023-03-18 16:36:36 -07:00
Poorna d276bd7395 replicate ls: fix panic (#4497) 2023-03-13 06:07:16 -07:00
Poorna dfeadd796a replicate status - drop stale ARNs from stats (#4494) 2023-03-10 07:17:17 -08:00
Shireesh Anjal 107c6dd265 Allow support proxy set|remove without registration (#4488) 2023-03-09 00:10:42 -08:00
Shubhendu aaed62cdd8 Skip subnet config get while --airgap mode of license register (#4479)
Signed-off-by: Shubhendu Ram Tripathi <shubhendu@minio.io>
2023-03-08 00:26:24 -08:00
Harshavardhana bf4a825530 upgrade dependencies and move to go1.20.x (#4490) 2023-03-04 16:34:53 -08:00
Krishnan Parthasarathi 5fbe8c26ba tier-add: --force flag to ignore in use check (#4481) 2023-02-27 16:12:59 -08:00
Anis Elleuch 1843bab500 subnet: Avoid general hard timeout for requests (#4478) 2023-02-21 09:32:38 -08:00
Anis Elleuch 40e51ee9af inspect: Avoid memory usage in subnet upload (#4477) 2023-02-21 19:57:51 +05:30
Klaus Post feccaabc78 Print custom info in trace (#4476) 2023-02-21 17:04:31 +05:30
Harshavardhana 54e2edd1be support unix-pipes with bigger buffers for performance (#4472) 2023-02-16 11:20:11 -08:00
Harshavardhana 47a2f48284 add more debugging tools to 'mc' container (#4475) 2023-02-15 05:06:51 -08:00
Anis Elleuch c02d5923fb Update madmin-go library (#4471) 2023-02-13 08:27:27 -08:00
Harshavardhana f5fec75b0a fix: do not print empty logs on screen (#4470) 2023-02-13 00:11:27 -08:00
Anis Elleuch 616f1cdb1f Implement 'mc admin user sts info' command (#4377) 2023-02-10 13:10:54 -08:00
Poorna a0c075b387 Remove mc admin bucket remote bandwidth command and introduce (#4430) 2023-02-10 12:50:11 -08:00
Shubhendu 95f4443e35 Added code to print the copy resume information (#4454)
Signed-off-by: Shubhendu Ram Tripathi <shubhendu@minio.io>
2023-02-10 12:49:36 -08:00
Poorna 023e0cacc5 mc rm: disallow --purge with flags other than --force (#4467) 2023-02-07 03:42:57 -08:00
Anis Elleuch 663e082161 Fix parsing --response-duration in trace command (#4466) 2023-02-03 21:40:24 -08:00
Harshavardhana 3aebb3362b remove replace flag for go-ieproxy to allow go install 2023-02-03 19:02:13 +05:30
Harshavardhana 2679713ec4 update to newer libraries (#4464) 2023-02-02 08:57:14 -08:00
Yauhen Matsiushonak 04ba6633f3 mc admin user list --json output doesn't include user groups (#4433) (#4463) 2023-02-01 22:31:55 +05:30
Anis Elleuch 7afd7beddd locks: Use timestamp when elapsed is zero (#4462) 2023-02-01 21:46:35 +05:30
Poorna cb9de43544 Improve replicate ls output (#4460) 2023-01-31 16:25:23 +05:30
Poorna c1c7561b4e Fix replicate add/update cmds to allow prefix in rule (#4459) 2023-01-31 16:24:55 +05:30
Kanagaraj M 2e95a70c98 Use --api-key flag on register when provided (#4458) 2023-01-28 12:29:38 -08:00
Harshavardhana 58b7fc447d fix: hide duration flag its not useful for users (#4457) 2023-01-27 02:07:09 -08:00
Krishnan Parthasarathi f8d8667238 Add support for restoring SSE-C encrypted objects (#4456) 2023-01-26 01:44:04 -08:00
Harshavardhana 842a816385 use humanize.IBytes instead of humanize.Bytes (#4455) 2023-01-24 07:14:25 -08:00
Harshavardhana 34a67cb169 cleanup mc to use 'go' errs to be 'e' (#4450) 2023-01-24 02:03:57 -08:00
Shubhendu 468fc49d0f Corrected the logic for calculating the expiration no of days (#4451)
Signed-off-by: Shubhendu Ram Tripathi <shubhendu@minio.io>
2023-01-23 07:11:38 -08:00
Shubhendu e9e6c2231f Corrected output for command mc admin info (#4448)
Signed-off-by: Shubhendu Ram Tripathi <shubhendu@minio.io>
2023-01-19 09:13:40 -08:00
Shireesh Anjal 58f9fec703 Support --airgap in unregister command (#4441) 2023-01-18 10:03:24 +05:30
Anis Elleuch 6e97f161c8 Add support of giving a comment to service accounts (#4438) 2023-01-14 21:22:28 +05:30
Shireesh Anjal cc1606ff5c Improve message when profile upload fails (#4443) 2023-01-14 05:09:44 +05:30
Aditya Manthramurthy 73727de391 Simplify/speedup container image publishing script (#4442) 2023-01-13 20:47:05 +05:30
Daniel Valdivia 14c2e506fa Add confirm flag to mc admin update --yes (#4439)
Signed-off-by: Daniel Valdivia <hola@danielvaldivia.com>
2023-01-11 08:44:16 +05:30
Shireesh Anjal 7c6499b8a8 Renew license online if license file not passed (#4429) 2023-01-09 01:19:23 -08:00
Poorna e6e2b57022 Rename admin replicate subcommands (#4383) 2023-01-06 14:29:42 -08:00
Harshavardhana fbef5dd7f0 support concurrent uploads for 'mc pipe' (#4435) 2023-01-06 12:17:45 -08:00
Poorna 55a9d204db rb: avoid throwing error for force delete of prefix (#4436) 2023-01-06 12:09:09 -08:00
Shireesh Anjal cca1fd7c82 Upload inspect data to SUBNET (#4420) 2023-01-06 11:36:21 -08:00
Anis Elleuch a933ca5ae6 trace: Add bootstrap tracing type (#4416) 2023-01-06 11:36:11 -08:00
Taran Pelkey eedcbfe138 Allow mirror to continue syncing after an object fails to sync (#4427) 2023-01-06 11:11:42 -08:00
dorman 176072dee4 trace: Add input and output filters options (#4353) 2022-12-24 07:21:38 -08:00
Harshavardhana 0dffa062ea upgrade UBI image to 8.7 (#4425) 2022-12-23 07:52:58 -08:00
Harshavardhana a5c59c6190 avoid converting API types to local forms in 'mc' (#4424) 2022-12-22 14:23:48 -08:00
Taran Pelkey 4654d71164 Change formatting of mc stat (#4397) 2022-12-22 14:23:22 -08:00
Poorna c32ab49547 Change mc replicate add|update to integrate create remote targets (#4403) 2022-12-22 11:00:13 -08:00
Krishnan Parthasarathi 2166c63e8f admin-trace: Fix support for tracing scanner calls (#4417) 2022-12-22 10:58:17 -08:00
Anis Elleuch 8f0ae83bf8 fix: Correctly print svc accounts list (#4422) 2022-12-22 09:18:57 -08:00
Harshavardhana e8792efe0a fix: replicate remove show partial operations if any (#4418) 2022-12-22 09:13:46 -08:00
Krishnan Parthasarathi f8a489be9d reorganize ILM tier commands (#4385) 2022-12-19 16:48:28 -08:00
Anis Elleuch 7370e6bfd3 Print 'Cancel upon user request' when the global context is cancelled (#4406) 2022-12-16 23:26:04 -08:00
Harshavardhana c24e9c7847 fix: improve the information on retention config (#4411) 2022-12-16 23:25:44 -08:00
Poorna e4a840380c show endpoint in the replication status (#4412) 2022-12-16 23:25:36 -08:00
Anis Elleuch d0a496826d heal: Reword new disks healing summary (#4413) 2022-12-16 23:25:24 -08:00
Aditya Manthramurthy ce7b02a310 fix: IDP enable/disable command (#4410) 2022-12-16 23:24:56 -08:00
Klaus Post 802f2813e4 Upgrade golang.org/x/net (#4405) 2022-12-13 08:36:13 -08:00
Aditya ManthramurthyandHarshavardhana 4b4cab0441 Add LDAP policy attach/detach commands (#4390)
Co-authored-by: Harshavardhana <harsha@minio.io>
2022-12-12 16:23:28 -08:00
Anis Elleuch b8974e5aed mirror: continue operations even if source object goes missing (#4402) 2022-12-12 12:09:42 -08:00
Klaus Post c18faa5ff6 Add full list of call types. (#4401) 2022-12-12 11:13:00 -08:00
Anis Elleuch c4c0547a57 trace: Add two validations for passed arguments (#4399) 2022-12-12 08:43:09 -08:00
Anis Elleuch 97beb1108d admin update: Add a prompt for confirmation (#4400) 2022-12-12 07:10:12 -08:00
Harshavardhana daa06599e4 stat: avoid unix epoch time when printing date (#4398) 2022-12-09 11:38:22 -08:00
Anis Elleuch 62d07d5ea1 Stat: Do not append a slash when --rewind is specified (#4396) 2022-12-09 02:34:53 -08:00
Anis Elleuch 6b0f191643 find: Add support of --versions flag (#4394) 2022-12-09 02:34:30 -08:00
Poorna 84cbb788e2 Report data usage in mc stat of bucket (#4392) 2022-12-08 10:43:39 -08:00
Anis Elleuch 3aa2b3a755 Add staticheck to make lint (#4395) 2022-12-08 07:51:44 -08:00
Harshavardhana c8f319d94b add HiddenAliases to avoid printing aliases when deprecated (#4393) 2022-12-08 02:07:01 -08:00
Poorna b61ad7a959 Move mc admin bucket quota to mc quota (#4389) 2022-12-07 12:11:52 -08:00
Harshavardhana dbc1f6ada0 add support for upload/download limits (#4388) 2022-12-06 14:39:16 -08:00
Harshavardhana 76d49771d9 rename force-delete to purge hidden flag (#4387) 2022-12-06 08:45:49 -08:00
Klaus Post 52a931bfa7 Add staticcheck to CI (#4386) 2022-12-05 08:32:04 -08:00
Aditya Manthramurthy a55d40caf7 fix: IDP remove commands (#4384) 2022-12-02 15:48:47 -08:00
Aditya Manthramurthy 854b4f123f Bump up madmin-go to v2 (#4382) 2022-12-01 10:41:14 -08:00
Vladimir Garvardt 9fb024f8ec Use NewArnFromString when parsing user-provided ARN string (#4378) 2022-12-01 07:55:07 -08:00
Shireesh Anjal 024656ba05 Move support logs to admin logs (#4381) 2022-11-30 19:34:01 -08:00
Shireesh Anjal c64833c018 Add commands to set, show and remove proxy (#4375) 2022-11-22 16:07:43 -08:00
Shireesh Anjal dc9794cdb0 Restructure mc support callhome command (#4372) 2022-11-22 09:06:25 -08:00
Krishnan Parthasarathi 6406549729 top-locks: Include lock duration in --json output (#4366) 2022-11-21 10:08:32 -08:00
Harshavardhana 12f9b4e241 fix: stat --json output for single alias (#4376) 2022-11-21 10:08:06 -08:00
Poorna b38e144774 Add site resync commands (#4269) 2022-11-18 12:14:05 -08:00
Krishnan Parthasarathi 2770f13a73 ilm-ls: report ExpiredObjectDeleteMarker correctly (#4373) 2022-11-17 13:20:39 -08:00
Taran Pelkey 1192c2d468 fix cp --zip so it copies to given destination name (#4358) 2022-11-16 14:53:29 -08:00
Klaus Post 9051548c80 fix: mc stat for filesystem items (#4371) 2022-11-15 07:56:11 -08:00
Anis Elleuch 89b53a7e52 ls: Fix listing versions when the system clock is off (#4370) 2022-11-15 07:55:05 -08:00
Anis Elleuch 3ee6095c47 du: Do not count directories in FS mode (#4369) 2022-11-15 07:54:18 -08:00
Aditya Manthramurthy a20ab1b3dc fix: examples for mc admin idp commands (#4368) 2022-11-14 18:38:59 -08:00
adfost fd7142e223 update license headers to 2022 (#4360) 2022-11-14 18:38:39 -08:00
adfost bec340af65 fix: 'du' clean the input path to avoid extra counting (#4361) 2022-11-14 11:12:37 -08:00
Andreas Auernhammer 7cde242709 encrypt: remove sse-s3 example (#4357)
Signed-off-by: Andreas Auernhammer <hi@aead.dev>
2022-11-09 21:05:08 -08:00
Krishnan Parthasarathi 66e2075ebd Improve ilm-add flags and ilm-ls output (#4262) 2022-11-09 12:19:18 -08:00
Aditya Manthramurthy 791080485b Add LDAP Policy Entities command (#4318) 2022-11-08 17:01:53 -08:00
Aditya Manthramurthy bc16bde337 Bump up madmin-go for IDP API client bugfix (#4351) 2022-11-07 15:47:39 -08:00
adfost ec67a51185 Replicate-update instead of replicate-edit (#4346) 2022-11-07 15:47:23 -08:00
Poorna 631bf7822b replicate diff: change ui (#4347) 2022-11-07 13:11:32 -08:00
adfost 8b1054cbdb Handling newerNoncurrentVersions Expiry and Transition in validation (#4348) 2022-11-04 11:31:27 -07:00
Shireesh Anjal e5c92be7db More improvements in format of perf test results (#4350) 2022-11-04 08:24:54 -07:00
Aditya Manthramurthy 583d449e38 Update admin IDP commands with new design (#4310) 2022-11-02 17:02:58 -07:00
Shireesh Anjal 655258cf74 Update version of madmin-go to v1.7.3 (#4344) 2022-11-02 12:35:34 -07:00
dorman a4a9b8f406 add help menu for cmd 'mc admin user add' (#4337) 2022-11-01 16:15:12 -07:00
dorman 2f5bf0c17f modify operation type in message (#4339) 2022-11-01 14:10:26 -07:00
Anis Elleuch b5ee028536 fix: stat command with a directory marker (#4341) 2022-11-01 14:09:57 -07:00
Harshavardhana cf7e0ae050 generalize input for ctx.Command.Name (#4338) 2022-11-01 08:04:26 -07:00
Krishnan Parthasarathi 15e52fd862 Fix typo in rebalance-stop output (#4336) 2022-10-31 18:00:57 -07:00
Harshavardhana e64706d7ea fix up rebalance commands for 'mc' error conventions and usage (#4333) 2022-10-30 16:45:20 -07:00
Krishnan Parthasarathi 5b0fc3ef94 feat: admin-rebalance subcommands (#4186) 2022-10-29 22:10:17 -07:00
Anis Elleuch 1bf8a56adc Add support for inspect data v2 (#4185) 2022-10-29 11:27:05 -07:00
Klaus Post 929062c86b Add new healing summary (#4323) 2022-10-29 03:09:23 -07:00
Poorna 710fe47b9b support inspect: bump up metadata version (#4331) 2022-10-28 02:49:37 -07:00
Shireesh Anjal a2753bbaab Improve format of perf tests output (#4330) 2022-10-27 23:28:06 -07:00
adfost 1f51635bc7 Updating usage for mc replicate edit (#4328) 2022-10-27 16:53:36 -07:00
Harshavardhana 88796ea618 improve retention CLI errors and comply with 'mc' style (#4321) 2022-10-21 20:39:29 -07:00
adfost fd6846bc88 Fixing typo in MC (#4320) 2022-10-21 00:42:13 -07:00
Harshavardhana ad254a8fe2 make sure to pass jobType to GenerateBatchJob() (#4319) 2022-10-20 16:26:33 -07:00
Poorna dccbca774a replication diff: add header (#4288) 2022-10-20 14:50:16 -07:00
Shireesh Anjal 3cc795610b Add command to unregister a cluster (#4314) 2022-10-20 11:36:25 -07:00
Aditya Manthramurthy b9b729a3c9 Add LDAP support for IDP Config commands (#4296) 2022-10-19 14:57:53 -07:00
Shireesh Anjal e8afb9b135 Improve help text for support profile|perf (#4311) 2022-10-19 10:32:32 -07:00
Harshavardhana 8493f97e04 update new deps (#4303) 2022-10-18 17:42:56 -07:00
bh4t 28073441c0 change example bucket names to simple names (#4308) 2022-10-18 11:53:33 -07:00
Anis Elleuch 42c16b288c Add number of offline disks in heal info summary (#4305) 2022-10-18 09:01:01 -07:00
Harshavardhana 839e44595c avoid unnecessary tea program for 'license info' (#4306) 2022-10-18 02:06:57 -07:00
Shireesh Anjal 81c04723f9 Print license info table with solid lines (#4301) 2022-10-17 09:44:34 -07:00
Harshavardhana 3fe6778ee7 list jobTypes currently supported (#4298) 2022-10-12 11:12:50 -07:00
Harshavardhana 318569a861 use showAppAndExit() for pager help (#4292) 2022-10-12 09:39:40 -07:00
Harshavardhana 27322636ae feat: Introduce 'mc batch' command (#4225) 2022-10-09 14:10:59 -07:00
Shireesh Anjal 02da50b05e Support --dev flag in license info|update (#4281) 2022-10-09 12:48:40 -07:00
Anis Elleuch be2e66c37c Keep help output after quitting (#4289) 2022-10-09 12:09:37 -07:00
Mukta Puri ec8687d57e Replace 'policy' with 'anonymous' in readme (#4287) 2022-10-07 09:03:39 -07:00
Shireesh Anjal d673ca79ea Show airgapped registration link in different color (#4282) 2022-10-06 07:41:05 -07:00
454 changed files with 34938 additions and 18466 deletions
+6
View File
@@ -1,3 +1,9 @@
## Community Contribution License
All community contributions in this pull request are licensed to the project maintainers
under the terms of the [Apache 2 license](https://www.apache.org/licenses/LICENSE-2.0).
By creating this pull request I represent that I have the right to license the
contributions to the project maintainers under the Apache 2 license.
## Description
+39
View File
@@ -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
+10 -6
View File
@@ -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.18.x, 1.19.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,10 +69,11 @@ jobs:
- name: Set up Go
uses: actions/setup-go@v2
with:
go-version: 1.19.x
go-version: 1.24.x
- name: Checkout code
uses: actions/checkout@v2
- name: Test 386
run: GOOS=linux GOARCH=386 go test -short ./...
+18
View File
@@ -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 }}
+14 -15
View File
@@ -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.19.x
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
+5 -1
View File
@@ -11,4 +11,8 @@ stage/
mc
.run*
.idea/
mc.RELEASE*
mc.RELEASE*
mc.gz
.DS_Store
.vscode/
.bin/
+37 -36
View File
@@ -1,41 +1,42 @@
version: "2"
linters:
disable-all: true
default: none
enable:
- typecheck
- goimports
- misspell
- govet
- revive
- ineffassign
- deadcode
- structcheck
- gomodguard
- gofmt
- govet
- ineffassign
- misspell
- revive
- staticcheck
- unused
- structcheck
- varcheck
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
View File
@@ -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
+4931 -1551
View File
File diff suppressed because it is too large Load Diff
+11 -16
View File
@@ -1,27 +1,22 @@
FROM golang:1.18-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.6
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"]
+3 -3
View File
@@ -1,4 +1,4 @@
FROM registry.access.redhat.com/ubi8/ubi-minimal:8.6
FROM registry.access.redhat.com/ubi8/ubi-minimal:8.8
LABEL maintainer="MinIO Inc <dev@min.io>"
@@ -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
View File
@@ -1,17 +1,24 @@
FROM registry.access.redhat.com/ubi8/ubi-minimal:8.6
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
View File
@@ -1,19 +1,24 @@
FROM registry.access.redhat.com/ubi8/ubi-minimal:8.6
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.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"]
+24
View File
@@ -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"]
+17 -12
View File
@@ -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,8 +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 v1.46.2
@echo "Installing stringer" && go install -v golang.org/x/tools/cmd/stringer@latest
@echo "Installing tools" && go install tool
crosscompile:
@(env bash $(PWD)/buildscripts/cross-compile.sh)
@@ -31,9 +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
@$(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
@@ -41,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"
@@ -52,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 | \
@@ -71,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)"
+48 -42
View File
@@ -1,41 +1,53 @@
# MinIO Client Quickstart Guide
[![Slack](https://slack.min.io/slack?type=svg)](https://slack.min.io) [![Go Report Card](https://goreportcard.com/badge/minio/mc)](https://goreportcard.com/report/minio/mc) [![Docker Pulls](https://img.shields.io/docker/pulls/minio/mc.svg?maxAge=604800)](https://hub.docker.com/r/minio/mc/) [![license](https://img.shields.io/badge/license-AGPL%20V3-blue)](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
policy 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)
+20 -20
View File
@@ -5,23 +5,23 @@ MinIO Client (mc)为ls,cat,cp,mirror,diff,find等UNIX命令提供了
```
ls 列出文件和文件夹。
mb 创建一个存储桶或一个文件夹。
cat 显示文件和对象内容。
pipe 将一个STDIN重定向到一个对象或者文件或者STDOUT。
share 生成用于共享的URL。
cp 拷贝文件和对象。
mirror 给存储桶和文件夹做镜像。
find 基于参数查找文件。
diff 对两个文件夹或者存储桶比较差异。
rm 删除文件和对象。
events 管理对象通知。
watch 监听文件和对象的事件。
policy 管理访问策略。
session 为cp命令管理保存的会话。
config 管理mc配置文件。
update 检查软件更新。
version 输出版本信息。
ls 列出文件和文件夹。
mb 创建一个存储桶或一个文件夹。
cat 显示文件和对象内容。
pipe 将一个STDIN重定向到一个对象或者文件或者STDOUT。
share 生成用于共享的URL。
cp 拷贝文件和对象。
mirror 给存储桶和文件夹做镜像。
find 基于参数查找文件。
diff 对两个文件夹或者存储桶比较差异。
rm 删除文件和对象。
events 管理对象通知。
watch 监听文件和对象的事件。
anonymous 管理访问策略。
session 为cp命令管理保存的会话。
config 管理mc配置文件。
update 检查软件更新。
version 输出版本信息。
```
## Docker容器
@@ -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)
+2 -2
View File
@@ -70,11 +70,11 @@ readlink() {
assert_is_supported_arch() {
case "${ARCH}" in
x86_64 | amd64 | ppc64le | aarch64 | arm* | s390x )
x86_64 | amd64 | ppc64le | aarch64 | arm* | s390x | loong64 | loongarch64 )
return
;;
*)
echo "Arch '${ARCH}' is not supported. Supported Arch: [x86_64, amd64, ppc64le, aarch64, arm*, s390x]"
echo "Arch '${ARCH}' is not supported. Supported Arch: [x86_64, amd64, ppc64le, aarch64, arm*, s390x, loong64, loongarch64]"
exit 1
esac
}
+1 -1
View File
@@ -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() {
+32 -3
View File
@@ -1,4 +1,4 @@
// Copyright (c) 2015-2021 MinIO, Inc.
// Copyright (c) 2015-2022 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
@@ -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.
+56 -17
View File
@@ -1,4 +1,4 @@
// Copyright (c) 2015-2021 MinIO, Inc.
// Copyright (c) 2015-2022 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
@@ -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
+94
View File
@@ -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)
}
+48
View File
@@ -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)
}
+77
View File
@@ -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)
}
@@ -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
//
@@ -21,29 +21,28 @@ import (
"github.com/minio/cli"
)
var supportLogsDisableCmd = cli.Command{
Name: "disable",
Usage: "disable uploading MinIO logs to SUBNET",
OnUsageError: onUsageError,
Action: mainDisableLogs,
var adminAccesskeyEnableCmd = cli.Command{
Name: "enable",
Usage: "enable an access key",
Action: mainAdminAccesskeyEnable,
Before: setGlobalsFromContext,
Flags: supportGlobalFlags,
Flags: globalFlags,
OnUsageError: onUsageError,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} ALIAS
{{.HelpName}} [FLAGS] [TARGET]
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Disable uploading logs for cluster with alias 'play' to SUBNET
{{.Prompt}} {{.HelpName}} play
1. Enable access key
{{.Prompt}} {{.HelpName}} myminio myaccesskey
`,
}
func mainDisableLogs(ctx *cli.Context) error {
setToggleMessageColor()
alias := validateLogsToggleCmd(ctx, "disable")
configureSubnetWebhook(alias, false)
return nil
func mainAdminAccesskeyEnable(ctx *cli.Context) error {
return enableDisableAccesskey(ctx, true)
}
+202
View File
@@ -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
}
+168
View File
@@ -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
}
+49
View File
@@ -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)
}
+149
View File
@@ -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
}
+46
View File
@@ -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
}
+9 -164
View File
@@ -18,178 +18,23 @@
package cmd
import (
"fmt"
"path/filepath"
"sort"
"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"
"github.com/minio/mc/pkg/probe"
"github.com/minio/pkg/console"
)
var adminBucketInfoFlags = []cli.Flag{}
type adminBucketInfoMessage struct {
Status string `json:"status"`
URL string `json:"url"`
UsageInfo madmin.BucketUsageInfo `json:"usage"`
Props BucketInfo `json:"props"`
}
type histogramDef struct {
start, end uint64
text string
}
var histogramTagsDesc = map[string]histogramDef{
"LESS_THAN_1024_B": {0, 1024, "less than 1024 bytes"},
"BETWEEN_1024_B_AND_1_MB": {1024, 1024 * 1024, "between 1024 bytes and 1 MB"},
"BETWEEN_1_MB_AND_10_MB": {1024 * 1024, 10 * 1024 * 1024, "between 1 MB and 10 MB"},
"BETWEEN_10_MB_AND_64_MB": {10 * 1024 * 1024, 64 * 1024 * 1024, "between 10 MB and 64 MB"},
"BETWEEN_64_MB_AND_128_MB": {64 * 1024 * 1024, 128 * 1024 * 1024, "between 64 MB and 128 MB"},
"BETWEEN_128_MB_AND_512_MB": {128 * 1024 * 1024, 512 * 1024 * 1024, "between 128 MB and 512 MB"},
"GREATER_THAN_512_MB": {512 * 1024 * 1024, 0, "greater than 512 MB"},
}
// Return a sorted list of histograms
func sortHistogramTags() (orderedTags []string) {
orderedTags = make([]string, 0, len(histogramTagsDesc))
for tag := range histogramTagsDesc {
orderedTags = append(orderedTags, tag)
}
sort.Slice(orderedTags, func(i, j int) bool {
return histogramTagsDesc[orderedTags[i]].start < histogramTagsDesc[orderedTags[j]].start
})
return
}
func countDigits(num uint64) (count uint) {
for num > 0 {
num /= 10
count++
}
return
}
func (bi adminBucketInfoMessage) String() string {
var b strings.Builder
fmt.Fprintf(&b, console.Colorize("Title", "Usage:\n"))
fmt.Fprintf(&b, "%16s: %s\n", "Total size", console.Colorize("Count", humanize.IBytes(bi.UsageInfo.Size)))
fmt.Fprintf(&b, "%16s: %s\n", "Objects count", console.Colorize("Count", humanize.Comma(int64(bi.UsageInfo.ObjectsCount))))
fmt.Fprintf(&b, "%16s: %s\n", "Versions count", console.Colorize("Count", humanize.Comma(int64(bi.UsageInfo.VersionsCount))))
fmt.Fprintf(&b, "\n")
fmt.Fprintf(&b, console.Colorize("Title", "Properties:\n"))
fmt.Fprintf(&b, prettyPrintBucketMetadata(bi.Props))
fmt.Fprintf(&b, "\n")
fmt.Fprintf(&b, console.Colorize("Title", "Object sizes histogram:\n"))
var maxDigits uint
for _, val := range bi.UsageInfo.ObjectSizesHistogram {
if d := countDigits(val); d > maxDigits {
maxDigits = d
}
}
sortedTags := sortHistogramTags()
for _, tagName := range sortedTags {
val, ok := bi.UsageInfo.ObjectSizesHistogram[tagName]
if ok {
fmt.Fprintf(&b, " %*d object(s) %s\n", maxDigits, val, histogramTagsDesc[tagName].text)
}
}
return b.String()
}
func (bi adminBucketInfoMessage) JSON() string {
jsonMessageBytes, e := json.MarshalIndent(bi, "", " ")
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
return string(jsonMessageBytes)
}
var adminBucketInfoCmd = cli.Command{
Name: "info",
Usage: "display bucket information",
Action: mainAdminBucketInfo,
OnUsageError: onUsageError,
Before: setGlobalsFromContext,
Flags: append(adminBucketInfoFlags, globalFlags...),
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} TARGET
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Display the usage data and configuration of a bucket on MinIO.
{{.Prompt}} {{.HelpName}} myminio/mybucket
`,
}
// checkAdminBucketInfoSyntax - validate all the passed arguments
func checkAdminBucketInfoSyntax(ctx *cli.Context) {
if len(ctx.Args()) != 1 {
showCommandHelpAndExit(ctx, ctx.Command.Name, 1) // last argument is exit code
}
Name: "info",
Usage: "display bucket information",
Action: mainAdminBucketInfo,
OnUsageError: onUsageError,
Before: setGlobalsFromContext,
Flags: append(adminBucketInfoFlags, globalFlags...),
HideHelpCommand: true,
}
// mainAdminBucketInfo is the handler for "mc admin bucket info" command.
func mainAdminBucketInfo(ctx *cli.Context) error {
checkAdminBucketInfoSyntax(ctx)
console.SetColor("Title", color.New(color.Bold, color.FgBlue))
console.SetColor("Count", color.New(color.FgGreen))
console.SetColor("Metadata", color.New(color.FgWhite))
console.SetColor("Key", color.New(color.FgCyan))
console.SetColor("Value", color.New(color.FgYellow))
console.SetColor("Unset", color.New(color.FgRed))
console.SetColor("Set", color.New(color.FgGreen))
// Get the alias parameter from cli
args := ctx.Args()
aliasedURL := args.Get(0)
// Create a new MinIO Admin Client
adminClient, err := newAdminClient(aliasedURL)
fatalIf(err, "Unable to initialize admin connection.")
s3Client, err := newClient(aliasedURL)
fatalIf(err, "Unable to initialize admin connection.")
aliasedURL = filepath.ToSlash(aliasedURL)
splits := splitStr(aliasedURL, "/", 3)
bucket := splits[1]
duinfo, e := adminClient.DataUsageInfo(globalContext)
fatalIf(probe.NewError(e).Trace(args...), "Unable to get data usage")
bi, err := s3Client.GetBucketInfo(globalContext)
fatalIf(err.Trace(args...), "Unable to get bucket properties")
bu, ok := duinfo.BucketsUsage[bucket]
if !ok {
fatalIf(errDummy().Trace(args...), "Unable to get bucket usage info. Bucket usage is not ready yet.")
}
printMsg(adminBucketInfoMessage{
Status: "success",
URL: aliasedURL,
UsageInfo: bu,
Props: bi,
})
func mainAdminBucketInfo(_ *cli.Context) error {
deprecatedError("mc stat")
return nil
}
+10 -133
View File
@@ -1,4 +1,4 @@
// Copyright (c) 2015-2021 MinIO, Inc.
// Copyright (c) 2015-2022 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
@@ -18,15 +18,7 @@
package cmd
import (
"fmt"
humanize "github.com/dustin/go-humanize"
"github.com/fatih/color"
"github.com/minio/cli"
json "github.com/minio/colorjson"
"github.com/minio/madmin-go"
"github.com/minio/mc/pkg/probe"
"github.com/minio/pkg/console"
)
var adminQuotaFlags = []cli.Flag{
@@ -40,133 +32,18 @@ var adminQuotaFlags = []cli.Flag{
},
}
// quotaMessage container for content message structure
type quotaMessage struct {
op string
Status string `json:"status"`
Bucket string `json:"bucket"`
Quota uint64 `json:"quota,omitempty"`
QuotaType string `json:"type,omitempty"`
}
func (q quotaMessage) String() string {
switch q.op {
case "set":
return console.Colorize("QuotaMessage",
fmt.Sprintf("Successfully set bucket quota of %s with %s type on `%s`", humanize.IBytes(q.Quota), q.QuotaType, q.Bucket))
case "unset":
return console.Colorize("QuotaMessage",
fmt.Sprintf("Successfully cleared bucket quota configured on `%s`", q.Bucket))
default:
return console.Colorize("QuotaInfo",
fmt.Sprintf("Bucket `%s` has %s quota of %s", q.Bucket, q.QuotaType, humanize.IBytes(q.Quota)))
}
}
func (q quotaMessage) JSON() string {
jsonMessageBytes, e := json.MarshalIndent(q, "", " ")
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
return string(jsonMessageBytes)
}
var adminBucketQuotaCmd = cli.Command{
Name: "quota",
Usage: "manage bucket quota",
Action: mainAdminBucketQuota,
OnUsageError: onUsageError,
Before: setGlobalsFromContext,
Flags: append(adminQuotaFlags, globalFlags...),
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} TARGET [--hard QUOTA | --clear]
QUOTA
quota accepts human-readable case-insensitive number
suffixes such as "k", "m", "g" and "t" referring to the metric units KB,
MB, GB and TB respectively. Adding an "i" to these prefixes, uses the IEC
units, so that "gi" refers to "gibibyte" or "GiB". A "b" at the end is
also accepted. Without suffixes the unit is bytes.
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Display bucket quota configured for "mybucket" on MinIO.
{{.Prompt}} {{.HelpName}} myminio/mybucket
3. Set hard quota of 1gb for a bucket "mybucket" on MinIO.
{{.Prompt}} {{.HelpName}} myminio/mybucket --hard 1GB
4. Clear bucket quota configured for bucket "mybucket" on MinIO.
{{.Prompt}} {{.HelpName}} myminio/mybucket --clear
`,
}
// checkAdminBucketQuotaSyntax - validate all the passed arguments
func checkAdminBucketQuotaSyntax(ctx *cli.Context) {
if len(ctx.Args()) == 0 || len(ctx.Args()) > 1 {
showCommandHelpAndExit(ctx, ctx.Command.Name, 1) // last argument is exit code
}
Name: "quota",
Usage: "manage bucket quota",
Action: mainAdminBucketQuota,
OnUsageError: onUsageError,
Before: setGlobalsFromContext,
Flags: append(adminQuotaFlags, globalFlags...),
HideHelpCommand: true,
}
// mainAdminBucketQuota is the handler for "mc admin bucket quota" command.
func mainAdminBucketQuota(ctx *cli.Context) error {
checkAdminBucketQuotaSyntax(ctx)
console.SetColor("QuotaMessage", color.New(color.FgGreen))
console.SetColor("QuotaInfo", color.New(color.FgBlue))
// Get the alias parameter from cli
args := ctx.Args()
aliasedURL := args.Get(0)
// Create a new MinIO Admin Client
client, err := newAdminClient(aliasedURL)
fatalIf(err, "Unable to initialize admin connection.")
_, targetURL := url2Alias(args[0])
if ctx.IsSet("hard") {
qType := madmin.HardQuota
quotaStr := ctx.String("hard")
quota, e := humanize.ParseBytes(quotaStr)
fatalIf(probe.NewError(e).Trace(quotaStr), "Unable to parse quota")
fatalIf(probe.NewError(client.SetBucketQuota(globalContext, targetURL, &madmin.BucketQuota{
Quota: quota,
Type: qType,
})).Trace(args...), "Unable to set bucket quota")
printMsg(quotaMessage{
op: "set",
Bucket: targetURL,
Quota: quota,
QuotaType: string(qType),
Status: "success",
})
} else if ctx.Bool("clear") {
if e := client.SetBucketQuota(globalContext, targetURL, &madmin.BucketQuota{}); e != nil {
fatalIf(probe.NewError(e).Trace(args...), "Unable to clear bucket quota config")
}
printMsg(quotaMessage{
op: "unset",
Bucket: targetURL,
Status: "success",
})
} else {
qCfg, e := client.GetBucketQuota(globalContext, targetURL)
fatalIf(probe.NewError(e).Trace(args...), "Unable to get bucket quota")
printMsg(quotaMessage{
op: "get",
Bucket: targetURL,
Quota: qCfg.Quota,
QuotaType: string(qCfg.Type),
Status: "success",
})
}
func mainAdminBucketQuota(_ *cli.Context) error {
deprecatedError("mc quota")
return nil
}
+5 -276
View File
@@ -1,4 +1,4 @@
// Copyright (c) 2015-2021 MinIO, Inc.
// Copyright (c) 2015-2022 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
@@ -18,292 +18,21 @@
package cmd
import (
"fmt"
"net/url"
"path"
"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"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio-go/v7/pkg/s3utils"
"github.com/minio/pkg/console"
)
var adminBucketRemoteAddFlags = []cli.Flag{
cli.StringFlag{
Name: "path",
Value: "auto",
Usage: "bucket path lookup supported by the server. Valid options are '[on,off,auto]'",
},
cli.StringFlag{
Name: "service",
Usage: "type of service. Valid options are '[replication]'",
},
cli.StringFlag{
Name: "region",
Usage: "region of the destination bucket (optional)",
},
cli.StringFlag{
Name: "bandwidth",
Usage: "Set bandwidth limit in bits per second (K,B,G,T for metric and Ki,Bi,Gi,Ti for IEC units)",
},
cli.BoolFlag{
Name: "sync",
Usage: "enable synchronous replication for this target. Default is async",
},
cli.UintFlag{
Name: "healthcheck-seconds",
Usage: "health check duration in seconds",
Value: 60,
},
cli.BoolFlag{
Name: "disable-proxy",
Usage: "disable proxying in active-active replication. If unset, default behavior is to proxy",
},
}
var adminBucketRemoteAddCmd = cli.Command{
Name: "add",
Usage: "add a new remote target",
Action: mainAdminBucketRemoteAdd,
OnUsageError: onUsageError,
Before: setGlobalsFromContext,
Flags: append(globalFlags, adminBucketRemoteAddFlags...),
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} TARGET http(s)://ACCESSKEY:SECRETKEY@DEST_URL/DEST_BUCKET [--path | --region | --bandwidth] --service
TARGET:
Also called as alias/sourcebucketname
DEST_BUCKET:
Also called as remote target bucket.
DEST_URL:
Also called as remote endpoint.
ACCESSKEY:
Also called as username.
SECRETKEY:
Also called as password.
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Set a new replication target "targetbucket" in region "us-west-1" on https://minio.siteb.example.com for
bucket 'sourcebucket'.
{{.Prompt}} {{.HelpName}} sitea/sourcebucket https://foobar:foo12345@minio.siteb.example.com/targetbucket \
--service "replication" --region "us-west-1"
2. Set a new synchronous replication target 'targetbucket' in region "us-west-1" on https://minio.siteb.example.com for
bucket 'sourcebucket' with bandwidth set to 2 gigabits per second.
{{.Prompt}} {{.HelpName}} sitea/sourcebucket https://foobar:foo12345@minio.siteb.example.com/targetbucket \
--service "replication" --region "us-west-1 --bandwidth "2G" --sync
`,
}
// checkAdminBucketRemoteAddSyntax - validate all the passed arguments
func checkAdminBucketRemoteAddSyntax(ctx *cli.Context) {
argsNr := len(ctx.Args())
if argsNr < 2 {
showCommandHelpAndExit(ctx, ctx.Command.Name, 1) // last argument is exit code
}
if argsNr > 2 {
fatalIf(errInvalidArgument().Trace(ctx.Args().Tail()...),
"Incorrect number of arguments for remote add command.")
}
}
// RemoteMessage container for content message structure
type RemoteMessage struct {
op string
Status string `json:"status"`
AccessKey string `json:"accessKey,omitempty"`
SecretKey string `json:"secretKey,omitempty"`
SourceBucket string `json:"sourceBucket"`
TargetURL string `json:"TargetURL,omitempty"`
TargetBucket string `json:"TargetBucket,omitempty"`
RemoteARN string `json:"RemoteARN,omitempty"`
Path string `json:"path,omitempty"`
Region string `json:"region,omitempty"`
ServiceType string `json:"service"`
Bandwidth int64 `json:"bandwidth"`
ReplicationSync bool `json:"replicationSync"`
Proxy bool `json:"proxy"`
HealthCheckDuration time.Duration `json:"healthcheckDuration"`
ResetID string `json:"resetID"`
ResetBefore time.Time `json:"resetBeforeDate"`
}
func (r RemoteMessage) String() string {
switch r.op {
case "ls":
message := console.Colorize("TargetURL", fmt.Sprintf("%s ", r.TargetURL))
message += console.Colorize("SourceBucket", r.SourceBucket)
message += console.Colorize("Arrow", "->")
message += console.Colorize("TargetBucket", r.TargetBucket)
message += " "
message += console.Colorize("ARN", r.RemoteARN)
syncStr := " "
if r.ReplicationSync && r.ServiceType == string(madmin.ReplicationService) {
syncStr = "sync"
}
message += " " + console.Colorize("SyncLabel", syncStr)
proxyStr := " "
if r.Proxy && r.ServiceType == string(madmin.ReplicationService) {
proxyStr = "proxy"
}
message += " "
message += console.Colorize("ProxyLabel", proxyStr)
return message
case "rm":
return console.Colorize("RemoteMessage", "Removed remote target for `"+r.SourceBucket+"` bucket successfully.")
case "add":
return console.Colorize("RemoteMessage", "Remote ARN = `"+r.RemoteARN+"`.")
case "edit":
return console.Colorize("RemoteMessage", "Remote target updated successfully for target with ARN:`"+r.RemoteARN+"`.")
}
return ""
}
// JSON returns jsonified message
func (r RemoteMessage) JSON() string {
r.Status = "success"
jsonMessageBytes, e := json.MarshalIndent(r, "", " ")
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
return string(jsonMessageBytes)
}
func extractCredentialURL(argURL string) (accessKey, secretKey string, u *url.URL) {
var parsedURL string
if hostKeyTokens.MatchString(argURL) {
fatalIf(errInvalidArgument().Trace(argURL), "temporary tokens are not allowed for remote targets")
}
if hostKeys.MatchString(argURL) {
parts := hostKeys.FindStringSubmatch(argURL)
if len(parts) != 5 {
fatalIf(errInvalidArgument().Trace(argURL), "Unsupported remote target format, please check --help")
}
accessKey = parts[2]
secretKey = parts[3]
parsedURL = fmt.Sprintf("%s%s", parts[1], parts[4])
}
var e error
if parsedURL == "" {
fatalIf(errInvalidArgument().Trace(argURL), "No valid credentials were detected")
}
u, e = url.Parse(parsedURL)
if e != nil {
fatalIf(errInvalidArgument().Trace(parsedURL), "Unsupported URL format %v", e)
}
return accessKey, secretKey, u
}
// fetchRemoteTarget - returns the dest bucket, dest endpoint, access and secret key
func fetchRemoteTarget(cli *cli.Context) (sourceBucket string, bktTarget *madmin.BucketTarget) {
args := cli.Args()
argCount := len(args)
if argCount < 2 {
fatalIf(probe.NewError(fmt.Errorf("Missing Remote target configuration")), "Unable to parse remote target")
}
_, sourceBucket = url2Alias(args[0])
p := cli.String("path")
if !isValidPath(p) {
fatalIf(errInvalidArgument().Trace(p),
"Unrecognized bucket path style. Valid options are `[on,off, auto]`.")
}
tgtURL := args[1]
accessKey, secretKey, u := extractCredentialURL(tgtURL)
var tgtBucket string
if u.Path != "" {
tgtBucket = path.Clean(u.Path[1:])
}
if e := s3utils.CheckValidBucketName(tgtBucket); e != nil {
fatalIf(probe.NewError(e).Trace(tgtURL), "Invalid target bucket specified")
}
serviceType := cli.String("service")
if !madmin.ServiceType(serviceType).IsValid() {
fatalIf(errInvalidArgument().Trace(serviceType), "Invalid service type. Valid option is `[replication]`.")
}
if cli.IsSet("sync") && serviceType != string(madmin.ReplicationService) {
fatalIf(errInvalidArgument(), "Invalid usage. --sync flag applies only to replication service")
}
bandwidthStr := cli.String("bandwidth")
bandwidth, err := getBandwidthInBytes(bandwidthStr)
if err != nil {
fatalIf(errInvalidArgument().Trace(bandwidthStr), "Invalid bandwidth number")
}
console.SetColor(cred, color.New(color.FgYellow, color.Italic))
creds := &madmin.Credentials{AccessKey: accessKey, SecretKey: secretKey}
disableproxy := cli.Bool("disable-proxy")
bktTarget = &madmin.BucketTarget{
TargetBucket: tgtBucket,
Secure: u.Scheme == "https",
Credentials: creds,
Endpoint: u.Host,
Path: p,
API: "s3v4",
Type: madmin.ServiceType(serviceType),
Region: cli.String("region"),
BandwidthLimit: int64(bandwidth),
ReplicationSync: cli.Bool("sync"),
DisableProxy: disableproxy,
HealthCheckDuration: time.Duration(cli.Uint("healthcheck-seconds")) * time.Second,
}
return sourceBucket, bktTarget
}
func getBandwidthInBytes(bandwidthStr string) (bandwidth uint64, err error) {
if bandwidthStr != "" {
bandwidth, err = humanize.ParseBytes(bandwidthStr)
if err != nil {
return
}
}
bandwidth = bandwidth / 8
return
Flags: globalFlags,
HideHelp: true,
}
// mainAdminBucketRemoteAdd is the handle for "mc admin bucket remote set" command.
func mainAdminBucketRemoteAdd(ctx *cli.Context) error {
checkAdminBucketRemoteAddSyntax(ctx)
console.SetColor("RemoteMessage", color.New(color.FgGreen))
// Get the alias parameter from cli
args := ctx.Args()
aliasedURL := args.Get(0)
// Create a new MinIO Admin Client
client, cerr := newAdminClient(aliasedURL)
fatalIf(cerr, "Unable to initialize admin connection.")
sourceBucket, bktTarget := fetchRemoteTarget(ctx)
arn, e := client.SetRemoteTarget(globalContext, sourceBucket, bktTarget)
if e != nil {
fatalIf(probe.NewError(e).Trace(args...), "Unable to configure remote target")
}
printMsg(RemoteMessage{
op: ctx.Command.Name,
TargetURL: bktTarget.URL().String(),
TargetBucket: bktTarget.TargetBucket,
AccessKey: bktTarget.Credentials.AccessKey,
SourceBucket: sourceBucket,
RemoteARN: arn,
ReplicationSync: bktTarget.ReplicationSync,
Proxy: !bktTarget.DisableProxy,
})
func mainAdminBucketRemoteAdd(_ *cli.Context) error {
deprecatedError("mc replicate add")
return nil
}
+39 -40
View File
@@ -1,4 +1,4 @@
// Copyright (c) 2015-2021 MinIO, Inc.
// Copyright (c) 2015-2022 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
@@ -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)
-196
View File
@@ -1,196 +0,0 @@
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
import (
"fmt"
"sort"
"strings"
"time"
"github.com/dustin/go-humanize"
"github.com/fatih/color"
"github.com/minio/cli"
json "github.com/minio/colorjson"
"github.com/minio/madmin-go"
"github.com/minio/mc/pkg/probe"
"github.com/minio/pkg/console"
)
var adminBandwidthInfoCmdFlags = []cli.Flag{
cli.StringFlag{
Name: "unit",
Value: "b",
Usage: "[b|bi|B|Bi] Display bandwidth in bits (IEC [bi] or SI [b]) or bytes (IEC [Bi] or SI [B])",
},
}
var adminBwInfoCmd = cli.Command{
Name: "bandwidth",
Usage: "Show bandwidth info for buckets on the MinIO server in bits or bytes per second. Ki,Bi,Mi,Gi represent IEC units.",
Action: mainAdminBwInfo,
Before: setGlobalsFromContext,
OnUsageError: onUsageError,
Flags: append(globalFlags, adminBandwidthInfoCmdFlags...),
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} FLAGS TARGET
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Show the bandwidth usage for all the buckets in a MinIO server setup
{{.Prompt}} {{.HelpName}} play/
2. Show the bandwidth usage for the bucket 'source-bucket' in a MinIO server setup
{{.Prompt}} {{.HelpName}} play/source-bucket
`,
}
func printTable(report madmin.Report, bits bool, iec bool) {
bucketMaxLength := 63
bucketColLength := 6
var bucketKeys []string
for bucket := range report.Report.BucketStats {
if len(bucket) <= bucketMaxLength && len(bucket) > bucketColLength {
bucketColLength = len(bucket)
}
bucketKeys = append(bucketKeys, bucket)
}
sort.Strings(bucketKeys)
dspOrder := []col{colGreen} // Header
for i := 0; i < len(report.Report.BucketStats); i++ {
dspOrder = append(dspOrder, colGrey)
}
var printColors []*color.Color
for _, c := range dspOrder {
printColors = append(printColors, getPrintCol(c))
}
cellText := make([][]string, len(report.Report.BucketStats)+1) // 1 for the header
tbl := console.NewTable(printColors, []bool{false, false, false}, 0)
bucketTitle := fmt.Sprintf("%-16v", "Bucket")
cellText[0] = []string{
bucketTitle,
"Configured Max Bandwidth",
"Current Bandwidth",
}
tbl.HeaderRowSeparator = true
index := 1
for _, bucket := range bucketKeys {
values := report.Report.BucketStats[bucket]
if len(bucket) > bucketMaxLength {
bucket = bucket[:bucketMaxLength] + ".."
}
var mul uint64
mul = 1
if bits {
mul = 8
}
limit := humanize.Bytes(uint64(values.LimitInBytesPerSecond) * mul)
current := humanize.Bytes(uint64(values.CurrentBandwidthInBytesPerSecond) * mul)
if iec {
limit = humanize.IBytes(uint64(values.LimitInBytesPerSecond)*mul) + "/sec"
current = humanize.IBytes(uint64(values.CurrentBandwidthInBytesPerSecond)*mul) + "/sec"
}
if bits {
limit = strings.ToLower(limit) + "/sec"
current = strings.ToLower(current) + "/sec"
}
if values.LimitInBytesPerSecond == 0 {
limit = "N/A" // N/A means cluster bandwidth is not configured
}
cellText[index] = []string{
bucket,
limit,
current,
}
index++
}
if len(report.Report.BucketStats) > 0 {
err := tbl.DisplayTable(cellText)
if err != nil {
console.Error(err)
}
}
}
func checkAdminBwInfoSyntax(ctx *cli.Context) {
u := ctx.String("unit")
if u != "bi" &&
u != "b" &&
u != "Bi" &&
u != "B" &&
u != "" {
showCommandHelpAndExit(ctx, "bandwidth", globalErrorExitStatus)
}
if len(ctx.Args()) > 1 || len(ctx.Args()) == 0 {
showCommandHelpAndExit(ctx, "bandwidth", globalErrorExitStatus)
}
}
func mainAdminBwInfo(ctx *cli.Context) {
checkAdminBwInfoSyntax(ctx)
aliasURL, bucket := getAliasAndBucket(ctx)
client := getClient(aliasURL)
reportCh := client.GetBucketBandwidth(globalContext, bucket)
firstPrint := true
bandwidthUnitsString := ctx.String("unit")
for {
select {
case report := <-reportCh:
if len(report.Report.BucketStats) == 0 {
continue
}
if report.Err != nil {
if strings.Contains(report.Err.Error(), "EOF") {
continue
}
console.Error(report.Err)
}
printBandwidth(report, firstPrint, bandwidthUnitsString == "bi" || bandwidthUnitsString == "b",
bandwidthUnitsString == "bi" || bandwidthUnitsString == "Bi")
firstPrint = false
case <-globalContext.Done():
return
}
}
}
func printBandwidth(report madmin.Report, firstPrint bool, bits bool, iec bool) {
rewindLines := len(report.Report.BucketStats) + 4
if firstPrint {
rewindLines = 0
}
if globalJSON {
reportJSON, e := json.MarshalIndent(report, "", " ")
fatalIf(probe.NewError(e), "Unable to marshal to JSON")
console.Println(string(reportJSON))
time.Sleep(1 * time.Second)
return
}
if len(report.Report.BucketStats) > 0 {
console.RewindLines(rewindLines)
// For the next iteration, rewind lines
printTable(report, bits, iec)
}
time.Sleep(1 * time.Second)
}
+5 -214
View File
@@ -1,4 +1,4 @@
// Copyright (c) 2015-2021 MinIO, Inc.
// Copyright (c) 2015-2022 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
@@ -18,230 +18,21 @@
package cmd
import (
"path"
"strconv"
"strings"
"time"
"github.com/fatih/color"
"github.com/minio/cli"
"github.com/minio/madmin-go"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio-go/v7/pkg/s3utils"
"github.com/minio/pkg/console"
)
var adminBucketRemoteEditFlags = []cli.Flag{
cli.StringFlag{
Name: "arn",
Usage: "ARN of target",
},
cli.StringFlag{
Name: "sync",
Usage: "enable synchronous replication for this target. Valid values are enable,disable.Defaults to disable if unset",
},
cli.StringFlag{
Name: "proxy",
Usage: "enable proxying in active-active replication. Valid values are enable,disable.By default proxying is enabled.",
},
cli.StringFlag{
Name: "bandwidth",
Usage: "Set bandwidth limit in bits per second (K,B,G,T for metric and Ki,Bi,Gi,Ti for IEC units)",
},
cli.UintFlag{
Name: "healthcheck-seconds",
Usage: "health check duration in seconds",
Value: 60,
},
cli.StringFlag{
Name: "path",
Value: "auto",
Usage: "bucket path lookup supported by the server. Valid options are '[on,off,auto]'",
},
}
var adminBucketRemoteEditCmd = cli.Command{
Name: "edit",
Usage: "edit remote target",
Action: mainAdminBucketRemoteEdit,
Before: setGlobalsFromContext,
OnUsageError: onUsageError,
Flags: append(globalFlags, adminBucketRemoteEditFlags...),
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} TARGET http(s)://ACCESSKEY:SECRETKEY@DEST_URL/DEST_BUCKET --arn arn
TARGET:
Also called as alias/sourcebucketname
DEST_BUCKET:
Also called as remote target bucket.
DEST_URL:
Also called as remote endpoint.
ACCESSKEY:
Also called as username.
SECRETKEY:
Also called as password.
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Edit credentials for existing remote target with arn where a remote target has been configured between sourcebucket on sitea to targetbucket on siteb.
{{.DisableHistory}}
{{.Prompt}} {{.HelpName}} sitea/sourcebucket \
https://foobar:newpassword@minio.siteb.example.com/targetbucket \
--arn "arn:minio:replication:us-west-1:993bc6b6-accd-45e3-884f-5f3e652aed2a:dest1"
{{.EnableHistory}}
2. Edit remote target for sourceBucket on sitea with specified ARN to disable proxying and enable synchronous replication
{{.Prompt}} {{.HelpName}} sitea/sourcebucket --sync "enable" --proxy "disable"
--arn "arn:minio:replication:us-west-1:993bc6b6-accd-45e3-884f-5f3e652aed2a:dest1"
`,
}
// checkAdminBucketRemoteEditSyntax - validate all the passed arguments
func checkAdminBucketRemoteEditSyntax(ctx *cli.Context) {
argsNr := len(ctx.Args())
if argsNr > 2 || argsNr == 0 {
showCommandHelpAndExit(ctx, ctx.Command.Name, 1) // last argument is exit code
}
if !ctx.IsSet("arn") {
fatalIf(errInvalidArgument().Trace(ctx.Args()...), "--arn flag needs to be set")
}
}
// modifyRemoteTarget - modifies the dest credentials or updates sync , disable-proxy settings
func modifyRemoteTarget(cli *cli.Context, targets []madmin.BucketTarget) (*madmin.BucketTarget, []madmin.TargetUpdateType) {
args := cli.Args()
foundIdx := -1
arn := cli.String("arn")
for i, t := range targets {
if t.Arn == arn {
foundIdx = i
break
}
}
if foundIdx < 0 {
fatalIf(errInvalidArgument().Trace(args...), "Unable to edit remote target - `"+arn+"` not found")
}
var ops []madmin.TargetUpdateType
bktTarget := targets[foundIdx].Clone()
if cli.IsSet("sync") {
syncState := strings.ToLower(cli.String("sync"))
switch syncState {
case "enable", "disable":
bktTarget.ReplicationSync = syncState == "enable"
ops = append(ops, madmin.SyncUpdateType)
default:
fatalIf(errInvalidArgument().Trace(args...), "--sync can be either [enable|disable]")
}
}
if cli.IsSet("proxy") {
proxyState := strings.ToLower(cli.String("proxy"))
switch proxyState {
case "enable", "disable":
bktTarget.DisableProxy = proxyState == "disable"
ops = append(ops, madmin.ProxyUpdateType)
default:
fatalIf(errInvalidArgument().Trace(args...), "--proxy can be either [enable|disable]")
}
}
if len(args) == 2 {
_, sourceBucket := url2Alias(args[0])
tgtURL := args[1]
accessKey, secretKey, u := extractCredentialURL(tgtURL)
var tgtBucket string
if u.Path != "" {
tgtBucket = path.Clean(u.Path[1:])
}
if e := s3utils.CheckValidBucketName(tgtBucket); e != nil {
fatalIf(probe.NewError(e).Trace(tgtURL), "Invalid target bucket specified")
}
secure := u.Scheme == "https"
host := u.Host
if u.Port() == "" {
port := 80
if secure {
port = 443
}
host = host + ":" + strconv.Itoa(port)
}
console.SetColor(cred, color.New(color.FgYellow, color.Italic))
creds := &madmin.Credentials{AccessKey: accessKey, SecretKey: secretKey}
if tgtBucket != bktTarget.TargetBucket {
fatalIf(errInvalidArgument().Trace(args...), "configured remote target bucket `"+tgtBucket+"` does not match "+bktTarget.TargetBucket+"` for this ARN `"+bktTarget.Arn+"`")
}
if sourceBucket != bktTarget.SourceBucket {
fatalIf(errInvalidArgument().Trace(args...), "configured source bucket `"+sourceBucket+"` does not match "+bktTarget.SourceBucket+"` for this ARN `"+bktTarget.Arn+"`")
}
bktTarget.TargetBucket = tgtBucket
bktTarget.Secure = secure
bktTarget.Credentials = creds
bktTarget.Endpoint = host
ops = append(ops, madmin.CredentialsUpdateType)
}
if cli.IsSet("bandwidth") {
bandwidthStr := cli.String("bandwidth")
bandwidth, err := getBandwidthInBytes(bandwidthStr)
if err != nil {
fatalIf(errInvalidArgument().Trace(bandwidthStr), "Invalid bandwidth number")
}
bktTarget.BandwidthLimit = int64(bandwidth)
ops = append(ops, madmin.BandwidthLimitUpdateType)
}
if cli.IsSet("healthcheck-seconds") {
bktTarget.HealthCheckDuration = time.Duration(cli.Uint("healthcheck-seconds")) * time.Second
ops = append(ops, madmin.HealthCheckDurationUpdateType)
}
if cli.IsSet("path") {
bktTarget.Path = cli.String("path")
ops = append(ops, madmin.PathUpdateType)
}
return &bktTarget, ops
Flags: globalFlags,
HideHelp: true,
}
// mainAdminBucketRemoteEdit is the handle for "mc admin bucket remote edit" command.
func mainAdminBucketRemoteEdit(ctx *cli.Context) error {
checkAdminBucketRemoteEditSyntax(ctx)
console.SetColor("RemoteMessage", color.New(color.FgGreen))
// Get the alias parameter from cli
args := ctx.Args()
aliasedURL := args.Get(0)
// Create a new MinIO Admin Client
client, cerr := newAdminClient(aliasedURL)
fatalIf(cerr, "Unable to initialize admin connection.")
_, sourceBucket := url2Alias(args[0])
targets, e := client.ListRemoteTargets(globalContext, sourceBucket, "")
fatalIf(probe.NewError(e).Trace(args...), "Unable to fetch remote target.")
bktTarget, ops := modifyRemoteTarget(ctx, targets)
arn, e := client.UpdateRemoteTarget(globalContext, bktTarget, ops...)
if e != nil {
fatalIf(probe.NewError(e).Trace(args...), "Unable to update remote target `"+bktTarget.Endpoint+"` from `"+bktTarget.SourceBucket+"` -> `"+bktTarget.TargetBucket+"`")
}
printMsg(RemoteMessage{
op: ctx.Command.Name,
TargetURL: bktTarget.URL().String(),
TargetBucket: bktTarget.TargetBucket,
AccessKey: bktTarget.Credentials.AccessKey,
SourceBucket: bktTarget.SourceBucket,
RemoteARN: arn,
})
func mainAdminBucketRemoteEdit(_ *cli.Context) error {
deprecatedError("mc replicate update")
return nil
}
-164
View File
@@ -1,164 +0,0 @@
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
import (
"fmt"
"path/filepath"
"github.com/fatih/color"
"github.com/minio/cli"
"github.com/minio/madmin-go"
"github.com/minio/mc/pkg/probe"
"github.com/minio/pkg/console"
)
var adminBucketRemoteListFlags = []cli.Flag{
cli.StringFlag{
Name: "service",
Usage: "type of service. valid options are '[replication]'",
},
}
var adminBucketRemoteListCmd = cli.Command{
Name: "ls",
Usage: "list remote target ARN(s)",
Action: mainAdminBucketRemoteList,
OnUsageError: onUsageError,
Before: setGlobalsFromContext,
Flags: append(globalFlags, adminBucketRemoteListFlags...),
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} TARGET
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Get remote bucket target for replication on MinIO server for bucket 'srcbucket'.
{{.Prompt}} {{.HelpName}} myminio/srcbucket --service "replication"
2. List all remote bucket target(s) on MinIO server for bucket 'srcbucket'.
{{.Prompt}} {{.HelpName}} myminio/srcbucket
3. List all remote bucket target(s) on MinIO tenant.
{{.Prompt}} {{.HelpName}} myminio
`,
}
// checkAdminBucketRemoteListSyntax - validate all the passed arguments
func checkAdminBucketRemoteListSyntax(ctx *cli.Context) {
if len(ctx.Args()) != 1 {
showCommandHelpAndExit(ctx, ctx.Command.Name, 1) // last argument is exit code
}
}
// mainAdminBucketRemoteList is the handle for "mc admin bucket remote list" command.
func mainAdminBucketRemoteList(ctx *cli.Context) error {
checkAdminBucketRemoteListSyntax(ctx)
// Additional command specific theme customization.
console.SetColor("RemoteListMessage", color.New(color.Bold, color.FgHiGreen))
console.SetColor("RemoteListEmpty", color.New(color.FgYellow))
console.SetColor("SourceBucket", color.New(color.FgYellow))
console.SetColor("TargetBucket", color.New(color.FgYellow))
console.SetColor("TargetURL", color.New(color.FgHiWhite))
console.SetColor("ARN", color.New(color.FgCyan))
console.SetColor("Arrow", color.New(color.FgHiWhite))
console.SetColor("SyncLabel", color.New(color.FgHiYellow))
console.SetColor("ProxyLabel", color.New(color.FgHiYellow))
// Get the alias parameter from cli
args := ctx.Args()
aliasedURL := args.Get(0)
aliasedURL = filepath.Clean(aliasedURL)
_, sourceBucket := url2Alias(aliasedURL)
// Create a new MinIO Admin Client
client, err := newAdminClient(aliasedURL)
fatalIf(err, "Unable to initialize admin connection.")
targets, e := client.ListRemoteTargets(globalContext, sourceBucket, ctx.String("service"))
fatalIf(probe.NewError(e).Trace(args...), "Unable to list remote target")
printRemotes(ctx, aliasedURL, targets)
return nil
}
func printRemotes(ctx *cli.Context, urlStr string, targets []madmin.BucketTarget) {
maxURLLen := 10
maxTgtLen := 6
maxSrcLen := 6
maxArnLen := 3
if !globalJSON {
if len(targets) == 0 {
console.Print(console.Colorize("RemoteListEmpty", fmt.Sprintf("No remote targets found for `%s`. \n", urlStr)))
return
}
for _, t := range targets {
l := len(t.Endpoint)
if l > maxURLLen {
maxURLLen = l
}
if len(t.TargetBucket) > maxTgtLen {
maxTgtLen = len(t.TargetBucket)
}
if len(t.SourceBucket) > maxSrcLen {
maxSrcLen = len(t.SourceBucket)
}
if len(t.Arn) > maxArnLen {
maxArnLen = len(t.Arn)
}
}
if maxURLLen > 0 {
console.Println(console.Colorize("RemoteListMessage", fmt.Sprintf("%-*.*s %-*.*s->%-*.*s %-*.*s %s %s", maxURLLen+8, maxURLLen+8, "Remote URL", maxSrcLen, maxSrcLen, "Source", maxTgtLen, maxTgtLen, "Target", maxArnLen, maxArnLen, "ARN", "SYNC", "PROXY")))
}
}
for _, target := range targets {
targetURL := target.URL().String()
if !globalJSON {
if maxURLLen > 0 {
targetURL = fmt.Sprintf("%-*.*s", maxURLLen+8, maxURLLen+8, target.URL().String())
}
if maxTgtLen > 0 {
target.TargetBucket = fmt.Sprintf("%-*.*s", maxTgtLen, maxTgtLen, target.TargetBucket)
}
if maxSrcLen > 0 {
target.SourceBucket = fmt.Sprintf("%-*.*s", maxSrcLen, maxSrcLen, target.SourceBucket)
}
if maxArnLen > 0 {
target.Arn = fmt.Sprintf("%-*.*s", maxArnLen, maxArnLen, target.Arn)
}
}
printMsg(RemoteMessage{
op: ctx.Command.Name,
AccessKey: target.Credentials.AccessKey,
TargetBucket: target.TargetBucket,
TargetURL: targetURL,
SourceBucket: target.SourceBucket,
RemoteARN: target.Arn,
ServiceType: string(target.Type),
ReplicationSync: target.ReplicationSync,
Bandwidth: target.BandwidthLimit,
Proxy: !target.DisableProxy,
ResetID: target.ResetID,
ResetBefore: target.ResetBeforeDate,
})
}
}
+1 -3
View File
@@ -1,4 +1,4 @@
// Copyright (c) 2015-2021 MinIO, Inc.
// Copyright (c) 2015-2022 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
@@ -22,9 +22,7 @@ import "github.com/minio/cli"
var adminBucketRemoteSubcommands = []cli.Command{
adminBucketRemoteAddCmd,
adminBucketRemoteEditCmd,
adminBucketRemoteListCmd,
adminBucketRemoteRmCmd,
adminBwInfoCmd,
}
var adminBucketRemoteCmd = cli.Command{
+39
View File
@@ -0,0 +1,39 @@
// Copyright (c) 2015-2022 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
import (
"github.com/minio/cli"
)
var adminBucketRemoteRmCmd = cli.Command{
Name: "remove",
ShortName: "rm",
Usage: "remove configured remote target",
Action: mainAdminBucketRemoteRemove,
OnUsageError: onUsageError,
Before: setGlobalsFromContext,
Flags: globalFlags,
HideHelp: true,
}
// mainAdminBucketRemoteRemove is the handle for "mc admin bucket remote rm" command.
func mainAdminBucketRemoteRemove(_ *cli.Context) error {
deprecatedError("mc replicate rm")
return nil
}
-93
View File
@@ -1,93 +0,0 @@
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
import (
"github.com/fatih/color"
"github.com/minio/cli"
"github.com/minio/mc/pkg/probe"
"github.com/minio/pkg/console"
)
var adminBucketRemoteRmFlags = []cli.Flag{
cli.StringFlag{
Name: "arn",
Usage: "ARN to be removed",
},
}
var adminBucketRemoteRmCmd = cli.Command{
Name: "rm",
Usage: "remove configured remote target",
Action: mainAdminBucketRemoteRemove,
OnUsageError: onUsageError,
Before: setGlobalsFromContext,
Flags: append(globalFlags, adminBucketRemoteRmFlags...),
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} TARGET
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Remove existing remote target with arn "arn:minio:replication:us-west-1:993bc6b6-accd-45e3-884f-5f3e652aed2a:dest1"
for bucket srcbucket on MinIO server.
{{.Prompt}} {{.HelpName}} myminio/srcbucket --arn "arn:minio:replication:us-west-1:993bc6b6-accd-45e3-884f-5f3e652aed2a:dest1"
`,
}
// checkAdminBucketRemoteRemoveSyntax - validate all the passed arguments
func checkAdminBucketRemoteRemoveSyntax(ctx *cli.Context) {
if len(ctx.Args()) != 1 {
showCommandHelpAndExit(ctx, ctx.Command.Name, 1) // last argument is exit code
}
}
// mainAdminBucketRemoteRemove is the handle for "mc admin bucket remote rm" command.
func mainAdminBucketRemoteRemove(ctx *cli.Context) error {
checkAdminBucketRemoteRemoveSyntax(ctx)
console.SetColor("RemoteMessage", color.New(color.FgGreen))
// Get the alias parameter from cli
args := ctx.Args()
aliasedURL := args.Get(0)
// Create a new MinIO Admin Client
client, cerr := newAdminClient(aliasedURL)
fatalIf(cerr.Trace(aliasedURL), "Unable to initialize admin connection.")
_, sourceBucket := url2Alias(args[0])
if sourceBucket == "" {
fatalIf(errInvalidArgument(), "Source bucket not specified in `"+args[0]+"`.")
}
arn := ctx.String("arn")
if arn == "" {
fatalIf(errInvalidArgument(), "ARN needs to be specified.")
}
fatalIf(probe.NewError(client.RemoveRemoteTarget(globalContext, sourceBucket, arn)).Trace(args...), "Unable to remove remote target")
printMsg(RemoteMessage{
op: ctx.Command.Name,
SourceBucket: sourceBucket,
RemoteARN: arn,
})
return nil
}
+2 -1
View File
@@ -1,4 +1,4 @@
// Copyright (c) 2015-2021 MinIO, Inc.
// Copyright (c) 2015-2022 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
@@ -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.
+17 -12
View File
@@ -21,16 +21,16 @@ import (
"context"
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
"strings"
"time"
"github.com/fatih/color"
"github.com/minio/cli"
json "github.com/minio/colorjson"
"github.com/minio/mc/pkg/probe"
"github.com/minio/pkg/console"
"github.com/minio/pkg/v3/console"
)
var adminClusterBucketExportCmd = cli.Command{
@@ -58,7 +58,7 @@ EXAMPLES:
func checkBucketExportSyntax(ctx *cli.Context) {
if len(ctx.Args()) != 1 {
showCommandHelpAndExit(ctx, "export", 1) // last argument is exit code
showCommandHelpAndExit(ctx, 1) // last argument is exit code
}
}
@@ -83,29 +83,31 @@ func mainClusterBucketExport(ctx *cli.Context) error {
aliasedURL = filepath.ToSlash(aliasedURL)
aliasedURL = filepath.Clean(aliasedURL)
_, bucket := url2Alias(aliasedURL)
r, e := client.ExportBucketMetadata(context.Background(), bucket)
fatalIf(probe.NewError(e).Trace(aliasedURL), "Unable to export bucket metadata.")
if bucket == "" {
bucket = "cluster"
bucket = "bucket"
}
// Create bucket metadata zip file
tmpFile, e := ioutil.TempFile("", fmt.Sprintf("%s-metadata-", bucket))
tmpFile, e := os.CreateTemp("", fmt.Sprintf("%s-%s-metadata-", strings.ReplaceAll(aliasedURL, "/", "-"), bucket))
fatalIf(probe.NewError(e), "Unable to download file data.")
ext := "zip"
// Copy zip content to target download file
_, e = io.Copy(tmpFile, r)
fatalIf(probe.NewError(e), "Unable to download bucket metadata.")
// Close everything
r.Close()
tmpFile.Close()
// We use 4 bytes of the 32 bytes to identify the file.
downloadPath := fmt.Sprintf("%s-metadata.%s", bucket, ext)
downloadPath := fmt.Sprintf("%s-%s-metadata.%s", aliasedURL, bucket, ext)
// Create necessary directories.
dir := filepath.Dir(downloadPath)
if e := os.MkdirAll(dir, 0o755); e != nil {
fatalIf(probe.NewError(e).Trace(dir), "Unable to create download directory")
}
fi, e := os.Stat(downloadPath)
if e == nil && !fi.IsDir() {
e = moveFile(downloadPath, downloadPath+"."+time.Now().Format(dateTimeFormatFilename))
@@ -115,14 +117,17 @@ func mainClusterBucketExport(ctx *cli.Context) error {
fatal(probe.NewError(e), "Unable to download file data")
}
}
fatalIf(probe.NewError(moveFile(tmpFile.Name(), downloadPath)), "Unable to rename downloaded data, file exists at %s", tmpFile.Name())
// Explicitly set permissions to 0o600 and override umask
// to ensure that the file is not world-readable.
e = os.Chmod(downloadPath, 0o600)
fatalIf(probe.NewError(e), "Unable to set file permissions for "+downloadPath)
if !globalJSON {
console.Infof("Bucket metadata successfully downloaded as %s\n", downloadPath)
return nil
}
v := struct {
File string `json:"file"`
Key string `json:"key,omitempty"`
+20 -10
View File
@@ -30,9 +30,9 @@ import (
"github.com/klauspost/compress/zip"
"github.com/minio/cli"
json "github.com/minio/colorjson"
"github.com/minio/madmin-go"
"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{
@@ -54,13 +54,13 @@ FLAGS:
{{end}}
EXAMPLES:
1. Recover bucket metadata for all buckets from previously saved bucket metadata backup.
{{.Prompt}} {{.HelpName}} myminio /backups/cluster-metadata.zip
{{.Prompt}} {{.HelpName}} myminio /backups/myminio-bucket-metadata.zip
`,
}
func checkBucketImportSyntax(ctx *cli.Context) {
if len(ctx.Args()) != 2 {
showCommandHelpAndExit(ctx, "import", 1) // last argument is exit code
showCommandHelpAndExit(ctx, 1) // last argument is exit code
}
}
@@ -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)
@@ -116,7 +117,7 @@ func mainClusterBucketImport(ctx *cli.Context) error {
BucketMetaImportErrs: rpt,
Status: "success",
URL: aliasedURL,
Op: "import",
Op: ctx.Command.Name,
})
return nil
@@ -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))
}
}
@@ -177,14 +180,13 @@ func (i importMetaMsg) String() string {
}
func (i importMetaMsg) JSON() string {
i.Status = "success"
buf := &bytes.Buffer{}
enc := json.NewEncoder(buf)
enc.SetIndent("", " ")
// Disable escaping special chars to display XML tags correctly
enc.SetEscapeHTML(false)
fatalIf(probe.NewError(enc.Encode(i.BucketMetaImportErrs.Buckets)), "Unable to marshal into JSON.")
fatalIf(probe.NewError(enc.Encode(i.Buckets)), "Unable to marshal into JSON.")
return buf.String()
}
@@ -195,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)
@@ -228,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 -6
View File
@@ -21,15 +21,25 @@ import (
"context"
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
"time"
"github.com/fatih/color"
"github.com/minio/cli"
json "github.com/minio/colorjson"
"github.com/minio/mc/pkg/probe"
"github.com/minio/pkg/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,12 +62,15 @@ 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
`,
}
func checkIAMExportSyntax(ctx *cli.Context) {
if len(ctx.Args()) != 1 {
showCommandHelpAndExit(ctx, "export", 1) // last argument is exit code
showCommandHelpAndExit(ctx, 1) // last argument is exit code
}
}
@@ -68,7 +81,9 @@ func mainClusterIAMExport(ctx *cli.Context) error {
// Get the alias parameter from cli
args := ctx.Args()
aliasedURL := args.Get(0)
aliasedURL := filepath.ToSlash(args.Get(0))
aliasedURL = filepath.Clean(aliasedURL)
console.SetColor("File", color.New(color.FgWhite, color.Bold))
// Create a new MinIO Admin Client
@@ -82,7 +97,7 @@ func mainClusterIAMExport(ctx *cli.Context) error {
fatalIf(probe.NewError(e).Trace(aliasedURL), "Unable to export IAM info.")
// Create iam info zip file
tmpFile, e := ioutil.TempFile("", fmt.Sprintf("%s-iam-info", aliasedURL))
tmpFile, e := os.CreateTemp("", fmt.Sprintf("%s-iam-info", aliasedURL))
fatalIf(probe.NewError(e), "Unable to download file data.")
ext := "zip"
@@ -95,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))
@@ -107,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
+138 -8
View File
@@ -22,11 +22,15 @@ import (
"fmt"
"io"
"os"
"path/filepath"
"strings"
"github.com/klauspost/compress/zip"
"github.com/minio/cli"
json "github.com/minio/colorjson"
"github.com/minio/madmin-go/v3"
"github.com/minio/mc/pkg/probe"
"github.com/minio/pkg/console"
"github.com/minio/pkg/v3/console"
)
var adminClusterIAMImportCmd = cli.Command{
@@ -53,9 +57,126 @@ 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, "import", 1) // last argument is exit code
showCommandHelpAndExit(ctx, 1) // last argument is exit code
}
}
@@ -66,7 +187,9 @@ func mainClusterIAMImport(ctx *cli.Context) error {
// Get the alias parameter from cli
args := ctx.Args()
aliasedURL := args.Get(0)
aliasedURL := filepath.ToSlash(args.Get(0))
aliasedURL = filepath.Clean(aliasedURL)
var r io.Reader
var sz int64
f, e := os.Open(args.Get(1))
@@ -84,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)
@@ -92,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
}
+6 -6
View File
@@ -1,4 +1,4 @@
// Copyright (c) 2015-2021 MinIO, Inc.
// Copyright (c) 2015-2022 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
@@ -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{
@@ -67,7 +67,7 @@ func (u configExportMessage) String() string {
bio := bufio.NewReader(bytes.NewReader(u.Value))
var lines []string
for {
s, err := bio.ReadString('\n')
s, e := bio.ReadString('\n')
// Make lines displaying environment variables bold.
if strings.HasPrefix(s, "# MINIO_") {
s = strings.TrimPrefix(s, "# ")
@@ -77,10 +77,10 @@ func (u configExportMessage) String() string {
} else {
lines = append(lines, s)
}
if err == io.EOF {
if e == io.EOF {
break
}
fatalIf(probe.NewError(err), "Unable to marshal to string.")
fatalIf(probe.NewError(e), "Unable to marshal to string.")
}
return strings.Join(lines, "")
}
@@ -97,7 +97,7 @@ func (u configExportMessage) JSON() string {
// checkAdminConfigExportSyntax - validate all the passed arguments
func checkAdminConfigExportSyntax(ctx *cli.Context) {
if !ctx.Args().Present() || len(ctx.Args()) > 1 {
showCommandHelpAndExit(ctx, "export", 1) // last argument is exit code
showCommandHelpAndExit(ctx, 1) // last argument is exit code
}
}
+7 -7
View File
@@ -1,4 +1,4 @@
// Copyright (c) 2015-2021 MinIO, Inc.
// Copyright (c) 2015-2022 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
@@ -27,9 +27,9 @@ import (
"github.com/fatih/color"
"github.com/minio/cli"
json "github.com/minio/colorjson"
"github.com/minio/madmin-go"
"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{
@@ -77,7 +77,7 @@ func (u configGetMessage) String() string {
bio := bufio.NewReader(bytes.NewReader(u.value))
var lines []string
for {
s, err := bio.ReadString('\n')
s, e := bio.ReadString('\n')
// Make lines displaying environment variables bold.
if strings.HasPrefix(s, "# MINIO_") {
s = strings.TrimPrefix(s, "# ")
@@ -87,10 +87,10 @@ func (u configGetMessage) String() string {
} else {
lines = append(lines, s)
}
if err == io.EOF {
if e == io.EOF {
break
}
fatalIf(probe.NewError(err), "Unable to marshal to string.")
fatalIf(probe.NewError(e), "Unable to marshal to string.")
}
return strings.Join(lines, "")
}
@@ -111,7 +111,7 @@ func (u configGetMessage) JSON() string {
// checkAdminConfigGetSyntax - validate all the passed arguments
func checkAdminConfigGetSyntax(ctx *cli.Context) {
if !ctx.Args().Present() || len(ctx.Args()) < 1 {
showCommandHelpAndExit(ctx, "get", 1) // last argument is exit code
showCommandHelpAndExit(ctx, 1) // last argument is exit code
}
}
+2 -2
View File
@@ -1,4 +1,4 @@
// Copyright (c) 2015-2021 MinIO, Inc.
// Copyright (c) 2015-2022 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
@@ -24,7 +24,7 @@ import (
"github.com/fatih/color"
json "github.com/minio/colorjson"
"github.com/minio/madmin-go"
"github.com/minio/madmin-go/v3"
"github.com/minio/mc/pkg/probe"
)
+4 -4
View File
@@ -1,4 +1,4 @@
// Copyright (c) 2015-2021 MinIO, Inc.
// Copyright (c) 2015-2022 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
@@ -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{
@@ -109,7 +109,7 @@ func (u configHistoryMessage) JSON() string {
// checkAdminConfigHistorySyntax - validate all the passed arguments
func checkAdminConfigHistorySyntax(ctx *cli.Context) {
if !ctx.Args().Present() || len(ctx.Args()) > 1 {
showCommandHelpAndExit(ctx, "history", 1) // last argument is exit code
showCommandHelpAndExit(ctx, 1) // last argument is exit code
}
}
@@ -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
+3 -3
View File
@@ -1,4 +1,4 @@
// Copyright (c) 2015-2021 MinIO, Inc.
// Copyright (c) 2015-2022 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
@@ -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{
@@ -78,7 +78,7 @@ func (u configImportMessage) JSON() string {
// checkAdminConfigImportSyntax - validate all the passed arguments
func checkAdminConfigImportSyntax(ctx *cli.Context) {
if !ctx.Args().Present() || len(ctx.Args()) > 1 {
showCommandHelpAndExit(ctx, "import", 1) // last argument is exit code
showCommandHelpAndExit(ctx, 1) // last argument is exit code
}
}
+10 -8
View File
@@ -1,4 +1,4 @@
// Copyright (c) 2015-2021 MinIO, Inc.
// Copyright (c) 2015-2022 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
@@ -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{
@@ -65,17 +65,18 @@ EXAMPLES:
type configResetMessage struct {
Status string `json:"status"`
targetAlias string
key string
restart bool
}
// String colorized service status message.
func (u configResetMessage) String() (msg string) {
msg += console.Colorize("ResetConfigSuccess",
"Key is successfully reset.\n")
suggestion := fmt.Sprintf("mc admin service restart %s", u.targetAlias)
fmt.Sprintf("'%s' is successfully reset.", u.key))
if u.restart {
suggestion := fmt.Sprintf("mc admin service restart %s", u.targetAlias)
msg += console.Colorize("ResetConfigSuccess",
fmt.Sprintf("Please restart your server with `%s`.\n", suggestion))
fmt.Sprintf("\nPlease restart your server with `%s`.", suggestion))
}
return
}
@@ -92,7 +93,7 @@ func (u configResetMessage) JSON() string {
// checkAdminConfigResetSyntax - validate all the passed arguments
func checkAdminConfigResetSyntax(ctx *cli.Context) {
if !ctx.Args().Present() {
showCommandHelpAndExit(ctx, "reset", 1) // last argument is exit code
showCommandHelpAndExit(ctx, 1) // last argument is exit code
}
}
@@ -115,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
@@ -144,6 +145,7 @@ func mainAdminConfigReset(ctx *cli.Context) error {
printMsg(configResetMessage{
targetAlias: aliasedURL,
restart: restart,
key: input,
})
return nil
+3 -3
View File
@@ -1,4 +1,4 @@
// Copyright (c) 2015-2021 MinIO, Inc.
// Copyright (c) 2015-2022 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
@@ -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{
@@ -77,7 +77,7 @@ func (u configRestoreMessage) JSON() string {
// checkAdminConfigRestoreSyntax - validate all the passed arguments
func checkAdminConfigRestoreSyntax(ctx *cli.Context) {
if !ctx.Args().Present() || len(ctx.Args()) > 2 {
showCommandHelpAndExit(ctx, "restore", 1) // last argument is exit code
showCommandHelpAndExit(ctx, 1) // last argument is exit code
}
}
+6 -6
View File
@@ -1,4 +1,4 @@
// Copyright (c) 2015-2021 MinIO, Inc.
// Copyright (c) 2015-2022 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
@@ -24,9 +24,9 @@ import (
"github.com/fatih/color"
"github.com/minio/cli"
json "github.com/minio/colorjson"
"github.com/minio/madmin-go"
"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{
@@ -88,7 +88,7 @@ func (u configSetMessage) JSON() string {
// checkAdminConfigSetSyntax - validate all the passed arguments
func checkAdminConfigSetSyntax(ctx *cli.Context) {
if !ctx.Args().Present() && len(ctx.Args()) < 1 {
showCommandHelpAndExit(ctx, "set", 1) // last argument is exit code
showCommandHelpAndExit(ctx, 1) // last argument is exit code
}
}
@@ -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
+1 -1
View File
@@ -1,4 +1,4 @@
// Copyright (c) 2015-2021 MinIO, Inc.
// Copyright (c) 2015-2022 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
+4 -6
View File
@@ -1,4 +1,4 @@
// Copyright (c) 2015-2021 MinIO, Inc.
// Copyright (c) 2015-2022 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
@@ -22,7 +22,6 @@ import (
"strings"
"github.com/minio/cli"
"github.com/minio/pkg/console"
)
var adminConsoleFlags = []cli.Flag{
@@ -47,12 +46,12 @@ var adminConsoleCmd = cli.Command{
Flags: append(adminConsoleFlags, globalFlags...),
Hidden: true,
HideHelpCommand: true,
CustomHelpTemplate: "This command is not supported now and replaced by 'support logs show' command. Please use 'mc support logs show'.\n",
CustomHelpTemplate: "This command is not supported now and replaced by 'admin logs' command. Please use 'mc admin logs'.\n",
}
// mainAdminConsole - the entry function of console command
func mainAdminConsole(ctx *cli.Context) error {
newCmd := []string{"mc support logs show"}
newCmd := []string{"mc admin logs"}
var flgStr string
@@ -67,7 +66,6 @@ func mainAdminConsole(ctx *cli.Context) error {
}
newCmd = append(newCmd, ctx.Args()...)
msg := fmt.Sprintf("Please use '%s'", strings.Join(newCmd, " "))
console.Infoln(msg)
deprecatedError(strings.Join(newCmd, " "))
return nil
}
+4 -4
View File
@@ -23,9 +23,9 @@ import (
humanize "github.com/dustin/go-humanize"
"github.com/fatih/color"
"github.com/minio/cli"
"github.com/minio/madmin-go"
"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{
@@ -48,7 +48,7 @@ EXAMPLES:
1. Cancel an ongoing decommissioning of a pool.
{{.Prompt}} {{.HelpName}} myminio/ http://server{5...8}/disk{1...4}
2. List all ongoing decommissioning of pools.
2. Cancel all ongoing decommissioning of pools.
{{.Prompt}} {{.HelpName}} myminio/
`,
}
@@ -56,7 +56,7 @@ EXAMPLES:
// checkAdminDecommissionCancelSyntax - validate all the passed arguments
func checkAdminDecommissionCancelSyntax(ctx *cli.Context) {
if len(ctx.Args()) > 2 || len(ctx.Args()) == 0 {
showCommandHelpAndExit(ctx, ctx.Command.Name, 1) // last argument is exit code
showCommandHelpAndExit(ctx, 1) // last argument is exit code
}
}
+3 -3
View File
@@ -1,4 +1,4 @@
// Copyright (c) 2015-2021 MinIO, Inc.
// Copyright (c) 2015-2022 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
@@ -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{
@@ -52,7 +52,7 @@ EXAMPLES:
// checkAdminDecommissionStartSyntax - validate all the passed arguments
func checkAdminDecommissionStartSyntax(ctx *cli.Context) {
if len(ctx.Args()) != 2 {
showCommandHelpAndExit(ctx, ctx.Command.Name, 1) // last argument is exit code
showCommandHelpAndExit(ctx, 1) // last argument is exit code
}
}
+15 -10
View File
@@ -1,4 +1,4 @@
// Copyright (c) 2015-2021 MinIO, Inc.
// Copyright (c) 2015-2022 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
@@ -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{
@@ -57,7 +57,7 @@ EXAMPLES:
// checkAdminDecommissionStatusSyntax - validate all the passed arguments
func checkAdminDecommissionStatusSyntax(ctx *cli.Context) {
if len(ctx.Args()) > 2 || len(ctx.Args()) == 0 {
showCommandHelpAndExit(ctx, ctx.Command.Name, 1) // last argument is exit code
showCommandHelpAndExit(ctx, 1) // last argument is exit code
}
}
@@ -96,10 +96,10 @@ func mainAdminDecommissionStatus(ctx *cli.Context) error {
usedStart := (poolStatus.Decommission.TotalSize - poolStatus.Decommission.StartSize)
usedCurrent := (poolStatus.Decommission.TotalSize - poolStatus.Decommission.CurrentSize)
if usedStart > usedCurrent {
duration := uint64(time.Since(poolStatus.Decommission.StartTime).Seconds())
duration := float64(time.Since(poolStatus.Decommission.StartTime)) / float64(time.Second)
if usedStart > usedCurrent && duration > 10 {
copied := uint64(usedStart - usedCurrent)
speed := copied / duration
speed := uint64(float64(copied) / duration)
msg = "Decommissioning rate at " + humanize.IBytes(speed) + "/sec " + "[" + humanize.IBytes(
uint64(usedCurrent)) + "/" + humanize.IBytes(uint64(poolStatus.Decommission.TotalSize)) + "]"
msg += "\nStarted: " + humanize.RelTime(time.Now().UTC(), poolStatus.Decommission.StartTime, "", "ago")
@@ -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 {
+1 -1
View File
@@ -1,4 +1,4 @@
// Copyright (c) 2015-2021 MinIO, Inc.
// Copyright (c) 2015-2022 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
+11 -7
View File
@@ -1,4 +1,4 @@
// Copyright (c) 2015-2021 MinIO, Inc.
// Copyright (c) 2015-2022 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
@@ -24,9 +24,9 @@ import (
"github.com/fatih/color"
"github.com/minio/cli"
json "github.com/minio/colorjson"
"github.com/minio/madmin-go"
"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{
@@ -48,13 +48,17 @@ FLAGS:
EXAMPLES:
1. Add users 'fivecent' and 'tencent' to the group 'allcents':
{{.Prompt}} {{.HelpName}} myminio allcents fivecent tencent
2. Add user "james" to group "staff", then add the "readwrite" policy to the group "staff".
{{.Prompt}} {{.HelpName}} myminio staff james
{{.Prompt}} mc admin policy attach myminio readwrite --group staff
`,
}
// checkAdminGroupAddSyntax - validate all the passed arguments
func checkAdminGroupAddSyntax(ctx *cli.Context) {
if len(ctx.Args()) < 3 {
showCommandHelpAndExit(ctx, "add", 1) // last argument is exit code
showCommandHelpAndExit(ctx, 1) // last argument is exit code
}
}
@@ -82,8 +86,8 @@ func (u groupMessage) String() string {
case "enable":
return console.Colorize("GroupMessage", "Enabled group `"+u.GroupName+"` successfully.")
case "add":
membersStr := fmt.Sprintf("{%s}", strings.Join(u.Members, ","))
return console.Colorize("GroupMessage", "Added members "+membersStr+" to group "+u.GroupName+" successfully.")
membersStr := fmt.Sprintf("`%s`", strings.Join(u.Members, ","))
return console.Colorize("GroupMessage", "Added members "+membersStr+" to group `"+u.GroupName+"` successfully.")
case "remove":
if len(u.Members) > 0 {
membersStr := fmt.Sprintf("{%s}", strings.Join(u.Members, ","))
@@ -136,7 +140,7 @@ func mainAdminGroupAdd(ctx *cli.Context) error {
fatalIf(probe.NewError(client.UpdateGroupMembers(globalContext, gAddRemove)).Trace(args...), "Unable to add new group")
printMsg(groupMessage{
op: "add",
op: ctx.Command.Name,
GroupName: args.Get(1),
Members: members,
})
+1 -1
View File
@@ -1,4 +1,4 @@
// Copyright (c) 2015-2021 MinIO, Inc.
// Copyright (c) 2015-2022 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
+4 -4
View File
@@ -1,4 +1,4 @@
// Copyright (c) 2015-2021 MinIO, Inc.
// Copyright (c) 2015-2022 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
@@ -20,9 +20,9 @@ package cmd
import (
"github.com/fatih/color"
"github.com/minio/cli"
"github.com/minio/madmin-go"
"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{
@@ -50,7 +50,7 @@ EXAMPLES:
// checkAdminGroupEnableSyntax - validate all the passed arguments
func checkAdminGroupEnableSyntax(ctx *cli.Context) {
if len(ctx.Args()) != 2 {
showCommandHelpAndExit(ctx, ctx.Command.Name, 1) // last argument is exit code
showCommandHelpAndExit(ctx, 1) // last argument is exit code
}
}
+4 -4
View File
@@ -1,4 +1,4 @@
// Copyright (c) 2015-2021 MinIO, Inc.
// Copyright (c) 2015-2022 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
@@ -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{
@@ -49,7 +49,7 @@ EXAMPLES:
// checkAdminGroupInfoSyntax - validate all the passed arguments
func checkAdminGroupInfoSyntax(ctx *cli.Context) {
if len(ctx.Args()) != 2 {
showCommandHelpAndExit(ctx, "info", 1) // last argument is exit code
showCommandHelpAndExit(ctx, 1) // last argument is exit code
}
}
@@ -72,7 +72,7 @@ func mainAdminGroupInfo(ctx *cli.Context) error {
fatalIf(probe.NewError(e).Trace(args...), "Unable to fetch group info")
printMsg(groupMessage{
op: "info",
op: ctx.Command.Name,
GroupName: group,
GroupStatus: gd.Status,
GroupPolicy: gd.Policy,
+5 -4
View File
@@ -1,4 +1,4 @@
// Copyright (c) 2015-2021 MinIO, Inc.
// Copyright (c) 2015-2022 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
@@ -21,11 +21,12 @@ 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{
Name: "list",
ShortName: "ls",
Usage: "display list of groups",
Action: mainAdminGroupList,
OnUsageError: onUsageError,
@@ -49,7 +50,7 @@ EXAMPLES:
// checkAdminGroupListSyntax - validate all the passed arguments
func checkAdminGroupListSyntax(ctx *cli.Context) {
if len(ctx.Args()) != 1 {
showCommandHelpAndExit(ctx, "list", 1) // last argument is exit code
showCommandHelpAndExit(ctx, 1) // last argument is exit code
}
}
@@ -71,7 +72,7 @@ func mainAdminGroupList(ctx *cli.Context) error {
fatalIf(probe.NewError(e).Trace(args...), "Unable to list groups")
printMsg(groupMessage{
op: "list",
op: ctx.Command.Name,
Groups: gs,
})
+6 -5
View File
@@ -1,4 +1,4 @@
// Copyright (c) 2015-2021 MinIO, Inc.
// Copyright (c) 2015-2022 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
@@ -20,13 +20,14 @@ package cmd
import (
"github.com/fatih/color"
"github.com/minio/cli"
"github.com/minio/madmin-go"
"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{
Name: "remove",
ShortName: "rm",
Usage: "remove group or members from a group",
Action: mainAdminGroupRemove,
OnUsageError: onUsageError,
@@ -53,7 +54,7 @@ EXAMPLES:
// checkAdminGroupRemoveSyntax - validate all the passed arguments
func checkAdminGroupRemoveSyntax(ctx *cli.Context) {
if len(ctx.Args()) < 2 {
showCommandHelpAndExit(ctx, "remove", 1) // last argument is exit code
showCommandHelpAndExit(ctx, 1) // last argument is exit code
}
}
@@ -85,7 +86,7 @@ func mainAdminGroupRemove(ctx *cli.Context) error {
fatalIf(probe.NewError(e).Trace(args...), "Could not perform remove operation")
printMsg(groupMessage{
op: "remove",
op: ctx.Command.Name,
GroupName: args.Get(1),
Members: members,
})
+1 -1
View File
@@ -1,4 +1,4 @@
// Copyright (c) 2015-2021 MinIO, Inc.
// Copyright (c) 2015-2022 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
+56 -6
View File
@@ -1,4 +1,4 @@
// Copyright (c) 2015-2021 MinIO, Inc.
// Copyright (c) 2015-2022 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
@@ -18,9 +18,10 @@
package cmd
import (
"errors"
"fmt"
"github.com/minio/madmin-go"
"github.com/minio/madmin-go/v3"
)
type hri struct {
@@ -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
}
+36 -26
View File
@@ -1,4 +1,4 @@
// Copyright (c) 2015-2021 MinIO, Inc.
// Copyright (c) 2015-2022 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
@@ -27,9 +27,9 @@ import (
humanize "github.com/dustin/go-humanize"
"github.com/fatih/color"
json "github.com/minio/colorjson"
"github.com/minio/madmin-go"
"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, "**"))
@@ -226,7 +235,7 @@ func (ui *uiData) printItemsQuietly(s *madmin.HealTaskStatus) (err error) {
return nil
}
func (ui *uiData) printStatsQuietly(s *madmin.HealTaskStatus) {
func (ui *uiData) printStatsQuietly() {
totalObjects, totalSize, totalTime := ui.getProgress()
healedStr := fmt.Sprintf("Healed:\t%s/%s objects; %s in %s\n",
@@ -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()
@@ -291,14 +304,14 @@ func (ui *uiData) printItemsJSON(s *madmin.HealTaskStatus) (err error) {
for _, item := range s.Items {
h := newHRI(&item)
jsonBytes, err := json.MarshalIndent(makeHR(h), "", " ")
fatalIf(probe.NewError(err), "Unable to marshal to JSON.")
jsonBytes, e := json.MarshalIndent(makeHR(h), "", " ")
fatalIf(probe.NewError(e), "Unable to marshal to JSON.")
console.Println(string(jsonBytes))
}
return nil
}
func (ui *uiData) printStatsJSON(s *madmin.HealTaskStatus) {
func (ui *uiData) printStatsJSON(_ *madmin.HealTaskStatus) {
var summary struct {
Status string `json:"status"`
Error string `json:"error,omitempty"`
@@ -321,8 +334,8 @@ func (ui *uiData) printStatsJSON(s *madmin.HealTaskStatus) {
summary.Size = ui.BytesScanned
summary.ElapsedTime = int64(ui.HealDuration.Round(time.Second).Seconds())
jBytes, err := json.MarshalIndent(summary, "", " ")
fatalIf(probe.NewError(err), "Unable to marshal to JSON.")
jBytes, e := json.MarshalIndent(summary, "", " ")
fatalIf(probe.NewError(e), "Unable to marshal to JSON.")
console.Println(string(jBytes))
}
@@ -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,16 +432,14 @@ 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 {
ui.printStatsJSON(&res)
} else if globalQuiet {
ui.printStatsQuietly(&res)
ui.printStatsQuietly()
}
return res, nil
}
+265 -160
View File
@@ -1,4 +1,4 @@
// Copyright (c) 2015-2021 MinIO, Inc.
// Copyright (c) 2015-2024 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
@@ -18,20 +18,23 @@
package cmd
import (
"bufio"
"fmt"
"math"
"net/url"
"os"
"path/filepath"
"sort"
"strings"
"time"
humanize "github.com/dustin/go-humanize"
"github.com/dustin/go-humanize"
"github.com/fatih/color"
"github.com/minio/cli"
json "github.com/minio/colorjson"
"github.com/minio/madmin-go"
"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,
@@ -104,14 +133,14 @@ EXAMPLES:
func checkAdminHealSyntax(ctx *cli.Context) {
if len(ctx.Args()) != 1 {
showCommandHelpAndExit(ctx, "heal", 1) // last argument is exit code
showCommandHelpAndExit(ctx, 1) // last argument is exit code
}
// Check for scan argument
scanArg := ctx.String("scan")
scanArg = strings.ToLower(scanArg)
if scanArg != scanNormalMode && scanArg != scanDeepMode {
showCommandHelpAndExit(ctx, "heal", 1) // last argument is exit code
showCommandHelpAndExit(ctx, 1) // last argument is exit code
}
}
@@ -143,34 +172,27 @@ type poolInfo struct {
endpoints []string
}
type diskInfo struct {
set setIndex
path string
state string
healStarted, healLastUpdate time.Time
usedSpace, totalSpace uint64
}
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
}
type serverInfo struct {
pool int
disks []diskInfo
disks []madmin.Disk
}
func (s serverInfo) onlineDisksForSet(index setIndex) (setFound bool, count int) {
for _, disk := range s.disks {
if disk.set != index {
if disk.PoolIndex != index.pool || disk.SetIndex != index.set {
continue
}
setFound = true
if disk.state == "ok" && disk.healStarted.IsZero() {
if disk.State == "ok" && !disk.Healing {
count++
}
}
@@ -210,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
}
@@ -225,8 +247,8 @@ func generateSetsStatus(disks []madmin.Disk) map[setIndex]setInfo {
func generateServersStatus(disks []madmin.Disk) map[string]serverInfo {
m := make(map[string]serverInfo)
for _, d := range disks {
u, err := url.Parse(d.Endpoint)
if err != nil {
u, e := url.Parse(d.Endpoint)
if e != nil {
continue
}
endpoint := u.Host
@@ -239,21 +261,7 @@ func generateServersStatus(disks []madmin.Disk) map[string]serverInfo {
pool: d.PoolIndex,
}
}
setIndex := setIndex{pool: d.PoolIndex, set: d.SetIndex}
di := diskInfo{
set: setIndex,
path: u.Path,
state: d.State,
usedSpace: d.UsedSpace,
totalSpace: d.TotalSpace,
}
if d.HealInfo != nil {
di.healStarted = d.HealInfo.Started
di.healLastUpdate = d.HealInfo.LastUpdate
}
serverSt.disks = append(serverSt.disks, di)
serverSt.disks = append(serverSt.disks, d)
m[endpoint] = serverSt
}
return m
@@ -333,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:"-"`
}
@@ -377,47 +387,73 @@ func (s verboseBackgroundHealStatusMessage) String() string {
_, ok := offlineEndpoints[endpoint]
if ok {
stateText := console.Colorize("NodeFailed", "OFFLINE")
fmt.Fprintf(&msg, fmt.Sprintf(" %s: %s\n", endpoint, stateText))
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, fmt.Sprintf(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, fmt.Sprintf(serverHeader, endpoint))
hdr := " %s:\n"
fmt.Fprintf(&serverHeader, hdr, endpoint)
}
for _, d := range serverStatus.disks {
if d.set.pool != pool {
if d.PoolIndex != pool {
continue
}
stateText := ""
switch {
case d.state == "ok" && !d.healStarted.IsZero():
case d.State == "ok" && d.Healing:
stateText = console.Colorize("DiskHealing", "HEALING")
case d.state == "ok":
case d.State == "ok":
if !s.allDrives {
continue
}
stateText = console.Colorize("DiskOK", "OK")
default:
stateText = console.Colorize("DiskFailed", d.state)
stateText = console.Colorize("DiskFailed", d.State)
}
fmt.Fprintf(&msg, " + %s : %s\n", d.path, stateText)
if !d.healStarted.IsZero() {
now := time.Now().UTC()
scanSpeed := float64(d.usedSpace) / float64(now.Sub(d.healStarted))
remainingTime := time.Duration(float64(setsStatus[d.set].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[d.set].incapableDisks)
fmt.Fprintf(&msg, " |__ Tolerance: %d drive(s)\n", parity-thisSet.incapableDisks)
}
}
fmt.Fprintf(&msg, "\n")
if serverHeaderPrinted {
fmt.Fprintf(&msg, "\n")
}
}
}
@@ -438,11 +474,11 @@ func (s verboseBackgroundHealStatusMessage) String() string {
summary := shortBackgroundHealStatusMessage{HealInfo: s.HealInfo}
fmt.Fprintf(&msg, "\n")
fmt.Fprintf(&msg, "Summary:\n")
fmt.Fprintf(&msg, "=======\n")
fmt.Fprintf(&msg, summary.String())
fmt.Fprintf(&msg, "\n")
fmt.Fprint(&msg, "\n")
fmt.Fprint(&msg, "Summary:\n")
fmt.Fprint(&msg, "=======\n")
fmt.Fprint(&msg, summary.String())
fmt.Fprint(&msg, "\n")
return msg.String()
}
@@ -465,86 +501,133 @@ type shortBackgroundHealStatusMessage struct {
func (s shortBackgroundHealStatusMessage) String() string {
healPrettyMsg := ""
var (
totalItems uint64
totalBytes uint64
itemsHealed uint64
bytesHealed uint64
startedAt time.Time
itemsHealed uint64
bytesHealed uint64
itemsFailed uint64
bytesFailed uint64
itemsHealedPerSec float64
bytesHealedPerSec float64
startedAt time.Time
setsExceedsStd int
setsExceedsReduced int
// The addition of Elapsed time of each parallel healing operation
// this is needed to calculate the rate of healing
accumulatedElapsedTime time.Duration
// ETA of healing - it is the latest ETA of all drives currently healing
healingRemaining time.Duration
)
dedup := make(map[setIndex]struct{})
var problematicDisks int
leastPct := 100.0
for _, set := range s.HealInfo.Sets {
setsStatus := generateSetsStatus(set.Disks)
// Furthest along disk...
var furthestHealingDisk *madmin.Disk
missingInSet := 0
for _, disk := range set.Disks {
if disk.HealInfo != nil {
// Avoid counting two disks beloning to the same pool/set
diskSet := setIndex{pool: disk.PoolIndex, set: disk.SetIndex}
_, found := dedup[diskSet]
if found {
// Ignore disk with non 'ok' status
if disk.State != madmin.DriveStateOk {
if disk.State != madmin.DriveStateUnformatted {
missingInSet++
problematicDisks++
}
continue
}
if disk.HealInfo != nil && !disk.HealInfo.Finished {
missingInSet++
thisSet := setsStatus[setIndex{pool: disk.PoolIndex, set: disk.SetIndex}]
refUsedSpace := uint64(math.MaxUint64)
if thisSet.readyDisksCount > 0 {
refUsedSpace = thisSet.readyDisksUsedSpace / uint64(thisSet.readyDisksCount)
}
if refUsedSpace < disk.UsedSpace {
refUsedSpace = disk.UsedSpace
}
if refUsedSpace > 0 {
if pct := float64(disk.UsedSpace) / float64(refUsedSpace); pct < leastPct {
leastPct = pct
}
} else {
// Unlikely to have max used space in an erasure set to be zero, but still set this to zero
leastPct = 0
}
disk := disk
if furthestHealingDisk == nil {
furthestHealingDisk = &disk
continue
}
dedup[diskSet] = struct{}{}
// Approximate values
totalItems += disk.HealInfo.ObjectsTotalCount
totalBytes += disk.HealInfo.ObjectsTotalSize
itemsHealed += disk.HealInfo.ItemsHealed
bytesHealed += disk.HealInfo.BytesDone
if !disk.HealInfo.Started.IsZero() {
if !disk.HealInfo.Started.Before(startedAt) {
startedAt = disk.HealInfo.Started
}
if !disk.HealInfo.LastUpdate.IsZero() {
accumulatedElapsedTime += disk.HealInfo.LastUpdate.Sub(disk.HealInfo.Started)
}
scanSpeed := float64(disk.UsedSpace) / float64(time.Now().Sub(disk.HealInfo.Started))
remainingTime := time.Duration(float64(setsStatus[diskSet].maxUsedSpace-disk.UsedSpace) / scanSpeed)
if remainingTime > healingRemaining {
healingRemaining = remainingTime
}
if disk.HealInfo.ItemsHealed+disk.HealInfo.ItemsFailed > furthestHealingDisk.HealInfo.ItemsHealed+furthestHealingDisk.HealInfo.ItemsFailed {
furthestHealingDisk = &disk
continue
}
}
}
if furthestHealingDisk != nil {
disk := furthestHealingDisk
// Approximate values
itemsHealed += disk.HealInfo.ItemsHealed
bytesHealed += disk.HealInfo.BytesDone
bytesFailed += disk.HealInfo.BytesFailed
itemsFailed += disk.HealInfo.ItemsFailed
if !disk.HealInfo.Started.IsZero() {
if !disk.HealInfo.Started.Before(startedAt) {
startedAt = disk.HealInfo.Started
}
if !disk.HealInfo.LastUpdate.IsZero() {
accumulatedElapsedTime += disk.HealInfo.LastUpdate.Sub(disk.HealInfo.Started)
}
bytesHealedPerSec += float64(time.Second) * float64(disk.HealInfo.BytesDone) / float64(disk.HealInfo.LastUpdate.Sub(disk.HealInfo.Started))
itemsHealedPerSec += float64(time.Second) * float64(disk.HealInfo.ItemsHealed+disk.HealInfo.ItemsFailed) / float64(disk.HealInfo.LastUpdate.Sub(disk.HealInfo.Started))
}
if n, ok := s.HealInfo.SCParity["STANDARD"]; ok && missingInSet > n {
setsExceedsStd++
}
if n, ok := s.HealInfo.SCParity["REDUCED_REDUNDANCY"]; ok && missingInSet > n {
setsExceedsReduced++
}
}
}
if startedAt.IsZero() && itemsHealed == 0 {
healPrettyMsg += "No active healing in progress."
healPrettyMsg += "No active healing is detected for new disks"
if problematicDisks > 0 {
healPrettyMsg += fmt.Sprintf(", though %d offline disk(s) found.", problematicDisks)
} else {
healPrettyMsg += "."
}
return healPrettyMsg
}
if totalItems > 0 && totalBytes > 0 {
// Objects healed information
itemsPct := 100 * float64(itemsHealed) / float64(totalItems)
bytesPct := 100 * float64(bytesHealed) / float64(totalBytes)
healPrettyMsg += fmt.Sprintf("Objects Healed: %s/%s (%s), %s/%s (%s)\n",
humanize.Comma(int64(itemsHealed)), humanize.Comma(int64(totalItems)), humanize.CommafWithDigits(itemsPct, 1)+"%%",
humanize.Bytes(bytesHealed), humanize.Bytes(totalBytes), humanize.CommafWithDigits(bytesPct, 1)+"%%")
} else {
healPrettyMsg += fmt.Sprintf("Objects Healed: %s, %s\n", humanize.Comma(int64(itemsHealed)), humanize.Bytes(bytesHealed))
}
// Objects healed information
healPrettyMsg += fmt.Sprintf("Objects Healed: %s, %s (%s)\n",
humanize.Comma(int64(itemsHealed)), humanize.IBytes(bytesHealed), humanize.CommafWithDigits(leastPct*100, 1)+"%")
healPrettyMsg += fmt.Sprintf("Objects Failed: %s\n", humanize.Comma(int64(itemsFailed)))
if accumulatedElapsedTime > 0 {
bytesHealedPerSec := float64(uint64(time.Second)*bytesHealed) / float64(accumulatedElapsedTime)
itemsHealedPerSec := float64(uint64(time.Second)*itemsHealed) / float64(accumulatedElapsedTime)
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)
}
if setsExceedsStd > 0 {
healPrettyMsg += "\n"
healPrettyMsg += fmt.Sprintf("%d of %d sets exceeds standard parity count EC:%d lost/offline disks", setsExceedsStd, len(s.HealInfo.Sets), s.HealInfo.SCParity["STANDARD"])
}
if setsExceedsReduced > 0 {
healPrettyMsg += "\n"
healPrettyMsg += fmt.Sprintf("%d of %d sets exceeds reduced parity count EC:%d lost/offline disks", setsExceedsReduced, len(s.HealInfo.Sets), s.HealInfo.SCParity["REDUCED_REDUNDANCY"])
}
return healPrettyMsg
}
@@ -606,12 +689,13 @@ func mainAdminHeal(ctx *cli.Context) error {
// Return the background heal status when the user
// doesn't pass a bucket or --recursive flag.
if bucket == "" && !ctx.Bool("recursive") {
bgHealStatus, berr := adminClnt.BackgroundHealStatus(globalContext)
fatalIf(probe.NewError(berr), "Failed to get the status of the background heal.")
bgHealStatus, e := adminClnt.BackgroundHealStatus(globalContext)
fatalIf(probe.NewError(e), "Unable to get background heal status.")
if ctx.Bool("verbose") {
printMsg(verboseBackgroundHealStatusMessage{
Status: "success",
HealInfo: bgHealStatus,
allDrives: ctx.Bool("all-drives"),
ToleranceForSC: strings.ToUpper(ctx.String("storage-class")),
})
} else {
@@ -623,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"),
@@ -638,17 +715,45 @@ 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 {
_, _, herr := adminClnt.Heal(globalContext, bucket, prefix, opts, "", forceStart, forceStop)
fatalIf(probe.NewError(herr), "Failed to stop heal sequence.")
_, _, e := adminClnt.Heal(globalContext, bucket, prefix, opts, "", forceStart, forceStop)
fatalIf(probe.NewError(e), "Unable to stop healing.")
printMsg(stopHealMessage{Status: "success", Alias: aliasedURL})
return nil
}
healStart, _, herr := adminClnt.Heal(globalContext, bucket, prefix, opts, "", forceStart, false)
fatalIf(probe.NewError(herr), "Failed to start heal sequence.")
if opts.Recursive && opts.Pool == nil && opts.Set == nil && isTerminal() && !ctx.Bool("force") {
fmt.Printf("You are about to scan and heal the whole namespace in all pools and sets, please confirm [y/N]: ")
answer, e := bufio.NewReader(os.Stdin).ReadString('\n')
fatalIf(probe.NewError(e), "Unable to parse user input.")
if answer = strings.TrimSpace(strings.ToLower(answer)); answer != "y" && answer != "yes" {
fmt.Println("Heal aborted!")
return nil
}
}
healStart, _, e := adminClnt.Heal(globalContext, bucket, prefix, opts, "", forceStart, false)
fatalIf(probe.NewError(e), "Unable to start healing.")
ui := uiData{
Bucket: bucket,
-139
View File
@@ -1,139 +0,0 @@
// Copyright (c) 2015-2022 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
import (
"errors"
"fmt"
"strings"
"github.com/charmbracelet/lipgloss"
"github.com/minio/cli"
json "github.com/minio/colorjson"
"github.com/minio/madmin-go"
"github.com/minio/mc/pkg/probe"
)
var adminIDPInfoCmd = cli.Command{
Name: "info",
Usage: "Show IDP server config info",
Before: setGlobalsFromContext,
Action: mainAdminIDPGet,
OnUsageError: onUsageError,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} TARGET ID_TYPE [CFG_NAME]
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Show configuration info for default (un-named) openid configuration.
{{.Prompt}} {{.HelpName}} play/ openid
2. Show configuration info for openid configuration named "dex_test".
{{.Prompt}} {{.HelpName}} play/ openid dex_test
`,
}
func mainAdminIDPGet(ctx *cli.Context) error {
if len(ctx.Args()) < 2 || len(ctx.Args()) > 3 {
showCommandHelpAndExit(ctx, "get", 1)
}
args := ctx.Args()
aliasedURL := args.Get(0)
// Create a new MinIO Admin Client
client, err := newAdminClient(aliasedURL)
fatalIf(err, "Unable to initialize admin connection.")
idpType := args.Get(1)
if idpType != "openid" {
fatalIf(probe.NewError(errors.New("not implemented")), "This feature is not yet available")
}
var cfgName string
if len(args) == 3 {
cfgName = args.Get(2)
}
result, e := client.GetIDPConfig(globalContext, idpType, cfgName)
fatalIf(probe.NewError(e), "Unable to get IDP config for '%s' to server", idpType)
// Print set config result
printMsg(idpConfig(result))
return nil
}
type idpConfig madmin.IDPConfig
func (i idpConfig) JSON() string {
bs, e := json.MarshalIndent(i, "", " ")
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
return string(bs)
}
func (i idpConfig) String() string {
// Determine required width for key column.
fieldColWidth := 0
for _, kv := range i.Info {
if fieldColWidth < len(kv.Key) {
fieldColWidth = len(kv.Key)
}
}
// Add 1 for the colon-suffix in each entry.
fieldColWidth++
fieldColStyle := lipgloss.NewStyle().
Width(fieldColWidth).
Foreground(lipgloss.Color("#04B575")). // green
Bold(true).
Align(lipgloss.Right)
valueColStyle := lipgloss.NewStyle().
PaddingLeft(1).
Align(lipgloss.Left)
envMarkStyle := lipgloss.NewStyle().
Foreground(lipgloss.Color("201")). // pinkish-red
PaddingLeft(1)
var lines []string
for _, kv := range i.Info {
envStr := ""
if kv.IsCfg && kv.IsEnv {
envStr = " (environment)"
}
lines = append(lines, fmt.Sprintf("%s%s%s",
fieldColStyle.Render(kv.Key+":"),
valueColStyle.Render(kv.Value),
envMarkStyle.Render(envStr),
))
}
boxContent := strings.Join(lines, "\n")
boxStyle := lipgloss.NewStyle().
BorderStyle(lipgloss.RoundedBorder())
return boxStyle.Render(boxContent)
}
-171
View File
@@ -1,171 +0,0 @@
// Copyright (c) 2015-2022 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
import (
"encoding/json"
"errors"
"strings"
"github.com/charmbracelet/lipgloss"
"github.com/minio/cli"
"github.com/minio/madmin-go"
"github.com/minio/mc/pkg/probe"
)
var adminIDPLsCmd = cli.Command{
Name: "ls",
Usage: "List IDP configurations",
Before: setGlobalsFromContext,
Action: mainAdminIDPList,
OnUsageError: onUsageError,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} TARGET ID_TYPE
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. List the available openid configurations.
{{.Prompt}} {{.HelpName}} play/ openid
`,
}
func mainAdminIDPList(ctx *cli.Context) error {
if len(ctx.Args()) != 2 {
showCommandHelpAndExit(ctx, "ls", 1)
}
args := ctx.Args()
aliasedURL := args.Get(0)
// Create a new MinIO Admin Client
client, err := newAdminClient(aliasedURL)
fatalIf(err, "Unable to initialize admin connection.")
idpType := args.Get(1)
if idpType != "openid" {
fatalIf(probe.NewError(errors.New("not implemented")), "This feature is not yet available")
}
result, e := client.ListIDPConfig(globalContext, idpType)
fatalIf(probe.NewError(e), "Unable to list IDP config for '%s'", idpType)
printMsg(idpCfgList(result))
return nil
}
type idpCfgList []madmin.IDPListItem
func (i idpCfgList) JSON() string {
bs, e := json.MarshalIndent(i, "", " ")
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
return string(bs)
}
func (i idpCfgList) String() string {
maxNameWidth := len("Name")
maxRoleARNWidth := len("RoleArn")
for _, item := range i {
name := item.Name
if name == "_" {
name = "(default)" // for the un-named config, don't show `_`
}
if maxNameWidth < len(name) {
maxNameWidth = len(name)
}
if maxRoleARNWidth < len(item.RoleARN) {
maxRoleARNWidth = len(item.RoleARN)
}
}
enabledWidth := 5
// Add 2 for padding
maxNameWidth += 2
maxRoleARNWidth += 2
enabledColStyle := lipgloss.NewStyle().
Align(lipgloss.Center).
PaddingLeft(1).
PaddingRight(1).
Width(enabledWidth)
nameColStyle := lipgloss.NewStyle().
Align(lipgloss.Right).
PaddingLeft(1).
PaddingRight(1).
Width(maxNameWidth)
arnColStyle := lipgloss.NewStyle().
Align(lipgloss.Left).
PaddingLeft(1).
PaddingRight(1).
Foreground(lipgloss.Color("#04B575")). // green
Width(maxRoleARNWidth)
styles := []lipgloss.Style{enabledColStyle, nameColStyle, arnColStyle}
headers := []string{"On?", "Name", "RoleARN"}
headerRow := []string{}
// Override some style settings for the header
for ii, hdr := range headers {
headerRow = append(headerRow,
styles[ii].Copy().
Bold(true).
Foreground(lipgloss.Color("#6495ed")). // green
Align(lipgloss.Center).
Render(hdr),
)
}
lines := []string{strings.Join(headerRow, "")}
enabledOff := "🔴"
enabledOn := "🟢"
for _, item := range i {
enabled := enabledOff
if item.Enabled {
enabled = enabledOn
}
line := []string{
styles[0].Render(enabled),
styles[1].Render(item.Name),
styles[2].Render(item.RoleARN),
}
if item.Name == "_" {
// For default config, don't display `_` and make it look faint.
line[1] = styles[1].Copy().
Faint(true).
Render("(default)")
}
lines = append(lines, strings.Join(line, ""))
}
boxContent := strings.Join(lines, "\n")
boxStyle := lipgloss.NewStyle().
BorderStyle(lipgloss.RoundedBorder())
return boxStyle.Render(boxContent)
}
-102
View File
@@ -1,102 +0,0 @@
// Copyright (c) 2015-2022 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
import (
"errors"
"strings"
"github.com/minio/cli"
"github.com/minio/mc/pkg/probe"
)
var adminIDPSetCmd = cli.Command{
Name: "set",
Usage: "Create/Update an IDP server configuration",
Before: setGlobalsFromContext,
Action: mainAdminIDPSet,
OnUsageError: onUsageError,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} TARGET ID_TYPE [CFG_NAME] [CFG_PARAMS...]
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Create/Update the default OpenID IDP configuration (CFG_NAME is omitted).
{{.Prompt}} {{.HelpName}} play/ openid \
client_id=minio-client-app \
client_secret=minio-client-app-secret \
config_url="http://localhost:5556/dex/.well-known/openid-configuration" \
scopes="openid,groups" \
redirect_uri="http://127.0.0.1:10000/oauth_callback" \
role_policy="consoleAdmin"
2. Create/Update configuration for OpenID IDP configuration named "dex_test".
{{.Prompt}} {{.HelpName}} play/ openid dex_test \
client_id=minio-client-app \
client_secret=minio-client-app-secret \
config_url="http://localhost:5556/dex/.well-known/openid-configuration" \
scopes="openid,groups" \
redirect_uri="http://127.0.0.1:10000/oauth_callback" \
role_policy="consoleAdmin"
`,
}
func mainAdminIDPSet(ctx *cli.Context) error {
if len(ctx.Args()) < 3 {
showCommandHelpAndExit(ctx, "set", 1)
}
args := ctx.Args()
aliasedURL := args.Get(0)
// Create a new MinIO Admin Client
client, err := newAdminClient(aliasedURL)
fatalIf(err, "Unable to initialize admin connection.")
idpType := args.Get(1)
if idpType != "openid" {
fatalIf(probe.NewError(errors.New("not implemented")), "This feature is not yet available")
}
var cfgName string
input := args[2:]
if !strings.Contains(args.Get(2), "=") {
cfgName = args.Get(2)
input = args[3:]
}
inputCfg := strings.Join(input, " ")
restart, e := client.SetIDPConfig(globalContext, idpType, cfgName, inputCfg)
fatalIf(probe.NewError(e), "Unable to set IDP config for '%s' to server", idpType)
// Print set config result
printMsg(configSetMessage{
targetAlias: aliasedURL,
restart: restart,
})
return nil
}
+7 -10
View File
@@ -19,24 +19,21 @@ package cmd
import "github.com/minio/cli"
var adminIDPSubcommands = []cli.Command{
adminIDPSetCmd,
adminIDPInfoCmd,
adminIDPLsCmd,
adminIDPRmCmd,
}
var adminIDPCmd = cli.Command{
Name: "idp",
Usage: "manage MinIO IDentity Provider server configuration",
Action: mainAdminIDP,
Before: setGlobalsFromContext,
Flags: globalFlags,
Subcommands: adminIDPSubcommands,
HideHelpCommand: true,
Hidden: true,
CustomHelpTemplate: `This command's functionality has moved and this command is DEPRECATED.
Please use commands under 'mc idp ldap|openid' instead.
`,
}
func mainAdminIDP(ctx *cli.Context) error {
commandNotFound(ctx, adminIDPSubcommands)
func mainAdminIDP(_ *cli.Context) error {
deprecatedError("mc idp ldap|openid")
return nil
}
+122 -66
View File
@@ -1,4 +1,4 @@
// Copyright (c) 2015-2021 MinIO, Inc.
// Copyright (c) 2015-2024 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
@@ -25,24 +25,31 @@ import (
"strings"
"time"
humanize "github.com/dustin/go-humanize"
"github.com/dustin/go-humanize"
"github.com/dustin/go-humanize/english"
"github.com/fatih/color"
"github.com/minio/cli"
json "github.com/minio/colorjson"
"github.com/minio/madmin-go"
"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,10 +66,13 @@ EXAMPLES:
}
type poolSummary struct {
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
@@ -72,32 +82,40 @@ 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{
index: disk.PoolIndex,
endpoints: set.NewStringSet(),
driveTolerance: info.StandardParity(),
}
}
pool.endpoints.Add(srv.Endpoint)
for _, disk := range srv.Disks {
if disk.SetIndex > pool.setsCount {
pool.setsCount = disk.SetIndex
}
if disk.DiskIndex > pool.drivesPerSet {
pool.drivesPerSet = disk.DiskIndex
}
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
}
}
// We calculated max set index and max disk index
// increase by one to show the number of sets and drives
for _, pool := range summary {
pool.setsCount++
pool.drivesPerSet++
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
}
@@ -116,35 +134,24 @@ 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
var totalOnlineDrivesCluster int
var totalOfflineDrivesCluster int
var totalOfflineNodes int
// Color palette initialization
console.SetColor("Info", color.New(color.FgGreen, color.Bold))
@@ -166,12 +173,12 @@ func (u clusterStruct) String() (msg string) {
// Loop through each server and put together info for each one
for _, srv := range u.Info.Servers {
// Check if MinIO server is offline ("Mode" field),
// If offline, error out
if srv.State == "offline" {
// Check if MinIO server is not online ("Mode" field),
if srv.State != string(madmin.ItemOnline) {
totalOfflineNodes++
// "PrintB" is color blue in console library package
msg += fmt.Sprintf("%s %s\n", console.Colorize("InfoFail", dot), console.Colorize("PrintB", srv.Endpoint))
msg += fmt.Sprintf(" Uptime: %s\n", console.Colorize("InfoFail", "offline"))
msg += fmt.Sprintf(" Uptime: %s\n", console.Colorize("InfoFail", srv.State))
if backendType == madmin.Erasure {
// Info about drives on a server, only available for non-FS types
@@ -188,8 +195,6 @@ func (u clusterStruct) String() (msg string) {
}
totalDrivesPerServer := OnDrives + OffDrives
totalOnlineDrivesCluster += OnDrives
totalOfflineDrivesCluster += OffDrives
dispNoOfDrives = strconv.Itoa(OnDrives) + "/" + strconv.Itoa(totalDrivesPerServer)
msg += fmt.Sprintf(" Drives: %s %s\n", dispNoOfDrives, console.Colorize("InfoFail", "OK "))
@@ -201,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))
@@ -210,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)
@@ -246,8 +255,6 @@ func (u clusterStruct) String() (msg string) {
}
totalDrivesPerServer := OnDrives + OffDrives
totalOnlineDrivesCluster += OnDrives
totalOfflineDrivesCluster += OffDrives
clr := "Info"
if OnDrives != totalDrivesPerServer {
clr = "InfoWarning"
@@ -267,15 +274,60 @@ func (u clusterStruct) String() (msg string) {
}
if backendType == madmin.Erasure {
msg += fmt.Sprintf("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)
@@ -286,21 +338,21 @@ func (u clusterStruct) String() (msg string) {
if u.Info.Versions.Count > 0 {
msg += ", " + english.Plural(int(u.Info.Versions.Count), "Version", "")
}
if u.Info.DeleteMarkers.Count > 0 {
msg += ", " + english.Plural(int(u.Info.DeleteMarkers.Count), "Delete Marker", "")
}
msg += "\n"
}
if backendType == madmin.Erasure {
if totalOfflineNodes != 0 {
msg += fmt.Sprintf("%s offline, ", english.Plural(totalOfflineNodes, "node", ""))
}
// Summary on total no of online and total
// number of offline drives at the Cluster level
bkInfo, ok := u.Info.Backend.(madmin.ErasureBackend)
if ok {
msg += fmt.Sprintf("%s online, %s offline\n",
english.Plural(bkInfo.OnlineDisks, "drive", ""),
english.Plural(bkInfo.OfflineDisks, "drive", ""))
} else {
msg += fmt.Sprintf("%s online, %s offline\n",
english.Plural(totalOnlineDrivesCluster, "drive", ""),
english.Plural(totalOfflineDrivesCluster, "drive", ""))
}
msg += fmt.Sprintf("%s online, %s offline, EC:%d\n",
english.Plural(u.Info.Backend.OnlineDisks, "drive", ""),
english.Plural(u.Info.Backend.OfflineDisks, "drive", ""),
u.Info.Backend.StandardSCParity)
}
// Remove the last new line if any
@@ -320,7 +372,7 @@ func (u clusterStruct) JSON() string {
// checkAdminInfoSyntax - validate arguments passed by a user
func checkAdminInfoSyntax(ctx *cli.Context) {
if len(ctx.Args()) == 0 || len(ctx.Args()) > 1 {
showCommandHelpAndExit(ctx, "info", 1) // last argument is exit code
showCommandHelpAndExit(ctx, 1) // last argument is exit code
}
}
@@ -335,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 {
@@ -345,6 +400,7 @@ func mainAdminInfo(ctx *cli.Context) error {
clusterInfo.Status = "success"
clusterInfo.Error = ""
}
clusterInfo.Info = admInfo
printMsg(clusterInfo)
+3 -4
View File
@@ -1,4 +1,4 @@
// Copyright (c) 2015-2021 MinIO, Inc.
// Copyright (c) 2015-2022 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
@@ -19,7 +19,6 @@ package cmd
import (
"github.com/minio/cli"
"github.com/minio/pkg/console"
)
var adminInspectCmd = cli.Command{
@@ -34,7 +33,7 @@ var adminInspectCmd = cli.Command{
}
// mainAdminHeal - the entry function of heal command
func mainAdminInspect(ctx *cli.Context) error {
console.Infoln("Please use 'mc support inspect'")
func mainAdminInspect(_ *cli.Context) error {
deprecatedError("mc support inspect")
return nil
}
+6 -6
View File
@@ -1,4 +1,4 @@
// Copyright (c) 2015-2021 MinIO, Inc.
// Copyright (c) 2015-2022 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
@@ -24,13 +24,13 @@ import (
"github.com/fatih/color"
"github.com/minio/cli"
"github.com/minio/mc/pkg/probe"
"github.com/minio/pkg/console"
"golang.org/x/crypto/ssh/terminal"
"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,
@@ -53,7 +53,7 @@ EXAMPLES:
// adminKMSCreateKeyCmd is the handler for the "mc admin kms key create" command.
func mainAdminKMSCreateKey(ctx *cli.Context) error {
if len(ctx.Args()) != 2 {
showCommandHelpAndExit(ctx, "create", 1) // last argument is exit code
showCommandHelpAndExit(ctx, 1) // last argument is exit code
}
client, err := newAdminClient(ctx.Args().Get(0))
@@ -63,7 +63,7 @@ func mainAdminKMSCreateKey(ctx *cli.Context) error {
e := client.CreateKey(globalContext, keyID)
fatalIf(probe.NewError(e), "Failed to create master key")
if terminal.IsTerminal(int(os.Stdout.Fd())) {
if term.IsTerminal(int(os.Stdout.Fd())) {
console.Println(color.GreenString(fmt.Sprintf("Created master key `%s` successfully", keyID)))
}
return nil
+116
View File
@@ -0,0 +1,116 @@
// Copyright (c) 2015-2023 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
import (
"fmt"
"os"
"github.com/fatih/color"
"github.com/jedib0t/go-pretty/v6/table"
"github.com/jedib0t/go-pretty/v6/text"
"github.com/minio/cli"
json "github.com/minio/colorjson"
"github.com/minio/mc/pkg/probe"
"github.com/minio/pkg/v3/console"
)
var adminKMSKeyListCmd = cli.Command{
Name: "list",
Usage: "request list of KMS master keys",
Action: mainAdminKMSKeyList,
OnUsageError: onUsageError,
Before: setGlobalsFromContext,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} TARGET
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Get list of master keys from a MinIO server/cluster.
$ {{.HelpName}} play
`,
}
// adminKMSKeyCmd is the handle for the "mc admin kms key" command.
func mainAdminKMSKeyList(ctx *cli.Context) error {
if len(ctx.Args()) == 0 || len(ctx.Args()) > 1 {
showCommandHelpAndExit(ctx, 1) // last argument is exit code
}
console.SetColor("KeyName", color.New(color.FgBlue))
// Get the alias parameter from cli
args := ctx.Args()
aliasedURL := args.Get(0)
// Create a new MinIO Admin Client
client, err := newAdminClient(aliasedURL)
fatalIf(err, "Unable to initialize admin connection.")
keys, e := client.ListKeys(globalContext, "*")
fatalIf(probe.NewError(e).Trace(args...), "Unable to list KMS keys")
var rows []table.Row
kmsKeys := []string{}
for idx, k := range keys {
rows = append(rows, table.Row{idx + 1, k.Name})
kmsKeys = append(kmsKeys, k.Name)
}
if globalJSON {
printMsg(kmsKeysMsg{
Status: "success",
Target: aliasedURL,
Keys: kmsKeys,
})
return nil
}
t := table.NewWriter()
t.SetOutputMirror(os.Stdout)
t.SetColumnConfigs([]table.ColumnConfig{{Align: text.AlignCenter}})
t.SetTitle("KMS Keys")
t.AppendHeader(table.Row{"S N", "Name"})
t.AppendRows(rows)
t.SetStyle(table.StyleLight)
t.Render()
return nil
}
type kmsKeysMsg struct {
Status string `json:"status"`
Target string `json:"target"`
Keys []string `json:"keys"`
}
func (k kmsKeysMsg) JSON() string {
kmsBytes, e := json.MarshalIndent(k, "", " ")
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
return string(kmsBytes)
}
func (k kmsKeysMsg) String() string {
return fmt.Sprintf("Keys: %s\n", k.Keys)
}
+22 -19
View File
@@ -1,4 +1,4 @@
// Copyright (c) 2015-2021 MinIO, Inc.
// Copyright (c) 2015-2022 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
@@ -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{
@@ -54,11 +54,12 @@ EXAMPLES:
// adminKMSKeyCmd is the handle for the "mc admin kms key" command.
func mainAdminKMSKeyStatus(ctx *cli.Context) error {
if len(ctx.Args()) == 0 || len(ctx.Args()) > 2 {
showCommandHelpAndExit(ctx, "status", 1) // last argument is exit code
showCommandHelpAndExit(ctx, 1) // last argument is exit code
}
console.SetColor("StatusSuccess", color.New(color.FgGreen, color.Bold))
console.SetColor("StatusError", color.New(color.FgRed, color.Bold))
console.SetColor("StatusUnknown", color.New(color.FgYellow, color.Bold))
client, err := newAdminClient(ctx.Args().Get(0))
fatalIf(err, "Unable to get a configured admin connection.")
@@ -72,8 +73,6 @@ func mainAdminKMSKeyStatus(ctx *cli.Context) error {
printMsg(kmsKeyStatusMsg{
KeyID: status.KeyID,
Encryption: status.EncryptionErr == "",
Decryption: status.DecryptionErr == "",
EncryptionErr: status.EncryptionErr,
DecryptionErr: status.DecryptionErr,
})
@@ -82,8 +81,6 @@ func mainAdminKMSKeyStatus(ctx *cli.Context) error {
type kmsKeyStatusMsg struct {
KeyID string `json:"keyId"`
Encryption bool `json:"encryption"`
Decryption bool `json:"decryption"`
EncryptionErr string `json:"encryptionError,omitempty"`
DecryptionErr string `json:"decryptionError,omitempty"`
Status string `json:"status"`
@@ -91,9 +88,6 @@ type kmsKeyStatusMsg struct {
func (s kmsKeyStatusMsg) JSON() string {
s.Status = "success"
if !s.Encryption && !s.Decryption {
s.Status = "error"
}
kmsBytes, e := json.MarshalIndent(s, "", " ")
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
@@ -102,16 +96,25 @@ func (s kmsKeyStatusMsg) JSON() string {
func (s kmsKeyStatusMsg) String() string {
msg := fmt.Sprintf("Key: %s\n", s.KeyID)
if s.Encryption {
msg += " - Encryption " + console.Colorize("StatusSuccess", "✔") + "\n"
} else {
msg += fmt.Sprintf(" - Encryption %s (%s)\n", console.Colorize("StatusError", "✗"), s.EncryptionErr)
success := console.Colorize("StatusSuccess", "✔")
failure := console.Colorize("StatusError", "✗")
dunno := console.Colorize("StatusUnknown", "?")
formatStatus := func(name string, unknown bool, err string) string {
st := ""
switch {
case !unknown && err == "":
st = success
case unknown:
st = dunno
case err != "":
st = fmt.Sprintf("%s (%s)", failure, err)
}
return fmt.Sprintf(" - %s %s\n", name, st)
}
if s.Decryption {
msg += " - Decryption " + console.Colorize("StatusSuccess", "✔") + "\n"
} else {
msg += fmt.Sprintf(" - Decryption %s (%s)\n", console.Colorize("StatusError", "✗"), s.DecryptionErr)
}
msg += formatStatus("Encryption", false, s.EncryptionErr)
msg += formatStatus("Decryption", s.EncryptionErr != "", s.DecryptionErr)
return msg
}
+2 -1
View File
@@ -1,4 +1,4 @@
// Copyright (c) 2015-2021 MinIO, Inc.
// Copyright (c) 2015-2022 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
@@ -22,6 +22,7 @@ import "github.com/minio/cli"
var adminKMSKeySubcommands = []cli.Command{
adminKMSCreateKeyCmd,
adminKMSKeyStatusCmd,
adminKMSKeyListCmd,
}
var adminKMSKeyCmd = cli.Command{
+1 -1
View File
@@ -1,4 +1,4 @@
// Copyright (c) 2015-2021 MinIO, Inc.
// Copyright (c) 2015-2022 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
+22 -26
View File
@@ -26,9 +26,9 @@ import (
"github.com/fatih/color"
"github.com/minio/cli"
json "github.com/minio/colorjson"
"github.com/minio/madmin-go"
"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"
@@ -46,11 +46,11 @@ var logsShowFlags = []cli.Flag{
},
}
var supportLogsShowCmd = cli.Command{
Name: "show",
var adminLogsCmd = cli.Command{
Name: "logs",
Usage: "show MinIO logs",
Action: mainLogsShowConsole,
OnUsageError: onUsageError,
Action: mainAdminLogs,
Before: setGlobalsFromContext,
Flags: append(logsShowFlags, globalFlags...),
HideHelpCommand: true,
@@ -62,18 +62,18 @@ FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Show logs for a MinIO server with alias 'play'
{{.Prompt}} {{.HelpName}} play
1. Show logs for a MinIO server with alias 'myminio'
{{.Prompt}} {{.HelpName}} myminio
2. Show last 5 log entries for node 'node1' for a MinIO server with alias 'myminio'
{{.Prompt}} {{.HelpName}} --last 5 myminio node1
3. Show application errors in logs for a MinIO server with alias 'play'
{{.Prompt}} {{.HelpName}} --type application play
3. Show application errors in logs for a MinIO server with alias 'myminio'
{{.Prompt}} {{.HelpName}} --type application myminio
`,
}
func checkLogsShowSyntax(ctx *cli.Context) {
if len(ctx.Args()) == 0 || len(ctx.Args()) > 3 {
showCommandHelpAndExit(ctx, "show", 1) // last argument is exit code
showCommandHelpAndExit(ctx, 1) // last argument is exit code
}
}
@@ -86,15 +86,15 @@ type logMessage struct {
// JSON - jsonify loginfo
func (l logMessage) JSON() string {
l.Status = "success"
logJSON, err := json.MarshalIndent(&l, "", " ")
fatalIf(probe.NewError(err), "Unable to marshal into JSON.")
logJSON, e := json.MarshalIndent(&l, "", " ")
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
return string(logJSON)
}
func getLogTime(lt string) string {
tm, err := time.Parse(time.RFC3339Nano, lt)
if err != nil {
tm, e := time.Parse(time.RFC3339Nano, lt)
if e != nil {
return lt
}
return tm.Format(logTimeFormat)
@@ -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))
@@ -164,8 +158,8 @@ func (l logMessage) String() string {
return fmt.Sprintf("%s\n", logMsg)
}
// mainLogsShowConsole - the entry function of support logs show
func mainLogsShowConsole(ctx *cli.Context) error {
// mainAdminLogs - the entry function of admin logs
func mainAdminLogs(ctx *cli.Context) error {
// Check for command syntax
checkLogsShowSyntax(ctx)
console.SetColor("LogMessage", color.New(color.Bold, color.FgRed))
@@ -209,7 +203,9 @@ func mainLogsShowConsole(ctx *cli.Context) error {
if node != "" {
logInfo.NodeName = ""
}
printMsg(logMessage{LogInfo: logInfo})
if logInfo.DeploymentID != "" {
printMsg(logMessage{LogInfo: logInfo})
}
}
return nil
}
+4 -1
View File
@@ -1,4 +1,4 @@
// Copyright (c) 2015-2021 MinIO, Inc.
// Copyright (c) 2015-2022 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
@@ -54,6 +54,9 @@ var adminCmdSubcommands = []cli.Command{
adminTraceCmd,
adminConsoleCmd,
adminClusterCmd,
adminRebalanceCmd,
adminLogsCmd,
adminAccesskeyCmd,
}
var adminCmd = cli.Command{
+12 -117
View File
@@ -1,4 +1,4 @@
// Copyright (c) 2015-2021 MinIO, Inc.
// Copyright (c) 2015-2022 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
@@ -18,127 +18,22 @@
package cmd
import (
"fmt"
"io/ioutil"
"github.com/fatih/color"
"github.com/minio/cli"
json "github.com/minio/colorjson"
"github.com/minio/madmin-go"
"github.com/minio/mc/pkg/probe"
"github.com/minio/pkg/console"
)
var adminPolicyAddCmd = cli.Command{
Name: "add",
Usage: "add new policy",
Action: mainAdminPolicyAdd,
OnUsageError: onUsageError,
Before: setGlobalsFromContext,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} TARGET POLICYNAME POLICYFILE
POLICYNAME:
Name of the canned policy on MinIO server.
POLICYFILE:
Name of the policy file associated with the policy name.
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Add a new canned policy 'writeonly'.
{{.Prompt}} {{.HelpName}} myminio writeonly /tmp/writeonly.json
`,
Name: "add",
Usage: "add an IAM policy",
Action: mainAdminPolicyAdd,
OnUsageError: onUsageError,
Before: setGlobalsFromContext,
Flags: globalFlags,
HideHelpCommand: true,
Hidden: true,
CustomHelpTemplate: `Please use 'mc admin policy create'`,
}
// checkAdminPolicyAddSyntax - validate all the passed arguments
func checkAdminPolicyAddSyntax(ctx *cli.Context) {
if len(ctx.Args()) != 3 {
showCommandHelpAndExit(ctx, "add", 1) // last argument is exit code
}
}
// userPolicyMessage container for content message structure
type userPolicyMessage struct {
op string
Status string `json:"status"`
Policy string `json:"policy,omitempty"`
PolicyInfo madmin.PolicyInfo `json:"policyInfo,omitempty"`
UserOrGroup string `json:"userOrGroup,omitempty"`
IsGroup bool `json:"isGroup"`
}
func (u userPolicyMessage) accountType() string {
switch u.op {
case "set", "unset", "update":
if u.IsGroup {
return "group"
}
return "user"
}
return ""
}
func (u userPolicyMessage) String() string {
switch u.op {
case "info":
buf, e := json.MarshalIndent(u.PolicyInfo, "", " ")
fatalIf(probe.NewError(e), "Unable to marshal to JSON.")
return string(buf)
case "list":
return console.Colorize("PolicyName", u.Policy)
case "remove":
return console.Colorize("PolicyMessage", "Removed policy `"+u.Policy+"` successfully.")
case "add":
return console.Colorize("PolicyMessage", "Added policy `"+u.Policy+"` successfully.")
case "set", "unset":
return console.Colorize("PolicyMessage",
fmt.Sprintf("Policy `%s` is %s on %s `%s`", u.Policy, u.op, u.accountType(), u.UserOrGroup))
case "update":
return console.Colorize("PolicyMessage",
fmt.Sprintf("Policy `%s` is added to %s `%s`", u.Policy, u.accountType(), u.UserOrGroup))
}
return ""
}
func (u userPolicyMessage) JSON() string {
u.Status = "success"
jsonMessageBytes, e := json.MarshalIndent(u, "", " ")
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
return string(jsonMessageBytes)
}
// mainAdminPolicyAdd is the handle for "mc admin policy add" command.
func mainAdminPolicyAdd(ctx *cli.Context) error {
checkAdminPolicyAddSyntax(ctx)
console.SetColor("PolicyMessage", color.New(color.FgGreen))
// Get the alias parameter from cli
args := ctx.Args()
aliasedURL := args.Get(0)
policy, e := ioutil.ReadFile(args.Get(2))
fatalIf(probe.NewError(e).Trace(args...), "Unable to get policy")
// Create a new MinIO Admin Client
client, err := newAdminClient(aliasedURL)
fatalIf(err, "Unable to initialize admin connection.")
fatalIf(probe.NewError(client.AddCannedPolicy(globalContext, args.Get(1), policy)).Trace(args...), "Unable to add new policy")
printMsg(userPolicyMessage{
op: "add",
Policy: args.Get(1),
})
func mainAdminPolicyAdd(_ *cli.Context) error {
deprecatedError("mc admin policy create")
return nil
}
+131
View File
@@ -0,0 +1,131 @@
// Copyright (c) 2015-2022 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
import (
"github.com/minio/cli"
"github.com/minio/madmin-go/v3"
"github.com/minio/mc/pkg/probe"
)
const (
errCodeChangeAlreadyApplied = "XMinioAdminPolicyChangeAlreadyApplied"
)
var adminAttachPolicyFlags = []cli.Flag{
cli.StringFlag{
Name: "user, u",
Usage: "attach policy to user",
},
cli.StringFlag{
Name: "group, g",
Usage: "attach policy to group",
},
}
var adminPolicyAttachCmd = cli.Command{
Name: "attach",
Usage: "attach an IAM policy to a user or group",
Action: mainAdminPolicyAttach,
OnUsageError: onUsageError,
Before: setGlobalsFromContext,
Flags: append(adminAttachPolicyFlags, globalFlags...),
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} [FLAGS] TARGET POLICY [POLICY...] [--user USER | --group GROUP]
Exactly one of --user or --group is required.
POLICY:
Name of the policy on the MinIO server.
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Attach the "readonly" policy to user "james".
{{.Prompt}} {{.HelpName}} myminio readonly --user james
2. Attach the "audit-policy" and "acct-policy" policies to group "legal".
{{.Prompt}} {{.HelpName}} myminio audit-policy acct-policy --group legal
`,
}
// mainAdminPolicyAttach is the handler for "mc admin policy attach" command.
func mainAdminPolicyAttach(ctx *cli.Context) error {
return userAttachOrDetachPolicy(ctx, true)
}
func userAttachOrDetachPolicy(ctx *cli.Context, attach bool) error {
if len(ctx.Args()) < 2 {
showCommandHelpAndExit(ctx, 1) // last argument is exit code
}
user := ctx.String("user")
group := ctx.String("group")
// Get the alias parameter from cli
args := ctx.Args()
aliasedURL := args.Get(0)
policies := args[1:]
req := madmin.PolicyAssociationReq{
User: user,
Group: group,
Policies: policies,
}
// Create a new MinIO Admin Client
client, err := newAdminClient(aliasedURL)
fatalIf(err, "Unable to initialize admin connection.")
var e error
var res madmin.PolicyAssociationResp
if attach {
res, e = client.AttachPolicy(globalContext, req)
} else {
res, e = client.DetachPolicy(globalContext, req)
}
if e != nil && madmin.ToErrorResponse(e).Code != errCodeChangeAlreadyApplied {
fatalIf(probe.NewError(e), "Unable to make user/group policy association")
}
var emptyResp madmin.PolicyAssociationResp
if res.UpdatedAt.Equal(emptyResp.UpdatedAt) {
// Older minio does not send a result, so we populate res manually to
// simulate a result. TODO(aditya): remove this after newer minio is
// released in a few months (Older API Deprecated in Jun 2023)
if attach {
res.PoliciesAttached = policies
} else {
res.PoliciesDetached = policies
}
}
m := policyAssociationMessage{
attach: attach,
Status: "success",
PoliciesAttached: res.PoliciesAttached,
PoliciesDetached: res.PoliciesDetached,
User: user,
Group: group,
}
printMsg(m)
return nil
}
+144
View File
@@ -0,0 +1,144 @@
// Copyright (c) 2015-2022 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
import (
"fmt"
"os"
"github.com/fatih/color"
"github.com/minio/cli"
json "github.com/minio/colorjson"
"github.com/minio/madmin-go/v3"
"github.com/minio/mc/pkg/probe"
"github.com/minio/pkg/v3/console"
)
var adminPolicyCreateCmd = cli.Command{
Name: "create",
Usage: "create a new IAM policy",
Action: mainAdminPolicyCreate,
OnUsageError: onUsageError,
Before: setGlobalsFromContext,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} TARGET POLICYNAME POLICYFILE
POLICYNAME:
Name of the canned policy on MinIO server.
POLICYFILE:
Name of the policy file associated with the policy name.
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Create a new canned policy 'writeonly'.
{{.Prompt}} {{.HelpName}} myminio writeonly /tmp/writeonly.json
`,
}
// checkAdminPolicyCreateSyntax - validate all the passed arguments
func checkAdminPolicyCreateSyntax(ctx *cli.Context) {
if len(ctx.Args()) != 3 {
showCommandHelpAndExit(ctx, 1) // last argument is exit code
}
}
// userPolicyMessage container for content message structure
type userPolicyMessage struct {
op string
Status string `json:"status"`
Policy string `json:"policy,omitempty"`
PolicyInfo madmin.PolicyInfo `json:"policyInfo,omitempty"`
UserOrGroup string `json:"userOrGroup,omitempty"`
IsGroup bool `json:"isGroup"`
}
func (u userPolicyMessage) accountType() string {
switch u.op {
case "attach", "detach":
if u.IsGroup {
return "group"
}
return "user"
}
return ""
}
func (u userPolicyMessage) String() string {
switch u.op {
case "info":
buf, e := json.MarshalIndent(u.PolicyInfo, "", " ")
fatalIf(probe.NewError(e), "Unable to marshal to JSON.")
return string(buf)
case "list":
return console.Colorize("PolicyName", u.Policy)
case "remove":
return console.Colorize("PolicyMessage", "Removed policy `"+u.Policy+"` successfully.")
case "create":
return console.Colorize("PolicyMessage", "Created policy `"+u.Policy+"` successfully.")
case "detach":
return console.Colorize("PolicyMessage",
fmt.Sprintf("Policy `%s` successfully detached from %s `%s`", u.Policy, u.accountType(), u.UserOrGroup))
case "attach":
return console.Colorize("PolicyMessage",
fmt.Sprintf("Policy `%s` successfully attached to %s `%s`", u.Policy, u.accountType(), u.UserOrGroup))
}
return ""
}
func (u userPolicyMessage) JSON() string {
u.Status = "success"
jsonMessageBytes, e := json.MarshalIndent(u, "", " ")
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
return string(jsonMessageBytes)
}
// mainAdminPolicyCreate is the handle for "mc admin policy create" command.
func mainAdminPolicyCreate(ctx *cli.Context) error {
checkAdminPolicyCreateSyntax(ctx)
console.SetColor("PolicyMessage", color.New(color.FgGreen))
// Get the alias parameter from cli
args := ctx.Args()
aliasedURL := args.Get(0)
policy, e := os.ReadFile(args.Get(2))
fatalIf(probe.NewError(e).Trace(args...), "Unable to get policy")
// Create a new MinIO Admin Client
client, err := newAdminClient(aliasedURL)
fatalIf(err, "Unable to initialize admin connection.")
fatalIf(probe.NewError(client.AddCannedPolicy(globalContext, args.Get(1), policy)).Trace(args...), "Unable to create new policy")
printMsg(userPolicyMessage{
op: ctx.Command.Name,
Policy: args.Get(1),
})
return nil
}
+67
View File
@@ -0,0 +1,67 @@
// Copyright (c) 2015-2022 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
import (
"github.com/minio/cli"
)
var adminDetachPolicyFlags = []cli.Flag{
cli.StringFlag{
Name: "user, u",
Usage: "detach policy from user",
},
cli.StringFlag{
Name: "group, g",
Usage: "detach policy from group",
},
}
var adminPolicyDetachCmd = cli.Command{
Name: "detach",
Usage: "detach an IAM policy from a user or group",
Action: mainAdminPolicyDetach,
OnUsageError: onUsageError,
Before: setGlobalsFromContext,
Flags: append(adminDetachPolicyFlags, globalFlags...),
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} [FLAGS] TARGET POLICY [POLICY...] [--user USER | --group GROUP]
Exactly one of --user or --group is required.
POLICY:
Name of the policy on the MinIO server.
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Detach the "readonly" policy from user "james".
{{.Prompt}} {{.HelpName}} myminio readonly --user james
2. Detach the "audit-policy" and "acct-policy" policies from group "legal".
{{.Prompt}} {{.HelpName}} myminio audit-policy acct-policy --group legal
`,
}
// mainAdmihPolicyDetach is the handler for "mc admin policy detach" command.
func mainAdminPolicyDetach(ctx *cli.Context) error {
return userAttachOrDetachPolicy(ctx, false)
}
+100
View File
@@ -0,0 +1,100 @@
// Copyright (c) 2015-2022 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
import (
"github.com/minio/cli"
"github.com/minio/madmin-go/v3"
"github.com/minio/mc/pkg/probe"
)
var adminPolicyEntitiesFlags = []cli.Flag{
cli.StringSliceFlag{
Name: "user, u",
Usage: "list policies associated with user(s)",
},
cli.StringSliceFlag{
Name: "group, g",
Usage: "list policies associated with group(s)",
},
cli.StringSliceFlag{
Name: "policy, p",
Usage: "list users or groups associated with policy",
},
}
var adminPolicyEntitiesCmd = cli.Command{
Name: "entities",
Usage: "list policy association entities",
Action: mainAdminPolicyEntities,
Before: setGlobalsFromContext,
Flags: append(adminPolicyEntitiesFlags, globalFlags...),
OnUsageError: onUsageError,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} [FLAGS] TARGET
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. List all entities associated with all policies
{{.Prompt}} {{.HelpName}} play/
2. List all entities associated with the policies 'finteam-policy' and 'mlteam-policy'
{{.Prompt}} {{.HelpName}} play/ --policy finteam-policy --policy mlteam-policy
3. List all policies associated with a pair of user entities
{{.Prompt}} {{.HelpName}} play/ --user bob --user james
4. List all policies associated with a pair of group entities
{{.Prompt}} {{.HelpName}} play/ --group auditors --group accounting
5. List all entities associated with a policy, group and user
{{.Prompt}} {{.HelpName}} play/ \
--policy finteam-policy --user bobfisher --group consulting
`,
}
// mainAdminPolicyEntities is the handler for "mc admin policy entities" command.
func mainAdminPolicyEntities(ctx *cli.Context) error {
if len(ctx.Args()) != 1 {
showCommandHelpAndExit(ctx, 1)
}
usersToQuery := ctx.StringSlice("user")
groupsToQuery := ctx.StringSlice("group")
policiesToQuery := ctx.StringSlice("policy")
args := ctx.Args()
aliasedURL := args.Get(0)
// Create a new MinIO Admin Client
client, err := newAdminClient(aliasedURL)
fatalIf(err, "Unable to initialize admin connection.")
res, e := client.GetPolicyEntities(globalContext,
madmin.PolicyEntitiesQuery{
Users: usersToQuery,
Groups: groupsToQuery,
Policy: policiesToQuery,
})
fatalIf(probe.NewError(e), "Unable to fetch policy entities")
printMsg(policyEntitiesFrom(res))
return nil
}
+12 -14
View File
@@ -1,4 +1,4 @@
// Copyright (c) 2015-2021 MinIO, Inc.
// Copyright (c) 2015-2022 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
@@ -22,9 +22,9 @@ import (
"github.com/fatih/color"
"github.com/minio/cli"
"github.com/minio/madmin-go"
"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{
@@ -36,7 +36,7 @@ var policyInfoFlags = []cli.Flag{
var adminPolicyInfoCmd = cli.Command{
Name: "info",
Usage: "show info on a policy",
Usage: "show info on an IAM policy",
Action: mainAdminPolicyInfo,
OnUsageError: onUsageError,
Before: setGlobalsFromContext,
@@ -65,7 +65,7 @@ EXAMPLES:
// checkAdminPolicyInfoSyntax - validate all the passed arguments
func checkAdminPolicyInfoSyntax(ctx *cli.Context) {
if len(ctx.Args()) != 2 {
showCommandHelpAndExit(ctx, "info", 1) // last argument is exit code
showCommandHelpAndExit(ctx, 1) // last argument is exit code
}
}
@@ -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
@@ -107,18 +108,15 @@ func mainAdminPolicyInfo(ctx *cli.Context) error {
policyFile := ctx.String("policy-file")
if policyFile != "" {
f, err := os.Create(policyFile)
if err != nil {
fatalIf(probe.NewError(err).Trace(args...), "Could not open given policy file")
}
_, err = f.Write(pinfo.Policy)
if err != nil {
fatalIf(probe.NewError(err).Trace(args...), "Could not write to given policy file")
}
f, e := os.Create(policyFile)
fatalIf(probe.NewError(e).Trace(args...), "Could not open given policy file")
_, e = f.Write(pinfo.Policy)
fatalIf(probe.NewError(e).Trace(args...), "Could not write to given policy file")
}
printMsg(userPolicyMessage{
op: "info",
op: ctx.Command.Name,
Policy: policyName,
PolicyInfo: *pinfo,
})
+6 -5
View File
@@ -1,4 +1,4 @@
// Copyright (c) 2015-2021 MinIO, Inc.
// Copyright (c) 2015-2022 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
@@ -21,12 +21,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"
)
var adminPolicyListCmd = cli.Command{
Name: "list",
Usage: "list all policies",
ShortName: "ls",
Usage: "list all IAM policies",
Action: mainAdminPolicyList,
OnUsageError: onUsageError,
Before: setGlobalsFromContext,
@@ -49,7 +50,7 @@ EXAMPLES:
// checkAdminPolicyListSyntax - validate all the passed arguments
func checkAdminPolicyListSyntax(ctx *cli.Context) {
if len(ctx.Args()) != 1 {
showCommandHelpAndExit(ctx, "list", 1) // last argument is exit code
showCommandHelpAndExit(ctx, 1) // last argument is exit code
}
}
@@ -72,7 +73,7 @@ func mainAdminPolicyList(ctx *cli.Context) error {
for k := range policies {
printMsg(userPolicyMessage{
op: "list",
op: ctx.Command.Name,
Policy: k,
})
}
+6 -5
View File
@@ -1,4 +1,4 @@
// Copyright (c) 2015-2021 MinIO, Inc.
// Copyright (c) 2015-2022 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
@@ -21,12 +21,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"
)
var adminPolicyRemoveCmd = cli.Command{
Name: "remove",
Usage: "remove policy",
ShortName: "rm",
Usage: "remove an IAM policy",
Action: mainAdminPolicyRemove,
OnUsageError: onUsageError,
Before: setGlobalsFromContext,
@@ -52,7 +53,7 @@ EXAMPLES:
// checkAdminPolicyRemoveSyntax - validate all the passed arguments
func checkAdminPolicyRemoveSyntax(ctx *cli.Context) {
if len(ctx.Args()) != 2 {
showCommandHelpAndExit(ctx, "remove", 1) // last argument is exit code
showCommandHelpAndExit(ctx, 1) // last argument is exit code
}
}
@@ -73,7 +74,7 @@ func mainAdminPolicyRemove(ctx *cli.Context) error {
fatalIf(probe.NewError(client.RemoveCannedPolicy(globalContext, args.Get(1))).Trace(args...), "Unable to remove policy")
printMsg(userPolicyMessage{
op: "remove",
op: ctx.Command.Name,
Policy: args.Get(1),
})
+12 -92
View File
@@ -1,4 +1,4 @@
// Copyright (c) 2015-2021 MinIO, Inc.
// Copyright (c) 2015-2022 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
@@ -18,102 +18,22 @@
package cmd
import (
"errors"
"strings"
"github.com/fatih/color"
"github.com/minio/cli"
"github.com/minio/mc/pkg/probe"
"github.com/minio/pkg/console"
)
var adminPolicySetCmd = cli.Command{
Name: "set",
Usage: "set IAM policy on a user or group",
Action: mainAdminPolicySet,
OnUsageError: onUsageError,
Before: setGlobalsFromContext,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} TARGET POLICYNAME [ user=username1 | group=groupname1 ]
POLICYNAME:
Name of the policy on the MinIO server. To set multiple policies, separate names with a comma (,).
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Set the "readwrite" policy for user "james".
{{.Prompt}} {{.HelpName}} myminio readwrite user=james
2. Set the "readonly" policy for group "auditors".
{{.Prompt}} {{.HelpName}} myminio readonly group=auditors
3. Set the "readonly" and the "diagnostics" policies for user "alice"
{{.Prompt}} {{.HelpName}} myminio readonly,diagnostics user=alice
`,
Name: "set",
Usage: "set IAM policy on a user or group",
Action: mainAdminPolicySet,
OnUsageError: onUsageError,
Before: setGlobalsFromContext,
Flags: globalFlags,
HideHelpCommand: true,
Hidden: true,
CustomHelpTemplate: `Please use 'mc admin policy attach'`,
}
var errBadUserGroupArg = errors.New("Last argument must be of the form user=xx or group=xx")
func checkAdminPolicySetSyntax(ctx *cli.Context) {
if len(ctx.Args()) != 3 {
showCommandHelpAndExit(ctx, "set", 1) // last argument is exit code
}
}
func parseEntityArg(arg string) (userOrGroup string, isGroup bool, err error) {
parts := strings.SplitN(arg, "=", 2)
switch {
case len(parts) != 2 || parts[1] == "":
err = errBadUserGroupArg
case strings.ToLower(parts[0]) == "user":
userOrGroup = parts[1]
isGroup = false
case strings.ToLower(parts[0]) == "group":
userOrGroup = parts[1]
isGroup = true
default:
err = errBadUserGroupArg
}
return
}
// mainAdminPolicySet is the handler for "mc admin policy set" command.
func mainAdminPolicySet(ctx *cli.Context) error {
checkAdminPolicySetSyntax(ctx)
console.SetColor("PolicyMessage", color.New(color.FgGreen))
console.SetColor("Policy", color.New(color.FgBlue))
// Get the alias parameter from cli
args := ctx.Args()
aliasedURL := args.Get(0)
policyName := strings.TrimSpace(args.Get(1))
entityArg := args.Get(2)
userOrGroup, isGroup, e1 := parseEntityArg(entityArg)
fatalIf(probe.NewError(e1).Trace(args...), "Bad last argument")
// Create a new MinIO Admin Client
client, err := newAdminClient(aliasedURL)
fatalIf(err, "Unable to initialize admin connection.")
e := client.SetPolicy(globalContext, policyName, userOrGroup, isGroup)
if e == nil {
printMsg(userPolicyMessage{
op: "set",
Policy: policyName,
UserOrGroup: userOrGroup,
IsGroup: isGroup,
})
} else {
fatalIf(probe.NewError(e), "Unable to set the policy")
}
func mainAdminPolicySet(_ *cli.Context) error {
deprecatedError("mc admin policy attach")
return nil
}
+12 -110
View File
@@ -1,4 +1,4 @@
// Copyright (c) 2015-2021 MinIO, Inc.
// Copyright (c) 2015-2022 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
@@ -18,120 +18,22 @@
package cmd
import (
"errors"
"fmt"
"strings"
"github.com/fatih/color"
"github.com/minio/cli"
"github.com/minio/mc/pkg/probe"
"github.com/minio/pkg/console"
)
var adminPolicyUnsetCmd = cli.Command{
Name: "unset",
Usage: "unset an IAM policy for a user or group",
Action: mainAdminPolicyUnset,
OnUsageError: onUsageError,
Before: setGlobalsFromContext,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} TARGET POLICYNAME [ user=username1 | group=groupname1 ]
POLICYNAME:
Name of the policy on the MinIO server.
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Unset the "diagnostics" policy for user "james".
{{.Prompt}} {{.HelpName}} myminio diagnostics user=james
2. Set the "diagnostics" policy for group "auditors".
{{.Prompt}} {{.HelpName}} myminio diagnostics group=auditors
`,
Name: "unset",
Usage: "unset an IAM policy for a user or group",
Action: mainAdminPolicyUnsetErr,
OnUsageError: onUsageError,
Before: setGlobalsFromContext,
Flags: globalFlags,
HideHelpCommand: true,
Hidden: true,
CustomHelpTemplate: `Please use 'mc admin policy detach'`,
}
func checkAdminPolicyUnsetSyntax(ctx *cli.Context) {
if len(ctx.Args()) != 3 {
showCommandHelpAndExit(ctx, "unset", 1) // last argument is exit code
}
}
func removeCannedPolicies(existingPolicies, policiesToRemove string) (string, error) {
policiesToRemove = strings.TrimSpace(policiesToRemove)
if policiesToRemove == "" {
return "", errors.New("empty policy name is not supported")
}
filteredPolicies := strings.Split(existingPolicies, ",")
for _, p1 := range strings.Split(policiesToRemove, ",") {
found := false
for i, p2 := range filteredPolicies {
if p1 == p2 {
found = true
filteredPolicies = append(filteredPolicies[:i], filteredPolicies[i+1:]...)
break
}
}
if !found {
return "", fmt.Errorf("policy `%s` not found", p1)
}
}
return strings.Join(filteredPolicies, ","), nil
}
// mainAdminPolicyUnset is the handler for "mc admin policy unset" command.
func mainAdminPolicyUnset(ctx *cli.Context) error {
checkAdminPolicyUnsetSyntax(ctx)
console.SetColor("PolicyMessage", color.New(color.FgGreen))
console.SetColor("Policy", color.New(color.FgBlue))
// Get the alias parameter from cli
args := ctx.Args()
aliasedURL := args.Get(0)
policiesToUnset := args.Get(1)
entityArg := args.Get(2)
userOrGroup, isGroup, e1 := parseEntityArg(entityArg)
fatalIf(probe.NewError(e1).Trace(args...), "Bad last argument")
// Create a new MinIO Admin Client
client, err := newAdminClient(aliasedURL)
fatalIf(err, "Unable to initialize admin connection.")
var existingPolicies string
if !isGroup {
userInfo, e := client.GetUserInfo(globalContext, userOrGroup)
fatalIf(probe.NewError(e).Trace(args...), "Unable to get user policy info")
existingPolicies = userInfo.PolicyName
} else {
groupInfo, e := client.GetGroupDescription(globalContext, userOrGroup)
fatalIf(probe.NewError(e).Trace(args...), "Unable to get group policy info")
existingPolicies = groupInfo.Policy
}
newPolicies, e := removeCannedPolicies(existingPolicies, policiesToUnset)
if e != nil {
fatalIf(probe.NewError(e).Trace(args...), "Unable to unset the policy")
}
e = client.SetPolicy(globalContext, newPolicies, userOrGroup, isGroup)
if e == nil {
printMsg(userPolicyMessage{
op: "unset",
Policy: policiesToUnset,
UserOrGroup: userOrGroup,
IsGroup: isGroup,
})
} else {
fatalIf(probe.NewError(e), "Unable to unset the policy")
}
func mainAdminPolicyUnsetErr(_ *cli.Context) error {
deprecatedError("mc admin policy detach")
return nil
}
+12 -115
View File
@@ -1,4 +1,4 @@
// Copyright (c) 2015-2021 MinIO, Inc.
// Copyright (c) 2015-2022 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
@@ -18,125 +18,22 @@
package cmd
import (
"errors"
"fmt"
"strings"
"github.com/fatih/color"
"github.com/minio/cli"
"github.com/minio/mc/pkg/probe"
"github.com/minio/pkg/console"
)
var adminPolicyUpdateCmd = cli.Command{
Name: "update",
Usage: "attach a new IAM policy to user or group",
Action: mainAdminPolicyUpdate,
OnUsageError: onUsageError,
Before: setGlobalsFromContext,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} TARGET POLICYNAME [ user=username1 | group=groupname1 ]
POLICYNAME:
Name of the policy on the MinIO server.
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Add the "diagnostics" policy for user "james".
{{.Prompt}} {{.HelpName}} myminio diagnostics user=james
2. Add the "diagnostics" policy for group "auditors".
{{.Prompt}} {{.HelpName}} myminio diagnostics group=auditors
`,
Name: "update",
Usage: "attach a new IAM policy to user or group",
Action: mainAdminPolicyUpdateErr,
OnUsageError: onUsageError,
Before: setGlobalsFromContext,
Flags: globalFlags,
HideHelpCommand: true,
Hidden: true,
CustomHelpTemplate: `Please use 'mc admin policy attach'`,
}
func checkAdminPolicyUpdateSyntax(ctx *cli.Context) {
if len(ctx.Args()) != 3 {
showCommandHelpAndExit(ctx, "update", 1) // last argument is exit code
}
}
func updateCannedPolicies(existingPolicies, policiesToAdd string) (string, error) {
policiesToAdd = strings.TrimSpace(policiesToAdd)
if policiesToAdd == "" {
return "", errors.New("empty policy name is unsupported")
}
var updatedPolicies []string
if existingPolicies != "" {
updatedPolicies = strings.Split(existingPolicies, ",")
}
for _, p1 := range strings.Split(policiesToAdd, ",") {
found := false
p1 = strings.TrimSpace(p1)
for _, p2 := range updatedPolicies {
if p1 == p2 {
found = true
break
}
}
if found {
return "", fmt.Errorf("policy `%s` already exists", p1)
}
updatedPolicies = append(updatedPolicies, p1)
}
return strings.Join(updatedPolicies, ","), nil
}
// mainAdminPolicyUpdate is the handler for "mc admin policy update" command.
func mainAdminPolicyUpdate(ctx *cli.Context) error {
checkAdminPolicyUpdateSyntax(ctx)
console.SetColor("PolicyMessage", color.New(color.FgGreen))
console.SetColor("Policy", color.New(color.FgBlue))
// Get the alias parameter from cli
args := ctx.Args()
aliasedURL := args.Get(0)
policiesToAdd := args.Get(1)
entityArg := args.Get(2)
userOrGroup, isGroup, e1 := parseEntityArg(entityArg)
fatalIf(probe.NewError(e1).Trace(args...), "Bad last argument")
// Create a new MinIO Admin Client
client, err := newAdminClient(aliasedURL)
fatalIf(err, "Unable to initialize admin connection.")
var existingPolicies string
if !isGroup {
userInfo, e := client.GetUserInfo(globalContext, userOrGroup)
fatalIf(probe.NewError(e).Trace(args...), "Unable to get user policy info")
existingPolicies = userInfo.PolicyName
} else {
groupInfo, e := client.GetGroupDescription(globalContext, userOrGroup)
fatalIf(probe.NewError(e).Trace(args...), "Unable to get group policy info")
existingPolicies = groupInfo.Policy
}
updatedPolicies, e := updateCannedPolicies(existingPolicies, policiesToAdd)
if e != nil {
fatalIf(probe.NewError(e).Trace(args...), "Unable to update the policy")
}
e = client.SetPolicy(globalContext, updatedPolicies, userOrGroup, isGroup)
if e == nil {
printMsg(userPolicyMessage{
op: "update",
Policy: policiesToAdd,
UserOrGroup: userOrGroup,
IsGroup: isGroup,
})
} else {
fatalIf(probe.NewError(e), "Unable to unset the policy")
}
func mainAdminPolicyUpdateErr(_ *cli.Context) error {
deprecatedError("mc admin policy attach")
return nil
}
+6 -2
View File
@@ -1,4 +1,4 @@
// Copyright (c) 2015-2021 MinIO, Inc.
// Copyright (c) 2015-2022 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
@@ -20,10 +20,14 @@ package cmd
import "github.com/minio/cli"
var adminPolicySubcommands = []cli.Command{
adminPolicyAddCmd,
adminPolicyCreateCmd,
adminPolicyRemoveCmd,
adminPolicyListCmd,
adminPolicyInfoCmd,
adminPolicyAttachCmd,
adminPolicyDetachCmd,
adminPolicyEntitiesCmd,
adminPolicyAddCmd,
adminPolicySetCmd,
adminPolicyUnsetCmd,
adminPolicyUpdateCmd,
+3 -4
View File
@@ -1,4 +1,4 @@
// Copyright (c) 2015-2021 MinIO, Inc.
// Copyright (c) 2015-2022 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
@@ -19,7 +19,6 @@ package cmd
import (
"github.com/minio/cli"
"github.com/minio/pkg/console"
)
var adminProfileStartCmd = cli.Command{
@@ -34,7 +33,7 @@ var adminProfileStartCmd = cli.Command{
}
// mainAdminProfileStart - the entry function of profile command
func mainAdminProfileStart(ctx *cli.Context) error {
console.Infoln("Please use 'mc support profile start'")
func mainAdminProfileStart(_ *cli.Context) error {
deprecatedError("mc support profile start")
return nil
}
+3 -4
View File
@@ -1,4 +1,4 @@
// Copyright (c) 2015-2021 MinIO, Inc.
// Copyright (c) 2015-2022 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
@@ -19,7 +19,6 @@ package cmd
import (
"github.com/minio/cli"
"github.com/minio/pkg/console"
)
var adminProfileStopCmd = cli.Command{
@@ -35,7 +34,7 @@ var adminProfileStopCmd = cli.Command{
}
// mainAdminProfileStop - the entry function of profile stop command
func mainAdminProfileStop(ctx *cli.Context) error {
console.Infoln("Please use 'mc support profile stop'")
func mainAdminProfileStop(_ *cli.Context) error {
deprecatedError("mc support profile stop")
return nil
}
+3 -4
View File
@@ -1,4 +1,4 @@
// Copyright (c) 2015-2021 MinIO, Inc.
// Copyright (c) 2015-2022 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
@@ -19,7 +19,6 @@ package cmd
import (
"github.com/minio/cli"
"github.com/minio/pkg/console"
)
var adminProfileSubcommands = []cli.Command{
@@ -40,7 +39,7 @@ var adminProfileCmd = cli.Command{
}
// mainAdminProfile is the handle for "mc admin profile" command.
func mainAdminProfile(ctx *cli.Context) error {
console.Infoln("Please use 'mc support profile'")
func mainAdminProfile(_ *cli.Context) error {
deprecatedError("mc support profile")
return nil
}
+117 -39
View File
@@ -1,4 +1,4 @@
// Copyright (c) 2015-2021 MinIO, Inc.
// Copyright (c) 2015-2024 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
@@ -18,30 +18,28 @@
package cmd
import (
"fmt"
"net/url"
"time"
"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"
defaultMetricsPath = "/minio/v2/metrics/cluster"
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",
@@ -55,15 +53,71 @@ var adminPrometheusGenerateCmd = cli.Command{
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} TARGET
{{.HelpName}} TARGET [METRIC-TYPE]
METRIC-TYPE:
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
`,
}
@@ -74,10 +128,9 @@ type PrometheusConfig struct {
// String colorized prometheus config yaml.
func (c PrometheusConfig) String() string {
b, err := yaml.Marshal(c)
if err != nil {
return fmt.Sprintf("error creating config string: %s", err)
}
b, e := yaml.Marshal(c)
fatalIf(probe.NewError(e), "Unable to generate Prometheus config")
return console.Colorize("yaml", string(b))
}
@@ -95,10 +148,9 @@ type StatConfig struct {
// String colorized stat config yaml.
func (t StatConfig) String() string {
b, err := yaml.Marshal(t)
if err != nil {
return fmt.Sprintf("error creating config string: %s", err)
}
b, e := yaml.Marshal(t)
fatalIf(probe.NewError(e), "Unable to generate Prometheus config")
return console.Colorize("yaml", string(b))
}
@@ -122,24 +174,10 @@ const (
defaultPrometheusJWTExpiry = 100 * 365 * 24 * time.Hour
)
var defaultConfig = PrometheusConfig{
ScrapeConfigs: []ScrapeConfig{
{
JobName: defaultJobName,
MetricsPath: defaultMetricsPath,
StaticConfigs: []StatConfig{
{
Targets: []string{""},
},
},
},
},
}
// checkAdminPrometheusSyntax - validate all the passed arguments
func checkAdminPrometheusSyntax(ctx *cli.Context) {
if len(ctx.Args()) != 1 {
showCommandHelpAndExit(ctx, "generate", 1) // last argument is exit code
if len(ctx.Args()) == 0 || len(ctx.Args()) > 2 {
showCommandHelpAndExit(ctx, 1) // last argument is exit code
}
}
@@ -163,18 +201,58 @@ func generatePrometheusConfig(ctx *cli.Context) error {
return e
}
metricsSubSystem := args.Get(1)
apiVer := ctx.String("api-version")
jobName := defaultJobName
metricsPath := ""
switch apiVer {
case "v2":
if metricsSubSystem == "" {
metricsSubSystem = "cluster"
}
validateV2Args(ctx, metricsSubSystem)
if metricsSubSystem != "cluster" {
jobName = defaultJobName + "-" + metricsSubSystem
}
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 api version `"+apiVer+"`")
}
config := PrometheusConfig{
ScrapeConfigs: []ScrapeConfig{
{
JobName: jobName,
MetricsPath: metricsPath,
StaticConfigs: []StatConfig{
{
Targets: []string{""},
},
},
},
},
}
if !ctx.Bool("public") {
token, e := getPrometheusToken(hostConfig)
if e != nil {
return e
}
// Setting the values
defaultConfig.ScrapeConfigs[0].BearerToken = token
config.ScrapeConfigs[0].BearerToken = token
}
defaultConfig.ScrapeConfigs[0].Scheme = u.Scheme
defaultConfig.ScrapeConfigs[0].StaticConfigs[0].Targets[0] = u.Host
config.ScrapeConfigs[0].Scheme = u.Scheme
config.ScrapeConfigs[0].StaticConfigs[0].Targets[0] = u.Host
printMsg(defaultConfig)
printMsg(config)
return nil
}
+110
View File
@@ -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)
}
+176 -68
View File
@@ -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,193 @@
package cmd
import (
"errors"
"io"
"io/ioutil"
"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"
prom2json "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
{{.HelpName}} TARGET [METRIC-TYPE]
METRIC-TYPE:
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. Metrics reported at node level.
{{.Prompt}} {{.HelpName}} play node
3. Metrics reported at bucket level.
{{.Prompt}} {{.HelpName}} play bucket
4. Resource metrics.
{{.Prompt}} {{.HelpName}} play resource
`,
}
const (
metricsRespBodyLimit = 10 << 20 // 10 MiB
metricsEndPoint = "/minio/v2/metrics/cluster"
)
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) {
if len(ctx.Args()) == 0 || len(ctx.Args()) > 1 {
showCommandHelpAndExit(ctx, "metrics", 1) // last argument is exit code
if len(ctx.Args()) == 0 || len(ctx.Args()) > 2 {
showCommandHelpAndExit(ctx, 1) // last argument is exit code
}
}
func printPrometheusMetrics(ctx *cli.Context) error {
func fetchMetrics(metricsURL string, token string) (*http.Response, error) {
req, e := http.NewRequest(http.MethodGet, metricsURL, nil)
if e != nil {
return nil, e
}
if token != "" {
req.Header.Add("Authorization", "Bearer "+token)
}
client := httpClient(60 * time.Second)
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
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusOK {
printMsg(prometheusMetricsReader{Reader: resp.Body})
return nil
}
return errors.New(resp.Status)
}
// JSON returns jsonified message
func (pm prometheusMetricsReader) JSON() string {
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 {
_, e := io.Copy(os.Stdout, pm.Reader)
fatalIf(probe.NewError(e), "Unable to read Prometheus metrics.")
return ""
}
// prometheusMetricsReader mirrors the MetricFamily proto message.
type prometheusMetricsReader struct {
Reader io.Reader
}
func mainSupportMetrics(ctx *cli.Context) error {
checkSupportMetricsSyntax(ctx)
// Get the alias parameter from cli
args := ctx.Args()
alias := cleanAlias(args.Get(0))
@@ -70,6 +212,7 @@ func printPrometheusMetrics(ctx *cli.Context) error {
if !isValidAlias(alias) {
fatalIf(errInvalidAlias(alias), "Invalid alias.")
}
hostConfig := mustGetHostConfig(alias)
if hostConfig == nil {
fatalIf(errInvalidAliasedURL(alias), "No such alias `"+alias+"` found.")
@@ -81,60 +224,25 @@ func printPrometheusMetrics(ctx *cli.Context) error {
return e
}
req, e := http.NewRequest(http.MethodGet, hostConfig.URL+metricsEndPoint, nil)
if e != nil {
return e
}
req.Header.Add("Authorization", "Bearer "+token)
client := httpClient(10 * time.Second)
resp, e := client.Do(req)
if e != nil {
return e
metricsSubSystem := args.Get(1)
apiVer := ctx.String("api-version")
metricsReq := prometheusMetricsReq{
aliasURL: hostConfig.URL,
token: token,
subsystem: metricsSubSystem,
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusOK {
printMsg(prometheusMetricsReader{Reader: io.LimitReader(resp.Body, metricsRespBodyLimit)})
}
return nil
}
// JSON returns jsonified message
func (pm prometheusMetricsReader) JSON() string {
mfChan := make(chan *dto.MetricFamily)
go func() {
if err := prom2json.ParseReader(pm.Reader, mfChan); err != nil {
fatalIf(probe.NewError(err), "error reading metrics:")
}
}()
result := []*prom2json.Family{}
for mf := range mfChan {
result = append(result, prom2json.NewFamily(mf))
}
jsonMessageBytes, e := json.MarshalIndent(result, "", " ")
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 := ioutil.ReadAll(pm.Reader)
if e != nil {
fatalIf(probe.NewError(e), "error reading metrics:")
}
return string(respBytes)
}
// prometheusMetricsReader mirrors the MetricFamily proto message.
type prometheusMetricsReader struct {
Reader io.Reader
}
func mainSupportMetrics(ctx *cli.Context) error {
checkSupportMetricsSyntax(ctx)
if err := printPrometheusMetrics(ctx); err != nil {
fatalIf(probe.NewError(err), "Error in listing prometheus metrics")
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
}

Some files were not shown because too many files have changed in this diff Show More