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
199 changed files with 8902 additions and 1976 deletions
+1 -1
View File
@@ -20,7 +20,7 @@ jobs:
runs-on: ${{ matrix.os }}
strategy:
matrix:
go-version: [1.21.x, 1.22.x]
go-version: [1.25.x]
os: [ubuntu-latest]
steps:
- uses: actions/checkout@v4
+2 -5
View File
@@ -19,7 +19,7 @@ jobs:
GO111MODULE: on
strategy:
matrix:
go-version: [1.22.x]
go-version: [1.25.x]
os: [ubuntu-latest, macos-latest, windows-latest]
steps:
- name: Set up Go ${{ matrix.go-version }} on ${{ matrix.os }}
@@ -69,7 +69,7 @@ jobs:
- name: Set up Go
uses: actions/setup-go@v2
with:
go-version: 1.22.x
go-version: 1.24.x
- name: Checkout code
uses: actions/checkout@v2
@@ -77,6 +77,3 @@ jobs:
- name: Test 386
run: GOOS=linux GOARCH=386 go test -short ./...
- name: Staticcheck
# Run with defaults, but allow errors with other formats ST1005
run: go install honnef.co/go/tools/cmd/staticcheck@latest && make lint
+1 -1
View File
@@ -16,7 +16,7 @@ jobs:
- name: Set up Go
uses: actions/setup-go@v5
with:
go-version: 1.22.5
go-version: 1.25.x
- name: Get official govulncheck
run: go install golang.org/x/vuln/cmd/govulncheck@latest
shell: bash
+2 -1
View File
@@ -14,4 +14,5 @@ mc
mc.RELEASE*
mc.gz
.DS_Store
.vscode/
.vscode/
.bin/
+37 -27
View File
@@ -1,32 +1,42 @@
version: "2"
linters:
disable-all: true
default: none
enable:
- typecheck
- goimports
- misspell
- staticcheck
- govet
- revive
- ineffassign
- gomodguard
- gofmt
- govet
- ineffassign
- misspell
- revive
- staticcheck
- unused
settings:
misspell:
locale: US
exclusions:
generated: lax
rules:
- path: (.+)\.go$
text: instead of using struct literal
- path: (.+)\.go$
text: should have a package comment
- path: (.+)\.go$
text: error strings should not be capitalized or end with punctuation or a newline
- path: (.+)\.go$
text: error strings should not end with punctuation or newlines
- path: (.+)\.go$
text: error strings should not be capitalized
paths:
- third_party$
- builtin$
- examples$
formatters:
enable:
- gofmt
- gofumpt
linters-settings:
golint:
min-confidence: 0
misspell:
locale: US
# 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
- goimports
exclusions:
generated: lax
paths:
- third_party$
- builtin$
- examples$
+2342 -152
View File
File diff suppressed because it is too large Load Diff
+2 -2
View File
@@ -1,4 +1,4 @@
FROM golang:1.21-alpine as build
FROM golang:1.22-alpine as build
LABEL maintainer="MinIO Inc <dev@min.io>"
@@ -19,4 +19,4 @@ 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"]
ENTRYPOINT ["mc"]
+1 -1
View File
@@ -1,4 +1,4 @@
FROM --platform=linux/amd64 registry.access.redhat.com/ubi9/ubi-minimal:latest as build
FROM registry.access.redhat.com/ubi9/ubi-minimal:latest AS build
RUN microdnf update --nodocs --assumeyes && microdnf install ca-certificates --nodocs --assumeyes
-24
View File
@@ -1,24 +0,0 @@
FROM --platform=linux/amd64 registry.access.redhat.com/ubi9/ubi-minimal:latest as build
RUN microdnf update --nodocs --assumeyes && microdnf install ca-certificates --nodocs --assumeyes
FROM registry.access.redhat.com/ubi9/ubi-micro:latest
ARG TARGETARCH
ARG RELEASE
LABEL maintainer="MinIO Inc <dev@min.io>"
# On RHEL the certificate bundle is located at:
# - /etc/pki/tls/certs/ca-bundle.crt (RHEL 6)
# - /etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem (RHEL 7)
COPY --from=build /etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem /etc/pki/ca-trust/extracted/pem/
COPY CREDITS /licenses/CREDITS
COPY LICENSE /licenses/LICENSE
ADD https://dl.minio.io/client/mc/release/linux-${TARGETARCH}/archive/mc.${RELEASE}.fips /usr/bin/mc
RUN chmod +x /usr/bin/mc
ENTRYPOINT ["mc"]
+1 -1
View File
@@ -1,4 +1,4 @@
FROM --platform=linux/amd64 registry.access.redhat.com/ubi8/ubi-minimal:latest as build
FROM registry.access.redhat.com/ubi8/ubi-minimal:latest AS build
RUN microdnf update --nodocs --assumeyes && microdnf install ca-certificates --nodocs --assumeyes
+8 -10
View File
@@ -2,14 +2,13 @@ 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_DIR = .bin/golangci/$(GOLANGCI_VERSION)
GOLANGCI = $(GOLANGCI_DIR)/golangci-lint
GOLANGCI = $(GOPATH)/bin/golangci-lint
all: build
@@ -19,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 $(GOLANGCI_DIR)
@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)
@@ -64,7 +62,7 @@ verify:
# 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 | \
@@ -78,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)"
+2 -2
View File
@@ -2,7 +2,7 @@
[![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://min.io/docs/minio/linux/reference/minio-mc.html)
- [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).
@@ -121,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
+3 -3
View File
@@ -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)
+43 -12
View File
@@ -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"
@@ -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.
@@ -114,7 +145,7 @@ func (a *accounter) Stat() accountStat {
close(a.isFinished)
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
}
+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)
}
+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 adminAccesskeyEnableCmd = cli.Command{
Name: "enable",
Usage: "enable an access key",
Action: mainAdminAccesskeyEnable,
Before: setGlobalsFromContext,
Flags: globalFlags,
OnUsageError: onUsageError,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} [FLAGS] [TARGET]
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Enable access key
{{.Prompt}} {{.HelpName}} myminio myaccesskey
`,
}
func mainAdminAccesskeyEnable(ctx *cli.Context) error {
return enableDisableAccesskey(ctx, true)
}
+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
}
-1
View File
@@ -121,7 +121,6 @@ func TestGetBandwidthInBytes(t *testing.T) {
}
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)
+5
View File
@@ -119,6 +119,11 @@ func mainClusterBucketExport(ctx *cli.Context) error {
}
fatalIf(probe.NewError(moveFile(tmpFile.Name(), downloadPath)), "Unable to rename downloaded data, file exists at %s", tmpFile.Name())
// Explicitly set permissions to 0o600 and override umask
// to ensure that the file is not world-readable.
e = os.Chmod(downloadPath, 0o600)
fatalIf(probe.NewError(e), "Unable to set file permissions for "+downloadPath)
if !globalJSON {
console.Infof("Bucket metadata successfully downloaded as %s\n", downloadPath)
return nil
+15 -4
View File
@@ -96,6 +96,7 @@ func mainClusterBucketImport(ctx *cli.Context) error {
f, e = os.Open(args.Get(1))
fatalIf(probe.NewError(e).Trace(args...), "Unable to get bucket metadata")
defer f.Close()
// Create a new MinIO Admin Client
client, err := newAdminClient(aliasedURL)
@@ -141,14 +142,15 @@ func statusTick(s madmin.MetaStatus) string {
}
func (i importMetaMsg) String() string {
m := i.BucketMetaImportErrs.Buckets
m := i.Buckets
totBuckets := len(m)
totErrs := 0
for _, st := range m {
if st.ObjectLock.Err != "" || st.Versioning.Err != "" ||
st.SSEConfig.Err != "" || st.Tagging.Err != "" ||
st.Lifecycle.Err != "" || st.Quota.Err != "" ||
st.Policy.Err != "" || st.Notification.Err != "" {
st.Policy.Err != "" || st.Notification.Err != "" ||
st.Cors.Err != "" || st.Err != "" {
totErrs++
}
}
@@ -168,7 +170,8 @@ func (i importMetaMsg) String() string {
if st.ObjectLock.Err != "" || st.Versioning.Err != "" ||
st.SSEConfig.Err != "" || st.Tagging.Err != "" ||
st.Lifecycle.Err != "" || st.Quota.Err != "" ||
st.Policy.Err != "" || st.Notification.Err != "" {
st.Policy.Err != "" || st.Notification.Err != "" ||
st.Cors.Err != "" || st.Err != "" {
fmt.Fprintln(&b, printImportErrs(bucket, st))
}
}
@@ -183,7 +186,7 @@ func (i importMetaMsg) JSON() string {
// Disable escaping special chars to display XML tags correctly
enc.SetEscapeHTML(false)
fatalIf(probe.NewError(enc.Encode(i.BucketMetaImportErrs.Buckets)), "Unable to marshal into JSON.")
fatalIf(probe.NewError(enc.Encode(i.Buckets)), "Unable to marshal into JSON.")
return buf.String()
}
@@ -194,6 +197,10 @@ func printImportErrs(bucket string, r madmin.BucketStatus) string {
key := fmt.Sprintf("%-10s: %s", "Name", bucket)
fmt.Fprintln(&b, console.Colorize("Name", key))
if r.Err != "" {
fmt.Fprintf(&b, "%2s%s %s", placeHolder, console.Colorize("errors", "Error: "), r.Err)
fmt.Fprintln(&b)
}
if r.ObjectLock.IsSet {
fmt.Fprintf(&b, "%2s%s %s", placeHolder, "Object lock: ", statusTick(r.ObjectLock))
fmt.Fprintln(&b)
@@ -227,5 +234,9 @@ func printImportErrs(bucket string, r madmin.BucketStatus) string {
fmt.Fprintf(&b, "%2s%s %s", placeHolder, "Tagging: ", statusTick(r.Tagging))
fmt.Fprintln(&b)
}
if r.Cors.IsSet {
fmt.Fprintf(&b, "%2s%s %s", placeHolder, "CORS: ", statusTick(r.Cors))
fmt.Fprintln(&b)
}
return b.String()
}
+22 -1
View File
@@ -32,13 +32,23 @@ import (
"github.com/minio/pkg/v3/console"
)
// iam export specific flags.
var (
iamExportFlags = []cli.Flag{
cli.StringFlag{
Name: "output,o",
Usage: "output iam export to a custom file path",
},
}
)
var adminClusterIAMExportCmd = cli.Command{
Name: "export",
Usage: "exports IAM info to zipped file",
Action: mainClusterIAMExport,
OnUsageError: onUsageError,
Before: setGlobalsFromContext,
Flags: globalFlags,
Flags: append(iamExportFlags, globalFlags...),
HideHelpCommand: true,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
@@ -52,6 +62,9 @@ FLAGS:
EXAMPLES:
1. Download all IAM metadata for cluster into zip file.
{{.Prompt}} {{.HelpName}} myminio
2. Download all IAM metadata to a custom file.
{{.Prompt}} {{.HelpName}} myminio --output /tmp/myminio-iam.zip
`,
}
@@ -97,6 +110,9 @@ func mainClusterIAMExport(ctx *cli.Context) error {
tmpFile.Close()
downloadPath := fmt.Sprintf("%s-iam-info.%s", aliasedURL, ext)
if ctx.String("output") != "" {
downloadPath = ctx.String("output")
}
fi, e := os.Stat(downloadPath)
if e == nil && !fi.IsDir() {
e = moveFile(downloadPath, downloadPath+"."+time.Now().Format(dateTimeFormatFilename))
@@ -109,6 +125,11 @@ func mainClusterIAMExport(ctx *cli.Context) error {
fatalIf(probe.NewError(moveFile(tmpFile.Name(), downloadPath)), "Unable to rename downloaded data, file exists at %s", tmpFile.Name())
// Explicitly set permissions to 0o600 and override umask
// to ensure that the file is not world-readable.
e = os.Chmod(downloadPath, 0o600)
fatalIf(probe.NewError(e), "Unable to set file permissions for "+downloadPath)
if !globalJSON {
console.Infof("IAM info successfully downloaded as %s\n", downloadPath)
return nil
+132 -5
View File
@@ -23,9 +23,12 @@ import (
"io"
"os"
"path/filepath"
"strings"
"github.com/klauspost/compress/zip"
"github.com/minio/cli"
json "github.com/minio/colorjson"
"github.com/minio/madmin-go/v3"
"github.com/minio/mc/pkg/probe"
"github.com/minio/pkg/v3/console"
)
@@ -54,6 +57,123 @@ EXAMPLES:
`,
}
type iamImportInfo madmin.ImportIAMResult
func (i iamImportInfo) JSON() string {
bs, e := json.MarshalIndent(madmin.ImportIAMResult(i), "", " ")
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
return string(bs)
}
func (i iamImportInfo) String() string {
var messages []string
info := madmin.ImportIAMResult(i)
messages = append(messages, processIAMEntities(info.Skipped, "Skipped")...)
messages = append(messages, processIAMEntities(info.Removed, "Removed")...)
messages = append(messages, processIAMEntities(info.Added, "Added")...)
messages = append(messages, processErrIAMEntities(info.Failed)...)
return strings.Join(messages, "\n")
}
func processIAMEntities(entities madmin.IAMEntities, action string) []string {
var messages []string
if len(entities.Policies) > 0 {
messages = append(messages, fmt.Sprintf("%s policies: %v", action, strings.Join(entities.Policies, ", ")))
}
if len(entities.Users) > 0 {
messages = append(messages, fmt.Sprintf("%s users: %v", action, strings.Join(entities.Users, ", ")))
}
if len(entities.Groups) > 0 {
messages = append(messages, fmt.Sprintf("%s groups: %v", action, strings.Join(entities.Groups, ", ")))
}
if len(entities.ServiceAccounts) > 0 {
messages = append(messages, fmt.Sprintf("%s service accounts: %v", action, strings.Join(entities.ServiceAccounts, ", ")))
}
var users []string
for _, pol := range entities.UserPolicies {
for name := range pol {
users = append(users, name)
}
}
if len(users) > 0 {
messages = append(messages, fmt.Sprintf("%s policies for users: %v", action, strings.Join(users, ", ")))
}
var groups []string
for _, pol := range entities.GroupPolicies {
for name := range pol {
groups = append(groups, name)
}
}
if len(groups) > 0 {
messages = append(messages, fmt.Sprintf("%s policies for groups: %v", action, strings.Join(groups, ", ")))
}
var stsarr []string
for _, pol := range entities.STSPolicies {
for name := range pol {
stsarr = append(stsarr, name)
}
}
if len(stsarr) > 0 {
messages = append(messages, fmt.Sprintf("%s policies for sts: %v", action, strings.Join(stsarr, ", ")))
}
return messages
}
func processErrIAMEntities(entities madmin.IAMErrEntities) []string {
var messages []string
var policies []string
for _, entry := range entities.Policies {
policies = append(policies, entry.Name)
}
if len(policies) > 0 {
messages = append(messages, fmt.Sprintf("Failed to add policies: %v", strings.Join(policies, ", ")))
}
var users []string
for _, entry := range entities.Users {
users = append(users, entry.Name)
}
if len(users) > 0 {
messages = append(messages, fmt.Sprintf("Failed to add users: %v", strings.Join(users, ", ")))
}
var groups []string
for _, entry := range entities.Groups {
groups = append(groups, entry.Name)
}
if len(groups) > 0 {
messages = append(messages, fmt.Sprintf("Failed to add groups: %v", strings.Join(groups, ", ")))
}
var sas []string
for _, entry := range entities.ServiceAccounts {
sas = append(sas, entry.Name)
}
if len(sas) > 0 {
messages = append(messages, fmt.Sprintf("Failed to add service accounts: %v", strings.Join(sas, ", ")))
}
var polusers []string
for _, pol := range entities.UserPolicies {
polusers = append(polusers, pol.Name)
}
if len(polusers) > 0 {
messages = append(messages, fmt.Sprintf("Failed to add policies for users: %v", strings.Join(polusers, ", ")))
}
var polgroups []string
for _, pol := range entities.GroupPolicies {
polgroups = append(polgroups, pol.Name)
}
if len(polgroups) > 0 {
messages = append(messages, fmt.Sprintf("Failed to add policies for groups: %v", strings.Join(polgroups, ", ")))
}
var polsts []string
for _, pol := range entities.STSPolicies {
polsts = append(polsts, pol.Name)
}
if len(polsts) > 0 {
messages = append(messages, fmt.Sprintf("Failed to add policies for sts: %v", strings.Join(polsts, ", ")))
}
return messages
}
func checkIAMImportSyntax(ctx *cli.Context) {
if len(ctx.Args()) != 2 {
showCommandHelpAndExit(ctx, 1) // last argument is exit code
@@ -87,6 +207,7 @@ func mainClusterIAMImport(ctx *cli.Context) error {
f, e = os.Open(args.Get(1))
fatalIf(probe.NewError(e).Trace(args...), "Unable to get IAM info")
defer f.Close()
// Create a new MinIO Admin Client
client, err := newAdminClient(aliasedURL)
@@ -95,11 +216,17 @@ func mainClusterIAMImport(ctx *cli.Context) error {
return nil
}
e = client.ImportIAM(context.Background(), f)
fatalIf(probe.NewError(e).Trace(aliasedURL), "Unable to import IAM info.")
if !globalJSON {
console.Infof("IAM info imported to %s from %s\n", aliasedURL, args.Get(1))
iamr, e := client.ImportIAMV2(context.Background(), f)
if e != nil {
f.Seek(0, 0)
e = client.ImportIAM(context.Background(), f)
fatalIf(probe.NewError(e).Trace(aliasedURL), "Unable to import IAM info.")
if !globalJSON {
console.Infof("IAM info imported to %s from %s\n", aliasedURL, args.Get(1))
}
} else {
printMsg(iamImportInfo(iamr))
}
return nil
}
+1 -1
View File
@@ -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
+2 -2
View File
@@ -116,13 +116,13 @@ func mainAdminConfigReset(ctx *cli.Context) error {
if len(ctx.Args()) == 1 {
// Call get config API
hr, e := client.HelpConfigKV(globalContext, "", "", ctx.IsSet("env"))
hr, e := client.HelpConfigKV(globalContext, "", "", ctx.Bool("env"))
fatalIf(probe.NewError(e), "Unable to get help for the sub-system")
// Print
printMsg(configHelpMessage{
Value: hr,
envOnly: ctx.IsSet("env"),
envOnly: ctx.Bool("env"),
})
return nil
+2 -2
View File
@@ -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
@@ -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
+42 -1
View File
@@ -18,6 +18,7 @@
package cmd
import (
"errors"
"fmt"
"github.com/minio/madmin-go/v3"
@@ -49,12 +50,52 @@ 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) {
+26 -16
View File
@@ -52,7 +52,7 @@ var (
func getHColCode(surplusShards, parityShards int) (c col, err error) {
if parityShards < 1 || parityShards > 8 || surplusShards > parityShards {
return c, fmt.Errorf("Invalid parity shard count/surplus shard count given")
return c, errors.New("Invalid parity shard count/surplus shard count given")
}
if surplusShards < 0 {
return colGrey, err
@@ -63,7 +63,7 @@ func getHColCode(surplusShards, parityShards int) (c col, err error) {
return hColOrder[index], err
}
}
return c, fmt.Errorf("cannot get a heal color code")
return c, errors.New("cannot get a heal color code")
}
type uiData struct {
@@ -127,7 +127,9 @@ func (ui *uiData) updateStats(i madmin.HealResultItem) error {
var afterCol col
h := newHRI(&i)
switch h.Type {
case madmin.HealItemMetadata, madmin.HealItemBucket:
case madmin.HealItemBucket:
_, afterCol, err = h.getBucketHCCChange()
case madmin.HealItemMetadata, madmin.HealItemBucketMetadata:
_, afterCol, err = h.getReplicatedFileHCCChange()
default:
_, afterCol, err = h.getObjectHCCChange()
@@ -205,17 +207,24 @@ func (ui *uiData) printItemsQuietly(s *madmin.HealTaskStatus) (err error) {
var b, a col
for _, item := range s.Items {
h := newHRI(&item)
hrStr := h.getHealResultStr()
switch h.Type {
case madmin.HealItemMetadata, madmin.HealItemBucket:
case madmin.HealItemBucket:
b, a, err = h.getBucketHCCChange()
case madmin.HealItemMetadata, madmin.HealItemBucketMetadata:
b, a, err = h.getReplicatedFileHCCChange()
default:
b, a, err = h.getObjectHCCChange()
}
if err != nil {
return err
errMsg := err.Error()
if h.Detail != "" {
errMsg = h.Detail
}
console.PrintC("[ERROR] ** ", hrStr, " **", ": ", errMsg, "\n")
continue
}
printColStr(b, a)
hrStr := h.getHealResultStr()
switch h.Type {
case madmin.HealItemMetadata, madmin.HealItemBucketMetadata:
console.PrintC(fmt.Sprintln("**", hrStr, "**"))
@@ -240,6 +249,7 @@ func (ui *uiData) printItemsJSON(s *madmin.HealTaskStatus) (err error) {
type healRec struct {
Status string `json:"status"`
Error string `json:"error,omitempty"`
Detail string `json:"detail,omitempty"`
Type string `json:"type"`
Name string `json:"name"`
Before struct {
@@ -267,7 +277,9 @@ func (ui *uiData) printItemsJSON(s *madmin.HealTaskStatus) (err error) {
var b, a col
var err error
switch h.Type {
case madmin.HealItemMetadata, madmin.HealItemBucket:
case madmin.HealItemBucket:
b, a, err = h.getBucketHCCChange()
case madmin.HealItemMetadata, madmin.HealItemBucketMetadata:
b, a, err = h.getReplicatedFileHCCChange()
default:
if h.Type == madmin.HealItemObject {
@@ -278,6 +290,7 @@ func (ui *uiData) printItemsJSON(s *madmin.HealTaskStatus) (err error) {
if err != nil {
r.Error = err.Error()
}
r.Detail = h.Detail
r.Before.Color = strings.ToLower(string(b))
r.After.Color = strings.ToLower(string(a))
r.Before.Online, r.After.Online = h.GetOnlineCounts()
@@ -369,7 +382,7 @@ func (ui *uiData) updateUI(s *madmin.HealTaskStatus) (err error) {
return nil
}
func (ui *uiData) UpdateDisplay(s *madmin.HealTaskStatus) (err error) {
func (ui *uiData) UpdateDisplay(s *madmin.HealTaskStatus) {
// Update state
ui.updateDuration(s)
for _, i := range s.Items {
@@ -379,13 +392,12 @@ func (ui *uiData) UpdateDisplay(s *madmin.HealTaskStatus) (err error) {
// Update display
switch {
case globalJSON:
err = ui.printItemsJSON(s)
ui.printItemsJSON(s)
case globalQuiet:
err = ui.printItemsQuietly(s)
ui.printItemsQuietly(s)
default:
err = ui.updateUI(s)
ui.updateUI(s)
}
return
}
func (ui *uiData) healResumeMsg(aliasedURL string) string {
@@ -420,10 +432,8 @@ func (ui *uiData) DisplayAndFollowHealStatus(aliasedURL string) (res madmin.Heal
console.RewindLines(8)
}
}
err = ui.UpdateDisplay(&res)
if err != nil {
return res, err
}
ui.UpdateDisplay(&res)
if res.Summary == "finished" {
if globalJSON {
+84 -37
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,8 +18,11 @@
package cmd
import (
"bufio"
"fmt"
"math"
"net/url"
"os"
"path/filepath"
"sort"
"strings"
@@ -76,6 +79,10 @@ var adminHealFlags = []cli.Flag{
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",
@@ -95,6 +102,10 @@ var adminHealFlags = []cli.Flag{
Name: "verbose, v",
Usage: "show verbose information",
},
cli.BoolFlag{
Name: "all-drives, a",
Usage: "select all drives for verbose printing",
},
}
var adminHealCmd = cli.Command{
@@ -162,8 +173,11 @@ type poolInfo struct {
}
type setInfo struct {
maxUsedSpace uint64
totalDisks int
totalDisks int
readyDisksCount int // disks online and not in healing state
readyDisksUsedSpace uint64 // the total used space of ready disks
incapableDisks int
}
@@ -218,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
}
@@ -327,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:"-"`
}
@@ -374,14 +390,16 @@ func (s verboseBackgroundHealStatusMessage) String() string {
fmt.Fprintf(&msg, " %s: %s\n", endpoint, stateText)
continue
}
var serverHeader strings.Builder
var serverHeaderPrinted bool
serverStatus := serversStatus[endpoint]
switch {
case showTolerance:
serverHeader := " %s: (Tolerance: %d server(s))\n"
fmt.Fprintf(&msg, serverHeader, endpoint, poolsInfo[serverStatus.pool].tolerance)
hdr := " %s: (Tolerance: %d server(s))\n"
fmt.Fprintf(&serverHeader, hdr, endpoint, poolsInfo[serverStatus.pool].tolerance)
default:
serverHeader := " %s:\n"
fmt.Fprintf(&msg, serverHeader, endpoint)
hdr := " %s:\n"
fmt.Fprintf(&serverHeader, hdr, endpoint)
}
for _, d := range serverStatus.disks {
@@ -393,25 +411,49 @@ func (s verboseBackgroundHealStatusMessage) String() string {
case d.State == "ok" && d.Healing:
stateText = console.Colorize("DiskHealing", "HEALING")
case d.State == "ok":
if !s.allDrives {
continue
}
stateText = console.Colorize("DiskOK", "OK")
default:
stateText = console.Colorize("DiskFailed", d.State)
}
fmt.Fprintf(&msg, " + %s : %s\n", d.DrivePath, stateText)
if d.Healing && d.HealInfo != nil {
now := time.Now().UTC()
scanSpeed := float64(d.UsedSpace) / float64(now.Sub(d.HealInfo.Started))
remainingTime := time.Duration(float64(setsStatus[setIndex{d.PoolIndex, d.SetIndex}].maxUsedSpace-d.UsedSpace) / scanSpeed)
estimationText := humanize.RelTime(now, now.Add(remainingTime), "", "")
fmt.Fprintf(&msg, " |__ Estimated: %s\n", estimationText)
if !serverHeaderPrinted {
serverHeaderPrinted = true
fmt.Fprint(&msg, serverHeader.String())
}
fmt.Fprintf(&msg, " |__ Capacity: %s/%s\n", humanize.IBytes(d.UsedSpace), humanize.IBytes(d.TotalSpace))
drivePath := d.DrivePath
if drivePath == "" {
if u, e := url.Parse(d.Endpoint); e == nil {
drivePath = u.Path
}
}
fmt.Fprintf(&msg, " + %s : %s\n", drivePath, stateText)
thisSet := setsStatus[setIndex{d.PoolIndex, d.SetIndex}]
if d.Healing && d.HealInfo != nil && !d.HealInfo.Finished {
refUsedSpace := uint64(math.MaxUint64)
if thisSet.readyDisksCount > 0 { // to avoid crashing
refUsedSpace = thisSet.readyDisksUsedSpace / uint64(thisSet.readyDisksCount)
}
if refUsedSpace < d.UsedSpace { // normalize
refUsedSpace = d.UsedSpace
}
fmt.Fprintf(&msg, " |__ Progress: %d%%\n", 100*d.UsedSpace/refUsedSpace)
fmt.Fprintf(&msg, " |__ Started: %s\n", humanize.Time(d.HealInfo.Started))
if d.HealInfo.RetryAttempts > 0 {
fmt.Fprintf(&msg, " |__ Retries: %d\n", d.HealInfo.RetryAttempts)
}
}
fmt.Fprintf(&msg, " |__ Capacity: %s/%s\n", humanize.IBytes(d.UsedSpace), humanize.IBytes(d.TotalSpace))
if showTolerance {
fmt.Fprintf(&msg, " |__ Tolerance: %d drive(s)\n", parity-setsStatus[setIndex{d.PoolIndex, d.SetIndex}].incapableDisks)
fmt.Fprintf(&msg, " |__ Tolerance: %d drive(s)\n", parity-thisSet.incapableDisks)
}
}
fmt.Fprintf(&msg, "\n")
if serverHeaderPrinted {
fmt.Fprintf(&msg, "\n")
}
}
}
@@ -472,9 +514,6 @@ func (s shortBackgroundHealStatusMessage) String() string {
// The addition of Elapsed time of each parallel healing operation
// this is needed to calculate the rate of healing
accumulatedElapsedTime time.Duration
// ETA of healing - it is the latest ETA of all drives currently healing
healingRemaining time.Duration
)
var problematicDisks int
@@ -495,12 +534,19 @@ func (s shortBackgroundHealStatusMessage) String() string {
continue
}
if disk.HealInfo != nil {
if disk.HealInfo != nil && !disk.HealInfo.Finished {
missingInSet++
diskSet := setIndex{pool: disk.PoolIndex, set: disk.SetIndex}
if maxUsedSpace := setsStatus[diskSet].maxUsedSpace; maxUsedSpace > 0 {
if pct := float64(disk.UsedSpace) / float64(maxUsedSpace); pct < leastPct {
thisSet := setsStatus[setIndex{pool: disk.PoolIndex, set: disk.SetIndex}]
refUsedSpace := uint64(math.MaxUint64)
if thisSet.readyDisksCount > 0 {
refUsedSpace = thisSet.readyDisksUsedSpace / uint64(thisSet.readyDisksCount)
}
if refUsedSpace < disk.UsedSpace {
refUsedSpace = disk.UsedSpace
}
if refUsedSpace > 0 {
if pct := float64(disk.UsedSpace) / float64(refUsedSpace); pct < leastPct {
leastPct = pct
}
} else {
@@ -508,12 +554,6 @@ func (s shortBackgroundHealStatusMessage) String() string {
leastPct = 0
}
scanSpeed := float64(disk.UsedSpace) / float64(time.Since(disk.HealInfo.Started))
remainingTime := time.Duration(float64(setsStatus[diskSet].maxUsedSpace-disk.UsedSpace) / scanSpeed)
if remainingTime > healingRemaining {
healingRemaining = remainingTime
}
disk := disk
if furthestHealingDisk == nil {
furthestHealingDisk = &disk
@@ -576,10 +616,6 @@ func (s shortBackgroundHealStatusMessage) String() string {
healPrettyMsg += fmt.Sprintf("Heal rate: %d obj/s, %s/s\n", int64(itemsHealedPerSec), humanize.IBytes(uint64(bytesHealedPerSec)))
}
// Estimation completion
now := time.Now()
healPrettyMsg += fmt.Sprintf("Estimated Completion: %s\n", humanize.RelTime(now, now.Add(healingRemaining), "", ""))
if problematicDisks > 0 {
healPrettyMsg += "\n"
healPrettyMsg += fmt.Sprintf("%d offline disk(s) found.", problematicDisks)
@@ -659,6 +695,7 @@ func mainAdminHeal(ctx *cli.Context) error {
printMsg(verboseBackgroundHealStatusMessage{
Status: "success",
HealInfo: bgHealStatus,
allDrives: ctx.Bool("all-drives"),
ToleranceForSC: strings.ToUpper(ctx.String("storage-class")),
})
} else {
@@ -705,6 +742,16 @@ func mainAdminHeal(ctx *cli.Context) error {
return nil
}
if opts.Recursive && opts.Pool == nil && opts.Set == nil && isTerminal() && !ctx.Bool("force") {
fmt.Printf("You are about to scan and heal the whole namespace in all pools and sets, please confirm [y/N]: ")
answer, e := bufio.NewReader(os.Stdin).ReadString('\n')
fatalIf(probe.NewError(e), "Unable to parse user input.")
if answer = strings.TrimSpace(strings.ToLower(answer)); answer != "y" && answer != "yes" {
fmt.Println("Heal aborted!")
return nil
}
}
healStart, _, e := adminClnt.Heal(globalContext, bucket, prefix, opts, "", forceStart, false)
fatalIf(probe.NewError(e), "Unable to start healing.")
+16 -16
View File
@@ -95,9 +95,11 @@ func clusterSummaryInfo(info madmin.InfoMessage) clusterInfo {
}
}
if disk.DiskIndex < (info.Backend.DrivesPerSet[disk.PoolIndex] - info.Backend.StandardSCParity) {
pool.drivesTotalFreeSpace += disk.AvailableSpace
pool.drivesTotalUsableSpace += disk.TotalSpace
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)
@@ -105,8 +107,6 @@ func clusterSummaryInfo(info madmin.InfoMessage) clusterInfo {
}
}
// This was already added in 2022 enough time has passed to remove
// any other deprecated calculations
for idx := range info.Backend.TotalSets {
pool := summary[idx]
if pool != nil {
@@ -150,11 +150,6 @@ func (u clusterStruct) String() (msg string) {
fatal(probe.NewError(errors.New("Unable to get service info")), "")
}
// Validate such that we expect the server to be atleast from 2022
if len(u.Info.Backend.TotalSets) == 0 || len(u.Info.Backend.DrivesPerSet) == 0 {
fatal(probe.NewError(errors.New("Unable to display service info, server is too old")), "")
}
// Initialization
var totalOfflineNodes int
@@ -299,6 +294,7 @@ func (u clusterStruct) String() (msg string) {
"Erasure sets",
})
var printSummary bool
// Keep the pool order while printing the output
for poolIdx := 0; poolIdx < len(clusterSummary); poolIdx++ {
summary := clusterSummary[poolIdx]
@@ -308,12 +304,14 @@ func (u clusterStruct) String() (msg string) {
totalSize := summary.drivesTotalUsableSpace
usedCurrent := summary.drivesTotalUsableSpace - summary.drivesTotalFreeSpace
var capacity string
if totalSize == 0 {
capacity = "0% (total: 0B)"
} else {
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,
@@ -322,10 +320,12 @@ func (u clusterStruct) String() (msg string) {
})
}
e := tbl.PopulateTable(&builder, cellText)
fatalIf(probe.NewError(e), "unable to populate the table")
if printSummary {
e := tbl.PopulateTable(&builder, cellText)
fatalIf(probe.NewError(e), "unable to populate the table")
msg += builder.String() + "\n"
msg += builder.String() + "\n"
}
}
// Summary on used space, total no of buckets and
+3 -9
View File
@@ -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))
+1
View File
@@ -56,6 +56,7 @@ var adminCmdSubcommands = []cli.Command{
adminClusterCmd,
adminRebalanceCmd,
adminLogsCmd,
adminAccesskeyCmd,
}
var adminCmd = cli.Command{
+9 -2
View File
@@ -23,6 +23,10 @@ import (
"github.com/minio/mc/pkg/probe"
)
const (
errCodeChangeAlreadyApplied = "XMinioAdminPolicyChangeAlreadyApplied"
)
var adminAttachPolicyFlags = []cli.Flag{
cli.StringFlag{
Name: "user, u",
@@ -97,10 +101,13 @@ func userAttachOrDetachPolicy(ctx *cli.Context, attach bool) error {
} else {
res, e = client.DetachPolicy(globalContext, req)
}
fatalIf(probe.NewError(e), "Unable to make user/group policy association")
if e != nil && madmin.ToErrorResponse(e).Code != errCodeChangeAlreadyApplied {
fatalIf(probe.NewError(e), "Unable to make user/group policy association")
}
var emptyResp madmin.PolicyAssociationResp
if res.UpdatedAt == emptyResp.UpdatedAt {
if res.UpdatedAt.Equal(emptyResp.UpdatedAt) {
// Older minio does not send a result, so we populate res manually to
// simulate a result. TODO(aditya): remove this after newer minio is
// released in a few months (Older API Deprecated in Jun 2023)
+3 -3
View File
@@ -32,7 +32,7 @@ var (
metricsV3Flags = []cli.Flag{
cli.StringFlag{
Name: "bucket",
Usage: "bucket name to list metrics for. only applicable with api version v3 for metric type 'bucket'",
Usage: "bucket name to list metrics for. only applicable with api version v3 for metric type 'api, replication'",
},
}
@@ -79,11 +79,11 @@ func validateV3Args(subsys string, bucket string) {
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 `"+bms+"`"))
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 `"+bms+"`"))
fatalIf(errInvalidArgument().Trace(), fmt.Sprintf("--bucket is applicable only for metric types `%s`", bms))
}
}
}
+6 -6
View File
@@ -83,27 +83,27 @@ func (i srRemoveStatus) String() string {
if i.RemoveAll {
return console.Colorize("UserMessage", "All site(s) were removed successfully")
}
if i.ReplicateRemoveStatus.Status == madmin.ReplicateRemoveStatusSuccess {
if i.Status == madmin.ReplicateRemoveStatusSuccess {
return console.Colorize("UserMessage", fmt.Sprintf("Following site(s) %s were removed successfully", i.sites))
}
if len(i.sites) == 1 {
return console.Colorize("UserMessage", fmt.Sprintf("Following site %s was removed partially, some operations failed:\nERROR: '%s'", i.sites, i.ReplicateRemoveStatus.ErrDetail))
return console.Colorize("UserMessage", fmt.Sprintf("Following site %s was removed partially, some operations failed:\nERROR: '%s'", i.sites, i.ErrDetail))
}
return console.Colorize("UserMessage", fmt.Sprintf("Following site(s) %s were removed partially, some operations failed: \nERROR: '%s'", i.sites, i.ReplicateRemoveStatus.ErrDetail))
return console.Colorize("UserMessage", fmt.Sprintf("Following site(s) %s were removed partially, some operations failed: \nERROR: '%s'", i.sites, i.ErrDetail))
}
func checkAdminReplicateRemoveSyntax(ctx *cli.Context) {
// Check argument count
argsNr := len(ctx.Args())
if ctx.IsSet("all") && argsNr > 1 {
if ctx.Bool("all") && argsNr > 1 {
fatalIf(errInvalidArgument().Trace(ctx.Args().Tail()...),
"")
}
if argsNr < 2 && !ctx.IsSet("all") {
if argsNr < 2 && !ctx.Bool("all") {
fatalIf(errInvalidArgument().Trace(ctx.Args().Tail()...),
"Need at least two arguments to remove command.")
}
if !ctx.IsSet("force") {
if !ctx.Bool("force") {
fatalIf(errDummy().Trace(),
"Site removal requires --force flag. This operation is *IRREVERSIBLE*. Please review carefully before performing this *DANGEROUS* operation.")
}
+5 -6
View File
@@ -74,13 +74,12 @@ func (m resyncCancelMessage) String() string {
}
func mainAdminReplicateResyncCancel(ctx *cli.Context) error {
{
// Check argument count
argsNr := len(ctx.Args())
if argsNr != 2 {
cli.ShowCommandHelpAndExit(ctx, "cancel", 1) // last argument is exit code
}
// Check argument count
argsNr := len(ctx.Args())
if argsNr != 2 {
showCommandHelpAndExit(ctx, 1) // last argument is exit code
}
console.SetColor("ResyncMessage", color.New(color.FgGreen))
// Get the alias parameter from cli
+6 -7
View File
@@ -21,10 +21,11 @@ import (
"fmt"
"strings"
"github.com/minio/madmin-go/v3"
"github.com/fatih/color"
"github.com/minio/cli"
json "github.com/minio/colorjson"
"github.com/minio/madmin-go/v3"
"github.com/minio/mc/pkg/probe"
"github.com/minio/pkg/v3/console"
)
@@ -74,12 +75,10 @@ func (m resyncMessage) String() string {
}
func mainAdminReplicateResyncStart(ctx *cli.Context) error {
{
// Check argument count
argsNr := len(ctx.Args())
if argsNr != 2 {
cli.ShowCommandHelpAndExit(ctx, "start", 1) // last argument is exit code
}
// Check argument count
argsNr := len(ctx.Args())
if argsNr != 2 {
showCommandHelpAndExit(ctx, 1) // last argument is exit code
}
console.SetColor("ResyncMessage", color.New(color.FgGreen))
+5 -7
View File
@@ -60,12 +60,10 @@ EXAMPLES:
}
func mainAdminReplicationResyncStatus(ctx *cli.Context) error {
{
// Check argument count
argsNr := len(ctx.Args())
if argsNr != 2 {
cli.ShowCommandHelpAndExit(ctx, "status", 1) // last argument is exit code
}
// Check argument count
argsNr := len(ctx.Args())
if argsNr != 2 {
showCommandHelpAndExit(ctx, 1) // last argument is exit code
}
console.SetColor("ResyncMessage", color.New(color.FgGreen))
@@ -208,7 +206,7 @@ func (m *resyncMetricsUI) View() string {
table.SetNoWhiteSpace(true)
var data [][]string
addLine := func(prefix string, value interface{}) {
addLine := func(prefix string, value any) {
data = append(data, []string{
prefix,
whiteStyle.Render(fmt.Sprint(value)),
+20 -33
View File
@@ -167,8 +167,8 @@ func (i srStatus) String() string {
if i.opts.Buckets {
messages = append(messages,
console.Colorize("SummaryHdr", "Bucket replication status:"))
switch {
case i.MaxBuckets == 0:
switch i.MaxBuckets {
case 0:
messages = append(messages, console.Colorize("Summary", "No Buckets present\n"))
default:
msg := console.Colorize(i.getTheme(len(info.BucketStats) == 0), fmt.Sprintf("%d/%d Buckets in sync", info.MaxBuckets-len(info.BucketStats), info.MaxBuckets)) + "\n"
@@ -204,8 +204,8 @@ func (i srStatus) String() string {
if i.opts.Policies {
messages = append(messages,
console.Colorize("SummaryHdr", "Policy replication status:"))
switch {
case i.MaxPolicies == 0:
switch i.MaxPolicies {
case 0:
messages = append(messages, console.Colorize("Summary", "No Policies present\n"))
default:
msg := console.Colorize(i.getTheme(len(i.PolicyStats) == 0), fmt.Sprintf("%d/%d Policies in sync", info.MaxPolicies-len(info.PolicyStats), info.MaxPolicies)) + "\n"
@@ -243,8 +243,8 @@ func (i srStatus) String() string {
if i.opts.Users {
messages = append(messages,
console.Colorize("SummaryHdr", "User replication status:"))
switch {
case i.MaxUsers == 0:
switch i.MaxUsers {
case 0:
messages = append(messages, console.Colorize("Summary", "No Users present\n"))
default:
msg := console.Colorize(i.getTheme(len(i.UserStats) == 0), fmt.Sprintf("%d/%d Users in sync", info.MaxUsers-len(i.UserStats), info.MaxUsers)) + "\n"
@@ -284,8 +284,8 @@ func (i srStatus) String() string {
if i.opts.Groups {
messages = append(messages,
console.Colorize("SummaryHdr", "Group replication status:"))
switch {
case i.MaxGroups == 0:
switch i.MaxGroups {
case 0:
messages = append(messages, console.Colorize("Summary", "No Groups present\n"))
default:
msg := console.Colorize(i.getTheme(len(i.GroupStats) == 0), fmt.Sprintf("%d/%d Groups in sync", i.MaxGroups-len(i.GroupStats), i.MaxGroups)) + "\n"
@@ -426,10 +426,7 @@ func (i srStatus) String() string {
currDowntime = UTCNow().Sub(m.LastOnline)
}
// normalize because total downtime is calculated at server side at heartbeat interval, may be slightly behind
totalDowntime := m.TotalDowntime
if currDowntime > totalDowntime {
totalDowntime = currDowntime
}
totalDowntime := max(currDowntime, m.TotalDowntime)
var linkStatus string
if m.Online {
linkStatus = healthDot + fmt.Sprintf(" online (total downtime: %s)", timeDurationToHumanizedDuration(totalDowntime).String())
@@ -478,7 +475,7 @@ func (i srStatus) getBucketStatusSummary(siteNames []string, nameIDMap map[strin
var messages []string
coloredDot := console.Colorize("Status", dot)
var found bool
for _, st := range i.SRStatusInfo.BucketStats[i.opts.EntityValue] {
for _, st := range i.BucketStats[i.opts.EntityValue] {
if st.HasBucket {
found = true
break
@@ -518,7 +515,7 @@ func (i srStatus) getBucketStatusSummary(siteNames []string, nameIDMap map[strin
rows := make([]string, len(rowLegend))
for j, sname := range siteNames {
dID := nameIDMap[sname]
ss := i.SRStatusInfo.BucketStats[i.opts.EntityValue][dID]
ss := i.BucketStats[i.opts.EntityValue][dID]
var theme, msgStr string
for r := range rowLegend {
switch r {
@@ -582,7 +579,7 @@ func (i srStatus) getPolicyStatusSummary(siteNames []string, nameIDMap map[strin
var messages []string
coloredDot := console.Colorize("Status", dot)
var found bool
for _, st := range i.SRStatusInfo.PolicyStats[i.opts.EntityValue] {
for _, st := range i.PolicyStats[i.opts.EntityValue] {
if st.HasPolicy {
found = true
break
@@ -603,7 +600,7 @@ func (i srStatus) getPolicyStatusSummary(siteNames []string, nameIDMap map[strin
rows := make([]string, len(rowLegend))
for j, sname := range siteNames {
dID := nameIDMap[sname]
ss := i.SRStatusInfo.PolicyStats[i.opts.EntityValue][dID]
ss := i.PolicyStats[i.opts.EntityValue][dID]
var theme, msgStr string
for r := range rowLegend {
switch r {
@@ -634,7 +631,7 @@ func (i srStatus) getUserStatusSummary(siteNames []string, nameIDMap map[string]
var messages []string
coloredDot := console.Colorize("Status", dot)
var found bool
for _, st := range i.SRStatusInfo.UserStats[i.opts.EntityValue] {
for _, st := range i.UserStats[i.opts.EntityValue] {
if st.HasUser {
found = true
break
@@ -662,7 +659,7 @@ func (i srStatus) getUserStatusSummary(siteNames []string, nameIDMap map[string]
rows := make([]string, len(rowLegend))
for j, sname := range siteNames {
dID := nameIDMap[sname]
ss := i.SRStatusInfo.UserStats[i.opts.EntityValue][dID]
ss := i.UserStats[i.opts.EntityValue][dID]
var theme, msgStr string
for r := range rowLegend {
switch r {
@@ -702,7 +699,7 @@ func (i srStatus) getGroupStatusSummary(siteNames []string, nameIDMap map[string
rowLegend := []string{"Info", "Policy mapping"}
detailFields := make([][]Field, len(rowLegend))
var found bool
for _, st := range i.SRStatusInfo.GroupStats[i.opts.EntityValue] {
for _, st := range i.GroupStats[i.opts.EntityValue] {
if st.HasGroup {
found = true
break
@@ -728,7 +725,7 @@ func (i srStatus) getGroupStatusSummary(siteNames []string, nameIDMap map[string
// b := i.opts.EntityValue
for j, sname := range siteNames {
dID := nameIDMap[sname]
ss := i.SRStatusInfo.GroupStats[i.opts.EntityValue][dID]
ss := i.GroupStats[i.opts.EntityValue][dID]
// sm := i.SRStatusInfo.StatsSummary
var theme, msgStr string
for r := range rowLegend {
@@ -767,7 +764,7 @@ func (i srStatus) getILMExpiryStatusSummary(siteNames []string, nameIDMap map[st
var messages []string
coloredDot := console.Colorize("Status", dot)
var found bool
for _, st := range i.SRStatusInfo.ILMExpiryStats[i.opts.EntityValue] {
for _, st := range i.ILMExpiryStats[i.opts.EntityValue] {
if st.HasILMExpiryRules {
found = true
break
@@ -788,7 +785,7 @@ func (i srStatus) getILMExpiryStatusSummary(siteNames []string, nameIDMap map[st
rows := make([]string, len(rowLegend))
for j, sname := range siteNames {
dID := nameIDMap[sname]
ss := i.SRStatusInfo.ILMExpiryStats[i.opts.EntityValue][dID]
ss := i.ILMExpiryStats[i.opts.EntityValue][dID]
var theme, msgStr string
for r := range rowLegend {
switch r {
@@ -817,17 +814,7 @@ func (i srStatus) getILMExpiryStatusSummary(siteNames []string, nameIDMap map[st
// Calculate srstatus options for command line flags
func srStatusOpts(ctx *cli.Context) (opts madmin.SRStatusOptions) {
if !(ctx.IsSet("buckets") ||
ctx.IsSet("users") ||
ctx.IsSet("groups") ||
ctx.IsSet("policies") ||
ctx.IsSet("ilm-expiry-rules") ||
ctx.IsSet("bucket") ||
ctx.IsSet("user") ||
ctx.IsSet("group") ||
ctx.IsSet("policy") ||
ctx.IsSet("ilm-expiry-rule") ||
ctx.IsSet("all")) || ctx.IsSet("all") {
if (!ctx.IsSet("buckets") && !ctx.IsSet("users") && !ctx.IsSet("groups") && !ctx.IsSet("policies") && !ctx.IsSet("ilm-expiry-rules") && !ctx.IsSet("bucket") && !ctx.IsSet("user") && !ctx.IsSet("group") && !ctx.IsSet("policy") && !ctx.IsSet("ilm-expiry-rule") && !ctx.IsSet("all")) || ctx.IsSet("all") {
opts.Buckets = true
opts.Users = true
opts.Groups = true
+148 -36
View File
@@ -26,13 +26,16 @@ import (
"io"
"os"
"sort"
"strconv"
"strings"
"time"
"github.com/charmbracelet/bubbles/spinner"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/lipgloss"
"github.com/dustin/go-humanize"
"github.com/fatih/color"
"github.com/klauspost/compress/zstd"
"github.com/minio/cli"
json "github.com/minio/colorjson"
"github.com/minio/madmin-go/v3"
@@ -62,9 +65,12 @@ var adminScannerInfoFlags = []cli.Flag{
Value: -1,
},
cli.StringFlag{
Name: "in",
Hidden: true,
Usage: "read previously saved json from file and replay",
Name: "in",
Usage: "read previously saved json from file and replay",
},
cli.StringFlag{
Name: "bucket",
Usage: "show scan stats about a given bucket",
},
}
@@ -103,10 +109,94 @@ func checkAdminScannerInfoSyntax(ctx *cli.Context) {
}
}
func mainAdminScannerInfo(ctx *cli.Context) error {
checkAdminScannerInfoSyntax(ctx)
// bucketScanMsg container for content message structure
type bucketScanMsg struct {
Status string `json:"status"`
Stats []madmin.BucketScanInfo `json:"stats"`
}
aliasedURL := ctx.Args().Get(0)
func (b bucketScanMsg) String() string {
var sb strings.Builder
sb.WriteString("\n")
sort.Slice(b.Stats, func(i, j int) bool { return b.Stats[i].LastUpdate.Before(b.Stats[j].LastUpdate) })
pt := newPrettyTable(" | ",
Field{"Pool", 5},
Field{"Set", 5},
Field{"LastUpdate", timeFieldMaxLen},
)
sb.WriteString(console.Colorize("Headers", pt.buildRow("Pool", "Set", "Last Update")) + "\n")
now := time.Now().UTC()
for i := range b.Stats {
sb.WriteString(
pt.buildRow(
strconv.Itoa(b.Stats[i].Pool+1),
strconv.Itoa(b.Stats[i].Set+1),
humanize.RelTime(now, b.Stats[i].LastUpdate, "", "ago"),
) + "\n")
}
var (
earliestESScan time.Time // the earliest ES that completed a bucket scan
latestESScan time.Time // the last ES that completed a bucket scan
fullScan = true
)
// Look for a bucket full scan inforation only if all
// erasure sets completed at least 16 cycles
for _, st := range b.Stats {
if len(st.Completed) < 16 {
fullScan = false
break
}
if earliestESScan.IsZero() {
// First stats
earliestESScan = st.Completed[0]
latestESScan = st.Completed[len(st.Completed)-1]
continue
}
if earliestESScan.Before(st.Completed[0]) {
earliestESScan = st.Completed[0]
}
if latestESScan.After(st.Completed[len(st.Completed)-1]) {
latestESScan = st.Completed[len(st.Completed)-1]
}
}
sb.WriteString("\n")
if fullScan {
took := latestESScan.Sub(earliestESScan)
sb.WriteString(
fmt.Sprintf(
"%s %s (took %s)\n",
console.Colorize("FullScan", "Full bucket scan: "),
humanize.RelTime(now, latestESScan, "", "ago"),
fmt.Sprintf("%dd%dh%dm", int(took.Hours()/24), int(took.Hours())%24, int(took.Minutes())%60)),
)
}
sb.WriteString("\n")
return sb.String()
}
func (b bucketScanMsg) JSON() string {
b.Status = "success"
jsonMessageBytes, e := json.MarshalIndent(b, "", " ")
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
return string(jsonMessageBytes)
}
func mainAdminScannerInfo(ctx *cli.Context) error {
console.SetColor("Headers", color.New(color.Bold, color.FgHiGreen))
console.SetColor("FullScan", color.New(color.Bold, color.FgHiGreen))
checkAdminScannerInfoSyntax(ctx)
ui := tea.NewProgram(initScannerMetricsUI(ctx.Int("max-paths")))
ctxt, cancel := context.WithCancel(globalContext)
@@ -117,12 +207,20 @@ func mainAdminScannerInfo(ctx *cli.Context) error {
go func() {
if _, e := ui.Run(); e != nil {
cancel()
fatalIf(probe.NewError(e).Trace(aliasedURL), "Unable to fetch scanner metrics")
fatalIf(probe.NewError(e), "Unable to fetch scanner metrics")
}
}()
f, e := os.Open(inFile)
fatalIf(probe.NewError(e).Trace(aliasedURL), "Unable to open input")
sc := bufio.NewReader(f)
fatalIf(probe.NewError(e), "Unable to open input")
defer f.Close()
in := io.Reader(f)
if strings.HasSuffix(inFile, ".zst") {
zr, e := zstd.NewReader(in)
fatalIf(probe.NewError(e), "Unable to open input")
defer zr.Close()
in = zr
}
sc := bufio.NewReader(in)
var lastTime time.Time
for {
b, e := sc.ReadBytes('\n')
@@ -148,9 +246,17 @@ func mainAdminScannerInfo(ctx *cli.Context) error {
}
// Create a new MinIO Admin Client
aliasedURL := ctx.Args().Get(0)
client, err := newAdminClient(aliasedURL)
fatalIf(err.Trace(aliasedURL), "Unable to initialize admin client.")
if bucket := ctx.String("bucket"); bucket != "" {
bucketStats, err := client.BucketScanInfo(globalContext, bucket)
fatalIf(probe.NewError(err).Trace(aliasedURL), "Unable to get bucket stats.")
printMsg(bucketScanMsg{Stats: bucketStats})
return nil
}
opts := madmin.MetricsOptions{
Type: madmin.MetricsScanner,
N: ctx.Int("n"),
@@ -291,7 +397,7 @@ func (m *scannerMetricsUI) View() string {
writtenRows++
}
_ = addRow
addRowF := func(format string, vals ...interface{}) {
addRowF := func(format string, vals ...any) {
s := fmt.Sprintf(format, vals...)
table.Append([]string{s})
writtenRows++
@@ -305,37 +411,43 @@ func (m *scannerMetricsUI) View() string {
title := metricsTitle
ui := metricsUint64
const wantCycles = 16
addRow("")
if len(sc.CyclesCompletedAt) < 2 {
addRow("Last full scan time: Unknown (not enough data)")
if sc.CurrentCycle == 0 && sc.CurrentStarted.IsZero() && sc.CyclesCompletedAt == nil {
addRowF(" "+title("Scanning:")+" %d bucket(s)", sc.OngoingBuckets)
} else {
addRow("Overall Statistics")
addRow("------------------")
sort.Slice(sc.CyclesCompletedAt, func(i, j int) bool {
return sc.CyclesCompletedAt[i].After(sc.CyclesCompletedAt[j])
})
if len(sc.CyclesCompletedAt) >= wantCycles {
sinceLast := sc.CyclesCompletedAt[0].Sub(sc.CyclesCompletedAt[wantCycles-1])
perMonth := float64(30*24*time.Hour) / float64(sinceLast)
cycleTime := console.Colorize("metrics-number", fmt.Sprintf("%dd%dh%dm", int(sinceLast.Hours()/24), int(sinceLast.Hours())%24, int(sinceLast.Minutes())%60))
perms := console.Colorize("metrics-number", fmt.Sprintf("%.02f", perMonth))
addRowF(title("Last full scan time:")+" %s; Estimated %s/month", cycleTime, perms)
const wantCycles = 16
if len(sc.CyclesCompletedAt) < 2 {
addRow("Last full scan time: Unknown (not enough data)")
} else {
sinceLast := sc.CyclesCompletedAt[0].Sub(sc.CyclesCompletedAt[1]) * time.Duration(wantCycles)
perMonth := float64(30*24*time.Hour) / float64(sinceLast)
cycleTime := console.Colorize("metrics-number", fmt.Sprintf("%dd%dh%dm", int(sinceLast.Hours()/24), int(sinceLast.Hours())%24, int(sinceLast.Minutes())%60))
perms := console.Colorize("metrics-number", fmt.Sprintf("%.02f", perMonth))
addRowF(title("Est. full scan time:")+" %s; Estimated %s/month", cycleTime, perms)
addRow("Overall Statistics")
addRow("------------------")
sort.Slice(sc.CyclesCompletedAt, func(i, j int) bool {
return sc.CyclesCompletedAt[i].After(sc.CyclesCompletedAt[j])
})
if len(sc.CyclesCompletedAt) >= wantCycles {
sinceLast := sc.CyclesCompletedAt[0].Sub(sc.CyclesCompletedAt[wantCycles-1])
perMonth := float64(30*24*time.Hour) / float64(sinceLast)
cycleTime := console.Colorize("metrics-number", fmt.Sprintf("%dd%dh%dm", int(sinceLast.Hours()/24), int(sinceLast.Hours())%24, int(sinceLast.Minutes())%60))
perms := console.Colorize("metrics-number", fmt.Sprintf("%.02f", perMonth))
addRowF(title("Last full scan time:")+" %s; Estimated %s/month", cycleTime, perms)
} else {
sinceLast := sc.CyclesCompletedAt[0].Sub(sc.CyclesCompletedAt[1]) * time.Duration(wantCycles)
perMonth := float64(30*24*time.Hour) / float64(sinceLast)
cycleTime := console.Colorize("metrics-number", fmt.Sprintf("%dd%dh%dm", int(sinceLast.Hours()/24), int(sinceLast.Hours())%24, int(sinceLast.Minutes())%60))
perms := console.Colorize("metrics-number", fmt.Sprintf("%.02f", perMonth))
addRowF(title("Est. full scan time:")+" %s; Estimated %s/month", cycleTime, perms)
}
}
if sc.CurrentCycle > 0 {
addRowF(title("Current cycle:")+" %s; Started: %v", ui(sc.CurrentCycle), console.Colorize("metrics-date", sc.CurrentStarted))
} else {
addRowF("%s", title("Current cycle:")+" (between cycles)")
}
}
if sc.CurrentCycle > 0 {
addRowF(title("Current cycle:")+" %s; Started: %v", ui(sc.CurrentCycle), console.Colorize("metrics-date", sc.CurrentStarted))
addRowF(title("Active drives:")+" %s", ui(uint64(len(sc.ActivePaths))))
} else {
addRowF(title("Current cycle:") + " (between cycles)")
addRowF(title("Active drives:")+" %s", ui(uint64(len(sc.ActivePaths))))
}
addRowF(title("Active drives:")+" %s", ui(uint64(len(sc.ActivePaths))))
getRate := func(x madmin.TimedAction) string {
if x.AccTime > 0 {
return fmt.Sprintf("; Rate: %v/day", ui(uint64(float64(24*time.Hour)/(float64(time.Minute)/float64(x.Count)))))
+4 -2
View File
@@ -173,7 +173,7 @@ func (m *serviceRestartUI) View() string {
func initServiceRestartUI(rowCount int, currentCh chan serviceRestartMessage) *serviceRestartUI {
var printColors []*color.Color
for i := 0; i < rowCount; i++ {
for range rowCount {
printColors = append(printColors, getPrintCol(colGreen))
}
@@ -251,7 +251,7 @@ func mainAdminServiceRestart(ctx *cli.Context) error {
fatalIf(err, "Unable to initialize admin connection.")
rowCount := 2
toWait := ctx.IsSet("wait")
toWait := ctx.Bool("wait")
if toWait {
rowCount = 3
}
@@ -269,6 +269,8 @@ func mainAdminServiceRestart(ctx *cli.Context) error {
})
if e != nil {
// Attempt an older API server might be old
// nolint:staticcheck
// we need this fallback
e = client.ServiceRestart(ctxt)
}
fatalIf(probe.NewError(e), "Unable to restart the server.")
+15 -2
View File
@@ -18,6 +18,8 @@
package cmd
import (
"context"
"github.com/fatih/color"
"github.com/minio/cli"
json "github.com/minio/colorjson"
@@ -74,7 +76,7 @@ func checkAdminServiceUnfreezeSyntax(ctx *cli.Context) {
}
func mainAdminServiceUnfreeze(ctx *cli.Context) error {
// Validate serivce unfreeze syntax.
// Validate service unfreeze syntax.
checkAdminServiceUnfreezeSyntax(ctx)
// Set color.
@@ -88,8 +90,19 @@ func mainAdminServiceUnfreeze(ctx *cli.Context) error {
client, err := newAdminClient(aliasedURL)
fatalIf(err, "Unable to initialize admin connection.")
ctxt, cancel := context.WithCancel(globalContext)
defer cancel()
// Unfreeze the specified MinIO server
fatalIf(probe.NewError(client.ServiceUnfreeze(globalContext)), "Unable to unfreeze the server.")
e := client.ServiceUnfreezeV2(ctxt)
if e != nil {
// Attempt an older API server might be old
// nolint:staticcheck
// we need this fallback
e = client.ServiceUnfreeze(ctxt)
}
// Unfreeze the specified MinIO server
fatalIf(probe.NewError(e), "Unable to unfreeze the server.")
// Success..
printMsg(serviceUnfreezeCommand{Status: "success", ServerURL: aliasedURL})
+1 -1
View File
@@ -28,7 +28,7 @@ var adminServiceSubcommands = []cli.Command{
var adminServiceCmd = cli.Command{
Name: "service",
Usage: "restart, stop and unfreeze a MinIO cluster",
Usage: "restart or unfreeze a MinIO cluster",
Action: mainAdminService,
Before: setGlobalsFromContext,
Flags: globalFlags,
+97 -24
View File
@@ -18,12 +18,15 @@
package cmd
import (
"bufio"
"bytes"
"context"
"fmt"
"hash/fnv"
"io"
"net/http"
"net/url"
"os"
"path"
"sort"
"strings"
@@ -33,6 +36,7 @@ import (
tea "github.com/charmbracelet/bubbletea"
"github.com/dustin/go-humanize"
"github.com/fatih/color"
"github.com/klauspost/compress/zstd"
"github.com/minio/cli"
json "github.com/minio/colorjson"
"github.com/minio/madmin-go/v3"
@@ -92,7 +96,7 @@ var adminTraceFlags = []cli.Flag{
cli.IntFlag{
Name: "stats-n",
Usage: "maximum number of stat entries",
Value: 30,
Value: 20,
Hidden: true,
},
cli.BoolFlag{
@@ -111,6 +115,10 @@ var adminTraceFlags = []cli.Flag{
Name: "filter-size",
Usage: "filter size, use with filter (see UNITS)",
},
cli.StringFlag{
Name: "in",
Usage: "read previously saved json from file and replay",
},
}
// traceCallTypes contains all call types and flags to apply when selected.
@@ -239,7 +247,7 @@ const traceTimeFormat = "2006-01-02T15:04:05.000"
var colors = []color.Attribute{color.FgCyan, color.FgWhite, color.FgYellow, color.FgGreen}
func checkAdminTraceSyntax(ctx *cli.Context) {
if len(ctx.Args()) != 1 {
if len(ctx.Args()) != 1 && len(ctx.String("in")) == 0 {
showCommandHelpAndExit(ctx, 1) // last argument is exit code
}
filterFlag := ctx.Bool("filter-request") || ctx.Bool("filter-response")
@@ -403,12 +411,10 @@ func (opts matchOpts) matches(traceInfo madmin.ServiceTraceInfo) bool {
}
}
if opts.requestSize > 0 && traceInfo.Trace.HTTP.CallStats.InputBytes < int(opts.requestSize) {
return false
}
if opts.responseSize > 0 && traceInfo.Trace.HTTP.CallStats.OutputBytes < int(opts.responseSize) {
return false
if traceInfo.Trace.HTTP != nil {
if (opts.requestSize > 0 && traceInfo.Trace.HTTP.CallStats.InputBytes < int(opts.requestSize)) || (opts.responseSize > 0 && traceInfo.Trace.HTTP.CallStats.OutputBytes < int(opts.responseSize)) {
return false
}
}
return true
@@ -489,7 +495,6 @@ func mainAdminTrace(ctx *cli.Context) error {
verbose := ctx.Bool("verbose")
stats := ctx.Bool("stats")
aliasedURL := ctx.Args().Get(0)
console.SetColor("Stat", color.New(color.FgYellow))
@@ -510,26 +515,81 @@ func mainAdminTrace(ctx *cli.Context) error {
for _, c := range colors {
console.SetColor(fmt.Sprintf("Node%d", c), color.New(c))
}
// Create a new MinIO Admin Client
client, err := newAdminClient(aliasedURL)
if err != nil {
fatalIf(err.Trace(aliasedURL), "Unable to initialize admin client.")
return nil
}
var traceCh <-chan madmin.ServiceTraceInfo
ctxt, cancel := context.WithCancel(globalContext)
defer cancel()
opts, e := tracingOpts(ctx, ctx.StringSlice("call"))
fatalIf(probe.NewError(e), "Unable to start tracing")
if inFile := ctx.String("in"); inFile != "" {
stats = true
ch := make(chan madmin.ServiceTraceInfo, 1000)
traceCh = ch
go func() {
f, e := os.Open(inFile)
fatalIf(probe.NewError(e), "Unable to open input")
defer f.Close()
in := io.Reader(f)
if strings.HasSuffix(inFile, ".zst") {
zr, e := zstd.NewReader(in)
fatalIf(probe.NewError(e), "Unable to open input")
defer zr.Close()
in = zr
}
sc := bufio.NewReader(in)
for ctxt.Err() == nil {
b, e := sc.ReadBytes('\n')
if e == io.EOF {
break
}
var t shortTraceMsg
e = json.Unmarshal(b, &t)
if e != nil || t.Type == "Bootstrap" {
// Ignore bootstrap, since their times skews averages.
continue
}
ch <- madmin.ServiceTraceInfo{
Trace: madmin.TraceInfo{
TraceType: t.trcType, // TODO: Grab from string, once we can.
NodeName: t.Host,
FuncName: t.FuncName,
Time: t.Time,
Path: t.Path,
Duration: t.Duration,
Bytes: t.Size,
Message: t.StatusMsg,
Error: t.Error,
Custom: t.Extra,
HTTP: nil,
HealResult: nil,
},
Err: nil,
}
}
close(ch)
select {}
}()
} else {
// Create a new MinIO Admin Client
aliasedURL := ctx.Args().Get(0)
client, err := newAdminClient(aliasedURL)
if err != nil {
fatalIf(err.Trace(aliasedURL), "Unable to initialize admin client.")
return nil
}
opts, e := tracingOpts(ctx, ctx.StringSlice("call"))
fatalIf(probe.NewError(e), "Unable to start tracing")
// Start listening on all trace activity.
traceCh = client.ServiceTrace(ctxt, opts)
}
mopts := matchingOpts(ctx)
// Start listening on all trace activity.
traceCh := client.ServiceTrace(ctxt, opts)
if stats {
filteredTraces := make(chan madmin.ServiceTraceInfo, 1)
ui := tea.NewProgram(initTraceStatsUI(ctx.Int("stats-n"), filteredTraces))
ui := tea.NewProgram(initTraceStatsUI(ctx.Bool("all"), ctx.Int("stats-n"), filteredTraces))
var te error
go func() {
for t := range traceCh {
@@ -542,12 +602,14 @@ func mainAdminTrace(ctx *cli.Context) error {
filteredTraces <- t
}
}
ui.Send(tea.Quit())
}()
if _, e := ui.Run(); e != nil {
cancel()
if te != nil {
e = te
}
aliasedURL := ctx.Args().Get(0)
fatalIf(probe.NewError(e).Trace(aliasedURL), "Unable to fetch http trace statistics")
}
return nil
@@ -915,9 +977,10 @@ type statItem struct {
}
type statTrace struct {
Calls map[string]statItem `json:"calls"`
Started time.Time
mu sync.Mutex
Calls map[string]statItem `json:"calls"`
Oldest time.Time
Latest time.Time
mu sync.Mutex
}
func (s *statTrace) JSON() string {
@@ -942,6 +1005,16 @@ func (s *statTrace) add(t madmin.ServiceTraceInfo) {
id := t.Trace.FuncName
s.mu.Lock()
defer s.mu.Unlock()
if t.Trace.TraceType != madmin.TraceBootstrap {
// We can't use bootstrap to find start/end
ended := t.Trace.Time.Add(t.Trace.Duration)
if s.Oldest.IsZero() {
s.Oldest = ended
}
if ended.After(s.Latest) {
s.Latest = ended
}
}
got := s.Calls[id]
if got.Name == "" {
got.Name = id
+1 -1
View File
@@ -244,7 +244,7 @@ func generateCredentials() (accessKey, secretKey string, err *probe.Error) {
if e != nil {
return "", "", probe.NewError(e)
}
for i := 0; i < accessKeyMaxLen; i++ {
for i := range accessKeyMaxLen {
keyBytes[i] = alphaNumericTable[keyBytes[i]%alphaNumericTableLen]
}
accessKey = string(keyBytes)
+49 -37
View File
@@ -20,10 +20,13 @@ package cmd
import (
"fmt"
"sort"
"strings"
"github.com/fatih/color"
"github.com/minio/cli"
"github.com/minio/pkg/v3/console"
"github.com/minio/pkg/v3/env"
"github.com/fatih/color"
)
var aliasListCmd = cli.Command{
@@ -75,6 +78,7 @@ func mainAliasList(ctx *cli.Context, deprecated bool) error {
console.SetColor("SecretKey", color.New(color.FgCyan))
console.SetColor("API", color.New(color.FgBlue))
console.SetColor("Path", color.New(color.FgCyan))
console.SetColor("Src", color.New(color.FgCyan))
alias := cleanAlias(ctx.Args().Get(0))
@@ -115,51 +119,59 @@ func (d byAlias) Len() int { return len(d) }
func (d byAlias) Swap(i, j int) { d[i], d[j] = d[j], d[i] }
func (d byAlias) Less(i, j int) bool { return d[i].Alias < d[j].Alias }
func buildAliasMessage(alias string, deprecated bool, aliasCfg *aliasConfigV10) aliasMessage {
aliasMsg := aliasMessage{
prettyPrint: false,
Alias: alias,
URL: aliasCfg.URL,
AccessKey: aliasCfg.AccessKey,
SecretKey: aliasCfg.SecretKey,
API: aliasCfg.API,
Src: aliasCfg.Src,
}
if deprecated {
aliasMsg.Lookup = aliasCfg.Path
} else {
aliasMsg.Path = aliasCfg.Path
}
return aliasMsg
}
// listAliases - list one or all aliases
func listAliases(alias string, deprecated bool) (aliases []aliasMessage) {
conf, err := loadMcConfig()
fatalIf(err.Trace(globalMCConfigVersion), "Unable to load config version `"+globalMCConfigVersion+"`.")
// If specific alias is requested, look for it and print.
if alias != "" {
if v, ok := conf.Aliases[alias]; ok {
aliasMsg := aliasMessage{
prettyPrint: false,
Alias: alias,
URL: v.URL,
AccessKey: v.AccessKey,
SecretKey: v.SecretKey,
API: v.API,
}
if deprecated {
aliasMsg.Lookup = v.Path
} else {
aliasMsg.Path = v.Path
}
return []aliasMessage{aliasMsg}
aliasCfg := mustGetHostConfig(alias)
if aliasCfg != nil {
return []aliasMessage{buildAliasMessage(alias, deprecated, aliasCfg)}
}
fatalIf(errInvalidAliasedURL(alias), "No such alias `"+alias+"` found.")
}
// list alias from the environment variable.
for _, envK := range env.List(mcEnvHostPrefix) {
aliasCfg, _ := expandAliasFromEnv(env.Get(envK, ""))
if aliasCfg == nil {
continue
}
alias := strings.ReplaceAll(envK, mcEnvHostPrefix, "")
aliases = append(aliases, buildAliasMessage(alias, deprecated, aliasCfg))
}
// list alias from the customized configuration.
for s, aliasCfg := range aliasToConfigMap {
aliases = append(aliases, buildAliasMessage(s, deprecated, aliasCfg))
}
// list alias from the default configuration.
conf, err := loadMcConfig()
fatalIf(err.Trace(globalMCConfigVersion), "Unable to load config version `"+globalMCConfigVersion+"`.")
for k, v := range conf.Aliases {
aliasMsg := aliasMessage{
prettyPrint: true,
Alias: k,
URL: v.URL,
AccessKey: v.AccessKey,
SecretKey: v.SecretKey,
API: v.API,
}
if deprecated {
aliasMsg.Lookup = v.Path
} else {
aliasMsg.Path = v.Path
}
aliases = append(aliases, aliasMsg)
v.Src = mustGetMcConfigPath()
aliases = append(aliases, buildAliasMessage(k, deprecated, &v))
}
// Sort by alias names lexically.
+3 -1
View File
@@ -73,6 +73,7 @@ type aliasMessage struct {
SecretKey string `json:"secretKey,omitempty"`
API string `json:"api,omitempty"`
Path string `json:"path,omitempty"`
Src string `json:"src,omitempty"`
// Deprecated field, replaced by Path
Lookup string `json:"lookup,omitempty"`
}
@@ -91,13 +92,14 @@ func (h aliasMessage) String() string {
Row{"SecretKey", "SecretKey"},
Row{"API", "API"},
Row{"Path", "Path"},
Row{"Src", "Src"},
)
// Handle deprecated lookup
path := h.Path
if path == "" {
path = h.Lookup
}
return t.buildRecord(h.Alias, h.URL, h.AccessKey, h.SecretKey, h.API, path)
return t.buildRecord(h.Alias, h.URL, h.AccessKey, h.SecretKey, h.API, path, h.Src)
case "remove":
return console.Colorize("AliasMessage", "Removed `"+h.Alias+"` successfully.")
case "add": // add is deprecated
+6 -9
View File
@@ -24,7 +24,6 @@ import (
"crypto/x509"
"fmt"
"math/rand"
"net"
"net/http"
"os"
"strings"
@@ -149,7 +148,7 @@ func checkAliasSetSyntax(ctx *cli.Context, accessKey, secretKey string, deprecat
}
} else {
if !isValidPath(path) {
fatalIf(errInvalidArgument().Trace(bucketLookup),
fatalIf(errInvalidArgument().Trace(path),
"Unrecognized path value. Valid options are `[auto, on, off]`.")
}
}
@@ -373,25 +372,23 @@ func configurePeerCertificate(s3Config *Config, peerCert *x509.Certificate) {
globalRootCAs.AddCert(peerCert)
}
tr = &http.Transport{
Proxy: http.ProxyFromEnvironment,
DialContext: (&net.Dialer{
Timeout: 10 * time.Second,
KeepAlive: 15 * time.Second,
}).DialContext,
Proxy: http.ProxyFromEnvironment,
DialContext: newCustomDialContext(&Config{}),
DialTLSContext: newCustomDialTLSContext(&tls.Config{RootCAs: globalRootCAs}),
MaxIdleConnsPerHost: 256,
IdleConnTimeout: 90 * time.Second,
TLSHandshakeTimeout: 10 * time.Second,
ExpectContinueTimeout: 10 * time.Second,
DisableCompression: true,
TLSClientConfig: &tls.Config{RootCAs: globalRootCAs},
}
case tr.TLSClientConfig == nil || tr.TLSClientConfig.RootCAs == nil:
if globalRootCAs != nil {
globalRootCAs.AddCert(peerCert)
}
tr.TLSClientConfig = &tls.Config{RootCAs: globalRootCAs}
tr.DialTLSContext = newCustomDialTLSContext(&tls.Config{RootCAs: globalRootCAs})
default:
tr.TLSClientConfig.RootCAs.AddCert(peerCert)
tr.DialTLSContext = newCustomDialTLSContext(tr.TLSClientConfig)
}
s3Config.Transport = tr
}
+7 -7
View File
@@ -116,11 +116,11 @@ func (s anonymousRules) JSON() string {
// anonymousMessage is container for anonymous command on bucket success and failure messages.
type anonymousMessage struct {
Operation string `json:"operation"`
Status string `json:"status"`
Bucket string `json:"bucket"`
Perms accessPerms `json:"permission"`
Anonymous map[string]interface{} `json:"anonymous,omitempty"`
Operation string `json:"operation"`
Status string `json:"status"`
Bucket string `json:"bucket"`
Perms accessPerms `json:"permission"`
Anonymous map[string]any `json:"anonymous,omitempty"`
}
// String colorized access message.
@@ -406,7 +406,7 @@ func runAnonymousLinksCmd(args cli.Args, recursive bool) {
// Encode public URL
u, e := url.Parse(content.URL.String())
errorIf(probe.NewError(e), "Unable to parse url `"+content.URL.String()+"`.")
errorIf(probe.NewError(e), "Unable to parse url `%s`.", content.URL)
publicURL := u.String()
// Construct the message to be displayed to the user
@@ -464,7 +464,7 @@ func runAnonymousCmd(args cli.Args) {
"Unable to "+operation+" anonymous `"+string(perms)+"` for `"+targetURL+"`.")
}
}
anonymousJSON := map[string]interface{}{}
anonymousJSON := map[string]any{}
if anonymousStr != "" {
e := json.Unmarshal([]byte(anonymousStr), &anonymousJSON)
fatalIf(probe.NewError(e), "Unable to unmarshal custom anonymous file.")
+29
View File
@@ -369,6 +369,15 @@ var completeCmds = map[string]complete.Predictor{
"/idp/openid/enable": aliasCompleter,
"/idp/openid/disable": aliasCompleter,
"/idp/openid/accesskey/list": aliasCompleter,
"/idp/openid/accesskey/ls": aliasCompleter,
"/idp/openid/accesskey/info": aliasCompleter,
"/idp/openid/accesskey/remove": aliasCompleter,
"/idp/openid/accesskey/rm": aliasCompleter,
"/idp/openid/accesskey/edit": aliasCompleter,
"/idp/openid/accesskey/enable": aliasCompleter,
"/idp/openid/accesskey/disable": aliasCompleter,
"/idp/ldap/add": aliasCompleter,
"/idp/ldap/update": aliasCompleter,
"/idp/ldap/remove": aliasCompleter,
@@ -388,6 +397,21 @@ var completeCmds = map[string]complete.Predictor{
"/idp/ldap/accesskey/remove": aliasCompleter,
"/idp/ldap/accesskey/rm": aliasCompleter,
"/idp/ldap/accesskey/info": aliasCompleter,
"/idp/ldap/accesskey/edit": aliasCompleter,
"/idp/ldap/accesskey/enable": aliasCompleter,
"/idp/ldap/accesskey/disable": aliasCompleter,
"/idp/ldap/accesskey/sts-revoke": aliasCompleter,
"/admin/accesskey/create": aliasCompleter,
"/admin/accesskey/list": aliasCompleter,
"/admin/accesskey/ls": aliasCompleter,
"/admin/accesskey/remove": aliasCompleter,
"/admin/accesskey/rm": aliasCompleter,
"/admin/accesskey/info": aliasCompleter,
"/admin/accesskey/edit": aliasCompleter,
"/admin/accesskey/enable": aliasCompleter,
"/admin/accesskey/disable": aliasCompleter,
"/admin/accesskey/sts-revoke": aliasCompleter,
"/admin/policy/info": aliasCompleter,
"/admin/policy/update": aliasCompleter,
@@ -489,6 +513,7 @@ var completeCmds = map[string]complete.Predictor{
"/support/top/drive": aliasCompleter,
"/support/top/disk": aliasCompleter,
"/support/top/net": aliasCompleter,
"/support/top/rpc": aliasCompleter,
"/support/upload": aliasCompleter,
"/license/register": aliasCompleter,
@@ -511,6 +536,10 @@ var completeCmds = map[string]complete.Predictor{
"/quota/clear": aliasCompleter,
"/put": complete.PredictOr(s3Completer, fsCompleter),
"/get": complete.PredictOr(s3Completer, fsCompleter),
"/cors/set": s3Complete{deepLevel: 2},
"/cors/get": s3Complete{deepLevel: 2},
"/cors/remove": s3Complete{deepLevel: 2},
}
// flagsToCompleteFlags transforms a cli.Flag to complete.Flags
+47 -12
View File
@@ -19,9 +19,9 @@ package cmd
import (
"fmt"
"strings"
"github.com/minio/cli"
json "github.com/minio/colorjson"
"github.com/minio/madmin-go/v3"
"github.com/minio/mc/pkg/probe"
)
@@ -40,26 +40,22 @@ USAGE:
{{.HelpName}} TARGET JOBTYPE
JOBTYPE:
` + supportedJobTypes() + `
- replicate
- keyrotate
- expire
Use the special value "list" to request server to list supported job types.
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Generate a new batch 'replication' job definition:
{{.Prompt}} {{.HelpName}} myminio replicate > replication.yaml
2. List all supported job types:
{{.Prompt}} {{.HelpName}} myminio list
`,
}
func supportedJobTypes() string {
var builder strings.Builder
for _, jobType := range madmin.SupportedJobTypes {
builder.WriteString(" - ")
builder.WriteString(string(jobType))
builder.WriteString("\n")
}
return builder.String()
}
// checkBatchGenerateSyntax - validate all the passed arguments
func checkBatchGenerateSyntax(ctx *cli.Context) {
if len(ctx.Args()) != 2 {
@@ -80,6 +76,45 @@ func mainBatchGenerate(ctx *cli.Context) error {
adminClient, err := newAdminClient(aliasedURL)
fatalIf(err, "Unable to initialize admin connection.")
if jobType == "list" {
supportedJobTypes, apiUnavailable, e := adminClient.GetSupportedBatchJobTypes(globalContext)
if e != nil {
fatalIf(probe.NewError(e), "Unable to list supported job types")
}
if apiUnavailable {
// Fallback to default supported jobs.
supportedJobTypes = madmin.SupportedJobTypes
}
if globalJSON {
j, err := json.Marshal(supportedJobTypes)
if err != nil {
fatalIf(probe.NewError(err), "Unable to marshal supported job types")
}
fmt.Println(string(j))
} else {
for _, jobType := range supportedJobTypes {
fmt.Println(jobType)
}
}
return nil
}
// Try GenerateV2 API.
template, apiUnavailable, e := adminClient.GenerateBatchJobV2(globalContext, madmin.GenerateBatchJobOpts{
Type: madmin.BatchJobType(jobType),
})
if e != nil {
fatalIf(probe.NewError(e), "Unable to generate template for %s", args.Get(1))
}
// Check if server supports GenerateV2 API.
if !apiUnavailable {
fmt.Println(template)
return nil
}
// As API is not supported we fallback to returning the static job template.
var found bool
for _, job := range madmin.SupportedJobTypes {
if jobType == string(job) {
+61 -3
View File
@@ -66,6 +66,7 @@ EXAMPLES:
type batchListMessage struct {
Status string `json:"status"`
Jobs []madmin.BatchJobResult `json:"jobs"`
Admin *madmin.AdminClient `json:"-"` // Add AdminClient to fetch job status
}
// String colorized batchList message
@@ -90,15 +91,35 @@ func (c batchListMessage) String() string {
table.SetTablePadding("\t") // pad with tabs
table.SetNoWhiteSpace(true)
table.SetHeader([]string{"ID", "TYPE", "USER", "STARTED"})
data := make([][]string, 0, 4)
// Add a new "STATUS" column to the table header
table.SetHeader([]string{"ID", "TYPE", "USER", "STARTED", "STATUS"})
data := make([][]string, 0, 5)
// Fetch the status for the batch job using BatchJobStatus API
for _, job := range c.Jobs {
jobStatus := "unknown"
jobMetric, err := c.Admin.BatchJobStatus(context.Background(), job.ID)
// Output error if the API call fails, but continue processing remaining jobs
if err != nil {
println("Failed to fetch job status for Job ID:", job.ID, "Error:", err.Error())
} else {
if jobMetric.LastMetric.Complete && !jobMetric.LastMetric.Failed {
jobStatus = "completed"
} else if !jobMetric.LastMetric.Complete && !jobMetric.LastMetric.Failed {
jobStatus = "in-progress"
} else if jobMetric.LastMetric.Failed {
jobStatus = "failed"
}
}
// Add jobStatus details to the data table
data = append(data, []string{
job.ID,
string(job.Type),
job.User,
humanize.Time(job.Started),
jobStatus,
})
}
@@ -111,7 +132,43 @@ func (c batchListMessage) String() string {
// JSON jsonified batchList message
func (c batchListMessage) JSON() string {
c.Status = "success"
batchListMessageBytes, e := json.MarshalIndent(c, "", " ")
// Create a temporary slice to hold jobs with derived statuses
jobsWithStatus := make([]map[string]interface{}, len(c.Jobs))
// Fetch the status for the batch job using BatchJobStatus API
for i, job := range c.Jobs {
jobStatus := "unknown"
jobMetric, err := c.Admin.BatchJobStatus(context.Background(), job.ID)
// Output error if the API call fails, but continue processing remaining jobs
if err != nil {
println("Failed to fetch job status for Job ID:", job.ID, "Error:", err.Error())
} else {
if jobMetric.LastMetric.Complete && !jobMetric.LastMetric.Failed {
jobStatus = "completed"
} else if !jobMetric.LastMetric.Complete && !jobMetric.LastMetric.Failed {
jobStatus = "in-progress"
} else if jobMetric.LastMetric.Failed {
jobStatus = "failed"
}
}
// Add the job details along with the derived status
jobsWithStatus[i] = map[string]interface{}{
"id": job.ID,
"type": job.Type,
"user": job.User,
"started": job.Started,
"status": jobStatus,
}
}
// Marshal the updated jobs into JSON
batchListMessageBytes, e := json.MarshalIndent(map[string]interface{}{
"status": c.Status,
"jobs": jobsWithStatus,
}, "", " ")
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
return string(batchListMessageBytes)
@@ -147,6 +204,7 @@ func mainBatchList(ctx *cli.Context) error {
printMsg(batchListMessage{
Status: "success",
Jobs: res.Jobs,
Admin: adminClient, // Pass the adminClient for status lookups
})
return nil
}
+33 -5
View File
@@ -128,10 +128,19 @@ func mainBatchStatus(ctx *cli.Context) error {
return
}
printMsg(batchJobStatusMessage{
m := batchJobStatusMessage{
Status: "in-progress",
Metric: job,
})
}
switch {
case job.Complete:
m.Status = "complete"
case job.Failed:
m.Status = "failed"
default:
// leave as is with in-progress
}
printMsg(m)
if job.Complete || job.Failed {
cancel()
return
@@ -223,7 +232,7 @@ func (m *batchJobMetricsUI) View() string {
table.SetNoWhiteSpace(true)
var data [][]string
addLine := func(prefix string, value interface{}) {
addLine := func(prefix string, value any) {
data = append(data, []string{
prefix,
whiteStyle.Render(fmt.Sprint(value)),
@@ -249,6 +258,8 @@ func (m *batchJobMetricsUI) View() string {
addLine("Objects: ", m.metric.Replicate.Objects)
addLine("Versions: ", m.metric.Replicate.Objects)
addLine("FailedObjects: ", m.metric.Replicate.ObjectsFailed)
addLine("DeleteMarker: ", m.metric.Replicate.DeleteMarkers)
addLine("FailedDeleteMarker: ", m.metric.Replicate.DeleteMarkersFailed)
if accElapsedTime > 0 {
bytesTransferredPerSec := float64(m.metric.Replicate.BytesTransferred) / accElapsedTime.Seconds()
objectsPerSec := float64(int64(time.Second)*m.metric.Replicate.Objects) / float64(accElapsedTime)
@@ -256,19 +267,36 @@ func (m *batchJobMetricsUI) View() string {
addLine("IOPs: ", fmt.Sprintf("%.2f objs/s", objectsPerSec))
}
addLine("Transferred: ", humanize.IBytes(uint64(m.metric.Replicate.BytesTransferred)))
addLine("Elapsed: ", accElapsedTime.String())
addLine("Elapsed: ", accElapsedTime.Round(time.Second).String())
addLine("CurrObjName: ", m.metric.Replicate.Object)
case string(madmin.BatchJobExpire):
addLine("JobType: ", m.metric.JobType)
addLine("Objects: ", m.metric.Expired.Objects)
addLine("FailedObjects: ", m.metric.Expired.ObjectsFailed)
addLine("DeleteMarker: ", m.metric.Expired.DeleteMarkers)
addLine("FailedDeleteMarker: ", m.metric.Expired.DeleteMarkersFailed)
addLine("CurrObjName: ", m.metric.Expired.Object)
if !m.metric.LastUpdate.IsZero() {
accElapsedTime := m.metric.LastUpdate.Sub(m.metric.StartTime)
addLine("Elapsed: ", accElapsedTime.String())
}
case string(madmin.BatchJobCatalog):
addLine("JobType: ", m.metric.JobType)
addLine("ObjectsScannedCount: ", m.metric.Catalog.ObjectsScannedCount)
addLine("ObjectsMatchedCount: ", m.metric.Catalog.ObjectsMatchedCount)
lastScanned := fmt.Sprintf("%s/%s", m.metric.Catalog.LastBucketScanned, m.metric.Catalog.LastObjectScanned)
addLine("LastScanned: ", lastScanned)
lastMatched := fmt.Sprintf("%s/%s", m.metric.Catalog.LastBucketMatched, m.metric.Catalog.LastObjectMatched)
addLine("LastMatched: ", lastMatched)
accElapsedTime := m.metric.LastUpdate.Sub(m.metric.StartTime)
addLine("RecordsWrittenCount: ", m.metric.Catalog.RecordsWrittenCount)
addLine("OutputObjectsCount: ", m.metric.Catalog.OutputObjectsCount)
addLine("Elapsed: ", accElapsedTime.Round(time.Second).String())
addLine("Scan Speed: ", fmt.Sprintf("%f objects/s", float64(m.metric.Catalog.ObjectsScannedCount)/accElapsedTime.Seconds()))
if m.metric.Catalog.ErrorMsg != "" {
addLine("Error: ", m.metric.Catalog.ErrorMsg)
}
}
table.AppendBulk(data)
+15 -6
View File
@@ -55,6 +55,10 @@ var catFlags = []cli.Flag{
Name: "tail",
Usage: "tail number of bytes at ending of file",
},
cli.IntFlag{
Name: "part-number",
Usage: "download only a specific part number",
},
}
// Display contents of a file.
@@ -162,6 +166,7 @@ type catOpts struct {
timeRef time.Time
startO int64
tailO int64
partN int
isZip bool
stdinMode bool
}
@@ -197,6 +202,7 @@ func parseCatSyntax(ctx *cli.Context) catOpts {
o.isZip = ctx.Bool("zip")
o.startO = ctx.Int64("offset")
o.tailO = ctx.Int64("tail")
o.partN = ctx.Int("part-number")
if o.tailO != 0 && o.startO != 0 {
fatalIf(errInvalidArgument().Trace(), "You cannot specify both --tail and --offset")
}
@@ -209,6 +215,9 @@ func parseCatSyntax(ctx *cli.Context) catOpts {
if o.stdinMode && (o.isZip || o.startO != 0 || o.tailO != 0) {
fatalIf(errInvalidArgument().Trace(), "You cannot use --zip --tail or --offset with stdin")
}
if (o.tailO != 0 || o.startO != 0) && o.partN > 0 {
fatalIf(errInvalidArgument().Trace(), "You cannot use --part-number with --tail or --offset")
}
return o
}
@@ -242,13 +251,10 @@ func catURL(ctx context.Context, sourceURL string, encKeyDB map[string][]prefixS
versionID = content.VersionID
}
if o.tailO > 0 && content.Size > 0 {
o.startO = content.Size - o.tailO
if o.startO < 0 {
o.startO = max(content.Size-o.tailO,
// Return all.
o.startO = 0
}
0)
}
if client.GetURL().Type == objectStorage {
size = content.Size - o.startO
if size < 0 {
@@ -256,10 +262,13 @@ func catURL(ctx context.Context, sourceURL string, encKeyDB map[string][]prefixS
return err.Trace(sourceURL)
}
}
if o.partN != 0 {
size = int64(-1)
}
} else {
return err.Trace(sourceURL)
}
gopts := GetOptions{VersionID: versionID, Zip: o.isZip, RangeStart: o.startO}
gopts := GetOptions{VersionID: versionID, Zip: o.isZip, RangeStart: o.startO, PartNumber: o.partN}
if reader, err = getSourceStreamFromURL(ctx, sourceURL, encKeyDB, getSourceOpts{
GetOptions: gopts,
preserve: false,
+10 -24
View File
@@ -20,7 +20,6 @@ package cmd
import (
"crypto/tls"
"fmt"
"net"
"net/http"
"net/url"
"sync"
@@ -58,9 +57,9 @@ func NewAdminFactory() func(config *Config) (*madmin.AdminClient, *probe.Error)
var found bool
if api, found = clientCache[confSum]; !found {
transport := getTransportForConfig(config, true)
transport := config.getTransport()
credsChain, err := getCredentialsChainForConfig(config, transport)
credsChain, err := config.getCredsChain()
if err != nil {
return nil, err
}
@@ -138,10 +137,7 @@ func newAnonymousClient(aliasedURL string) (*madmin.AnonymousClient, *probe.Erro
}
// By default enable HTTPs.
useTLS := true
if targetURL.Scheme == "http" {
useTLS = false
}
useTLS := targetURL.Scheme != "http"
// Construct an anonymous client
anonClient, e := madmin.NewAnonymousClient(targetURL.Host, useTLS)
@@ -149,29 +145,19 @@ func newAnonymousClient(aliasedURL string) (*madmin.AnonymousClient, *probe.Erro
return nil, probe.NewError(e)
}
// Keep TLS config.
tlsConfig := &tls.Config{
RootCAs: globalRootCAs,
// Can't use SSLv3 because of POODLE and BEAST
// Can't use TLSv1.0 because of POODLE and BEAST using CBC cipher
// Can't use TLSv1.1 because of RC4 cipher usage
MinVersion: tls.VersionTLS12,
}
if globalInsecure {
tlsConfig.InsecureSkipVerify = true
}
// Set custom transport
var transport http.RoundTripper = &http.Transport{
Proxy: ieproxy.GetProxyFunc(),
DialContext: (&net.Dialer{
Timeout: 10 * time.Second,
KeepAlive: 15 * time.Second,
}).DialContext,
Proxy: ieproxy.GetProxyFunc(),
DialContext: newCustomDialContext(&Config{}),
DialTLSContext: newCustomDialTLSContext(&tls.Config{
RootCAs: globalRootCAs,
MinVersion: tls.VersionTLS12,
InsecureSkipVerify: globalInsecure,
}),
MaxIdleConnsPerHost: 256,
IdleConnTimeout: 90 * time.Second,
TLSHandshakeTimeout: 10 * time.Second,
ExpectContinueTimeout: 10 * time.Second,
TLSClientConfig: tlsConfig,
// Set this value so that the underlying transport round-tripper
// doesn't try to auto decode the body of objects with
// content-encoding set to `gzip`.
+2 -2
View File
@@ -35,8 +35,8 @@ func (h adminPolicyHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusForbidden)
return
}
switch {
case r.Method == "PUT":
switch r.Method {
case "PUT":
length, e := strconv.Atoi(r.Header.Get("Content-Length"))
if e != nil {
w.WriteHeader(http.StatusBadRequest)
+85 -10
View File
@@ -22,6 +22,7 @@ import (
"errors"
"fmt"
"io"
"maps"
"os"
"path"
"path/filepath"
@@ -32,6 +33,8 @@ import (
"syscall"
"time"
"github.com/google/uuid"
"github.com/pkg/xattr"
"github.com/rjeczalik/notify"
@@ -40,6 +43,7 @@ import (
"github.com/minio/mc/pkg/hookreader"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio-go/v7"
"github.com/minio/minio-go/v7/pkg/cors"
"github.com/minio/minio-go/v7/pkg/encrypt"
"github.com/minio/minio-go/v7/pkg/lifecycle"
"github.com/minio/minio-go/v7/pkg/notification"
@@ -300,8 +304,12 @@ func (f *fsClient) put(_ context.Context, reader io.Reader, size int64, progress
objectPath := f.PathURL.Path
// Write to a temporary file "object.part.minio" before commit.
objectPartPath := objectPath + partSuffix
if err := checkPathLength(objectPath); err != nil {
return 0, err
}
// Write to a temporary file "objectpath/uuid" before commit.
objectPartPath := filepath.Join(filepath.Dir(objectPath), uuid.NewString())
// We cannot resume this operation, then we
// should remove any partial download if any.
@@ -392,6 +400,49 @@ func (f *fsClient) Put(ctx context.Context, reader io.Reader, size int64, progre
return f.put(ctx, reader, size, progress, opts)
}
// checkPathLength - returns error if given path name length more than 255
func checkPathLength(pathName string) *probe.Error {
// Apple OS X path length is limited to 1016
if runtime.GOOS == "darwin" && len(pathName) > 1016 {
return probe.NewError(errors.New("file name too long"))
}
// Disallow more than 32,767 characters on windows, there
// are no known name_max limits on Windows.
// Refer: https://learn.microsoft.com/en-us/windows/win32/fileio/maximum-file-path-limitation?tabs=registry
if runtime.GOOS == "windows" && len(pathName) > 32767 {
return probe.NewError(errors.New("file name too long"))
}
// On Unix we reject paths if they are just '.', '..' or '/'
if pathName == "." || pathName == ".." || pathName == "/" {
return probe.NewError(errors.New("file access denied"))
}
// Check each path segment length is > 255 on all Unix
// platforms, look for this value as NAME_MAX in
// /usr/include/linux/limits.h
var count int64
for _, p := range pathName {
switch p {
case '/':
count = 0 // Reset
case '\\':
if runtime.GOOS == "windows" {
count = 0
} else {
count++
}
default:
count++
}
if count > 255 {
return probe.NewError(errors.New("file name too long"))
}
} // Success.
return nil
}
func (f *fsClient) putN(_ context.Context, reader io.Reader, size int64, progress io.Reader, opts PutOptions) (int64, *probe.Error) {
// ContentType is not handled on purpose.
// For filesystem this is a redundant information.
@@ -414,8 +465,12 @@ func (f *fsClient) putN(_ context.Context, reader io.Reader, size int64, progres
objectPath := f.PathURL.Path
// Write to a temporary file "object.part.minio" before commit.
objectPartPath := objectPath + partSuffix
if err := checkPathLength(objectPath); err != nil {
return 0, err
}
// Write to a temporary file ""objectpath/uuid"" before commit.
objectPartPath := filepath.Join(filepath.Dir(objectPath), uuid.NewString())
// We cannot resume this operation, then we
// should remove any partial download if any.
@@ -580,9 +635,7 @@ func (f *fsClient) Get(_ context.Context, opts GetOptions) (io.ReadCloser, *Clie
if pErr != nil {
return nil, content, nil
}
for k, v := range metaData {
content.Metadata[k] = v
}
maps.Copy(content.Metadata, metaData)
content.Metadata[metadataKey] = fileAttr
}
@@ -1307,9 +1360,7 @@ func (f *fsClient) Stat(_ context.Context, opts StatOptions) (content *ClientCon
if pErr != nil {
return content, nil
}
for k, v := range metaData {
content.Metadata[k] = v
}
maps.Copy(content.Metadata, metaData)
content.Metadata[metadataKey] = fileAttr
}
@@ -1507,3 +1558,27 @@ func (f *fsClient) GetPart(_ context.Context, _ int) (io.ReadCloser, *probe.Erro
APIType: "filesystem",
})
}
// GetBucketCors - not implemented
func (f *fsClient) GetBucketCors(_ context.Context) (*cors.Config, *probe.Error) {
return nil, probe.NewError(APINotImplemented{
API: "GetBucketCors",
APIType: "filesystem",
})
}
// SetBucketCors - not implemented
func (f *fsClient) SetBucketCors(_ context.Context, _ []byte) *probe.Error {
return probe.NewError(APINotImplemented{
API: "SetBucketCors",
APIType: "filesystem",
})
}
// DeleteBucketCors - not implemented
func (f *fsClient) DeleteBucketCors(_ context.Context) *probe.Error {
return probe.NewError(APINotImplemented{
API: "DeleteBucketCors",
APIType: "filesystem",
})
}
-1
View File
@@ -1,5 +1,4 @@
//go:build darwin
// +build darwin
// Copyright (c) 2015-2021 MinIO, Inc.
//
-1
View File
@@ -1,5 +1,4 @@
//go:build linux
// +build linux
// Copyright (c) 2015-2021 MinIO, Inc.
//
-1
View File
@@ -1,5 +1,4 @@
//go:build solaris || openbsd
// +build solaris openbsd
// Copyright (c) 2015-2021 MinIO, Inc.
//
+1 -2
View File
@@ -1,5 +1,4 @@
//go:build windows
// +build windows
// Copyright (c) 2015-2021 MinIO, Inc.
//
@@ -56,6 +55,6 @@ func IsDeleteEvent(event notify.Event) bool {
// getAllXattrs returns the extended attributes for a file if supported
// by the OS
func getAllXattrs(path string) (map[string]string, error) {
func getAllXattrs(_ string) (map[string]string, error) {
return nil, nil
}
+6
View File
@@ -38,6 +38,7 @@ func newTraceV4() httptracer.HTTPTracer {
// Request - Trace HTTP Request
func (t traceV4) Request(req *http.Request) (err error) {
origAuth := req.Header.Get("Authorization")
sseKey := req.Header.Get("X-Amz-Server-Side-Encryption-Customer-Key")
printTrace := func() error {
reqTrace, rerr := httputil.DumpRequestOut(req, false) // Only display header
@@ -47,6 +48,11 @@ func (t traceV4) Request(req *http.Request) (err error) {
return rerr
}
if strings.TrimSpace(sseKey) != "" {
// Stripe out SSE-C key from: X-Amz-Server-Side-Encryption-Customer-Key=<key>
req.Header.Set("X-Amz-Server-Side-Encryption-Customer-Key", "**REDACTED**")
}
if strings.TrimSpace(origAuth) != "" {
// Authorization (S3 v4 signature) Format:
// Authorization: AWS4-HMAC-SHA256 Credential=AKIAJNACEGBGMXBHLEZA/20150524/us-east-1/s3/aws4_request, SignedHeaders=host;x-amz-content-sha256;x-amz-date, Signature=bbfaa693c626021bcb5f911cd898a1a30206c1fad6bad1e0eb89e282173bd24c
+149 -127
View File
@@ -26,7 +26,7 @@ import (
"fmt"
"hash/fnv"
"io"
"math/rand"
"maps"
"net"
"net/http"
"net/url"
@@ -37,9 +37,10 @@ import (
"sort"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/klauspost/compress/gzhttp"
"github.com/minio/minio-go/v7/pkg/cors"
"github.com/minio/pkg/v3/env"
"github.com/minio/minio-go/v7"
@@ -55,8 +56,6 @@ import (
"github.com/minio/pkg/v3/mimedb"
"github.com/minio/mc/pkg/deadlineconn"
"github.com/minio/mc/pkg/httptracer"
"github.com/minio/mc/pkg/limiter"
"github.com/minio/mc/pkg/probe"
)
@@ -106,6 +105,14 @@ func newCustomDialContext(c *Config) dialContext {
KeepAlive: 15 * time.Second,
}
if ip, ok := globalResolvers[addr]; ok {
if _, port, err := net.SplitHostPort(addr); err == nil {
addr = net.JoinHostPort(ip.String(), port)
} else {
addr = ip.String()
}
}
conn, err := dialer.DialContext(ctx, network, addr)
if err != nil {
return nil, err
@@ -119,6 +126,31 @@ func newCustomDialContext(c *Config) dialContext {
}
}
// newCustomDialTLSContext setups a custom TLS dialer for any external communication and proxies.
func newCustomDialTLSContext(tlsConf *tls.Config) dialContext {
return func(ctx context.Context, network, addr string) (net.Conn, error) {
dialer := &tls.Dialer{
NetDialer: &net.Dialer{
Timeout: 10 * time.Second,
KeepAlive: 15 * time.Second,
},
Config: tlsConf,
}
if ip, ok := globalResolvers[addr]; ok {
dialer.Config = dialer.Config.Clone()
if host, port, err := net.SplitHostPort(addr); err == nil {
dialer.Config.ServerName = host // Set SNI
addr = net.JoinHostPort(ip.String(), port)
} else {
dialer.Config.ServerName = addr // Set SNI
addr = ip.String()
}
}
return dialer.DialContext(ctx, network, addr)
}
}
var timeSentinel = time.Unix(0, 0).UTC()
// getConfigHash returns the Hash for che *Config
@@ -147,120 +179,35 @@ func isHostTLS(config *Config) bool {
return useTLS
}
// getTransportForConfig returns a corresponding *http.Transport for the *Config
// set withS3v2 bool to true to add traceV2 tracer.
func getTransportForConfig(config *Config, withS3v2 bool) http.RoundTripper {
var transport http.RoundTripper
useTLS := isHostTLS(config)
if config.Transport != nil {
transport = config.Transport
} else {
tr := &http.Transport{
Proxy: http.ProxyFromEnvironment,
DialContext: newCustomDialContext(config),
MaxIdleConnsPerHost: 1024,
WriteBufferSize: 32 << 10, // 32KiB moving up from 4KiB default
ReadBufferSize: 32 << 10, // 32KiB moving up from 4KiB default
IdleConnTimeout: 90 * time.Second,
TLSHandshakeTimeout: 10 * time.Second,
ExpectContinueTimeout: 10 * time.Second,
// Set this value so that the underlying transport round-tripper
// doesn't try to auto decode the body of objects with
// content-encoding set to `gzip`.
//
// Refer:
// https://golang.org/src/net/http/transport.go?h=roundTrip#L1843
DisableCompression: true,
}
if useTLS {
// Keep TLS config.
tlsConfig := &tls.Config{
RootCAs: globalRootCAs,
// Can't use SSLv3 because of POODLE and BEAST
// Can't use TLSv1.0 because of POODLE and BEAST using CBC cipher
// Can't use TLSv1.1 because of RC4 cipher usage
MinVersion: tls.VersionTLS12,
}
if config.Insecure {
tlsConfig.InsecureSkipVerify = true
}
tr.TLSClientConfig = tlsConfig
// Because we create a custom TLSClientConfig, we have to opt-in to HTTP/2.
// See https://github.com/golang/go/issues/14275
//
// TODO: Enable http2.0 when upstream issues related to HTTP/2 are fixed.
//
// if e = http2.ConfigureTransport(tr); e != nil {
// return nil, probe.NewError(e)
// }
}
transport = tr
}
transport = limiter.New(config.UploadLimit, config.DownloadLimit, transport)
if config.Debug {
if strings.EqualFold(config.Signature, "S3v4") {
transport = httptracer.GetNewTraceTransport(newTraceV4(), transport)
} else if strings.EqualFold(config.Signature, "S3v2") && withS3v2 {
transport = httptracer.GetNewTraceTransport(newTraceV2(), transport)
}
}
transport = gzhttp.Transport(transport)
return transport
type notifyExpiringTLS struct {
transport http.RoundTripper
}
// getCredentialsChainForConfig returns an []credentials.Provider array for the config
// and the STS configuration (if present)
func getCredentialsChainForConfig(config *Config, transport http.RoundTripper) ([]credentials.Provider, *probe.Error) {
var credsChain []credentials.Provider
// if an STS endpoint is set, we will add that to the chain
if stsEndpoint := env.Get("MC_STS_ENDPOINT_"+config.Alias, ""); stsEndpoint != "" {
// set AWS_WEB_IDENTITY_TOKEN_FILE is MC_WEB_IDENTITY_TOKEN_FILE is set
if val := env.Get("MC_WEB_IDENTITY_TOKEN_FILE_"+config.Alias, ""); val != "" {
os.Setenv("AWS_WEB_IDENTITY_TOKEN_FILE", val)
if val := env.Get("MC_ROLE_ARN_"+config.Alias, ""); val != "" {
os.Setenv("AWS_ROLE_ARN", val)
}
if val := env.Get("MC_ROLE_SESSION_NAME_"+config.Alias, randString(32, rand.NewSource(time.Now().UnixNano()), "mc-session-name-")); val != "" {
os.Setenv("AWS_ROLE_SESSION_NAME", val)
}
}
var globalExpiringCerts sync.Map
stsEndpointURL, err := url.Parse(stsEndpoint)
if err != nil {
return nil, probe.NewError(fmt.Errorf("Error parsing sts endpoint: %v", err))
}
credsSts := &credentials.IAM{
Client: &http.Client{
Transport: transport,
},
Endpoint: stsEndpointURL.String(),
}
credsChain = append(credsChain, credsSts)
func (n notifyExpiringTLS) RoundTrip(req *http.Request) (res *http.Response, err error) {
if n.transport == nil {
return nil, errors.New("invalid transport")
}
signType := credentials.SignatureV4
if strings.EqualFold(config.Signature, "s3v2") {
signType = credentials.SignatureV2
res, err = n.transport.RoundTrip(req)
if err != nil || res.TLS == nil || len(res.TLS.PeerCertificates) == 0 {
return res, err
}
// Credentials
creds := &credentials.Static{
Value: credentials.Value{
AccessKeyID: config.AccessKey,
SecretAccessKey: config.SecretKey,
SessionToken: config.SessionToken,
SignerType: signType,
},
cert := res.TLS.PeerCertificates[0] // leaf certificate
validityDur := cert.NotAfter.Sub(cert.NotBefore)
// Warn if less than 10% of time left and it is less than 28 days.
if time.Until(cert.NotAfter) < time.Duration(min(0.1*float64(validityDur), 28*24*float64(time.Hour))) {
globalExpiringCerts.Store(req.Host, cert.NotAfter)
}
credsChain = append(credsChain, creds)
return credsChain, nil
return res, err
}
// useTrailingHeaders will enable trailing headers on S3 clients.
var useTrailingHeaders atomic.Bool
// newFactory encloses New function with client cache.
func newFactory() func(config *Config) (Client, *probe.Error) {
clientCache := make(map[uint32]*minio.Client)
@@ -300,9 +247,9 @@ func newFactory() func(config *Config) (Client, *probe.Error) {
var found bool
if api, found = clientCache[confSum]; !found {
transport := getTransportForConfig(config, true)
transport := config.getTransport()
credsChain, err := getCredentialsChainForConfig(config, transport)
credsChain, err := config.getCredsChain()
if err != nil {
return nil, err
}
@@ -310,11 +257,12 @@ func newFactory() func(config *Config) (Client, *probe.Error) {
var e error
options := minio.Options{
Creds: credentials.NewChainCredentials(credsChain),
Secure: useTLS,
Region: env.Get("MC_REGION", env.Get("AWS_REGION", "")),
BucketLookup: config.Lookup,
Transport: transport,
Creds: credentials.NewChainCredentials(credsChain),
Secure: useTLS,
Region: env.Get("MC_REGION", env.Get("AWS_REGION", "")),
BucketLookup: config.Lookup,
Transport: transport,
TrailingHeaders: useTrailingHeaders.Load(),
}
api, e = minio.New(hostName, &options)
@@ -940,6 +888,7 @@ func (c *S3Client) Get(ctx context.Context, opts GetOptions) (io.ReadCloser, *Cl
o := minio.GetObjectOptions{
ServerSideEncryption: opts.SSE,
VersionID: opts.VersionID,
PartNumber: opts.PartNumber,
}
if opts.Zip {
o.Set("x-minio-extract", "true")
@@ -950,6 +899,9 @@ func (c *S3Client) Get(ctx context.Context, opts GetOptions) (io.ReadCloser, *Cl
return nil, nil, probe.NewError(err)
}
}
if opts.Preserve {
o.Set("X-Amz-Tagging-Directive", "ACCESS")
}
// Disallow automatic decompression for some objects with content-encoding set.
o.Set("Accept-Encoding", "identity")
@@ -985,9 +937,7 @@ func (c *S3Client) Copy(ctx context.Context, source string, opts CopyOptions, pr
}
metadata := make(map[string]string, len(opts.metadata))
for k, v := range opts.metadata {
metadata[k] = v
}
maps.Copy(metadata, opts.metadata)
delete(metadata, "X-Amz-Storage-Class")
if opts.storageClass != "" {
@@ -1073,9 +1023,7 @@ func (c *S3Client) Put(ctx context.Context, reader io.Reader, size int64, progre
}
metadata := make(map[string]string, len(putOpts.metadata))
for k, v := range putOpts.metadata {
metadata[k] = v
}
maps.Copy(metadata, putOpts.metadata)
// Do not copy storage class, it needs to be specified in putOpts
delete(metadata, "X-Amz-Storage-Class")
@@ -1135,6 +1083,8 @@ func (c *S3Client) Put(ctx context.Context, reader io.Reader, size int64, progre
}
}
disableSha256 := putOpts.checksum.IsSet() // pre-emptively disable sha256 payload, if checksum is set.
opts := minio.PutObjectOptions{
UserMetadata: metadata,
UserTags: tagsMap,
@@ -1147,7 +1097,9 @@ func (c *S3Client) Put(ctx context.Context, reader io.Reader, size int64, progre
StorageClass: strings.ToUpper(putOpts.storageClass),
ServerSideEncryption: putOpts.sse,
SendContentMd5: putOpts.md5,
Checksum: putOpts.checksum,
DisableMultipart: putOpts.disableMultipart,
DisableContentSha256: disableSha256,
PartSize: putOpts.multipartSize,
NumThreads: putOpts.multipartThreads,
ConcurrentStreamParts: putOpts.concurrentStream, // if enabled honors NumThreads for piped() uploads
@@ -1680,7 +1632,10 @@ func (c *S3Client) Stat(ctx context.Context, opts StatOptions) (*ClientContent,
}
if path == "" {
content, err := c.bucketStat(ctx, BucketStatOptions{bucket: bucket, ignoreBucketExists: opts.ignoreBucketExists})
content, err := c.bucketStat(ctx, BucketStatOptions{
bucket: bucket,
ignoreBucketExists: opts.ignoreBucketExists,
})
if err != nil {
return nil, err.Trace(bucket)
}
@@ -1707,21 +1662,32 @@ func (c *S3Client) Stat(ctx context.Context, opts StatOptions) (*ClientContent,
if opts.isZip {
o.Set("x-minio-extract", "true")
}
o.Set("x-amz-checksum-mode", "ENABLED")
ctnt, err := c.getObjectStat(ctx, bucket, path, o)
if err == nil {
return ctnt, nil
}
// Ignore object missing error but return for other errors
if !errors.As(err.ToGoError(), &ObjectMissing{}) && !errors.As(err.ToGoError(), &ObjectIsDeleteMarker{}) {
return nil, err
}
// when versionID is specified we do not have to perform List() operation
// when headOnly is specified we do not have to perform List() operation
if (opts.versionID != "" || opts.headOnly) && errors.As(err.ToGoError(), &ObjectMissing{}) || errors.As(err.ToGoError(), &ObjectIsDeleteMarker{}) {
return nil, probe.NewError(ObjectMissing{opts.timeRef})
}
// The object is not found, look for a directory marker or a prefix
path += string(c.targetURL.Separator)
}
nonRecursive := false
maxKeys := 1
for objectStat := range c.listObjectWrapper(ctx, bucket, path, nonRecursive, opts.timeRef, opts.includeVersions, opts.includeVersions, false, maxKeys, opts.isZip) {
for objectStat := range c.listObjectWrapper(ctx, bucket, path, nonRecursive, opts.timeRef,
opts.includeVersions, opts.includeVersions, false, maxKeys, opts.isZip) {
if objectStat.Err != nil {
return nil, probe.NewError(objectStat.Err)
}
@@ -2291,9 +2257,7 @@ func (c *S3Client) objectInfo2ClientContent(bucket string, entry minio.ObjectInf
content.Tags = entry.UserTags
content.ReplicationStatus = entry.ReplicationStatus
for k, v := range entry.UserMetadata {
content.UserMetadata[k] = v
}
maps.Copy(content.UserMetadata, entry.UserMetadata)
for k := range entry.Metadata {
content.Metadata[k] = entry.Metadata.Get(k)
}
@@ -2320,7 +2284,16 @@ func (c *S3Client) objectInfo2ClientContent(bucket string, entry minio.ObjectInf
} else {
content.Type = os.FileMode(0o664)
}
setChecksum := func(k, v string) {
if v != "" {
content.Checksum = map[string]string{k: v}
}
}
setChecksum("CRC32", entry.ChecksumCRC32)
setChecksum("CRC32C", entry.ChecksumCRC32C)
setChecksum("SHA1", entry.ChecksumSHA1)
setChecksum("SHA256", entry.ChecksumSHA256)
setChecksum("CRC64NVME", entry.ChecksumCRC64NVME)
return content
}
@@ -3051,3 +3024,52 @@ func (c *S3Client) GetPart(ctx context.Context, part int) (io.ReadCloser, *probe
}
return reader, nil
}
// SetBucketCors - Set bucket cors configuration.
func (c *S3Client) SetBucketCors(ctx context.Context, corsXML []byte) *probe.Error {
bucketName, _ := c.url2BucketAndObject()
if bucketName == "" {
return probe.NewError(BucketNameEmpty{})
}
corsCfg, err := cors.ParseBucketCorsConfig(bytes.NewReader(corsXML))
if err != nil {
return probe.NewError(err)
}
err = c.api.SetBucketCors(ctx, bucketName, corsCfg)
if err != nil {
return probe.NewError(err)
}
return nil
}
// GetBucketCors - Get bucket cors configuration.
func (c *S3Client) GetBucketCors(ctx context.Context) (*cors.Config, *probe.Error) {
bucketName, _ := c.url2BucketAndObject()
if bucketName == "" {
return nil, probe.NewError(BucketNameEmpty{})
}
corsCfg, err := c.api.GetBucketCors(ctx, bucketName)
if err != nil {
return nil, probe.NewError(err)
}
return corsCfg, nil
}
// DeleteBucketCors - Delete bucket cors configuration.
func (c *S3Client) DeleteBucketCors(ctx context.Context) *probe.Error {
bucketName, _ := c.url2BucketAndObject()
if bucketName == "" {
return probe.NewError(BucketNameEmpty{})
}
err := c.api.SetBucketCors(ctx, bucketName, nil)
if err != nil {
return probe.NewError(err)
}
return nil
}
+24 -25
View File
@@ -26,7 +26,7 @@ import (
"net/http/httptest"
"strconv"
minio "github.com/minio/minio-go/v7"
"github.com/minio/minio-go/v7"
checkv1 "gopkg.in/check.v1"
)
@@ -35,8 +35,8 @@ type bucketHandler struct {
}
func (h bucketHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
switch {
case r.Method == "GET":
switch r.Method {
case "GET":
// Handler for incoming getBucketLocation request.
if _, ok := r.URL.Query()["location"]; ok {
response := []byte("<LocationConstraint xmlns=\"http://doc.s3.amazonaws.com/2006-03-01\"></LocationConstraint>")
@@ -44,28 +44,28 @@ func (h bucketHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
w.Write(response)
return
}
switch {
case r.URL.Path == "/":
switch r.URL.Path {
case "/":
// Handler for incoming ListBuckets request.
response := []byte("<ListAllMyBucketsResult xmlns=\"http://doc.s3.amazonaws.com/2006-03-01\"><Buckets><Bucket><Name>bucket</Name><CreationDate>2015-05-20T23:05:09.230Z</CreationDate></Bucket></Buckets><Owner><ID>minio</ID><DisplayName>minio</DisplayName></Owner></ListAllMyBucketsResult>")
w.Header().Set("Content-Length", strconv.Itoa(len(response)))
w.Write(response)
case r.URL.Path == "/bucket/":
case "/bucket/":
// Handler for incoming ListObjects request.
response := []byte("<ListBucketResult xmlns=\"http://doc.s3.amazonaws.com/2006-03-01\"><Contents><ETag>259d04a13802ae09c7e41be50ccc6baa</ETag><Key>object</Key><LastModified>2015-05-21T18:24:21.097Z</LastModified><Size>22061</Size><Owner><ID>minio</ID><DisplayName>minio</DisplayName></Owner><StorageClass>STANDARD</StorageClass></Contents><Delimiter></Delimiter><EncodingType></EncodingType><IsTruncated>false</IsTruncated><Marker></Marker><MaxKeys>1000</MaxKeys><Name>testbucket</Name><NextMarker></NextMarker><Prefix></Prefix></ListBucketResult>")
w.Header().Set("Content-Length", strconv.Itoa(len(response)))
w.Write(response)
}
case r.Method == "PUT":
switch {
case r.URL.Path == h.resource:
case "PUT":
switch r.URL.Path {
case h.resource:
w.WriteHeader(http.StatusOK)
default:
w.WriteHeader(http.StatusBadRequest)
}
case r.Method == "HEAD":
switch {
case r.URL.Path == h.resource:
case "HEAD":
switch r.URL.Path {
case h.resource:
w.WriteHeader(http.StatusOK)
default:
w.WriteHeader(http.StatusForbidden)
@@ -85,8 +85,8 @@ func (h objectHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
return
}
switch {
case r.Method == http.MethodPut:
switch r.Method {
case http.MethodPut:
// Handler for PUT object request.
length, e := strconv.Atoi(r.Header.Get("Content-Length"))
if e != nil {
@@ -100,7 +100,7 @@ func (h objectHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
}
w.Header().Set("ETag", "9af2f8218b150c351ad802c6f3d66abe")
w.WriteHeader(http.StatusOK)
case r.Method == http.MethodHead:
case http.MethodHead:
// Handler for Stat object request.
if r.URL.Path != h.resource {
w.WriteHeader(http.StatusNotFound)
@@ -110,7 +110,7 @@ func (h objectHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Last-Modified", UTCNow().Format(http.TimeFormat))
w.Header().Set("ETag", "9af2f8218b150c351ad802c6f3d66abe")
w.WriteHeader(http.StatusOK)
case r.Method == http.MethodPost:
case http.MethodPost:
// Handler for multipart upload request.
if _, ok := r.URL.Query()["uploads"]; ok {
if r.URL.Path == h.resource {
@@ -132,7 +132,7 @@ func (h objectHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNotFound)
return
}
case r.Method == http.MethodGet:
case http.MethodGet:
// Handler for get bucket location request.
if _, ok := r.URL.Query()["location"]; ok {
response := []byte("<LocationConstraint xmlns=\"http://doc.s3.amazonaws.com/2006-03-01\"></LocationConstraint>")
@@ -171,8 +171,8 @@ func (h stsHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusInternalServerError)
return
}
switch {
case r.Method == http.MethodPost:
switch r.Method {
case http.MethodPost:
token := r.Form.Get("WebIdentityToken")
if token == string(h.jwt) {
response := []byte("<AssumeRoleWithWebIdentityResponse xmlns=\"https://sts.amazonaws.com/doc/2011-06-15/\"><AssumeRoleWithWebIdentityResult><AssumedRoleUser><Arn></Arn><AssumeRoleId></AssumeRoleId></AssumedRoleUser><Credentials><AccessKeyId>7NL5BR739GUQ0ZOD4JNB</AccessKeyId><SecretAccessKey>A2mxZSxPnHNhSduedUHczsXZpVSSssOLpDruUmTV</SecretAccessKey><Expiration>0001-01-01T00:00:00Z</Expiration><SessionToken>eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJhY2Nlc3NLZXkiOiI3Tkw1QlI3MzlHVVEwWk9ENEpOQiIsImV4cCI6MTY5OTYwMzMwNiwicGFyZW50IjoibWluaW8iLCJzZXNzaW9uUG9saWN5IjoiZXlKV1pYSnphVzl1SWpvaU1qQXhNaTB4TUMweE55SXNJbE4wWVhSbGJXVnVkQ0k2VzNzaVJXWm1aV04wSWpvaVFXeHNiM2NpTENKQlkzUnBiMjRpT2xzaVlXUnRhVzQ2S2lKZGZTeDdJa1ZtWm1WamRDSTZJa0ZzYkc5M0lpd2lRV04wYVc5dUlqcGJJbXR0Y3pvcUlsMTlMSHNpUldabVpXTjBJam9pUVd4c2IzY2lMQ0pCWTNScGIyNGlPbHNpY3pNNktpSmRMQ0pTWlhOdmRYSmpaU0k2V3lKaGNtNDZZWGR6T25Nek9qbzZLaUpkZlYxOSJ9.uuE_x7PO8QoPfUk9KzUELoAqxihIknZAvJLl5aYJjwpSjJYFTPLp6EvuyJX2hc18s9HzeiJ-vU0dPzsy50dXmg</SessionToken></Credentials></AssumeRoleWithWebIdentityResult><ResponseMetadata></ResponseMetadata></AssumeRoleWithWebIdentityResponse>")
@@ -181,13 +181,12 @@ func (h stsHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Server", "MinIO")
w.Write(response)
return
} else {
response := []byte("<ErrorResponse xmlns=\"https://sts.amazonaws.com/doc/2011-06-15/\"><Error><Type></Type><Code>AccessDenied</Code><Message>Access denied: Invalid Token</Message></Error><RequestId></RequestId></ErrorResponse>")
w.Header().Set("Content-Length", strconv.Itoa(len(response)))
w.Header().Set("Content-Type", "application/xml")
w.Write(response)
return
}
response := []byte("<ErrorResponse xmlns=\"https://sts.amazonaws.com/doc/2011-06-15/\"><Error><Type></Type><Code>AccessDenied</Code><Message>Access denied: Invalid Token</Message></Error><RequestId></RequestId></ErrorResponse>")
w.Header().Set("Content-Length", strconv.Itoa(len(response)))
w.Header().Set("Content-Type", "application/xml")
w.Write(response)
return
}
}
+1 -2
View File
@@ -65,8 +65,7 @@ func TestSTSS3Operation(t *testing.T) {
t.Fatal(err)
}
var reader io.Reader
reader = bytes.NewReader(object.data)
var reader io.Reader = bytes.NewReader(object.data)
n, err := s3c.Put(context.Background(), reader, int64(len(object.data)), nil, PutOptions{
metadata: map[string]string{
"Content-Type": "application/octet-stream",
+44 -1
View File
@@ -50,6 +50,7 @@ type url2StatOptions struct {
encKeyDB map[string][]prefixSSEPair
timeRef time.Time
isZip bool
headOnly bool
ignoreBucketExistsCheck bool
}
@@ -204,7 +205,15 @@ func url2Stat(ctx context.Context, opts url2StatOptions) (client Client, content
alias, _ := url2Alias(opts.urlStr)
sse := getSSE(opts.urlStr, opts.encKeyDB[alias])
content, err = client.Stat(ctx, StatOptions{preserve: opts.fileAttr, sse: sse, timeRef: opts.timeRef, versionID: opts.versionID, isZip: opts.isZip, ignoreBucketExists: opts.ignoreBucketExistsCheck})
content, err = client.Stat(ctx, StatOptions{
preserve: opts.fileAttr,
sse: sse,
timeRef: opts.timeRef,
versionID: opts.versionID,
isZip: opts.isZip,
ignoreBucketExists: opts.ignoreBucketExistsCheck,
headOnly: opts.headOnly,
})
if err != nil {
return nil, nil, err.Trace(opts.urlStr)
}
@@ -258,3 +267,37 @@ func guessURLContentType(urlStr string) string {
contentType := mimedb.TypeByExtension(filepath.Ext(url.Path))
return contentType
}
// urlParts - split URL into parts.
func urlParts(urlStr string) []string {
// Convert '/' on windows to filepath.Separator.
urlStr = filepath.FromSlash(urlStr)
if runtime.GOOS == "windows" {
// Remove '/' prefix before alias if any to support '\\home' alias
// style under Windows
urlStr = strings.TrimPrefix(urlStr, string(filepath.Separator))
}
// Remove everything after alias (i.e. after '/').
return strings.Split(urlStr, string(filepath.Separator))
}
// isURLPrefix - check if source and destination be subdirectories of each other
func isURLPrefix(src string, dest string) bool {
srcURLParts := urlParts(src)
dstURLParts := urlParts(dest)
minIndex := min(len(srcURLParts), len(dstURLParts))
isPrefix := true
for i := range minIndex {
// if one of the URLs ends with '/' and other does not
if (i == minIndex-1) && (dstURLParts[i] == "" || srcURLParts[i] == "" || dstURLParts[i] == "*" || srcURLParts[i] == "*") {
continue
}
if srcURLParts[i] != dstURLParts[i] {
isPrefix = false
break
}
}
return isPrefix
}
+35 -1
View File
@@ -17,7 +17,11 @@
package cmd
import checkv1 "gopkg.in/check.v1"
import (
"testing"
checkv1 "gopkg.in/check.v1"
)
// TestURL - tests url parsing and fields.
func (s *TestSuite) TestURL(c *checkv1.C) {
@@ -52,3 +56,33 @@ func (s *TestSuite) TestURLJoinPath(c *checkv1.C) {
url = urlJoinPath(url1, url2)
c.Assert(url, checkv1.Equals, "http://s3.mycompany.io/dev/mybucket/bin/")
}
func Test_isURLPrefix(t *testing.T) {
type args struct {
src string
dest string
}
tests := []struct {
name string
args args
want bool
}{
{"test1", args{"s3/test", "s3/test/test"}, true},
{"test2", args{"s3/test/", "s3/test/test"}, true},
{"test3", args{"s3/test/test", "s3/test/"}, true},
{"test4", args{"s3/test/test", "s3/test/test.123"}, false},
{"test5", args{"s3/test/", "s3/test/test/test/test"}, true},
{"test6", args{"s3/test/*", "s3/test/test/"}, true},
{"test7", args{"s3/test/*", "s3/test1/test/"}, false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := isURLPrefix(tt.args.src, tt.args.dest); got != tt.want {
t.Errorf("isURLPrefix() = %v, want %v", got, tt.want)
}
if got := isURLPrefix(tt.args.dest, tt.args.src); got != tt.want {
t.Errorf("isURLPrefix() = %v, want %v", got, tt.want)
}
})
}
}
+171 -2
View File
@@ -19,16 +19,28 @@ package cmd
import (
"context"
"crypto/tls"
"fmt"
"io"
"maps"
"math/rand"
"net/http"
"net/url"
"os"
"strings"
"time"
"github.com/klauspost/compress/gzhttp"
"github.com/minio/mc/pkg/httptracer"
"github.com/minio/mc/pkg/limiter"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio-go/v7"
"github.com/minio/minio-go/v7/pkg/cors"
"github.com/minio/minio-go/v7/pkg/credentials"
"github.com/minio/minio-go/v7/pkg/encrypt"
"github.com/minio/minio-go/v7/pkg/lifecycle"
"github.com/minio/minio-go/v7/pkg/replication"
"github.com/minio/pkg/v3/env"
)
// DirOpt - list directory option.
@@ -49,6 +61,7 @@ type GetOptions struct {
VersionID string
Zip bool
RangeStart int64
PartNumber int
Preserve bool
}
@@ -63,6 +76,7 @@ type PutOptions struct {
multipartThreads uint
concurrentStream bool
ifNotExists bool
checksum minio.ChecksumType
}
// StatOptions holds options of the HEAD operation
@@ -75,6 +89,7 @@ type StatOptions struct {
includeVersions bool
isZip bool
ignoreBucketExists bool
headOnly bool
}
// BucketStatOptions - bucket stat.
@@ -123,8 +138,8 @@ type Client interface {
GetObjectLockConfig(ctx context.Context) (status string, mode minio.RetentionMode, validity uint64, unit minio.ValidityUnit, perr *probe.Error)
// Access policy operations.
GetAccess(ctx context.Context) (access, policyJSON string, error *probe.Error)
GetAccessRules(ctx context.Context) (policyRules map[string]string, error *probe.Error)
GetAccess(ctx context.Context) (access, policyJSON string, err *probe.Error)
GetAccessRules(ctx context.Context) (policyRules map[string]string, err *probe.Error)
SetAccess(ctx context.Context, access string, isJSON bool) *probe.Error
// I/O operations
@@ -189,6 +204,11 @@ type Client interface {
// OD operations
GetPart(ctx context.Context, part int) (io.ReadCloser, *probe.Error)
PutPart(ctx context.Context, reader io.Reader, size int64, progress io.Reader, opts PutOptions) (n int64, err *probe.Error)
// Cors operations
GetBucketCors(ctx context.Context) (*cors.Config, *probe.Error)
SetBucketCors(ctx context.Context, corsXML []byte) *probe.Error
DeleteBucketCors(ctx context.Context) *probe.Error
}
// ClientContent - Content container for content metadata
@@ -202,6 +222,7 @@ type ClientContent struct {
Metadata map[string]string
Tags map[string]string
UserMetadata map[string]string
Checksum map[string]string
ETag string
Expires time.Time
@@ -244,9 +265,157 @@ type Config struct {
Transport http.RoundTripper
}
// getCredsChain returns an []credentials.Provider array for the config
// and the STS configuration (if present)
func (config *Config) getCredsChain() ([]credentials.Provider, *probe.Error) {
var credsChain []credentials.Provider
// if an STS endpoint is set, we will add that to the chain
if stsEndpoint := env.Get("MC_STS_ENDPOINT_"+config.Alias, ""); stsEndpoint != "" {
// set AWS_WEB_IDENTITY_TOKEN_FILE is MC_WEB_IDENTITY_TOKEN_FILE is set
if val := env.Get("MC_WEB_IDENTITY_TOKEN_FILE_"+config.Alias, ""); val != "" {
os.Setenv("AWS_WEB_IDENTITY_TOKEN_FILE", val)
if val := env.Get("MC_ROLE_ARN_"+config.Alias, ""); val != "" {
os.Setenv("AWS_ROLE_ARN", val)
}
if val := env.Get("MC_ROLE_SESSION_NAME_"+config.Alias, randString(32, rand.NewSource(time.Now().UnixNano()), "mc-session-name-")); val != "" {
os.Setenv("AWS_ROLE_SESSION_NAME", val)
}
}
stsEndpointURL, err := url.Parse(stsEndpoint)
if err != nil {
return nil, probe.NewError(fmt.Errorf("Error parsing sts endpoint: %w", err))
}
credsSts := &credentials.IAM{
Client: &http.Client{
Transport: config.getTransport(),
},
Endpoint: stsEndpointURL.String(),
}
credsChain = append(credsChain, credsSts)
}
signType := credentials.SignatureV4
if strings.EqualFold(config.Signature, "s3v2") {
signType = credentials.SignatureV2
}
// Credentials
creds := &credentials.Static{
Value: credentials.Value{
AccessKeyID: config.AccessKey,
SecretAccessKey: config.SecretKey,
SessionToken: config.SessionToken,
SignerType: signType,
},
}
credsChain = append(credsChain, creds)
return credsChain, nil
}
// getTransport returns a corresponding *http.Transport for the *Config
// set withS3v2 bool to true to add traceV2 tracer.
func (config *Config) getTransport() http.RoundTripper {
if config.Transport == nil {
config.initTransport(true)
}
return config.Transport
}
func (config *Config) isTLS() bool {
if stsEndpoint := env.Get("MC_STS_ENDPOINT_"+config.Alias, ""); stsEndpoint != "" {
stsEndpointURL, err := url.Parse(stsEndpoint)
if err != nil {
return false
}
return isHostTLS(config) || stsEndpointURL.Scheme == "https"
}
return isHostTLS(config)
}
func (config *Config) initTransport(withS3v2 bool) {
var transport http.RoundTripper
useTLS := config.isTLS()
if config.Transport != nil {
transport = config.Transport
} else {
tr := &http.Transport{
Proxy: http.ProxyFromEnvironment,
DialContext: newCustomDialContext(config),
MaxIdleConnsPerHost: 1024,
WriteBufferSize: 32 << 10, // 32KiB moving up from 4KiB default
ReadBufferSize: 32 << 10, // 32KiB moving up from 4KiB default
IdleConnTimeout: 90 * time.Second,
TLSHandshakeTimeout: 10 * time.Second,
ExpectContinueTimeout: 10 * time.Second,
// Set this value so that the underlying transport round-tripper
// doesn't try to auto decode the body of objects with
// content-encoding set to `gzip`.
//
// Refer:
// https://golang.org/src/net/http/transport.go?h=roundTrip#L1843
DisableCompression: true,
}
if useTLS {
tr.DialTLSContext = newCustomDialTLSContext(&tls.Config{
RootCAs: globalRootCAs,
MinVersion: tls.VersionTLS12,
InsecureSkipVerify: config.Insecure,
})
// Because we create a custom TLSClientConfig, we have to opt-in to HTTP/2.
// See https://github.com/golang/go/issues/14275
//
// TODO: Enable http2.0 when upstream issues related to HTTP/2 are fixed.
//
// if e = http2.ConfigureTransport(tr); e != nil {
// return nil, probe.NewError(e)
// }
}
if len(globalCustomHeader) > 0 {
transport = &headerTransport{
RoundTripper: tr,
customHeader: globalCustomHeader.Clone(),
}
} else {
transport = tr
}
}
transport = limiter.New(config.UploadLimit, config.DownloadLimit, transport)
if config.Debug {
if strings.EqualFold(config.Signature, "S3v4") {
transport = httptracer.GetNewTraceTransport(newTraceV4(), transport)
} else if strings.EqualFold(config.Signature, "S3v2") && withS3v2 {
transport = httptracer.GetNewTraceTransport(newTraceV2(), transport)
}
} else {
if !globalJSONLine && !globalJSON {
transport = notifyExpiringTLS{transport: transport}
}
}
transport = gzhttp.Transport(transport)
config.Transport = transport
}
// SelectObjectOpts - opts entered for select API
type SelectObjectOpts struct {
InputSerOpts map[string]map[string]string
OutputSerOpts map[string]map[string]string
CompressionType minio.SelectCompressionType
}
type headerTransport struct {
http.RoundTripper
customHeader http.Header
}
func (h *headerTransport) RoundTrip(request *http.Request) (*http.Response, error) {
maps.Copy(request.Header, h.customHeader)
return h.RoundTripper.RoundTrip(request)
}
+20 -16
View File
@@ -21,10 +21,12 @@ import (
"context"
"errors"
"io"
"maps"
"net/http"
"os"
"path/filepath"
"regexp"
"slices"
"strconv"
"strings"
"time"
@@ -35,6 +37,7 @@ import (
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio-go/v7"
"github.com/minio/minio-go/v7/pkg/encrypt"
"github.com/minio/minio-go/v7/pkg/tags"
"github.com/minio/pkg/v3/env"
)
@@ -134,15 +137,12 @@ func isReadAt(reader io.Reader) (ok bool) {
// which happen to also be io.ReaderAt compatible
// we need to add special conditions for them to
// be ignored by this function.
for _, f := range []string{
if slices.Contains([]string{
"/dev/stdin",
"/dev/stdout",
"/dev/stderr",
} {
if f == v.Name() {
ok = false
break
}
}, v.Name()) {
ok = false
}
}
return
@@ -353,16 +353,14 @@ func uploadSourceToTargetURL(ctx context.Context, uploadOpts uploadSourceToTarge
}
// Optimize for server side copy if the host is same.
if sourceAlias == targetAlias && !uploadOpts.isZip {
if sourceAlias == targetAlias && !uploadOpts.isZip && !uploadOpts.urls.checksum.IsSet() {
// preserve new metadata and save existing ones.
if uploadOpts.preserve {
currentMetadata, err := getAllMetadata(ctx, sourceAlias, sourceURL.String(), srcSSE, uploadOpts.urls)
if err != nil {
return uploadOpts.urls.WithError(err.Trace(sourceURL.String()))
}
for k, v := range currentMetadata {
metadata[k] = v
}
maps.Copy(metadata, currentMetadata)
}
// Get metadata from target content as well
@@ -400,9 +398,7 @@ func uploadSourceToTargetURL(ctx context.Context, uploadOpts uploadSourceToTarge
if err != nil {
return uploadOpts.urls.WithError(err.Trace(sourceURL.String()))
}
for k, v := range currentMetadata {
metadata[k] = v
}
maps.Copy(metadata, currentMetadata)
}
// Get metadata from target content as well
@@ -446,9 +442,7 @@ func uploadSourceToTargetURL(ctx context.Context, uploadOpts uploadSourceToTarge
}
metadata := make(map[string]string, len(content.Metadata))
for k, v := range content.Metadata {
metadata[k] = v
}
maps.Copy(metadata, content.Metadata)
// Get metadata from target content as well
for k, v := range uploadOpts.urls.TargetContent.Metadata {
@@ -460,6 +454,15 @@ func uploadSourceToTargetURL(ctx context.Context, uploadOpts uploadSourceToTarge
metadata[http.CanonicalHeaderKey(k)] = v
}
if content.Tags != nil {
tags, err := tags.NewTags(content.Tags, true)
if err != nil {
return uploadOpts.urls.WithError(probe.NewError(err))
}
metadata["X-Amz-Tagging"] = tags.String()
delete(metadata, "X-Amz-Tagging-Count")
}
var e error
var multipartSize uint64
var multipartThreads int
@@ -495,6 +498,7 @@ func uploadSourceToTargetURL(ctx context.Context, uploadOpts uploadSourceToTarge
multipartSize: multipartSize,
multipartThreads: uint(multipartThreads),
ifNotExists: uploadOpts.ifNotExists,
checksum: uploadOpts.urls.checksum,
}
if isReadAt(reader) || length == 0 {
-101
View File
@@ -1,101 +0,0 @@
// Copyright (c) 2015-2022 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
import "github.com/minio/cli"
var configCmd = cli.Command{
Name: "config",
Usage: "configure MinIO client",
Action: func(ctx *cli.Context) error {
cli.ShowCommandHelp(ctx, ctx.Args().First())
return nil
},
Hidden: true,
Before: setGlobalsFromContext,
HideHelpCommand: true,
Flags: globalFlags,
Subcommands: []cli.Command{
configHostCmd,
},
}
var configHostCmd = cli.Command{
Name: "host",
Usage: "add, remove and list hosts in configuration file",
Action: func(ctx *cli.Context) error {
cli.ShowCommandHelp(ctx, ctx.Args().First())
return nil
},
Before: setGlobalsFromContext,
Flags: globalFlags,
Subcommands: []cli.Command{
configHostAddCmd,
configHostRemoveCmd,
configHostListCmd,
},
HideHelpCommand: true,
}
var configHostAddFlags = []cli.Flag{
cli.StringFlag{
Name: "lookup",
Value: "auto",
Usage: "bucket lookup supported by the server. Valid options are '[dns, path, auto]'",
},
cli.StringFlag{
Name: "api",
Usage: "API signature. Valid options are '[S3v4, S3v2]'",
},
}
var configHostAddCmd = cli.Command{
Name: "add",
ShortName: "a",
Usage: "add a new host to configuration file",
Action: func(cli *cli.Context) error {
return mainAliasSet(cli, true)
},
Before: setGlobalsFromContext,
Flags: append(configHostAddFlags, globalFlags...),
HideHelpCommand: true,
}
var configHostListCmd = cli.Command{
Name: "list",
ShortName: "ls",
Usage: "list hosts in configuration file",
Action: func(cli *cli.Context) error {
return mainAliasList(cli, true)
},
Before: setGlobalsFromContext,
Flags: globalFlags,
HideHelpCommand: true,
}
var configHostRemoveCmd = cli.Command{
Name: "remove",
ShortName: "rm",
Usage: "remove a host from configuration file",
Action: func(cli *cli.Context) error {
return mainAliasRemove(cli)
},
Before: setGlobalsFromContext,
Flags: globalFlags,
HideHelpCommand: true,
}
+3 -6
View File
@@ -19,6 +19,7 @@ package cmd
import (
"fmt"
"maps"
"os"
"path/filepath"
"runtime"
@@ -94,9 +95,7 @@ func fixConfigV3() {
cfgV3 := newConfigV3()
isMutated := false
for k, v := range brokenMcCfgV3.Data().(*brokenConfigV3).Aliases {
cfgV3.Aliases[k] = v
}
maps.Copy(cfgV3.Aliases, brokenMcCfgV3.Data().(*brokenConfigV3).Aliases)
for host, brokenHostCfgV3 := range brokenMcCfgV3.Data().(*brokenConfigV3).Hosts {
@@ -144,9 +143,7 @@ func fixConfigV6ForHosts() {
isMutated := false
// Copy aliases.
for k, v := range brokenMcCfgV6.Data().(*configV6).Aliases {
newCfgV6.Aliases[k] = v
}
maps.Copy(newCfgV6.Aliases, brokenMcCfgV6.Data().(*configV6).Aliases)
url := &ClientURL{}
// Copy hosts.
+11 -21
View File
@@ -19,6 +19,7 @@ package cmd
import (
"fmt"
"maps"
"strings"
"github.com/minio/mc/pkg/probe"
@@ -70,9 +71,7 @@ func migrateConfigV1ToV101() {
cfgV101 := newConfigV101()
// Copy aliases.
for k, v := range mcCfgV1.Data().(*configV1).Aliases {
cfgV101.Aliases[k] = v
}
maps.Copy(cfgV101.Aliases, mcCfgV1.Data().(*configV1).Aliases)
// Copy hosts.
for k, hostCfgV1 := range mcCfgV1.Data().(*configV1).Hosts {
@@ -128,9 +127,7 @@ func migrateConfigV101ToV2() {
cfgV2 := newConfigV2()
// Copy aliases.
for k, v := range mcCfgV101.Data().(*configV101).Aliases {
cfgV2.Aliases[k] = v
}
maps.Copy(cfgV2.Aliases, mcCfgV101.Data().(*configV101).Aliases)
// Copy hosts.
for k, hostCfgV101 := range mcCfgV101.Data().(*configV101).Hosts {
@@ -166,9 +163,7 @@ func migrateConfigV2ToV3() {
cfgV3 := newConfigV3()
// Copy aliases.
for k, v := range mcCfgV2.Data().(*configV2).Aliases {
cfgV3.Aliases[k] = v
}
maps.Copy(cfgV3.Aliases, mcCfgV2.Data().(*configV2).Aliases)
// Copy hosts.
for k, hostCfgV2 := range mcCfgV2.Data().(*configV2).Hosts {
@@ -203,9 +198,7 @@ func migrateConfigV3ToV4() {
fatalIf(probe.NewError(e), "Unable to load mc config V3.")
cfgV4 := newConfigV4()
for k, v := range mcCfgV3.Data().(*configV3).Aliases {
cfgV4.Aliases[k] = v
}
maps.Copy(cfgV4.Aliases, mcCfgV3.Data().(*configV3).Aliases)
// New hostConfig has API signature. All older entries were V4
// only. So it is safe to assume V4 as default for all older
// entries.
@@ -244,9 +237,7 @@ func migrateConfigV4ToV5() {
fatalIf(probe.NewError(e), "Unable to load mc config V4.")
cfgV5 := newConfigV5()
for k, v := range mcCfgV4.Data().(*configV4).Aliases {
cfgV5.Aliases[k] = v
}
maps.Copy(cfgV5.Aliases, mcCfgV4.Data().(*configV4).Aliases)
for host, hostCfgV4 := range mcCfgV4.Data().(*configV4).Hosts {
cfgV5.Hosts[host] = hostConfigV5{
AccessKeyID: hostCfgV4.AccessKeyID,
@@ -286,9 +277,7 @@ func migrateConfigV5ToV6() {
// Add new Google Cloud Storage alias.
cfgV6.Aliases["gcs"] = "https://storage.googleapis.com"
for k, v := range mcCfgV5.Data().(*configV5).Aliases {
cfgV6.Aliases[k] = v
}
maps.Copy(cfgV6.Aliases, mcCfgV5.Data().(*configV5).Aliases)
// Add defaults.
cfgV6.Hosts["*s3*amazonaws.com"] = hostConfigV6{
@@ -366,7 +355,8 @@ func migrateConfigV6ToV7() {
continue
}
}
if host == "https://s3.amazonaws.com" {
switch host {
case "https://s3.amazonaws.com":
// Only one entry can exist for "s3" domain.
cfgV7.Hosts["s3"] = hostConfigV7{
URL: host,
@@ -374,7 +364,7 @@ func migrateConfigV6ToV7() {
SecretKey: hostCfgV6.SecretAccessKey,
API: hostCfgV6.API,
}
} else if host == "https://storage.googleapis.com" {
case "https://storage.googleapis.com":
// Only one entry can exist for "gcs" domain.
cfgV7.Hosts["gcs"] = hostConfigV7{
URL: host,
@@ -382,7 +372,7 @@ func migrateConfigV6ToV7() {
SecretKey: hostCfgV6.SecretAccessKey,
API: hostCfgV6.API,
}
} else {
default:
// Assign a generic "cloud1", cloud2..." key
// for all other entries that has valid keys set.
alias := fmt.Sprintf("cloud%d", aliasIndex)
+6 -13
View File
@@ -17,7 +17,10 @@
package cmd
import "strings"
import (
"slices"
"strings"
)
var validAPIs = []string{"S3v4", "S3v2"}
@@ -73,21 +76,11 @@ func isValidAPI(api string) (ok bool) {
// isValidLookup - validates if bucket lookup is of valid type
func isValidLookup(lookup string) (ok bool) {
l := strings.ToLower(strings.TrimSpace(lookup))
for _, v := range []string{"dns", "path", "auto"} {
if l == v {
return true
}
}
return false
return slices.Contains([]string{"dns", "path", "auto"}, l)
}
// isValidPath - validates the alias path config
func isValidPath(path string) (ok bool) {
l := strings.ToLower(strings.TrimSpace(path))
for _, v := range []string{"on", "off", "auto"} {
if l == v {
return true
}
}
return false
return slices.Contains([]string{"on", "off", "auto"}, l)
}
+1
View File
@@ -46,6 +46,7 @@ type aliasConfigV10 struct {
Path string `json:"path"`
License string `json:"license,omitempty"`
APIKey string `json:"apiKey,omitempty"`
Src string `json:"src,omitempty"`
}
// configV10 config version.
+17 -8
View File
@@ -185,6 +185,7 @@ func getAliasConfig(alias string) (*aliasConfigV10, *probe.Error) {
// if host is exact return quickly.
if _, ok := mcCfg.Aliases[alias]; ok {
hostCfg := mcCfg.Aliases[alias]
hostCfg.Src = mustGetMcConfigPath()
return &hostCfg, nil
}
@@ -194,15 +195,18 @@ func getAliasConfig(alias string) (*aliasConfigV10, *probe.Error) {
// mustGetHostConfig retrieves host specific configuration such as access keys, signature type.
func mustGetHostConfig(alias string) *aliasConfigV10 {
aliasCfg, _ := getAliasConfig(alias)
// look for it in the environment variable first.
aliasCfg, _ := expandAliasFromEnv(env.Get(mcEnvHostPrefix+alias, ""))
// If alias is not found,
// look for it in the environment variable.
if aliasCfg == nil {
aliasCfg, _ = expandAliasFromEnv(env.Get(mcEnvHostPrefix+alias, ""))
}
// look for it in the customized configuration.
if aliasCfg == nil {
aliasCfg = aliasToConfigMap[alias]
}
if aliasCfg == nil {
aliasCfg, _ = getAliasConfig(alias)
}
return aliasCfg
}
@@ -244,9 +248,12 @@ func parseEnvURLStr(envURL string) (*url.URL, string, string, string, *probe.Err
return nil, "", "", "", probe.NewError(e)
}
// Look for if URL has invalid values and return error.
if !((u.Scheme == "http" || u.Scheme == "https") &&
(u.Path == "/" || u.Path == "") && u.Opaque == "" &&
!u.ForceQuery && u.RawQuery == "" && u.Fragment == "") {
if (u.Scheme != "http" && u.Scheme != "https") ||
(u.Path != "/" && u.Path != "") ||
u.Opaque != "" ||
u.ForceQuery ||
u.RawQuery != "" ||
u.Fragment != "" {
return nil, "", "", "", errInvalidArgument().Trace(u.String())
}
if accessKey == "" && secretKey == "" {
@@ -286,6 +293,7 @@ func readAliasesFromFile(envConfigFile string) *probe.Error {
if err != nil {
return err.Trace(envLine)
}
aliasConfig.Src = envConfigFile
aliasToConfigMap[alias] = aliasConfig
}
if e := scanner.Err(); e != nil {
@@ -306,6 +314,7 @@ func expandAliasFromEnv(envURL string) (*aliasConfigV10, *probe.Error) {
AccessKey: accessKey,
SecretKey: secretKey,
SessionToken: sessionToken,
Src: "env",
}, nil
}
+84
View File
@@ -0,0 +1,84 @@
// 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/fatih/color"
"github.com/minio/cli"
"github.com/minio/pkg/v3/console"
)
var corsGetCmd = cli.Command{
Name: "get",
Usage: "get a bucket CORS configuration",
Action: mainCorsGet,
OnUsageError: onUsageError,
Before: setGlobalsFromContext,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} ALIAS/BUCKET
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Get the CORS configuration for the bucket 'mybucket':
{{.Prompt}} {{.HelpName}} myminio/mybucket
`,
}
// checkCorsGetSyntax - validate all the passed arguments
func checkCorsGetSyntax(ctx *cli.Context) {
if len(ctx.Args()) != 1 {
showCommandHelpAndExit(ctx, 1) // last argument is exit code
}
}
// mainCorsGet is the handle for "mc cors get" command.
func mainCorsGet(ctx *cli.Context) error {
checkCorsGetSyntax(ctx)
console.SetColor("CorsMessage", color.New(color.FgGreen))
console.SetColor("CorsNotFound", color.New(color.FgYellow))
// args[0] is the ALIAS/BUCKET argument.
args := ctx.Args()
urlStr := args.Get(0)
client, err := newClient(urlStr)
fatalIf(err.Trace(urlStr), "Unable to initialize client for "+urlStr)
corsCfg, err := client.GetBucketCors(globalContext)
fatalIf(err.Trace(urlStr), "Unable to get bucket CORS configuration for "+urlStr)
status := "success"
if corsCfg == nil {
status = "not found"
}
printMsg(corsMessage{
op: "get",
Status: status,
CorsCfg: corsCfg,
})
return nil
}
+40
View File
@@ -0,0 +1,40 @@
// 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 corsSubcommands = []cli.Command{
corsSetCmd,
corsGetCmd,
corsRemoveCmd,
}
var corsCmd = cli.Command{
Name: "cors",
Usage: "manage bucket CORS configuration",
Action: mainCors,
Before: setGlobalsFromContext,
Flags: globalFlags,
Subcommands: corsSubcommands,
}
func mainCors(ctx *cli.Context) error {
commandNotFound(ctx, corsSubcommands)
return nil
}
+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/fatih/color"
"github.com/minio/cli"
"github.com/minio/pkg/v3/console"
)
var corsRemoveCmd = cli.Command{
Name: "remove",
Usage: "remove a bucket CORS configuration",
Action: mainCorsRemove,
OnUsageError: onUsageError,
Before: setGlobalsFromContext,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} ALIAS/BUCKET
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Remove the CORS configuration for the bucket 'mybucket':
{{.Prompt}} {{.HelpName}} myminio/mybucket
`,
}
// checkCorsRemoveSyntax - validate all the passed arguments
func checkCorsRemoveSyntax(ctx *cli.Context) {
if len(ctx.Args()) != 1 {
showCommandHelpAndExit(ctx, 1) // last argument is exit code
}
}
// mainCorsRemove is the handle for "mc cors remove" command.
func mainCorsRemove(ctx *cli.Context) error {
checkCorsRemoveSyntax(ctx)
console.SetColor("CorsMessage", color.New(color.FgGreen))
// args[0] is the ALIAS/BUCKET argument.
args := ctx.Args()
urlStr := args.Get(0)
client, err := newClient(urlStr)
fatalIf(err.Trace(urlStr), "Unable to initialize client for "+urlStr)
err = client.DeleteBucketCors(globalContext)
fatalIf(err.Trace(urlStr), "Unable to remove bucket CORS configuration for "+urlStr)
printMsg(corsMessage{
op: "remove",
Status: "success",
})
return nil
}
+131
View File
@@ -0,0 +1,131 @@
// 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 (
"io"
"os"
"github.com/fatih/color"
"github.com/minio/cli"
json "github.com/minio/colorjson"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio-go/v7/pkg/cors"
"github.com/minio/pkg/v3/console"
)
var corsSetCmd = cli.Command{
Name: "set",
Usage: "set a bucket CORS configuration",
Action: mainCorsSet,
OnUsageError: onUsageError,
Before: setGlobalsFromContext,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} ALIAS/BUCKET CORSFILE
CORSFILE:
Path to the XML file containing the CORS configuration.
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Set the CORS configuration for the bucket 'mybucket':
{{.Prompt}} {{.HelpName}} myminio/mybucket /path/to/cors.xml
2. Set the CORS configuration for the bucket 'mybucket' using stdin:
{{.Prompt}} {{.HelpName}} myminio/mybucket -
`,
}
// corsMessage container for output message.
type corsMessage struct {
op string
Status string `json:"status"`
Message string `json:"message,omitempty"`
CorsCfg *cors.Config `json:"cors,omitempty"`
}
func (c corsMessage) String() string {
switch c.op {
case "get":
if c.CorsCfg == nil {
return console.Colorize("CorsNotFound", "No bucket CORS configuration found.")
}
corsXML, e := c.CorsCfg.ToXML()
fatalIf(probe.NewError(e), "Unable to marshal to XML.")
return string(corsXML)
case "set":
return console.Colorize("CorsMessage", "Set bucket CORS config successfully.")
case "remove":
return console.Colorize("CorsMessage", "Removed bucket CORS config successfully.")
}
return ""
}
func (c corsMessage) JSON() string {
jsonBytes, e := json.MarshalIndent(&c, "", " ")
fatalIf(probe.NewError(e), "Unable to marshal to JSON.")
return string(jsonBytes)
}
// checkCorsSetSyntax - validate all the passed arguments
func checkCorsSetSyntax(ctx *cli.Context) {
if len(ctx.Args()) != 2 {
showCommandHelpAndExit(ctx, 1) // last argument is exit code
}
}
// mainCorsSet is the handle for "mc cors set" command.
func mainCorsSet(ctx *cli.Context) error {
checkCorsSetSyntax(ctx)
console.SetColor("CorsMessage", color.New(color.FgGreen))
// args[0] is the ALIAS/BUCKET argument.
args := ctx.Args()
urlStr := args.Get(0)
// args[1] is the CORSFILE which is a local file, or in the case of "-", stdin.
var e error
in := os.Stdin
if f := args.Get(1); f != "-" {
in, e = os.Open(f)
fatalIf(probe.NewError(e).Trace(args...), "Unable to open bucket CORS configuration file.")
defer in.Close()
}
corsXML, e := io.ReadAll(in)
fatalIf(probe.NewError(e).Trace(args...), "Unable to read bucket CORS configuration file.")
client, err := newClient(urlStr)
fatalIf(err.Trace(urlStr), "Unable to initialize client for "+urlStr)
fatalIf(client.SetBucketCors(globalContext, corsXML), "Unable to set bucket CORS configuration for "+urlStr)
printMsg(corsMessage{
op: "set",
Status: "success",
})
return nil
}
+28 -17
View File
@@ -22,6 +22,7 @@ import (
"errors"
"fmt"
"io"
"maps"
"path/filepath"
"strings"
@@ -29,6 +30,7 @@ import (
"github.com/minio/cli"
json "github.com/minio/colorjson"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio-go/v7"
"github.com/minio/pkg/v3/console"
)
@@ -72,8 +74,9 @@ var (
Usage: "disable multipart upload feature",
},
cli.BoolFlag{
Name: "md5",
Usage: "force all upload(s) to calculate md5sum checksum",
Name: "md5",
Usage: "force all upload(s) to calculate md5sum checksum",
Hidden: true,
},
cli.StringFlag{
Name: "tags",
@@ -95,6 +98,11 @@ var (
Name: "zip",
Usage: "Extract from remote zip file (MinIO server source only)",
},
cli.IntFlag{
Name: "max-workers",
Usage: "maximum number of concurrent copies (default: autodetect)",
},
checksumFlag,
}
)
@@ -155,7 +163,7 @@ EXAMPLES:
{{.Prompt}} {{.HelpName}} --recursive 'workdir/documents/May 2014/' s3/miniocloud
09. Copy a folder with encrypted objects recursively from Amazon S3 to MinIO cloud storage using s3 encryption.
{{.Prompt}} {{.HelpName}} --recursive --enc-s3 "s3/documents/=my-aws-key" --enc-s3 "myminio/documents/=my-minio-key" s3/documents/ myminio/documents/
{{.Prompt}} {{.HelpName}} --recursive --enc-s3 "s3/documents" --enc-s3 "myminio/documents" s3/documents/ myminio/documents/
10. Copy a folder with encrypted objects recursively from Amazon S3 to MinIO cloud storage.
{{.Prompt}} {{.HelpName}} --recursive --enc-c "s3/documents/=MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTIzNDU2Nzg5MDA" --enc-c "myminio/documents/=MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTIzNDU2Nzg5BBB" s3/documents/ myminio/documents/
@@ -276,7 +284,7 @@ func doCopy(ctx context.Context, copyOpts doCopyOpts) URLs {
// doCopyFake - Perform a fake copy to update the progress bar appropriately.
func doCopyFake(cpURLs URLs, pg Progress) URLs {
if progressReader, ok := pg.(*progressBar); ok {
progressReader.ProgressBar.Add64(cpURLs.SourceContent.Size)
progressReader.Add64(cpURLs.SourceContent.Size)
}
return cpURLs
@@ -315,7 +323,6 @@ func doCopySession(ctx context.Context, cancelCopy context.CancelFunc, cli *cli.
} else {
pg = newAccounter(totalBytes)
}
sourceURLs := cli.Args()[:len(cli.Args())-1]
targetURL := cli.Args()[len(cli.Args())-1] // Last one is target
@@ -327,6 +334,11 @@ func doCopySession(ctx context.Context, cancelCopy context.CancelFunc, cli *cli.
newerThan := cli.String("newer-than")
rewind := cli.String("rewind")
versionID := cli.String("version-id")
md5, checksum := parseChecksum(cli)
if withLock {
// The Content-MD5 header is required for any request to upload an object with a retention period configured using Amazon S3 Object Lock.
md5, checksum = true, minio.ChecksumNone
}
go func() {
totalBytes := int64(0)
@@ -359,7 +371,7 @@ func doCopySession(ctx context.Context, cancelCopy context.CancelFunc, cli *cli.
quitCh := make(chan struct{})
statusCh := make(chan URLs)
parallel := newParallelManager(statusCh)
parallel := newParallelManager(statusCh, cli.Int("max-workers"))
go func() {
gracefulStop := func() {
@@ -415,12 +427,11 @@ func doCopySession(ctx context.Context, cancelCopy context.CancelFunc, cli *cli.
isZip := cli.Bool("zip")
if cli.String("attr") != "" {
userMetaMap, _ := getMetaDataEntry(cli.String("attr"))
for metadataKey, metaDataVal := range userMetaMap {
cpURLs.TargetContent.UserMetadata[metadataKey] = metaDataVal
}
maps.Copy(cpURLs.TargetContent.UserMetadata, userMetaMap)
}
cpURLs.MD5 = cli.Bool("md5") || withLock
cpURLs.MD5 = md5
cpURLs.checksum = checksum
cpURLs.DisableMultipart = cli.Bool("disable-multipart")
// Verify if previously copied, notify progress bar.
@@ -477,7 +488,7 @@ loop:
console.Eraseline()
}
errorIf(cpURLs.Error.Trace(cpURLs.SourceContent.URL.String()),
fmt.Sprintf("Failed to copy `%s`.", cpURLs.SourceContent.URL.String()))
"Failed to copy `%s`.", cpURLs.SourceContent.URL)
if isErrIgnored(cpURLs.Error) {
cpAllFilesErr = false
continue loop
@@ -485,13 +496,13 @@ loop:
errSeen = true
if progressReader, pgok := pg.(*progressBar); pgok {
if progressReader.ProgressBar.Get() > 0 {
if progressReader.Get() > 0 {
writeContSize := (int)(cpURLs.SourceContent.Size)
totalPGSize := (int)(progressReader.ProgressBar.Total)
written := (int)(progressReader.ProgressBar.Get())
totalPGSize := (int)(progressReader.Total)
written := (int)(progressReader.Get())
if totalPGSize > writeContSize && written > writeContSize {
progressReader.ProgressBar.Set((written - writeContSize))
progressReader.ProgressBar.Update()
progressReader.Set((written - writeContSize))
progressReader.Update()
}
}
}
@@ -506,7 +517,7 @@ loop:
if !globalQuiet && !globalJSON {
console.Eraseline()
}
} else if progressReader.ProgressBar.Get() > 0 {
} else if progressReader.Get() > 0 {
progressReader.Finish()
}
} else {
+14 -11
View File
@@ -48,11 +48,12 @@ func getMetaDataEntry(metadataString string) (map[string]string, *probe.Error) {
var key, value strings.Builder
writeRune := func(ch rune, pt pToken) {
if pt == KEY {
switch pt {
case KEY:
key.WriteRune(ch)
} else if pt == VALUE {
case VALUE:
value.WriteRune(ch)
} else {
default:
panic("Invalid parser token type")
}
}
@@ -73,26 +74,28 @@ func getMetaDataEntry(metadataString string) (map[string]string, *probe.Error) {
}
if ch == '"' {
if ps == DQSTRING {
switch ps {
case DQSTRING:
ps = NORMAL
} else if ps == QSTRING {
case QSTRING:
writeRune(ch, pt)
} else if ps == NORMAL {
case NORMAL:
ps = DQSTRING
} else {
default:
break
}
continue
}
if ch == '\'' {
if ps == QSTRING {
switch ps {
case QSTRING:
ps = NORMAL
} else if ps == DQSTRING {
case DQSTRING:
writeRune(ch, pt)
} else if ps == NORMAL {
case NORMAL:
ps = QSTRING
} else {
default:
break
}
continue
+1
View File
@@ -28,6 +28,7 @@ func checkCopySyntax(cliCtx *cli.Context) {
if len(cliCtx.Args()) < 2 {
showCommandHelpAndExit(cliCtx, 1) // last argument is exit code.
}
parseChecksum(cliCtx)
// extract URLs.
URLs := cliCtx.Args()
+1 -1
View File
@@ -336,7 +336,7 @@ func prepareCopyURLs(ctx context.Context, o prepareCopyURLsOpts) chan URLs {
defer close(copyURLsCh)
copyURLsContent, err := guessCopyURLType(ctx, o)
if err != nil {
copyURLsCh <- URLs{Error: errUnableToGuess().Trace(o.sourceURLs...)}
copyURLsCh <- URLs{Error: errUnableToGuess(err.Cause.Error()).Trace(o.sourceURLs...)}
return
}
+1 -1
View File
@@ -184,7 +184,7 @@ func doDiffMain(ctx context.Context, firstURL, secondURL string) error {
}
// Diff first and second urls.
for diffMsg := range objectDifference(ctx, firstClient, secondClient, true) {
for diffMsg := range bucketObjectDifference(ctx, firstClient, secondClient) {
if diffMsg.Error != nil {
errorIf(diffMsg.Error, "Unable to calculate objects difference.")
// Ignore error and proceed to next object.
+34 -17
View File
@@ -161,17 +161,23 @@ func metadataEqual(m1, m2 map[string]string) bool {
return true
}
func objectDifference(ctx context.Context, sourceClnt, targetClnt Client, isMetadata bool) (diffCh chan diffMessage) {
sourceURL := sourceClnt.GetURL().String()
sourceCh := sourceClnt.List(ctx, ListOptions{Recursive: true, WithMetadata: isMetadata, ShowDir: DirNone})
targetURL := targetClnt.GetURL().String()
targetCh := targetClnt.List(ctx, ListOptions{Recursive: true, WithMetadata: isMetadata, ShowDir: DirNone})
return difference(sourceURL, sourceCh, targetURL, targetCh, isMetadata, false)
func bucketObjectDifference(ctx context.Context, sourceClnt, targetClnt Client) (diffCh chan diffMessage) {
return objectDifference(ctx, sourceClnt, targetClnt, mirrorOptions{
isMetadata: false,
})
}
func bucketDifference(ctx context.Context, sourceClnt, targetClnt Client) (diffCh chan diffMessage) {
func objectDifference(ctx context.Context, sourceClnt, targetClnt Client, opts mirrorOptions) (diffCh chan diffMessage) {
sourceURL := sourceClnt.GetURL().String()
sourceCh := sourceClnt.List(ctx, ListOptions{Recursive: true, WithMetadata: opts.isMetadata, ShowDir: DirNone})
targetURL := targetClnt.GetURL().String()
targetCh := targetClnt.List(ctx, ListOptions{Recursive: true, WithMetadata: opts.isMetadata, ShowDir: DirNone})
return difference(sourceURL, sourceCh, targetURL, targetCh, opts, false)
}
func bucketDifference(ctx context.Context, sourceClnt, targetClnt Client, opts mirrorOptions) (diffCh chan diffMessage) {
sourceURL := sourceClnt.GetURL().String()
sourceCh := make(chan *ClientContent)
@@ -215,11 +221,16 @@ func bucketDifference(ctx context.Context, sourceClnt, targetClnt Client) (diffC
}
}()
return difference(sourceURL, sourceCh, targetURL, targetCh, false, false)
return difference(sourceURL, sourceCh, targetURL, targetCh, opts, false)
}
func differenceInternal(sourceURL string, srcCh <-chan *ClientContent, targetURL string, tgtCh <-chan *ClientContent,
cmpMetadata, returnSimilar bool, diffCh chan<- diffMessage,
func differenceInternal(sourceURL string,
srcCh <-chan *ClientContent,
targetURL string,
tgtCh <-chan *ClientContent,
opts mirrorOptions,
returnSimilar bool,
diffCh chan<- diffMessage,
) *probe.Error {
// Pop first entries from the source and targets
srcCtnt, srcOk := <-srcCh
@@ -232,8 +243,14 @@ func differenceInternal(sourceURL string, srcCh <-chan *ClientContent, targetURL
tgtEOF = !tgtOk
// No objects from source AND target: Finish
if srcEOF && tgtEOF {
break
if opts.sourceListingOnly {
if srcEOF {
break
}
} else {
if srcEOF && tgtEOF {
break
}
}
if !srcEOF && srcCtnt.Err != nil {
@@ -332,7 +349,7 @@ func differenceInternal(sourceURL string, srcCh <-chan *ClientContent, targetURL
firstContent: srcCtnt,
secondContent: tgtCtnt,
}
} else if cmpMetadata &&
} else if opts.isMetadata &&
!metadataEqual(srcCtnt.UserMetadata, tgtCtnt.UserMetadata) &&
!metadataEqual(srcCtnt.Metadata, tgtCtnt.Metadata) {
@@ -375,13 +392,13 @@ func differenceInternal(sourceURL string, srcCh <-chan *ClientContent, targetURL
// objectDifference function finds the difference between all objects
// recursively in sorted order from source and target.
func difference(sourceURL string, sourceCh <-chan *ClientContent, targetURL string, targetCh <-chan *ClientContent, cmpMetadata, returnSimilar bool) (diffCh chan diffMessage) {
func difference(sourceURL string, sourceCh <-chan *ClientContent, targetURL string, targetCh <-chan *ClientContent, opts mirrorOptions, returnSimilar bool) (diffCh chan diffMessage) {
diffCh = make(chan diffMessage, 10000)
go func() {
defer close(diffCh)
err := differenceInternal(sourceURL, sourceCh, targetURL, targetCh, cmpMetadata, returnSimilar, diffCh)
err := differenceInternal(sourceURL, sourceCh, targetURL, targetCh, opts, returnSimilar, diffCh)
if err != nil {
// handle this specifically for filesystem related errors.
switch v := err.ToGoError().(type) {
+2 -2
View File
@@ -128,7 +128,7 @@ func du(ctx context.Context, urlStr string, timeRef time.Time, withVersions bool
clnt, pErr := newClientFromAlias(targetAlias, targetURL)
if pErr != nil {
errorIf(pErr.Trace(urlStr), "Failed to summarize disk usage `"+urlStr+"`.")
errorIf(pErr.Trace(urlStr), "Failed to summarize disk usage `%s`.", urlStr)
return 0, 0, exitStatus(globalErrorExitStatus) // End of journey.
}
@@ -156,7 +156,7 @@ func du(ctx context.Context, urlStr string, timeRef time.Time, withVersions bool
errorIf(content.Err.Trace(clnt.GetURL().String()), "Unable to list folder.")
continue
}
errorIf(content.Err.Trace(urlStr), "Failed to find disk usage of `"+urlStr+"` recursively.")
errorIf(content.Err.Trace(urlStr), "Failed to find disk usage of `%s` recursively.", urlStr)
return 0, 0, exitStatus(globalErrorExitStatus)
}
+1 -1
View File
@@ -125,7 +125,7 @@ func ParseDuration(s string) (Duration, error) {
var err error
// The next character must be [0-9.]
if !(s[0] == '.' || '0' <= s[0] && s[0] <= '9') {
if s[0] != '.' && ('0' > s[0] || s[0] > '9') {
return 0, errors.New("invalid duration " + orig)
}
// Consume [0-9]*
+3 -1
View File
@@ -22,6 +22,7 @@ import (
"encoding/base64"
"encoding/hex"
"fmt"
"path/filepath"
"sort"
"strings"
@@ -60,6 +61,7 @@ func (p byPrefixLength) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
// get SSE Key if object prefix matches with given resource.
func getSSE(resource string, encKeys []prefixSSEPair) encrypt.ServerSide {
resource = filepath.ToSlash(resource)
for _, k := range encKeys {
if strings.HasPrefix(resource, k.Prefix) {
return k.SSE
@@ -168,7 +170,7 @@ func validateAndParseKey(ctx *cli.Context, key string, keyType sseKeyType) (SSEP
}
func validateOverLappingSSEKeys(keyMap []prefixSSEPair) (err *probe.Error) {
for i := 0; i < len(keyMap); i++ {
for i := range keyMap {
for j := i + 1; j < len(keyMap); j++ {
if strings.HasPrefix(keyMap[i].Prefix, keyMap[j].Prefix) ||
strings.HasPrefix(keyMap[j].Prefix, keyMap[i].Prefix) {
+3 -3
View File
@@ -46,14 +46,14 @@ type errorMessage struct {
}
// fatalIf wrapper function which takes error and selectively prints stack frames if available on debug
func fatalIf(err *probe.Error, msg string, data ...interface{}) {
func fatalIf(err *probe.Error, msg string, data ...any) {
if err == nil {
return
}
fatal(err, msg, data...)
}
func fatal(err *probe.Error, msg string, data ...interface{}) {
func fatal(err *probe.Error, msg string, data ...any) {
if globalJSON {
errorMsg := errorMessage{
Message: msg,
@@ -128,7 +128,7 @@ func exitStatus(status int) error {
}
// errorIf synonymous with fatalIf but doesn't exit on error != nil
func errorIf(err *probe.Error, msg string, data ...interface{}) {
func errorIf(err *probe.Error, msg string, data ...any) {
if err == nil {
return
}
+10 -7
View File
@@ -36,6 +36,7 @@ import (
"github.com/minio/cli"
"github.com/minio/mc/pkg/probe"
"github.com/minio/pkg/v3/console"
"golang.org/x/text/unicode/norm"
// golang does not support flat keys for path matching, find does
"github.com/minio/pkg/v3/wildcard"
@@ -49,9 +50,9 @@ type findMessage struct {
// String calls tells the console what to print and how to print it.
func (f findMessage) String() string {
var msg string
msg += f.contentMessage.Key
msg += f.Key
if f.VersionID != "" {
msg += " (" + f.contentMessage.VersionID + ")"
msg += " (" + f.VersionID + ")"
}
return console.Colorize("Find", msg)
}
@@ -117,7 +118,7 @@ func getExitStatus(err error) int {
return 0
}
if pe, ok := err.(*exec.ExitError); ok {
if es, ok := pe.ProcessState.Sys().(syscall.WaitStatus); ok {
if es, ok := pe.Sys().(syscall.WaitStatus); ok {
return es.ExitStatus()
}
}
@@ -273,7 +274,7 @@ func doFind(ctxCtx context.Context, ctx *findContext) error {
lstOptions := ListOptions{
WithOlderVersions: ctx.withVersions,
WithDeleteMarkers: false,
WithDeleteMarkers: ctx.withVersions,
Recursive: true,
ShowDir: DirFirst,
WithMetadata: len(ctx.matchMeta) > 0 || len(ctx.matchTags) > 0,
@@ -486,8 +487,10 @@ func getRegexMap(cliCtx *cli.Context, key string) map[string]*regexp.Regexp {
reMap[split[0]] = nil
continue
}
// Normalize character encoding.
norm := norm.NFC.String(split[1])
var err error
reMap[split[0]], err = regexp.Compile(split[1])
reMap[split[0]], err = regexp.Compile(norm)
if err != nil {
fatalIf(probe.NewError(err), fmt.Sprintf("Unable to compile metadata regex for %s=%s", split[0], split[1]))
}
@@ -507,7 +510,7 @@ func matchRegexMaps(m map[string]*regexp.Regexp, v map[string]string) bool {
continue
}
val, ok := v[k]
if !ok || !reg.MatchString(val) {
if !ok || !reg.MatchString(norm.NFC.String(val)) {
return false
}
}
@@ -529,7 +532,7 @@ func matchMetadataRegexMaps(m map[string]*regexp.Regexp, v map[string]string) bo
if !ok {
val, ok = v[http.CanonicalHeaderKey(fmt.Sprintf("X-Amz-Meta-%s", k))]
}
if !ok || !reg.MatchString(val) {
if !ok || !reg.MatchString(norm.NFC.String(val)) {
return false
}
}
+55
View File
@@ -18,9 +18,14 @@
package cmd
import (
"errors"
"fmt"
"strings"
"time"
"github.com/minio/cli"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio-go/v7"
)
const envPrefix = "MC_"
@@ -59,6 +64,11 @@ var globalFlags = []cli.Flag{
Usage: "enable debug output",
EnvVar: envPrefix + "DEBUG",
},
cli.StringSliceFlag{
Name: "resolve",
Usage: "resolves HOST[:PORT] to an IP address. Example: minio.local:9000=10.10.75.1",
EnvVar: envPrefix + "RESOLVE",
},
cli.BoolFlag{
Name: "insecure",
Usage: "disable SSL certificate verification",
@@ -86,6 +96,10 @@ var globalFlags = []cli.Flag{
Hidden: true,
Value: 10 * time.Minute,
},
cli.StringSliceFlag{
Name: "custom-header,H",
Usage: "add custom HTTP header to the request. 'key:value' format.",
},
}
// bundled encryption flags
@@ -111,3 +125,44 @@ var encS3Flag = cli.StringSliceFlag{
Usage: "encrypt/decrypt objects using server-side default keys and configurations. (multiple keys can be provided).",
EnvVar: envPrefix + "ENC_S3",
}
var checksumFlag = cli.StringFlag{
Name: "checksum",
Usage: "Add checksum to uploaded object. Values: CRC64NVME, CRC32, CRC32C, SHA1 or SHA256. Requires server trailing headers (AWS, MinIO)",
Value: "",
}
func parseChecksum(ctx *cli.Context) (useMD5 bool, ct minio.ChecksumType) {
useMD5 = ctx.Bool("md5")
if cs := ctx.String("checksum"); cs != "" {
switch strings.ToUpper(cs) {
case "CRC32":
ct = minio.ChecksumCRC32
case "CRC32C":
ct = minio.ChecksumCRC32C
case "CRC32-FO":
ct = minio.ChecksumFullObjectCRC32
case "CRC32C-FO":
ct = minio.ChecksumFullObjectCRC32C
case "SHA1":
ct = minio.ChecksumSHA1
case "SHA256":
ct = minio.ChecksumSHA256
case "CRC64N", "CRC64NVME":
ct = minio.ChecksumCRC64NVME
case "MD5":
useMD5 = true
default:
err := fmt.Errorf("unknown checksum type: %s. Should be one of CRC64NVME, MD5, CRC32, CRC32C, SHA1 or SHA256", cs)
fatalIf(probe.NewError(err), "")
}
if ct.IsSet() {
useTrailingHeaders.Store(true)
if useMD5 {
err := errors.New("cannot combine MD5 with checksum")
fatalIf(probe.NewError(err), "")
}
}
}
return
}
-1
View File
@@ -1,5 +1,4 @@
//go:build !windows
// +build !windows
// Copyright (c) 2015-2021 MinIO, Inc.
//
-1
View File
@@ -1,5 +1,4 @@
//go:build windows
// +build windows
// Copyright (c) 2015-2021 MinIO, Inc.
//
+1 -1
View File
@@ -92,7 +92,7 @@ func guessGetURLType(ctx context.Context, o prepareCopyURLsOpts) (*copyURLsConte
return cc, probe.NewError(fmt.Errorf("Please set a full path for s3 resource."))
}
cc.sourceContent = s3clnt.objectInfo2ClientContent(bucket, minio.ObjectInfo{
Key: path,
Key: path, VersionID: o.versionID,
})
client, err = newClient(o.targetURL)

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