Compare commits

...
Author SHA1 Message Date
Anis Elleuch 7e9625733d ilm: Add doc to the complete mc guide (#3270) 2020-07-19 12:45:36 -07:00
kannappanr 1513d76ca9 Fix typos in the examples (#3289) 2020-07-10 22:17:54 -07:00
P R 87dc0bf80e mc ilm list cell alignment for text (#3291) 2020-07-10 22:17:54 -07:00
Harshavardhana 69c0d33543 support proper proxy for all transports (#3290)
fixes #3225
2020-07-10 22:17:54 -07:00
Harshavardhana 8d891755e0 move to latest released minio to fix policy (#3288)
fixes #3265
2020-07-10 22:17:54 -07:00
ebozduman a9cd7869eb Fixes copy with partial metadata failure (#3282) 2020-07-10 22:17:54 -07:00
Harshavardhana c40ab338a3 support goreleaser for mc (#3286) 2020-07-10 22:17:54 -07:00
ebozduman 0fcd10d793 Adds support to preserve X-Amz-Meta-Mc-Attrs when os -> fs (#3285) 2020-07-10 22:17:54 -07:00
Anis Elleuch b7b75c5f46 cli: Load global flags in initBeforeRunningCmd (#3283)
app.Before receives a cli.Context but without flags parsed. There is no
point calling ctx.Bool() or ctx.IsSet() at that stage.

However, flags are parsed in commands, so minio initialization and
setting global variables (globalJSON, globalQuiet, etc..) can be moved
to the Before function of all commands.

Avoid setting command.Before for non leaf commands, otherwise Before
function will be called multiples times until it reaches the leaf
command.
2020-07-10 22:17:54 -07:00
Anis Elleuch b97b7b8987 policy: Recalculate permission mode after setting a new one (#3280)
`mc policy set` can confuse users by showing that a bucket has 'none'
policy mode although issuing `mc policy get` will show it is `custom`
when the bucket already other policy statements for some sub-resources.

For better UX, mc will issue another request to get the real policy
mode.
2020-07-10 22:17:54 -07:00
poornas 8f3d514e3b Fix mc cp regression for recursive copy (#3278)
Fixes #3267. Revert commit dc430afe07
which attempted to preserve similar behavior across mc cp and mc
mirror, but introduces a regression for cp when wildcards are
specified.
2020-07-10 22:17:54 -07:00
Anis Elleuch bb3c0d45f2 s3: Use list object v1 in case of GCS (#3274) 2020-06-24 06:31:59 -07:00
Harshavardhana 9ebde383d4 make sure active/active enables watch by default (#3271)
- effectively use context everywhere
- effectively look for source-mtime in all
  variations
- `mc diff` should do metadata diff as well
2020-06-23 16:57:00 -07:00
Harshavardhana cfea4fdc75 fix: overwrite is implicit with active-active (#3268)
refactor lengthy options as mirrorOptions{} for
ease of readability and usage.
2020-06-23 09:31:19 -07:00
Harshavardhana dd47bdfeaa fix: support STS for admin commands (#3264) 2020-06-19 14:31:24 -07:00
ebozduman ec9b92cbb7 Apply global context for all apis (#3240) 2020-06-19 14:31:19 -07:00
poornas 975423abe2 Fix mc cp when legal-hold or retention is set (#3257)
- Send Content-MD5 header if default retention is set on the bucket
- legal-hold needs to be case insensitive
2020-06-16 11:28:25 -07:00
Harshavardhana 3dd971f673 rename multi-master to active-active (#3255) 2020-06-15 18:18:08 -07:00
Anis Elleuch 133dd1f7da add helpers for repeated code in bucket and object info (#3251)
Use bucketInfo2ClientContent() and objectInfo2ClientContent()
extensively to avoid code duplication.
2020-06-12 07:40:49 -07:00
Klaus Post bdefdc0169 cp: Fix Windows paths (#3250)
Paths without `/` separator were not trimmed correctly.

Fixes #3241

Regression originating from #3115
2020-06-10 09:31:59 -07:00
Anis Elleuch c51e3b3ec9 Return 1 as exit code when the cmd is unknown (#3249) 2020-06-09 08:52:04 -07:00
Harshavardhana 88223f96be simplify FS put behavior for partial files (#3246) 2020-06-08 12:26:03 -07:00
Harshavardhana fa520cbd1a enable golang-lint CI run and -race tests (#3247) 2020-06-08 05:55:10 -07:00
Justin Hutchings 166db95464 Add CodeQL security scanning (#3243) 2020-06-05 10:26:11 -07:00
Federico Pellegrin 0e27dd4ed4 Fix policy command flags order online help and partially doc (#3244) 2020-06-05 01:09:38 -07:00
kannappanr 2403e7a744 Check if destination and source are same (#3234)
Fixes #3229
2020-05-27 20:15:08 -07:00
Anis Elleuch ea03e61fac Avoid annoying error when alias has a leading slash (#3236)
```
mc config host list
mc config host add
mc config host remove
mc admin prometheus generate
```

The above mc commands generate an annoying error message complaining
about the leading slash in the alias argument.

Although alias does not support any slash or backslash, we allow the
user to enter it for convenience and the code will just clean it before
using it.
2020-05-27 14:23:31 -07:00
poornas f55e9c1997 Add admin bucket quota command to manage quota (#3179) 2020-05-26 22:56:53 -07:00
kannappanr 7664bb2c8d mirror: check if bucket exists before creating it (#3233)
Fixes #3228
2020-05-26 20:04:20 -07:00
kannappanr 09f832f597 copyobject: Do not ignore storage class in the target (#3232)
Fixes #3230
2020-05-24 14:23:28 -07:00
Anis Elleuch 4cc297ba4e diff: Disable comparing modtimes when multimaster context is not found (#3226) 2020-05-21 23:50:29 -07:00
Harshavardhana bf731558cd remove panic on double close watch channel (#3223) 2020-05-19 14:31:24 -07:00
Anis Elleuch 949dd282f9 fix copy issue when the source is not seekable (#3216)
The downloaded data will be stored in [file].part.minio
first and then renamed to [file]

The code also does not behave correctly when the source 
reader is not seekable. the reader is wrapped by a reader 
hook and then tested if it is seekable or not, though the 
reader hook is always seekable.
2020-05-18 20:05:46 -07:00
P R 61b74e90bf mc ilm fix some functionality changes (#3221) 2020-05-18 19:57:08 -07:00
Harshavardhana 3b479cf92e refactor cleanup ilm command to make it more maintainable (#3220) 2020-05-15 16:54:34 -07:00
Bala FA 09c31c4ab2 add bucket tagging support (#3182) 2020-05-15 12:10:50 -07:00
Anis Elleuch 71196b1013 completion: Complete path starting with ~/ (#3217)
posener/complete library does not support paths starting
with a tilde. This commit implements a workaround for that.
2020-05-15 08:12:47 -07:00
P R 72c8e92459 Add ilm command. (#3097) 2020-05-14 08:55:21 -07:00
César Nieto a6d82862cd make WatchOptions and WatchObject fields public (#3218) 2020-05-12 10:42:34 -07:00
ebozduman 672390b86a fix a simple typo #3159 2020-05-09 21:33:26 -07:00
Harshavardhana 2e586e6b9d support session tokens as part of ENV (#3213) 2020-05-07 15:21:12 -07:00
P R ad0bc4c33d progress bar update on obj write failure (#3195)
Fixes #3193
2020-05-07 10:28:27 -07:00
ebozduman a75dca16bd fix: cp preserve ownership issue (#3202) 2020-05-07 09:00:48 -07:00
Bala FA 4e3b501528 add --storage-class flag to pipe command. (#3204)
Fixes #3157
2020-05-06 23:06:01 -07:00
Harshavardhana dc2ad27429 fix mirror crash if source is deleted (#3206) 2020-05-05 23:55:35 -07:00
Harshavardhana b99c313366 cleanup legal-hold/retention and update docs (#3197) 2020-05-04 20:09:36 -07:00
kannappanr e13751f5d5 doc: Remove example related to object locked bucket (#3201)
mv does not support this command for object locked buckets.
2020-05-04 10:09:49 -07:00
Bala FA ca650e227a fix: create empty probe error to fatalIf() (#3199)
Fixes #3198
2020-05-04 07:58:28 -07:00
Harshavardhana df8bb795ba refactor watch mirror for performance (#3196) 2020-05-02 12:07:21 -07:00
Harshavardhana 2fe7d04043 run go mod tidy 2020-04-26 15:34:57 -07:00
Nitish Tiwari 138d7656ba fix: Update to use minio-go with jsoniter (#3191)
Also remove unused args in doMirror()
2020-04-24 23:56:51 -07:00
Anis Elleuch 2018319125 sql: Adapt the code to the change in minio-go SQL API (#3161) 2020-04-24 09:34:51 -07:00
Harshavardhana c8c5c15249 fix auto-complete for missing commands (#3189) 2020-04-23 20:11:35 -07:00
Chloe Kudryavtsev 32d8ef24ef feat: allow fetching arbitrary object puburls (#3043)
This fix should be backward-compatible, since strings do not need 
to be initialized by default, and JSON explicitly allows it to be omitted
when empty.
2020-04-22 18:36:41 -07:00
ebozduman f82a7b13c1 fix: copy filesytem to objectstore regression (#3183) 2020-04-22 18:28:50 -07:00
BigUstad 49c2beec79 check object stat first before continuing with sql select call. (#3188) 2020-04-22 18:28:30 -07:00
Harshavardhana 24a72e4a33 fix add disable-multipart/md5 options for mirror (#3174) 2020-04-21 13:05:01 +05:30
Anis Elleuch c7166eac3a mirror: Use source time attr in multi-master mode (#3162) 2020-04-20 17:03:47 -07:00
Harshavardhana 20dd7011b9 Add lock/stale bot 2020-04-19 13:42:05 -07:00
Harshavardhana f23f814764 fix: allow watch to use queueCh from parallel manager (#3180) 2020-04-19 10:59:05 -07:00
kannappanr e1617a504b Canonicalize metadata recevied as part of events (#3181) 2020-04-19 10:10:40 -07:00
Harshavardhana 89930fed29 rb shouldn't hang on empty folders (#3178)
fixes #3176
fixes #3177
2020-04-19 09:50:18 -07:00
Marco Perrando 8c262e1f3f Fix: sql does not accept --encrypt-key flag. (#3175) 2020-04-18 23:09:07 -07:00
Harshavardhana e6a6cfcebf Update issue templates 2020-04-17 12:12:42 -07:00
Harshavardhana bb43b2adf1 add bug_report template 2020-04-17 12:09:51 -07:00
Harshavardhana 2d6a960f94 fix avoid multiple HEAD operations (#3173)
- Get() already has the metadata to preserve
- Stat() doesn't need to be sent multiple times
  do preserve attributes, use it once.
2020-04-17 01:01:34 -07:00
Harshavardhana 4036009dc2 fix optimize content-type detection for only FS (#3172)
Also avoid a secondary Stat() operation during
GetObject(), when preserving the metadata

Fixes #3170
2020-04-16 19:03:02 -07:00
BigUstad ab2500e2ef match S3 within URL in full appropriately (#3163)
Fixes #3140
2020-04-16 18:25:40 -07:00
Harshavardhana 5c4add2000 optimize client admin transport (#3168) 2020-04-16 18:24:11 -07:00
Anis Elleuch 59187f2ef7 s3: Use head API before listing in client.Stat() (#3156)
Stat() is supposed to return valid information for existing
objects and existing prefixes as well.

The current mechanism issues a listing request and searches
for the object or prefix in the returned list, but this could take
time if there are a lot of entries under a parent prefix.

The new commit changes the internal behavior but not the
functional output. It issues a HEAD request first, if there
is no object then assumes it is a prefix and does listing
in order to find it.
2020-04-16 16:23:37 -07:00
Nitish Tiwari 37ee28a051 Enforce issue templates for new issues (#3171) 2020-04-16 12:13:11 -07:00
Harshavardhana 91ca683b03 improve signature probe avoid repeated code (#3169) 2020-04-16 11:45:28 -07:00
Harshavardhana 68b638f2f9 update mc to latest minio (#3167) 2020-04-15 12:37:18 -07:00
Daniel Valdivia 42023a1298 allow mc event remove to remove individual events (#3145) 2020-04-14 18:44:29 -07:00
BigUstad 150bc75a2c Documentation for mc tag (#3136) 2020-04-14 18:40:29 -07:00
Harshavardhana 4388f6d69b trim alias from obd filename avoid local write failure (#3164) 2020-04-14 17:37:31 -07:00
Sidhartha Mani 9e4e435c56 make admin obd deadline configurable (#3154) 2020-04-14 13:12:06 -07:00
Bala FA dfa1e42b25 add mc mv command (#3134)
Fixes #3077
2020-04-14 11:59:16 -07:00
Harshavardhana cb9e103714 upgrade to latest pkg/madmin package (#3151) 2020-04-10 08:57:45 -07:00
ebozduman dee04e3d73 Adds and rewords policy examples (#3146) 2020-04-08 18:53:34 -07:00
Nitish Tiwari 18f81e5458 cp: Add object lock related flags (#3127)
- Adds --retention-mode,--retention-duration &
  --legal-hold flags in cp command

- Adds --bypass flag in rm command
2020-04-07 19:51:20 -07:00
Harshavardhana 8cae137525 fix all the build errors 2020-04-03 22:22:20 -07:00
Bala FA 3b31837927 add disableMultipart option to Copy() (#3141) 2020-04-03 20:14:05 -07:00
Harshavardhana f0f56ac906 update to minio-go latest release v6.0.52 (#3142) 2020-04-03 18:16:56 -07:00
Daniel Valdivia 4d36c1f8b8 Make NewS3Config and NewAdminFactory Public (#3138) 2020-04-02 19:41:31 -07:00
César Nieto a9e875b503 set S3Client struct as public (#3139) 2020-04-02 19:33:44 -07:00
Bala FA 51ef254a41 add --disable-multipart flag in cp (#3135) 2020-04-02 08:21:33 -07:00
Harshavardhana e05f02d9f4 add build trimpaths to remove gopath (#3137) 2020-04-01 15:09:42 -07:00
Daniel Valdivia 0ea8d1d479 Make BuildS3Config public (#3132) 2020-04-01 07:41:53 -07:00
Sidhartha Mani eeeca2332d Onboard Diagnostics (#3114)
Also colorize JSON output in all admin commands
2020-04-01 01:35:46 -07:00
BigUstad 080414009e mc watch windows URL/absolute path event path (#3133) 2020-03-31 09:50:29 -07:00
poornas 25de1da81b Add legalhold command (#3095) 2020-03-31 09:18:26 -07:00
kannappanr 1fb87a492e cleanup tag command (#3126) 2020-03-23 09:23:52 -07:00
BigUstad 71eb7f6689 Add tag command (#3117) 2020-03-22 20:59:49 -07:00
Anis Elleuch 64a78e7811 Add global context and adapt context change in admin API (#3125)
This commit adds a new global context, monitors os signals
and cancels the global context in such cases to exit
on going process gracefully.

It will also update minio-go and adapts the code with
the new context changes in the admin API.
2020-03-21 13:42:41 -07:00
Harshavardhana b010699112 cleanup legacy metadata handling (#3118) 2020-03-19 17:00:20 -07:00
poornas 3230acae32 mc retention: add --recursive and --bypass flags. (#3100)
--bypass flag allows overriding governance if user
has override permissions
2020-03-19 12:24:09 -07:00
ebozduman 91da0da183 fix for incorrect mtime handling (#3121) 2020-03-18 11:33:53 -07:00
Anis Elleuch fc04dc6463 info: Add missing new lines in the output (#3119) 2020-03-17 15:28:21 -07:00
poornas fd43df09a1 mc cp: Fix prefix handling in TypeC (#3115)
for copy from filesystem to objectstorage.

Avoid prefixing dirname to file on target side
when doing a `mc cp /tmp/dir myminio/bucket --r`
to make `mc mirror` and `mc cp` behavior consistent
2020-03-15 17:47:35 -07:00
Anis Elleuch b621ae58f5 heal: Show scheduled next healing (#3111)
mc admin heal alias command will show the next healing time.

Also, show 'Never completed' when the server returns zero last healing activity
2020-03-14 22:30:27 -07:00
Jeffrey Clark bcbbfa7352 Secret key prompt (#3083) 2020-03-14 00:03:44 -07:00
Anis Elleuch 5b5d65a142 info: Fix showing offline nodes in the pretty output (#3112)
Also do some simplification in the code.
2020-03-13 18:16:17 -07:00
Klaus Post 1a27f7f51d mc cp -continue: Fix escape/colorization of JSON (#3116) 2020-03-13 13:21:39 -07:00
poornas 1092f6932f fix: Make sure Ctrl-C cancels mc cp right away (#3113) 2020-03-11 21:42:38 -07:00
Nitish Tiwari 128f81461c Update docs for mc admin update (#3110) 2020-03-10 21:34:54 -07:00
Kody A Kantor 7a26f993a2 resolve build issues on illumos (#3098) 2020-03-09 21:23:21 -07:00
Anis Elleuch c170a2db6c Update minio-go to bring some fixes (#3106) 2020-03-06 15:21:06 -08:00
Harshavardhana d58cf3c8c6 fix go mod tidy 2020-03-06 12:14:00 -08:00
Anis Elleuch a7dd97f140 Add support of threads & goroutines profiling type (#3108) 2020-03-06 12:12:38 -08:00
kannappanr 093bf0d54a deprecate 'mc session' documentation (#3104) 2020-03-05 09:27:51 -08:00
kannappanr a0d9e26dc7 Support arm32, 386 compilation: (#3103) 2020-03-05 09:27:20 -08:00
Harshavardhana 24e7caa146 Use listObjectsV1 for GCS S3 implementation (#3101)
Fixes #3073
2020-03-03 23:13:10 +03:00
poornas b65d6797cd retention - cleanup unused code (#3094) 2020-02-26 10:56:49 +05:30
Harshavardhana 67e90b8fcb fix handling of directories in Stat (#3092)
Fixes #3089
Fixes #3091
2020-02-25 18:08:20 +05:30
Dmitry Wagin fd89251270 added pkg/disk/stat_freebsd.go (#3090) 2020-02-25 09:26:56 +05:30
Harshavardhana 4152714126 fix go mod tidy again 2020-02-19 12:05:24 +05:30
ebozduman 3862184a8a honor prefix for object and directory names in 'rm -r' (#3012) 2020-02-19 10:42:41 +05:30
Harshavardhana 7e1e91d9c9 go mod tidy (#3081) 2020-02-19 09:02:21 +05:30
Harshavardhana 5d9a04bac6 allow mirror to copy zero byte file (#3084)
this PR also cleans up code and avoids
extra calls for source target
2020-02-18 11:09:42 -08:00
kannappanr 2f2aecb09d use latest minio-go version (#3080) 2020-02-14 11:22:22 -08:00
poornas e03d8d99a3 Fix crash in mc admin console (#3079)
Fixes : #3078
2020-02-14 10:54:22 -08:00
Harshavardhana f7c366ae3d add debug support for 'config host add' (#3076) 2020-02-13 21:36:10 +05:30
Harshavardhana 0724774bd8 Fix go.sum file missing entries (#3071) 2020-02-06 12:02:46 +05:30
Andreas Auernhammer 551a124804 add the mc admin kms subcommands (#2882)
This commit adds the first set of KMS admin
commands.

For new there is only the
`mc admin kms key status <endpoint> [key-ID]` command
that can be used to fetch status information for a
KMS master key. Listing and rotation commands are
planed.
2020-02-05 10:29:17 -08:00
Reinhard Koehn 609274326b Ensure 64bit alignment on 32bit builds for atomics (#3065)
Keep elements that are used with atomic.* functions as first element
of struct because it guarantees 64bit alignment on 32 bit machines.
atomic.* functions crash if operand is not aligned at 64bit.
See https://github.com/golang/go/issues/599
2020-02-04 13:17:27 -08:00
ebozduman ac9b942397 check for bucket exists in 'admin heal' (#3059) 2020-02-01 10:55:13 -08:00
Harshavardhana b70a79e39b fix: handle symlinks by reading/following as needed (#3053)
Avoid using filepath.EvalSymlinks and let the caller
fail appropriately for symlinks.

Fixes #3011
2020-01-23 02:33:58 -08:00
Harshavardhana 0baee49a66 fix: update admin docs for latest changes (#3054) 2020-01-20 16:51:06 -08:00
Harshavardhana 6a2da1a6ef upgrade to latest server to remove replace tags (#3051) 2020-01-18 17:01:00 -08:00
Harshavardhana 28aae43c8c fix: best effort save permissions always (#3050) 2020-01-17 14:02:12 -08:00
Harshavardhana 0596acea95 admin/console: Fix a crash in console string generation (#3049) 2020-01-17 05:51:01 -08:00
Harshavardhana 8694ddb3ee Update pkg/madmin to support multiple profilers (#3048) 2020-01-16 12:31:49 -08:00
Maël Valais c27941bc2a cp: add missing } in help template (#3047) 2020-01-15 01:43:14 -08:00
Harshavardhana 79e183fd0f fix: update minio-go to support snowball data-transfer (#3042) 2020-01-11 15:15:30 -08:00
Anis Elleuch 632f0949bd retention: Error out early when url argument does not point to S3 server (#3041) 2020-01-10 16:53:09 -08:00
Harshavardhana 374100da7e fix: update docs for --attr command (#3040)
Also canonicalize metadata headers automatically
before, minio-go consumes it.
2020-01-10 19:18:42 +05:30
Harshavardhana 3f87064138 fix: du to ignore too many recursive symlinks (#3033) 2020-01-08 07:30:44 -08:00
Harshavardhana 63821bbe3f fix: crash in cp when cpURLs return error (#3035) 2020-01-07 12:17:00 -08:00
Klaus Post 2a66f9ba2b Only rename config directories (#3032)
If the user placed an `mc.exe` in the user directory and wasn't used it, it would be renamed.
2020-01-07 10:45:39 -08:00
poornas 27a033440e Add lock and retention docs (#3034) 2020-01-06 15:16:47 -08:00
Bala FA 50766862c1 fix default flag behaviour in du command (#3031)
- `mc du` without args should print help like other `mc` commands
- `mc du` should behave like `du -h --max-depth=1` as default
- optional `--recursive` if they want capacity for each folder.
fixes #2871
2020-01-04 12:56:35 -08:00
Harshavardhana 6d1a41458b Use colorjson to indent json properly in cp (#3030)
Additionally also do not initialize progress bar in json
or quiet mode in mirror.

Fixes #3029
Fixes #3017
2020-01-03 12:14:39 -08:00
Harshavardhana 9663319e9e Update mc dependencies to recent dep change on MinIO (#3026) 2019-12-31 11:27:59 -08:00
kannappanr 8f0b923312 Mirror: Generate STag and ETag on destination only in Multimaster mode (#3021) 2019-12-26 12:54:28 -08:00
191 changed files with 28969 additions and 4439 deletions
+19
View File
@@ -0,0 +1,19 @@
---
name: Bug report
about: Bug report template
title: ''
labels: community, triage
assignees: ''
---
## Expected behavior
## Actual behavior
## Steps to reproduce the behavior
## mc --version
- (paste output of `mc --version`)
## System information
+5
View File
@@ -0,0 +1,5 @@
blank_issues_enabled: false
contact_links:
- name: MinIO Community Support
url: https://slack.min.io
about: Please ask and answer questions here.
+39
View File
@@ -0,0 +1,39 @@
# Configuration for Lock Threads - https://github.com/dessant/lock-threads-app
# Number of days of inactivity before a closed issue or pull request is locked
daysUntilLock: 365
# Skip issues and pull requests created before a given timestamp. Timestamp must
# follow ISO 8601 (`YYYY-MM-DD`). Set to `false` to disable
skipCreatedBefore: false
# Issues and pull requests with these labels will be ignored. Set to `[]` to disable
exemptLabels: []
# Label to add before locking, such as `outdated`. Set to `false` to disable
lockLabel: false
# Comment to post before locking. Set to `false` to disable
lockComment: >-
This thread has been automatically locked since there has not been
any recent activity after it was closed. Please open a new issue for
related bugs.
# Assign `resolved` as the reason for locking. Set to `false` to disable
setLockReason: true
# Limit to only `issues` or `pulls`
only: issues
# Optionally, specify configuration settings just for `issues` or `pulls`
# issues:
# exemptLabels:
# - help-wanted
# lockLabel: outdated
# pulls:
# daysUntilLock: 30
# Repository to extend settings from
# _extends: repo
+59
View File
@@ -0,0 +1,59 @@
# Configuration for probot-stale - https://github.com/probot/stale
# Number of days of inactivity before an Issue or Pull Request becomes stale
daysUntilStale: 90
# Number of days of inactivity before an Issue or Pull Request with the stale label is closed.
# Set to false to disable. If disabled, issues still need to be closed manually, but will remain marked as stale.
daysUntilClose: 30
# Only issues or pull requests with all of these labels are check if stale. Defaults to `[]` (disabled)
onlyLabels: []
# Issues or Pull Requests with these labels will never be considered stale. Set to `[]` to disable
exemptLabels:
- "security"
- "pending discussion"
# Set to true to ignore issues in a project (defaults to false)
exemptProjects: false
# Set to true to ignore issues in a milestone (defaults to false)
exemptMilestones: false
# Set to true to ignore issues with an assignee (defaults to false)
exemptAssignees: false
# Label to use when marking as stale
staleLabel: stale
# Comment to post when marking as stale. Set to `false` to disable
markComment: >-
This issue has been automatically marked as stale because it has not had
recent activity. It will be closed after 21 days if no further activity
occurs. Thank you for your contributions.
# Comment to post when removing the stale label.
# unmarkComment: >
# Your comment here.
# Comment to post when closing a stale Issue or Pull Request.
# closeComment: >
# Your comment here.
# Limit the number of actions per hour, from 1-30. Default is 30
limitPerRun: 1
# Limit to only `issues` or `pulls`
# only: issues
# Optionally, specify configuration settings that are specific to just 'issues' or 'pulls':
# pulls:
# daysUntilStale: 30
# markComment: >
# This pull request has been automatically marked as stale because it has not had
# recent activity. It will be closed if no further activity occurs. Thank you
# for your contributions.
# issues:
# exemptLabels:
# - confirmed
+52
View File
@@ -0,0 +1,52 @@
name: "Code scanning - action"
on:
push:
pull_request:
schedule:
- cron: '0 19 * * 0'
jobs:
CodeQL-Build:
# CodeQL runs on ubuntu-latest and windows-latest
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v2
with:
# We must fetch at least the immediate parents so that if this is
# a pull request then we can checkout the head.
fetch-depth: 2
# If this run was triggered by a pull request event, then checkout
# the head of the pull request instead of the merge commit.
- run: git checkout HEAD^2
if: ${{ github.event_name == 'pull_request' }}
# Initializes the CodeQL tools for scanning.
- name: Initialize CodeQL
uses: github/codeql-action/init@v1
# Override language selection by uncommenting this and choosing your languages
# with:
# languages: go, javascript, csharp, python, cpp, java
# Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
# If this step fails, then you should remove it and run the build manually (see below)
- name: Autobuild
uses: github/codeql-action/autobuild@v1
# ℹ️ Command-line programs to run using the OS shell.
# 📚 https://git.io/JvXDl
# ✏️ If the Autobuild fails above, remove it and uncomment the following three lines
# and modify them (or add more) to build your code if your project
# uses a compiled language
#- run: |
# make bootstrap
# make release
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v1
+9 -5
View File
@@ -30,14 +30,18 @@ jobs:
if: matrix.os == 'windows-latest'
env:
GO111MODULE: on
run: go test -v -race ./...
run: |
go build --ldflags="-s -w" -o %GOPATH%\bin\mc.exe
go test -v -race --timeout 30m ./...
- name: Build on ${{ matrix.os }}
if: matrix.os == 'ubuntu-latest'
env:
GO111MODULE: on
run: |
make
diff -au <(gofmt -d *.go) <(printf "")
diff -au <(gofmt -d cmd) <(printf "")
diff -au <(gofmt -d pkg) <(printf "")
go test -v -race ./...
make test
diff -au <(gofmt -s -d cmd) <(printf "")
diff -au <(gofmt -s -d pkg) <(printf "")
make test-race
make verify
make crosscompile
+2 -1
View File
@@ -9,4 +9,5 @@ parts/
prime/
stage/
mc
.run*
.run*
.idea/
+28
View File
@@ -0,0 +1,28 @@
linters-settings:
golint:
min-confidence: 0
misspell:
locale: US
linters:
disable-all: true
enable:
- typecheck
- goimports
- misspell
- govet
- golint
- ineffassign
- gosimple
- deadcode
- structcheck
issues:
exclude-use-default: false
exclude:
- instead of using struct literal
- should have a package comment
- error strings should not be capitalized or end with punctuation or a newline
service:
golangci-lint-version: 1.20.0 # use the fixed version to not introduce new linters unexpectedly
+167
View File
@@ -0,0 +1,167 @@
project_name: mc
release:
name_template: "Version {{.Version}}"
disable: true
github:
owner: minio
name: mc
env:
- CGO_ENABLED=0
- GO111MODULE=on
before:
hooks:
- make clean
- go generate ./...
- go mod tidy
- go mod download
builds:
-
goos:
- linux
- darwin
- windows
- freebsd
goarch:
- amd64
- arm64
- arm
- ppc64le
- s390x
goarm:
- 7
ignore:
- goos: darwin
goarch: arm64
- goos: darwin
goarch: arm
- goos: darwin
goarch: ppc64le
- goos: darwin
goarch: s390x
- goos: windows
goarch: arm64
- goos: windows
goarch: arm
- goos: windows
goarch: ppc64le
- goos: windows
goarch: s390x
- goos: freebsd
goarch: arm
- goos: freebsd
goarch: arm64
- goos: freebsd
goarch: ppc64le
- goos: freebsd
goarch: s390x
flags:
- -tags=kqueue
- -trimpath
ldflags:
- "-s -w -X github.com/minio/mc/cmd.Version={{.Version}} -X github.com/minio/mc/cmd.ReleaseTag={{.Tag}} -X github.com/minio/mc/cmd.CommitID={{.FullCommit}} -X github.com/minio/mc/cmd.ShortCommitID={{.ShortCommit}}"
archives:
-
format: binary
name_template: "{{ .Binary }}-release/{{ .Os }}-{{ .Arch }}/{{ .Binary }}.{{ .Version }}"
nfpms:
-
id: minio
package_name: mc
vendor: MinIO, Inc.
homepage: https://min.io/
maintainer: dev@min.io
description: MinIO Client (mc) provides a modern alternative to UNIX commands like ls, cat, cp, mirror, diff, find etc. It supports filesystems and Amazon S3 compatible cloud storage service (AWS Signature v2 and v4).
license: Apache 2.0
bindir: /usr/bin
formats:
- deb
- rpm
overrides:
deb:
file_name_template: "{{ .Binary }}-release/debs/{{ .ProjectName }}-{{ .Version }}_{{ .Arch }}"
replacements:
arm: armv7
files:
"NOTICE": "/usr/share/mc/NOTICE"
"CREDITS": "/usr/share/mc/CREDITS"
"LICENSE": "/usr/share/mc/LICENSE"
"README.md": "/usr/share/mc/README.md"
rpm:
file_name_template: "{{ .Binary }}-release/rpms/{{ .ProjectName }}-{{ .Version }}.{{ .Arch }}"
replacements:
amd64: x86_64
arm64: aarch64
arm: armv7
files:
"NOTICE": "/usr/share/mc/NOTICE"
"CREDITS": "/usr/share/mc/CREDITS"
"LICENSE": "/usr/share/mc/LICENSE"
"README.md": "/usr/share/mc/README.md"
checksum:
algorithm: sha256
signs:
-
signature: "${artifact}.asc"
cmd: "sh"
args:
- '-c'
- 'gpg --quiet --detach-sign -a ${artifact}'
artifacts: all
changelog:
sort: asc
filters:
exclude:
- '^Update yaml files'
dockers:
-
goos: linux
goarch: amd64
dockerfile: Dockerfile.release
image_templates:
- minio/mc:{{ .Tag }}
- minio/mc:latest
-
goos: linux
goarch: ppc64le
dockerfile: Dockerfile.ppc64le.release
image_templates:
- minio/mc:{{ .Tag }}-ppc64le
-
goos: linux
goarch: s390x
dockerfile: Dockerfile.s390x.release
image_templates:
- minio/mc:{{ .Tag }}-s390x
-
goos: linux
goarch: arm64
goarm: ''
dockerfile: Dockerfile.arm64.release
image_templates:
- minio/mc:{{ .Tag }}-arm64
-
goos: linux
goarch: arm
goarm: '7'
dockerfile: Dockerfile.arm.release
image_templates:
- minio/mc:{{ .Tag }}-arm
+20083
View File
File diff suppressed because it is too large Load Diff
+5 -5
View File
@@ -1,4 +1,4 @@
FROM golang:1.13-alpine
FROM golang:1.13-alpine as build
LABEL maintainer="MinIO Inc <dev@min.io>"
@@ -11,12 +11,12 @@ RUN \
git clone https://github.com/minio/mc && cd mc && \
go install -v -ldflags "$(go run buildscripts/gen-ldflags.go)"
FROM alpine:3.10
FROM alpine:3.12
COPY --from=0 /go/bin/mc /usr/bin/mc
COPY --from=build /go/bin/mc /usr/bin/mc
RUN \
apk add --no-cache ca-certificates && \
echo 'hosts: files mdns4_minimal [NOTFOUND=return] dns mdns4' >> /etc/nsswitch.conf
apk add --no-cache ca-certificates 'curl>7.61.0' && \
curl -s -q -O https://raw.githubusercontent.com/minio/minio/master/CREDITS
ENTRYPOINT ["mc"]
+12
View File
@@ -0,0 +1,12 @@
FROM multiarch/qemu-user-static:x86_64-arm as qemu
FROM arm32v7/alpine:3.12
LABEL maintainer="MinIO Inc <dev@min.io>"
COPY --from=qemu /usr/bin/qemu-arm-static /usr/bin
COPY mc /usr/bin/mc
RUN apk add --no-cache ca-certificates 'curl>7.61.0' && \
curl -s -q -O https://raw.githubusercontent.com/minio/minio/release/CREDITS
ENTRYPOINT ["mc"]
+12
View File
@@ -0,0 +1,12 @@
FROM multiarch/qemu-user-static:x86_64-arm as qemu
FROM arm64v8/alpine:3.12
LABEL maintainer="MinIO Inc <dev@min.io>"
COPY --from=qemu /usr/bin/qemu-arm-static /usr/bin
COPY mc /usr/bin/mc
RUN apk add --no-cache ca-certificates 'curl>7.61.0' && \
curl -s -q -O https://raw.githubusercontent.com/minio/minio/release/CREDITS
ENTRYPOINT ["mc"]
+3 -5
View File
@@ -1,10 +1,8 @@
FROM alpine:3.10
FROM alpine:3.12
COPY mc /usr/bin/
COPY CREDITS /
RUN \
apk add --no-cache ca-certificates && \
echo 'hosts: files mdns4_minimal [NOTFOUND=return] dns mdns4' >> /etc/nsswitch.conf \
chmod +x /usr/bin/mc
RUN apk add --no-cache ca-certificates
ENTRYPOINT ["mc"]
+12
View File
@@ -0,0 +1,12 @@
FROM multiarch/qemu-user-static:x86_64-arm as qemu
FROM ppc64le/alpine:3.12
LABEL maintainer="MinIO Inc <dev@min.io>"
COPY --from=qemu /usr/bin/qemu-arm-static /usr/bin
COPY mc /usr/bin/mc
RUN apk add --no-cache ca-certificates 'curl>7.61.0' && \
curl -s -q -O https://raw.githubusercontent.com/minio/minio/release/CREDITS
ENTRYPOINT ["mc"]
+5 -6
View File
@@ -1,11 +1,10 @@
FROM alpine:3.10
FROM alpine:3.12
MAINTAINER MinIO Inc <dev@min.io>
RUN \
apk add --no-cache ca-certificates && \
apk add --no-cache --virtual .build-deps curl && \
curl https://dl.min.io/client/mc/release/linux-amd64/mc > /usr/bin/mc && \
chmod +x /usr/bin/mc && apk del .build-deps
COPY mc /usr/bin/mc
RUN apk add --no-cache ca-certificates 'curl>7.61.0' && \
curl -s -q -O https://raw.githubusercontent.com/minio/minio/release/CREDITS
ENTRYPOINT ["mc"]
+12
View File
@@ -0,0 +1,12 @@
FROM multiarch/qemu-user-static:x86_64-arm as qemu
FROM s390x/alpine:3.12
LABEL maintainer="MinIO Inc <dev@min.io>"
COPY --from=qemu /usr/bin/qemu-arm-static /usr/bin
COPY mc /usr/bin/mc
RUN apk add --no-cache ca-certificates 'curl>7.61.0' && \
curl -s -q -O https://raw.githubusercontent.com/minio/minio/release/CREDITS
ENTRYPOINT ["mc"]
+16 -25
View File
@@ -18,18 +18,12 @@ checks:
getdeps:
@mkdir -p ${GOPATH}/bin
@which golint 1>/dev/null || (echo "Installing golint" && GO111MODULE=off go get -u golang.org/x/lint/golint)
ifeq ($(GOARCH),s390x)
@which staticcheck 1>/dev/null || (echo "Installing staticcheck" && GO111MODULE=off go get honnef.co/go/tools/cmd/staticcheck)
else
@which staticcheck 1>/dev/null || (echo "Installing staticcheck" && wget --quiet https://github.com/dominikh/go-tools/releases/download/2019.2.3/staticcheck_${GOOS}_${GOARCH}.tar.gz && tar xf staticcheck_${GOOS}_${GOARCH}.tar.gz && mv staticcheck/staticcheck ${GOPATH}/bin/staticcheck && chmod +x ${GOPATH}/bin/staticcheck && rm -f staticcheck_${GOOS}_${GOARCH}.tar.gz && rm -rf staticcheck)
endif
@which misspell 1>/dev/null || (echo "Installing misspell" && GO111MODULE=off go get -u github.com/client9/misspell/cmd/misspell)
@which golangci-lint 1>/dev/null || (echo "Installing golangci-lint" && curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(GOPATH)/bin v1.27.0)
crosscompile:
@(env bash $(PWD)/buildscripts/cross-compile.sh)
verifiers: getdeps vet fmt lint staticcheck spelling
verifiers: getdeps vet fmt lint
docker: build
@docker build -t $(TAG) . -f Dockerfile.dev
@@ -44,19 +38,9 @@ fmt:
@GO111MODULE=on gofmt -d pkg/
lint:
@echo "Running $@"
@GO111MODULE=on ${GOPATH}/bin/golint -set_exit_status github.com/minio/mc/cmd/...
@GO111MODULE=on ${GOPATH}/bin/golint -set_exit_status github.com/minio/mc/pkg/...
staticcheck:
@echo "Running $@"
@GO111MODULE=on ${GOPATH}/bin/staticcheck github.com/minio/mc/cmd/...
@GO111MODULE=on ${GOPATH}/bin/staticcheck github.com/minio/mc/pkg/...
spelling:
@GO111MODULE=on ${GOPATH}/bin/misspell -locale US -error `find cmd/`
@GO111MODULE=on ${GOPATH}/bin/misspell -locale US -error `find pkg/`
@GO111MODULE=on ${GOPATH}/bin/misspell -locale US -error `find docs/`
@echo "Running $@ check"
@GO111MODULE=on ${GOPATH}/bin/golangci-lint cache clean
@GO111MODULE=on ${GOPATH}/bin/golangci-lint run --timeout=5m --config ./.golangci.yml
# Builds mc, runs the verifiers then runs the tests.
check: test
@@ -66,14 +50,21 @@ test: verifiers build
@echo "Running functional tests"
@(env bash $(PWD)/functional-tests.sh)
coverage: build
@echo "Running all coverage for MinIO"
@(env bash $(PWD)/buildscripts/go-coverage.sh)
test-race: verifiers build
@echo "Running unit tests under -race"
@GO111MODULE=on go test -race -v --timeout 20m ./... 1>/dev/null
# Verify mc binary
verify:
@echo "Verifying build with race"
@GO111MODULE=on CGO_ENABLED=1 go build -race -tags kqueue -trimpath --ldflags "$(LDFLAGS)" -o $(PWD)/mc 1>/dev/null
@echo "Running functional tests"
@(env bash $(PWD)/functional-tests.sh)
# Builds mc locally.
build: checks
@echo "Building mc binary to './mc'"
@GO111MODULE=on CGO_ENABLED=0 go build -tags kqueue --ldflags $(BUILD_LDFLAGS) -o $(PWD)/mc
@GO111MODULE=on CGO_ENABLED=0 go build -trimpath -tags kqueue --ldflags $(BUILD_LDFLAGS) -o $(PWD)/mc
# Builds MinIO and installs it to $GOPATH/bin.
install: build
+1 -1
View File
@@ -1,4 +1,4 @@
MinIO Client (C) 2014, 2015 MinIO, Inc.
MinIO Client (C) 2014-2020 MinIO, Inc.
This product includes software developed at MinIO, Inc.
(https://min.io/).
+25 -22
View File
@@ -4,28 +4,31 @@
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).
```
ls list buckets and objects
mb make a bucket
rb remove a bucket
cat display object contents
head display first 'n' lines of an object
pipe stream STDIN to an object
share generate URL for temporary access to an object
cp copy objects
mirror synchronize objects to a remote site
find search for objects
sql run sql queries on objects
stat stat contents of objects
diff list differences in object name, size, and date between buckets
rm remove objects
event manage object notifications
watch watch for object events
policy manage anonymous access to objects
admin manage MinIO servers
session manage saved sessions for cp command
config manage mc configuration file
update check for a new software update
version print version info
ls list buckets and objects
mb make a bucket
rb remove a bucket
cat display object contents
head display first 'n' lines of an object
pipe stream STDIN to an object
share generate URL for temporary access to an object
cp copy objects
mirror synchronize objects to a remote site
find search for objects
sql run sql queries on objects
stat stat contents of objects
lock set and get object lock configuration
retention set object retention for objects with a given prefix
legalhold set object legal hold for objects
diff list differences in object name, size, and date between buckets
rm remove objects
event manage object notifications
watch watch for object events
policy manage anonymous access to objects
admin manage MinIO servers
session manage saved sessions for cp command
config manage mc configuration file
update check for a new software update
version print version info
```
## Docker Container
+4 -4
View File
@@ -92,7 +92,7 @@ make
添加一个或多个S3兼容的服务,请参考下面说明。`mc`将所有的配置信息都存储在``~/.mc/config.json``文件中。
```
mc config host add <ALIAS> <YOUR-S3-ENDPOINT> <YOUR-ACCESS-KEY> <YOUR-SECRET-KEY> <API-SIGNATURE>
mc config host add <ALIAS> <YOUR-S3-ENDPOINT> <YOUR-ACCESS-KEY> <YOUR-SECRET-KEY> [--api API-SIGNATURE]
```
别名就是给你的云存储服务起了一个短点的外号。S3 endpoint,access key和secret key是你的云存储服务提供的。API签名是可选参数,默认情况下,它被设置为"S3v4"。
@@ -101,21 +101,21 @@ mc config host add <ALIAS> <YOUR-S3-ENDPOINT> <YOUR-ACCESS-KEY> <YOUR-SECRET-KEY
从MinIO服务获得URL、access key和secret key。
```
mc config host add minio http://192.168.1.51 BKIKJAA5BMMU2RHO6IBB V7f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12 S3v4
mc config host add minio http://192.168.1.51 BKIKJAA5BMMU2RHO6IBB V7f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12 --api s3v4
```
### 示例-Amazon S3云存储
参考[AWS Credentials指南](http://docs.aws.amazon.com/general/latest/gr/aws-security-credentials.html)获取你的AccessKeyID和SecretAccessKey。
```
mc config host add s3 https://s3.amazonaws.com BKIKJAA5BMMU2RHO6IBB V7f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12 S3v4
mc config host add s3 https://s3.amazonaws.com BKIKJAA5BMMU2RHO6IBB V7f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12 --api s3v4
```
### 示例-Google云存储
参考[Google Credentials Guide](https://cloud.google.com/storage/docs/migrating?hl=en#keys)获取你的AccessKeyID和SecretAccessKey。
```
mc config host add gcs https://storage.googleapis.com BKIKJAA5BMMU2RHO6IBB V8f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12 S3v2
mc config host add gcs https://storage.googleapis.com BKIKJAA5BMMU2RHO6IBB V8f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12 --api s3v2
```
注意:Google云存储只支持旧版签名版本V2,所以你需要选择S3v2。
+1 -1
View File
@@ -8,7 +8,7 @@ function _init() {
export CGO_ENABLED=0
## List of architectures and OS to test coss compilation.
SUPPORTED_OSARCH="linux/ppc64le linux/arm64 linux/s390x darwin/amd64 freebsd/amd64"
SUPPORTED_OSARCH="linux/ppc64le linux/arm64 linux/s390x darwin/amd64 freebsd/amd64 linux/arm linux/386 windows/amd64"
}
function _build() {
-5
View File
@@ -1,5 +0,0 @@
#!/usr/bin/env bash
set -e
GO111MODULE=on CGO_ENABLED=0 go test -v -coverprofile=coverage.txt -covermode=atomic ./...
+189
View File
@@ -0,0 +1,189 @@
/*
* MinIO Client (C) 2020 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cmd
import (
"fmt"
humanize "github.com/dustin/go-humanize"
"github.com/fatih/color"
"github.com/minio/cli"
json "github.com/minio/mc/pkg/colorjson"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio/pkg/console"
"github.com/minio/minio/pkg/madmin"
)
var adminQuotaFlags = []cli.Flag{
cli.StringFlag{
Name: "fifo",
Usage: "set fifo quota, allowing automatic deletion of older content",
},
cli.StringFlag{
Name: "hard",
Usage: "set a hard quota, disallowing writes after quota is reached",
},
cli.BoolFlag{
Name: "clear",
Usage: "clears bucket quota configured for bucket",
},
}
// quotaMessage container for content message structure
type quotaMessage struct {
op string
Status string `json:"status"`
Bucket string `json:"bucket"`
Quota uint64 `json:"quota,omitempty"`
QuotaType string `json:"type,omitempty"`
}
func (q quotaMessage) String() string {
switch q.op {
case "set":
return console.Colorize("QuotaMessage",
fmt.Sprintf("Successfully set bucket quota of %s with %s type on `%s`", humanize.IBytes(q.Quota), q.QuotaType, q.Bucket))
case "unset":
return console.Colorize("QuotaMessage",
fmt.Sprintf("Successfully cleared bucket quota configured on `%s`", q.Bucket))
default:
return console.Colorize("QuotaInfo",
fmt.Sprintf("Bucket `%s` has %s quota of %s", q.Bucket, q.QuotaType, humanize.IBytes(q.Quota)))
}
}
func (q quotaMessage) JSON() string {
jsonMessageBytes, e := json.MarshalIndent(q, "", " ")
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
return string(jsonMessageBytes)
}
var adminBucketQuotaCmd = cli.Command{
Name: "quota",
Usage: "Manage bucket quota",
Action: mainAdminBucketQuota,
Before: initBeforeRunningCmd,
Flags: append(adminQuotaFlags, globalFlags...),
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} TARGET [--fifo QUOTA | --hard QUOTA | --clear]
QUOTA
quota accepts human-readable case-insensitive number
suffixes such as "k", "m", "g" and "t" referring to the metric units KB,
MB, GB and TB respectively. Adding an "i" to these prefixes, uses the IEC
units, so that "gi" refers to "gibibyte" or "GiB". A "b" at the end is
also accepted. Without suffixes the unit is bytes.
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Display bucket quota configured for "mybucket" on MinIO.
{{.Prompt}} {{.HelpName}} myminio/mybucket
2. Set FIFO quota for a bucket "mybucket" on MinIO.
{{.Prompt}} {{.HelpName}} myminio/mybucket --fifo 64kB
3. Set hard quota of 1gb for a bucket "mybucket" on MinIO.
{{.Prompt}} {{.HelpName}} myminio/mybucket --hard 1gb
4. Clear bucket quota configured for bucket "mybucket" on MinIO.
{{.Prompt}} {{.HelpName}} myminio/mybucket --clear
`,
}
// checkAdminBucketQuotaSyntax - validate all the passed arguments
func checkAdminBucketQuotaSyntax(ctx *cli.Context) {
if len(ctx.Args()) == 0 || len(ctx.Args()) > 1 {
cli.ShowCommandHelpAndExit(ctx, "quota", 1) // last argument is exit code
}
if ctx.IsSet("hard") && ctx.IsSet("fifo") {
fatalIf(errInvalidArgument(), "Only one of --hard or --fifo flags can be set")
}
if (ctx.IsSet("hard") || ctx.IsSet("fifo")) && len(ctx.Args()) == 0 {
fatalIf(errInvalidArgument().Trace(ctx.Args()...), "please specify bucket and quota")
}
if ctx.IsSet("clear") && len(ctx.Args()) == 0 {
fatalIf(errInvalidArgument().Trace(ctx.Args()...), "clear flag must be passed with target alone")
}
}
// mainAdminBucketQuota is the handler for "mc admin bucket quota" command.
func mainAdminBucketQuota(ctx *cli.Context) error {
checkAdminBucketQuotaSyntax(ctx)
console.SetColor("QuotaMessage", color.New(color.FgGreen))
console.SetColor("QuotaInfo", color.New(color.FgBlue))
// Get the alias parameter from cli
args := ctx.Args()
aliasedURL := args.Get(0)
// Create a new MinIO Admin Client
client, err := newAdminClient(aliasedURL)
fatalIf(err, "Unable to initialize admin connection.")
quotaStr := ctx.String("fifo")
if ctx.IsSet("hard") {
quotaStr = ctx.String("hard")
}
_, targetURL := url2Alias(args[0])
if ctx.IsSet("fifo") || ctx.IsSet("hard") && len(args) == 1 {
qType := madmin.FIFOQuota
if ctx.IsSet("hard") {
qType = madmin.HardQuota
}
quota, e := humanize.ParseBytes(quotaStr)
fatalIf(probe.NewError(e).Trace(quotaStr), "Unable to parse quota")
if e = client.SetBucketQuota(globalContext, targetURL, &madmin.BucketQuota{Quota: quota, Type: qType}); e != nil {
fatalIf(probe.NewError(e).Trace(args...), "Unable to set bucket quota")
}
printMsg(quotaMessage{
op: "set",
Bucket: targetURL,
Quota: quota,
QuotaType: string(qType),
Status: "success",
})
} else if ctx.Bool("clear") && len(args) == 1 {
if err := client.SetBucketQuota(globalContext, targetURL, &madmin.BucketQuota{}); err != nil {
fatalIf(probe.NewError(err).Trace(args...), "Unable to clear bucket quota config")
}
printMsg(quotaMessage{
op: "unset",
Bucket: targetURL,
Status: "success",
})
} else {
qCfg, e := client.GetBucketQuota(globalContext, targetURL)
fatalIf(probe.NewError(e).Trace(args...), "Unable to get bucket quota")
printMsg(quotaMessage{
op: "get",
Bucket: targetURL,
Quota: qCfg.Quota,
QuotaType: string(qCfg.Type),
Status: "success",
})
}
return nil
}
+37
View File
@@ -0,0 +1,37 @@
/*
* MinIO Client (C) 2020 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cmd
import "github.com/minio/cli"
var adminBucketCmd = cli.Command{
Name: "bucket",
Usage: "manage buckets defined in the MinIO server",
Action: mainAdminBucket,
Flags: globalFlags,
Subcommands: []cli.Command{
adminBucketQuotaCmd,
},
HideHelpCommand: true,
}
// mainAdminBucket is the handle for "mc admin bucket" command.
func mainAdminBucket(ctx *cli.Context) error {
cli.ShowCommandHelp(ctx, ctx.Args().First())
return nil
// Sub-commands like "quota", "usage" have their own main.
}
+3 -4
View File
@@ -17,16 +17,15 @@
package cmd
import (
"encoding/json"
"github.com/minio/cli"
json "github.com/minio/mc/pkg/colorjson"
"github.com/minio/mc/pkg/probe"
)
var adminConfigExportCmd = cli.Command{
Name: "export",
Usage: "export all config keys to STDOUT",
Before: setGlobalsFromContext,
Before: initBeforeRunningCmd,
Action: mainAdminConfigExport,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
@@ -84,7 +83,7 @@ func mainAdminConfigExport(ctx *cli.Context) error {
fatalIf(err, "Unable to initialize admin connection.")
// Call get config API
buf, e := client.GetConfig()
buf, e := client.GetConfig(globalContext)
fatalIf(probe.NewError(e), "Cannot get server config")
// Print
+6 -7
View File
@@ -22,13 +22,12 @@ import (
"github.com/minio/cli"
json "github.com/minio/mc/pkg/colorjson"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio/pkg/madmin"
)
var adminConfigGetCmd = cli.Command{
Name: "get",
Usage: "interactively retrieve a config key parameters",
Before: setGlobalsFromContext,
Before: initBeforeRunningCmd,
Action: mainAdminConfigGet,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
@@ -57,13 +56,13 @@ EXAMPLES:
// configGetMessage container to hold locks information.
type configGetMessage struct {
Status string `json:"status"`
Value madmin.Targets `json:"value"`
Status string `json:"status"`
Value []byte `json:"value"`
}
// String colorized service status message.
func (u configGetMessage) String() string {
return u.Value.String()
return string(u.Value)
}
// JSON jsonified service status Message message.
@@ -96,7 +95,7 @@ func mainAdminConfigGet(ctx *cli.Context) error {
if len(ctx.Args()) == 1 {
// Call get config API
hr, e := client.HelpConfigKV("", "", false)
hr, e := client.HelpConfigKV(globalContext, "", "", false)
fatalIf(probe.NewError(e), "Cannot get help for the sub-system")
// Print
@@ -109,7 +108,7 @@ func mainAdminConfigGet(ctx *cli.Context) error {
}
// Call get config API
buf, e := client.GetConfigKV(strings.Join(args.Tail(), " "))
buf, e := client.GetConfigKV(globalContext, strings.Join(args.Tail(), " "))
fatalIf(probe.NewError(e), "Cannot get server '%s' config", args.Tail())
// Print
+1 -1
View File
@@ -17,12 +17,12 @@
package cmd
import (
"encoding/json"
"strings"
"text/tabwriter"
"text/template"
"github.com/fatih/color"
json "github.com/minio/mc/pkg/colorjson"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio/pkg/madmin"
)
+4 -4
View File
@@ -24,8 +24,8 @@ import (
"github.com/fatih/color"
"github.com/minio/cli"
json "github.com/minio/mc/pkg/colorjson"
"github.com/minio/mc/pkg/console"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio/pkg/console"
)
var historyListFlags = []cli.Flag{
@@ -43,7 +43,7 @@ var historyListFlags = []cli.Flag{
var adminConfigHistoryCmd = cli.Command{
Name: "history",
Usage: "show all historic configuration changes",
Before: setGlobalsFromContext,
Before: initBeforeRunningCmd,
Action: mainAdminConfigHistory,
Flags: append(append([]cli.Flag{}, globalFlags...), historyListFlags...),
CustomHelpTemplate: `NAME:
@@ -127,14 +127,14 @@ func mainAdminConfigHistory(ctx *cli.Context) error {
fatalIf(err, "Unable to initialize admin connection.")
if ctx.IsSet("clear") {
fatalIf(probe.NewError(client.ClearConfigHistoryKV("all")), "Cannot clear server configuration.")
fatalIf(probe.NewError(client.ClearConfigHistoryKV(globalContext, "all")), "Cannot clear server configuration.")
// Print
printMsg(configHistoryMessage{})
return nil
}
chEntries, e := client.ListConfigHistoryKV(ctx.Int("count"))
chEntries, e := client.ListConfigHistoryKV(globalContext, ctx.Int("count"))
fatalIf(probe.NewError(e), "Cannot list server history configuration.")
hentries := make([]historyEntry, len(chEntries))
+4 -4
View File
@@ -17,20 +17,20 @@
package cmd
import (
"encoding/json"
"fmt"
"os"
"github.com/fatih/color"
"github.com/minio/cli"
"github.com/minio/mc/pkg/console"
json "github.com/minio/mc/pkg/colorjson"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio/pkg/console"
)
var adminConfigImportCmd = cli.Command{
Name: "import",
Usage: "import multiple config keys from STDIN",
Before: setGlobalsFromContext,
Before: initBeforeRunningCmd,
Action: mainAdminConfigImport,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
@@ -96,7 +96,7 @@ func mainAdminConfigImport(ctx *cli.Context) error {
fatalIf(err, "Unable to initialize admin connection.")
// Call set config API
fatalIf(probe.NewError(client.SetConfig(os.Stdin)), "Cannot set server config")
fatalIf(probe.NewError(client.SetConfig(globalContext, os.Stdin)), "Cannot set server config")
// Print
printMsg(configImportMessage{
+5 -5
View File
@@ -23,8 +23,8 @@ import (
"github.com/fatih/color"
"github.com/minio/cli"
json "github.com/minio/mc/pkg/colorjson"
"github.com/minio/mc/pkg/console"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio/pkg/console"
)
var adminConfigEnvFlags = []cli.Flag{
@@ -37,7 +37,7 @@ var adminConfigEnvFlags = []cli.Flag{
var adminConfigResetCmd = cli.Command{
Name: "reset",
Usage: "interactively reset a config key parameters",
Before: setGlobalsFromContext,
Before: initBeforeRunningCmd,
Action: mainAdminConfigReset,
Flags: append(adminConfigEnvFlags, globalFlags...),
CustomHelpTemplate: `NAME:
@@ -64,7 +64,7 @@ type configResetMessage struct {
// String colorized service status message.
func (u configResetMessage) String() (msg string) {
msg += console.Colorize("ResetConfigSuccess",
"Reseteting key has been successful.\n")
"Key is successfully reset.\n")
suggestion := fmt.Sprintf("mc admin service restart %s", u.targetAlias)
msg += console.Colorize("ResetConfigSuccess",
fmt.Sprintf("Please restart your server with `%s`.\n", suggestion))
@@ -107,7 +107,7 @@ func mainAdminConfigReset(ctx *cli.Context) error {
if len(ctx.Args()) == 1 {
// Call get config API
hr, e := client.HelpConfigKV("", "", ctx.IsSet("env"))
hr, e := client.HelpConfigKV(globalContext, "", "", ctx.IsSet("env"))
fatalIf(probe.NewError(e), "Cannot get help for the sub-system")
// Print
@@ -121,7 +121,7 @@ func mainAdminConfigReset(ctx *cli.Context) error {
// Call reset config API
input := strings.Join(args.Tail(), " ")
fatalIf(probe.NewError(client.DelConfigKV(input)),
fatalIf(probe.NewError(client.DelConfigKV(globalContext, input)),
"Cannot reset '%s' on the server", input)
// Print set config result
+3 -3
View File
@@ -22,14 +22,14 @@ import (
"github.com/fatih/color"
"github.com/minio/cli"
json "github.com/minio/mc/pkg/colorjson"
"github.com/minio/mc/pkg/console"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio/pkg/console"
)
var adminConfigRestoreCmd = cli.Command{
Name: "restore",
Usage: "rollback back changes to a specific config history",
Before: setGlobalsFromContext,
Before: initBeforeRunningCmd,
Action: mainAdminConfigRestore,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
@@ -94,7 +94,7 @@ func mainAdminConfigRestore(ctx *cli.Context) error {
fatalIf(err, "Unable to initialize admin connection.")
// Call get config API
fatalIf(probe.NewError(client.RestoreConfigHistoryKV(args.Get(1))), "Cannot restore server configuration.")
fatalIf(probe.NewError(client.RestoreConfigHistoryKV(globalContext, args.Get(1))), "Cannot restore server configuration.")
// Print
printMsg(configRestoreMessage{
+4 -4
View File
@@ -23,15 +23,15 @@ import (
"github.com/fatih/color"
"github.com/minio/cli"
json "github.com/minio/mc/pkg/colorjson"
"github.com/minio/mc/pkg/console"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio/pkg/console"
"github.com/minio/minio/pkg/madmin"
)
var adminConfigSetCmd = cli.Command{
Name: "set",
Usage: "interactively set a config key parameters",
Before: setGlobalsFromContext,
Before: initBeforeRunningCmd,
Action: mainAdminConfigSet,
Flags: append(adminConfigEnvFlags, globalFlags...),
CustomHelpTemplate: `NAME:
@@ -105,7 +105,7 @@ func mainAdminConfigSet(ctx *cli.Context) error {
if !strings.Contains(input, madmin.KvSeparator) {
// Call get config API
hr, e := client.HelpConfigKV(args.Get(1), args.Get(2), ctx.IsSet("env"))
hr, e := client.HelpConfigKV(globalContext, args.Get(1), args.Get(2), ctx.IsSet("env"))
fatalIf(probe.NewError(e), "Cannot get help for the sub-system")
// Print
@@ -119,7 +119,7 @@ func mainAdminConfigSet(ctx *cli.Context) error {
}
// Call set config API
fatalIf(probe.NewError(client.SetConfigKV(input)),
fatalIf(probe.NewError(client.SetConfigKV(globalContext, input)),
"Cannot set '%s' to server", input)
// Print set config result
-1
View File
@@ -22,7 +22,6 @@ var adminConfigCmd = cli.Command{
Name: "config",
Usage: "manage MinIO server configuration",
Action: mainAdminConfig,
Before: setGlobalsFromContext,
Flags: globalFlags,
Subcommands: []cli.Command{
adminConfigGetCmd,
+39 -31
View File
@@ -17,6 +17,7 @@
package cmd
import (
"context"
"fmt"
"strings"
"time"
@@ -24,8 +25,8 @@ import (
"github.com/fatih/color"
"github.com/minio/cli"
json "github.com/minio/mc/pkg/colorjson"
"github.com/minio/mc/pkg/console"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio/pkg/console"
"github.com/minio/minio/pkg/madmin"
)
@@ -48,7 +49,7 @@ var adminConsoleCmd = cli.Command{
Name: "console",
Usage: "show console logs for MinIO server",
Action: mainAdminConsole,
Before: setGlobalsFromContext,
Before: initBeforeRunningCmd,
Flags: append(adminConsoleFlags, globalFlags...),
HideHelpCommand: true,
CustomHelpTemplate: `NAME:
@@ -103,7 +104,6 @@ func getLogTime(lt string) string {
func (l logMessage) String() string {
var hostStr string
var b = &strings.Builder{}
if l.NodeName != "" {
hostStr = fmt.Sprintf("%s ", colorizedNodeName(l.NodeName))
}
@@ -116,22 +116,23 @@ func (l logMessage) String() string {
fmt.Fprintf(b, "%s %s", hostStr, log.ConsoleMsg)
return b.String()
}
traceLength := len(l.Trace.Source)
apiString := "API: " + l.API.Name + "("
if l.API.Args != nil && l.API.Args.Bucket != "" {
apiString = apiString + "bucket=" + l.API.Args.Bucket
if l.API != nil {
apiString := "API: " + l.API.Name + "("
if l.API.Args != nil && l.API.Args.Bucket != "" {
apiString = apiString + "bucket=" + l.API.Args.Bucket
}
if l.API.Args != nil && l.API.Args.Object != "" {
apiString = apiString + ", object=" + l.API.Args.Object
}
apiString += ")"
fmt.Fprintf(b, "\n%s %s", hostStr, console.Colorize("API", apiString))
}
if l.API.Args != nil && l.API.Args.Object != "" {
apiString = apiString + ", object=" + l.API.Args.Object
if l.Time != "" {
fmt.Fprintf(b, "\n%s Time: %s", hostStr, getLogTime(l.Time))
}
if l.DeploymentID != "" {
fmt.Fprintf(b, "\n%s DeploymentID: %s", hostStr, l.DeploymentID)
}
apiString += ")"
var msg = console.Colorize("LogMessage", l.Trace.Message)
fmt.Fprintf(b, "\n%s %s", hostStr, console.Colorize("Api", apiString))
fmt.Fprintf(b, "\n%s Time: %s", hostStr, getLogTime(l.Time))
fmt.Fprintf(b, "\n%s DeploymentID: %s", hostStr, l.DeploymentID)
if l.RequestID != "" {
fmt.Fprintf(b, "\n%s RequestID: %s", hostStr, l.RequestID)
}
@@ -141,16 +142,23 @@ func (l logMessage) String() string {
if l.UserAgent != "" {
fmt.Fprintf(b, "\n%s UserAgent: %s", hostStr, l.UserAgent)
}
fmt.Fprintf(b, "\n%s Error: %s", hostStr, msg)
for key, value := range l.Trace.Variables {
if value != "" {
fmt.Fprintf(b, "\n%s %s=%s", hostStr, key, value)
if l.Trace != nil {
if l.Trace.Message != "" {
fmt.Fprintf(b, "\n%s Error: %s", hostStr, console.Colorize("LogMessage", l.Trace.Message))
}
if l.Trace.Variables != nil {
for key, value := range l.Trace.Variables {
if value != "" {
fmt.Fprintf(b, "\n%s %s=%s", hostStr, key, value)
}
}
}
if l.Trace.Source != nil {
traceLength := len(l.Trace.Source)
for i, element := range l.Trace.Source {
fmt.Fprintf(b, "\n%s %8v: %s", hostStr, traceLength-i, element)
}
}
}
for i, element := range l.Trace.Source {
fmt.Fprintf(b, "\n%s %8v: %s", hostStr, traceLength-i, element)
}
logMsg := strings.TrimPrefix(b.String(), "\n")
return fmt.Sprintf("%s\n", logMsg)
@@ -177,8 +185,7 @@ func mainAdminConsole(ctx *cli.Context) error {
fatalIf(errInvalidArgument().Trace(ctx.Args()...), "please set a proper limit, for example: '--limit 5' to display last 5 logs, omit this flag to display all available logs")
}
}
var logType string
logType = strings.ToLower(ctx.String("type"))
logType := strings.ToLower(ctx.String("type"))
if logType != "minio" && logType != "application" && logType != "all" {
fatalIf(errInvalidArgument().Trace(ctx.Args()...), "Invalid value for --type flag. Valid options are [minio, application, all]")
}
@@ -188,11 +195,12 @@ func mainAdminConsole(ctx *cli.Context) error {
fatalIf(err.Trace(aliasedURL), "Cannot initialize admin client.")
return nil
}
doneCh := make(chan struct{})
defer close(doneCh)
ctxt, cancel := context.WithCancel(globalContext)
defer cancel()
// Start listening on all console log activity.
logCh := client.GetLogs(node, limit, logType, doneCh)
logCh := client.GetLogs(ctxt, node, limit, logType)
for logInfo := range logCh {
if logInfo.Err != nil {
fatalIf(probe.NewError(logInfo.Err), "Cannot listen to console logs")
+3 -3
View File
@@ -23,8 +23,8 @@ import (
"github.com/fatih/color"
"github.com/minio/cli"
json "github.com/minio/mc/pkg/colorjson"
"github.com/minio/mc/pkg/console"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio/pkg/console"
"github.com/minio/minio/pkg/madmin"
)
@@ -32,7 +32,7 @@ var adminGroupAddCmd = cli.Command{
Name: "add",
Usage: "add users to a new or existing group",
Action: mainAdminGroupAdd,
Before: setGlobalsFromContext,
Before: initBeforeRunningCmd,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
@@ -131,7 +131,7 @@ func mainAdminGroupAdd(ctx *cli.Context) error {
Members: members,
IsRemove: false,
}
fatalIf(probe.NewError(client.UpdateGroupMembers(gAddRemove)).Trace(args...), "Cannot add new group")
fatalIf(probe.NewError(client.UpdateGroupMembers(globalContext, gAddRemove)).Trace(args...), "Cannot add new group")
printMsg(groupMessage{
op: "add",
+1 -1
View File
@@ -24,7 +24,7 @@ var adminGroupDisableCmd = cli.Command{
Name: "disable",
Usage: "Disable a group",
Action: mainAdminGroupEnableDisable,
Before: setGlobalsFromContext,
Before: initBeforeRunningCmd,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
+3 -3
View File
@@ -21,8 +21,8 @@ import (
"github.com/fatih/color"
"github.com/minio/cli"
"github.com/minio/mc/pkg/console"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio/pkg/console"
"github.com/minio/minio/pkg/madmin"
)
@@ -30,7 +30,7 @@ var adminGroupEnableCmd = cli.Command{
Name: "enable",
Usage: "Enable a group",
Action: mainAdminGroupEnableDisable,
Before: setGlobalsFromContext,
Before: initBeforeRunningCmd,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
@@ -79,7 +79,7 @@ func mainAdminGroupEnableDisable(ctx *cli.Context) error {
err1 = errors.New("cannot happen")
fatalIf(probe.NewError(err1).Trace(args...), "Could not get group enable")
}
err1 = client.SetGroupStatus(group, status)
err1 = client.SetGroupStatus(globalContext, group, status)
fatalIf(probe.NewError(err1).Trace(args...), "Could not get group enable")
printMsg(groupMessage{
+3 -3
View File
@@ -19,15 +19,15 @@ package cmd
import (
"github.com/fatih/color"
"github.com/minio/cli"
"github.com/minio/mc/pkg/console"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio/pkg/console"
)
var adminGroupInfoCmd = cli.Command{
Name: "info",
Usage: "display group info",
Action: mainAdminGroupInfo,
Before: setGlobalsFromContext,
Before: initBeforeRunningCmd,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
@@ -66,7 +66,7 @@ func mainAdminGroupInfo(ctx *cli.Context) error {
fatalIf(err, "Unable to initialize admin connection.")
group := args.Get(1)
gd, err1 := client.GetGroupDescription(group)
gd, err1 := client.GetGroupDescription(globalContext, group)
fatalIf(probe.NewError(err1).Trace(args...), "Could not get group info")
printMsg(groupMessage{
+3 -3
View File
@@ -19,15 +19,15 @@ package cmd
import (
"github.com/fatih/color"
"github.com/minio/cli"
"github.com/minio/mc/pkg/console"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio/pkg/console"
)
var adminGroupListCmd = cli.Command{
Name: "list",
Usage: "display list of groups",
Action: mainAdminGroupList,
Before: setGlobalsFromContext,
Before: initBeforeRunningCmd,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
@@ -65,7 +65,7 @@ func mainAdminGroupList(ctx *cli.Context) error {
client, err := newAdminClient(aliasedURL)
fatalIf(err, "Unable to initialize admin connection.")
gs, err1 := client.ListGroups()
gs, err1 := client.ListGroups(globalContext)
fatalIf(probe.NewError(err1).Trace(args...), "Could not get group list")
printMsg(groupMessage{
+3 -3
View File
@@ -19,8 +19,8 @@ package cmd
import (
"github.com/fatih/color"
"github.com/minio/cli"
"github.com/minio/mc/pkg/console"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio/pkg/console"
"github.com/minio/minio/pkg/madmin"
)
@@ -28,7 +28,7 @@ var adminGroupRemoveCmd = cli.Command{
Name: "remove",
Usage: "remove group or members from a group",
Action: mainAdminGroupRemove,
Before: setGlobalsFromContext,
Before: initBeforeRunningCmd,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
@@ -79,7 +79,7 @@ func mainAdminGroupRemove(ctx *cli.Context) error {
IsRemove: true,
}
e := client.UpdateGroupMembers(gAddRemove)
e := client.UpdateGroupMembers(globalContext, gAddRemove)
fatalIf(probe.NewError(e).Trace(args...), "Could not perform remove operation")
printMsg(groupMessage{
-1
View File
@@ -22,7 +22,6 @@ var adminGroupCmd = cli.Command{
Name: "group",
Usage: "manage groups",
Action: mainAdminGroup,
Before: setGlobalsFromContext,
Flags: globalFlags,
Subcommands: []cli.Command{
adminGroupAddCmd,
+5 -8
View File
@@ -20,16 +20,14 @@ import (
"errors"
"fmt"
"math"
"os"
"strings"
"syscall"
"time"
humanize "github.com/dustin/go-humanize"
"github.com/fatih/color"
json "github.com/minio/mc/pkg/colorjson"
"github.com/minio/mc/pkg/console"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio/pkg/console"
"github.com/minio/minio/pkg/madmin"
)
@@ -404,16 +402,15 @@ func (ui *uiData) healResumeMsg(aliasedURL string) string {
}
func (ui *uiData) DisplayAndFollowHealStatus(aliasedURL string) (res madmin.HealTaskStatus, err error) {
trapCh := signalTrap(os.Interrupt, syscall.SIGTERM, syscall.SIGKILL)
trapMsg := ui.healResumeMsg(aliasedURL)
quitMsg := ui.healResumeMsg(aliasedURL)
firstIter := true
for {
select {
case <-trapCh:
return res, errors.New(trapMsg)
case <-globalContext.Done():
return res, errors.New(quitMsg)
default:
_, res, err = ui.Client.Heal(ui.Bucket, ui.Prefix, *ui.HealOpts,
_, res, err = ui.Client.Heal(globalContext, ui.Bucket, ui.Prefix, *ui.HealOpts,
ui.ClientToken, ui.ForceStart, false)
if err != nil {
return res, err
+34 -8
View File
@@ -25,8 +25,8 @@ import (
"github.com/fatih/color"
"github.com/minio/cli"
json "github.com/minio/mc/pkg/colorjson"
"github.com/minio/mc/pkg/console"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio/pkg/console"
"github.com/minio/minio/pkg/madmin"
)
@@ -67,7 +67,7 @@ var adminHealCmd = cli.Command{
Name: "heal",
Usage: "heal disks, buckets and objects on MinIO server",
Action: mainAdminHeal,
Before: setGlobalsFromContext,
Before: initBeforeRunningCmd,
Flags: append(adminHealFlags, globalFlags...),
HideHelpCommand: true,
CustomHelpTemplate: `NAME:
@@ -150,11 +150,24 @@ type backgroundHealStatusMessage struct {
// String colorized to show background heal status message.
func (s backgroundHealStatusMessage) String() string {
dot := console.Colorize("Dot", " ● ")
healPrettyMsg := console.Colorize("HealBackgroundTitle", "Background healing status:\n")
healPrettyMsg += fmt.Sprintf(" Total items scanned: %s\n",
healPrettyMsg += dot + fmt.Sprintf("%s item(s) scanned in total\n",
console.Colorize("HealBackground", s.HealInfo.ScannedItemsCount))
healPrettyMsg += fmt.Sprintf(" Last background heal check: %s\n",
console.Colorize("HealBackground", timeDurationToHumanizedDuration(time.Since(s.HealInfo.LastHealActivity)).String()+" ago"))
lastHealingTime := dot + "Never executed"
if !s.HealInfo.LastHealActivity.IsZero() {
lastHealingTime = dot + "Completed " + timeDurationToHumanizedDuration(time.Since(s.HealInfo.LastHealActivity)).StringShort() + " ago"
}
healPrettyMsg += console.Colorize("HealBackground", lastHealingTime) + "\n"
now := time.Now()
if !s.HealInfo.NextHealRound.IsZero() && s.HealInfo.NextHealRound.After(now) {
nextHealingRound := timeDurationToHumanizedDuration(s.HealInfo.NextHealRound.Sub(now)).StringShort()
healPrettyMsg += dot + fmt.Sprintf("Next scheduled in %s\n", console.Colorize("HealBackground", nextHealingRound))
}
return healPrettyMsg
}
@@ -185,6 +198,7 @@ func mainAdminHeal(ctx *cli.Context) error {
aliasedURL := args.Get(0)
console.SetColor("Heal", color.New(color.FgGreen, color.Bold))
console.SetColor("Dot", color.New(color.FgGreen, color.Bold))
console.SetColor("HealBackgroundTitle", color.New(color.FgGreen, color.Bold))
console.SetColor("HealBackground", color.New(color.Bold))
console.SetColor("HealUpdateUI", color.New(color.FgYellow, color.Bold))
@@ -202,10 +216,22 @@ func mainAdminHeal(ctx *cli.Context) error {
splits := splitStr(aliasedURL, "/", 3)
bucket, prefix := splits[1], splits[2]
clnt, err := newClient(aliasedURL)
if err != nil {
fatalIf(err.Trace(clnt.GetURL().String()), "Unable to create client for URL ", aliasedURL)
return nil
}
for content := range clnt.List(globalContext, false, false, false, DirNone) {
if content.Err != nil {
fatalIf(content.Err.Trace(clnt.GetURL().String()), "Unable to heal bucket `"+bucket+"`.")
return nil
}
}
// Return the background heal status when the user
// doesn't pass a bucket or --recursive flag.
if bucket == "" && !ctx.Bool("recursive") {
bgHealStatus, berr := client.BackgroundHealStatus()
bgHealStatus, berr := client.BackgroundHealStatus(globalContext)
fatalIf(probe.NewError(berr), "Failed to get the status of the background heal.")
printMsg(backgroundHealStatusMessage{Status: "success", HealInfo: bgHealStatus})
return nil
@@ -221,13 +247,13 @@ func mainAdminHeal(ctx *cli.Context) error {
forceStart := ctx.Bool("force-start")
forceStop := ctx.Bool("force-stop")
if forceStop {
_, _, herr := client.Heal(bucket, prefix, opts, "", forceStart, forceStop)
_, _, herr := client.Heal(globalContext, bucket, prefix, opts, "", forceStart, forceStop)
fatalIf(probe.NewError(herr), "Failed to stop heal sequence.")
printMsg(stopHealMessage{Status: "success", Alias: aliasedURL})
return nil
}
healStart, _, herr := client.Heal(bucket, prefix, opts, "", forceStart, false)
healStart, _, herr := client.Heal(globalContext, bucket, prefix, opts, "", forceStart, false)
fatalIf(probe.NewError(herr), "Failed to start heal sequence.")
ui := uiData{
+47 -43
View File
@@ -21,6 +21,7 @@ import (
"fmt"
"reflect"
"strconv"
"strings"
"time"
humanize "github.com/dustin/go-humanize"
@@ -28,8 +29,8 @@ import (
"github.com/fatih/color"
"github.com/minio/cli"
json "github.com/minio/mc/pkg/colorjson"
"github.com/minio/mc/pkg/console"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio/pkg/console"
"github.com/minio/minio/pkg/madmin"
)
@@ -37,7 +38,7 @@ var adminInfoCmd = cli.Command{
Name: "info",
Usage: "display MinIO server information",
Action: mainAdminInfo,
Before: setGlobalsFromContext,
Before: initBeforeRunningCmd,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
@@ -61,50 +62,64 @@ type clusterStruct struct {
Info madmin.InfoMessage `json:"info,omitempty"`
}
// String provides colorized info messages.
// String provides colorized info messages depending on the type of a server
// FS server non-FS server
// ============================== ===================================
// ● <ip>:<port> ● <ip>:<port>
// Uptime: xxx Uptime: xxx
// Version: xxx Version: xxx
// Network: X/Y OK Network: X/Y OK
//
// U Used, B Buckets, O Objects Drives: N/N OK
//
// U Used, B Buckets, O Objects
// N drives online, K drives offline
//
func (u clusterStruct) String() (msg string) {
// Check cluster level "Status" field for error
if u.Status == "error" {
fatal(probe.NewError(errors.New(u.Error)), "Cannot get service status")
}
// If nothing has been collected, error out
if u.Info.Servers == nil {
fatal(probe.NewError(errors.New("Cannot get service status")), "")
}
// Initialization
var totalOnlineDisksCluster int
var totalOfflineDisksCluster int
// Dot represents server status, online (green) or offline (red)
dot := "●"
// Color palette initialization
console.SetColor("Info", color.New(color.FgGreen, color.Bold))
console.SetColor("InfoFail", color.New(color.FgRed, color.Bold))
// MinIO server type default
backendType := "Unknown"
// Set the type of MinIO server ("FS", "Erasure", "Unknown")
v := reflect.ValueOf(u.Info.Backend)
if v.Kind() == reflect.Map {
for _, key := range v.MapKeys() {
val := v.MapIndex(key)
switch t := val.Interface().(type) {
case string:
backendType = t
}
}
}
// Loop through each server and put together info for each one
for _, srv := range u.Info.Servers {
// Check if MinIO server is offline ("Mode" field),
// If offline, error out
if u.Info.Mode == "offline" {
if srv.State == "offline" {
// "PrintB" is color blue in console library package
msg += fmt.Sprintf("%s %s\n", console.Colorize("InfoFail", dot), console.Colorize("PrintB", srv.Endpoint))
msg += fmt.Sprintf(" Uptime: %s\n", console.Colorize("InfoFail", "offline"))
return
msg += fmt.Sprintf(" Uptime: %s\n\n", console.Colorize("InfoFail", "offline"))
// Continue to the next server
continue
}
// Check cluster level "Status" field for error
if u.Status == "error" {
fatal(probe.NewError(errors.New(u.Error)), "Cannot get service status")
}
// Set the type of MinIO server ("FS", "Erasure", "Unknown")
v := reflect.ValueOf(u.Info.Backend)
if v.Kind() == reflect.Map {
for _, key := range v.MapKeys() {
val := v.MapIndex(key)
switch t := val.Interface().(type) {
case string:
backendType = t
}
}
}
// Print server title
msg += fmt.Sprintf("%s %s\n", console.Colorize("Info", dot), console.Colorize("PrintB", srv.Endpoint))
@@ -132,19 +147,6 @@ func (u clusterStruct) String() (msg string) {
msg += fmt.Sprintf(" Network: %s %s\n", displayNwInfo, console.Colorize("Info", "OK "))
}
// Choose and display information depending on the type of a server
// FS server non-FS server
// ============================== ===================================
// ● <ip>:<port> ● <ip>:<port>
// Uptime: xxx Uptime: xxx
// Version: xxx Version: xxx
// Network: X/Y OK Network: X/Y OK
//
// U Used, B Buckets, O Objects Drives: N/N OK
//
// U Used, B Buckets, O Objects
// N drives online, K drives offline
//
if backendType != "FS" {
// Info about drives on a server, only available for non-FS types
var OffDisks int
@@ -166,27 +168,29 @@ func (u clusterStruct) String() (msg string) {
msg += fmt.Sprintf(" Drives: %s %s\n", dispNoOfDisks, console.Colorize("Info", "OK "))
}
if u.Info.Buckets.Count != 0 {
msg += "\n"
}
msg += "\n"
}
// Summary on used space, total no of buckets and
// total no of objects at the Cluster level
usedTotal := humanize.IBytes(uint64(u.Info.Usage.Size))
if u.Info.Buckets.Count > 0 {
msg += fmt.Sprintf("%s Used, %s, %s", usedTotal,
msg += fmt.Sprintf("%s Used, %s, %s\n", usedTotal,
english.Plural(int(u.Info.Buckets.Count), "Bucket", ""),
english.Plural(int(u.Info.Objects.Count), "Object", ""))
}
if backendType != "FS" {
// Summary on total no of online and total
// number of offline disks at the Cluster level
msg += fmt.Sprintf("\n%s online, %s offline",
msg += fmt.Sprintf("%s online, %s offline\n",
english.Plural(totalOnlineDisksCluster, "drive", ""),
english.Plural(totalOfflineDisksCluster, "drive", ""))
}
// Remove the last new line if any
// since this is a String() function
msg = strings.TrimSuffix(msg, "\n")
return
}
@@ -218,7 +222,7 @@ func mainAdminInfo(ctx *cli.Context) error {
var clusterInfo clusterStruct
// Fetch info of all servers (cluster or single server)
admInfo, e := client.ServerInfo()
admInfo, e := client.ServerInfo(globalContext)
if e != nil {
clusterInfo.Status = "error"
clusterInfo.Error = e.Error()
+91
View File
@@ -0,0 +1,91 @@
/*
* MinIO Client (C) 2020 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cmd
import (
"fmt"
"github.com/minio/cli"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio/pkg/madmin"
)
var adminKMSKeyStatusCmd = cli.Command{
Name: "status",
Usage: "request status information for a KMS master key",
Action: mainAdminKMSKeyStatus,
Before: initBeforeRunningCmd,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} TARGET [KEY_NAME]
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Get default master key and its status from a MinIO server/cluster.
$ {{.HelpName}} play
2. Get the status of one particular master key from a MinIO server/cluster.
$ {{.HelpName}} play my-master-key
`,
}
// adminKMSKeyCmd is the handle for the "mc admin kms key" command.
func mainAdminKMSKeyStatus(ctx *cli.Context) error {
if len(ctx.Args()) == 0 || len(ctx.Args()) > 2 {
cli.ShowCommandHelpAndExit(ctx, "status", 1) // last argument is exit code
}
client, err := newAdminClient(ctx.Args().Get(0))
fatalIf(err, "Cannot get a configured admin connection.")
var keyID string
if len(ctx.Args()) == 2 {
keyID = ctx.Args().Get(1)
}
status, e := client.GetKeyStatus(globalContext, keyID)
fatalIf(probe.NewError(e), "Failed to get status information")
printMsg(kmsKeyStatusMsg(*status))
return nil
}
type kmsKeyStatusMsg madmin.KMSKeyStatus
func (s kmsKeyStatusMsg) String() string {
msg := fmt.Sprintf("Key: %s\n", s.KeyID)
if s.EncryptionErr == "" {
msg = fmt.Sprintf("%s %s", msg, "\t • Encryption ✔\n")
} else {
return fmt.Sprintf("%s \t • Encryption failed: %s\n", msg, s.EncryptionErr)
}
if s.DecryptionErr == "" {
msg = fmt.Sprintf("%s %s", msg, "\t • Decryption ✔\n")
} else {
return fmt.Sprintf("%s \t • Decryption failed: %s\n", msg, s.DecryptionErr)
}
return msg
}
func (s kmsKeyStatusMsg) JSON() string {
const fmtStr = `{"key-id":"%s","encryption-error":"%s","decryption-error":"%s"}`
return fmt.Sprintf(fmtStr, s.KeyID, s.EncryptionErr, s.DecryptionErr)
}
+36
View File
@@ -0,0 +1,36 @@
/*
* MinIO Client (C) 2020 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cmd
import "github.com/minio/cli"
var adminKMSKeyCmd = cli.Command{
Name: "key",
Usage: "Manage KMS master keys: Request key status information",
Action: mainAdminKMSKey,
Flags: globalFlags,
Subcommands: []cli.Command{
adminKMSKeyStatusCmd,
},
HideHelpCommand: true,
}
// mainAdminKMSKey is the handle for the "mc admin kms key" command.
func mainAdminKMSKey(ctx *cli.Context) error {
cli.ShowCommandHelp(ctx, ctx.Args().First())
return nil
}
+36
View File
@@ -0,0 +1,36 @@
/*
* MinIO Client (C) 2020 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cmd
import "github.com/minio/cli"
var adminKMSCmd = cli.Command{
Name: "kms",
Usage: "perform KMS management operations",
Action: mainAdminKMS,
Flags: globalFlags,
Subcommands: []cli.Command{
adminKMSKeyCmd,
},
HideHelpCommand: true,
}
// mainAdminKMS is the handle for the "mc admin kms" command.
func mainAdminKMS(ctx *cli.Context) error {
cli.ShowCommandHelp(ctx, ctx.Args().First())
return nil
}
+10 -1
View File
@@ -22,12 +22,18 @@ var (
adminFlags = []cli.Flag{}
)
const (
// dot represents a list item, for eg. server status - online (green) or offline (red)
dot = "●"
// check represents successful operation
check = "✔"
)
var adminCmd = cli.Command{
Name: "admin",
Usage: "manage MinIO servers",
Action: mainAdmin,
HideHelpCommand: true,
Before: setGlobalsFromContext,
Flags: append(adminFlags, globalFlags...),
Subcommands: []cli.Command{
adminServiceCmd,
@@ -43,6 +49,9 @@ var adminCmd = cli.Command{
adminTraceCmd,
adminConsoleCmd,
adminPrometheusCmd,
adminKMSCmd,
adminOBDCmd,
adminBucketCmd,
},
}
+418
View File
@@ -0,0 +1,418 @@
/*
* MinIO Client (C) 2020 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cmd
import (
"context"
"encoding/json"
"flag"
"fmt"
"os"
"path/filepath"
"strings"
"syscall"
"time"
"github.com/fatih/color"
"github.com/klauspost/compress/gzip"
"github.com/minio/cli"
cjson "github.com/minio/mc/pkg/colorjson"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio/pkg/console"
"github.com/minio/minio/pkg/madmin"
)
var adminOBDFlags = []cli.Flag{
OBDDataTypeFlag{
Name: "tests",
Usage: "choose OBD tests to run [" + options.String() + "]",
Value: nil,
EnvVar: "MC_OBD_DATA",
Hidden: true,
},
cli.DurationFlag{
Name: "deadline",
Usage: "maximum duration that OBD tests should be allowed to run",
Value: 3600 * time.Second,
EnvVar: "MC_OBD_DEADLINE",
},
}
var adminOBDCmd = cli.Command{
Name: "obd",
Usage: "run on-board diagnostics",
Action: mainAdminOBD,
Before: initBeforeRunningCmd,
Flags: append(adminOBDFlags, globalFlags...),
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} TARGET
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Get server information of the 'play' MinIO server.
{{.Prompt}} {{.HelpName}} play/
`,
}
type clusterOBDStruct struct {
Status string `json:"status"`
Error string `json:"error,omitempty"`
Info madmin.OBDInfo `json:"obdInfo,omitempty"`
}
func (u clusterOBDStruct) String() string {
u.Status = ""
data, err := json.Marshal(u)
if err != nil {
fatalIf(probe.NewError(err), "unable to marshal into JSON.")
}
return string(data)
}
// JSON jsonifies service status message.
func (u clusterOBDStruct) JSON() string {
statusJSONBytes, e := json.MarshalIndent(u, " ", " ")
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
return string(statusJSONBytes)
}
// checkAdminInfoSyntax - validate arguments passed by a user
func checkAdminOBDSyntax(ctx *cli.Context) {
if len(ctx.Args()) == 0 || len(ctx.Args()) > 1 {
cli.ShowCommandHelpAndExit(ctx, "obd", 1) // last argument is exit code
}
}
//compress and tar obd output
func tarGZ(c clusterOBDStruct, alias string) error {
filename := fmt.Sprintf("%s-obd_%s.json.gz", filepath.Clean(alias), time.Now().Format("20060102150405"))
f, err := os.OpenFile(filename, os.O_CREATE|os.O_RDWR, 0666)
if err != nil {
return err
}
defer f.Close()
defer func() {
fmt.Println("OBD data saved to", filename)
}()
gzWriter := gzip.NewWriter(f)
defer gzWriter.Close()
enc := json.NewEncoder(gzWriter)
if err := enc.Encode(c); err != nil {
return err
}
warningMsgBoundary := "*********************************************************************************"
warning := warnText(" WARNING!!")
warningContents := infoText(` ** THIS FILE MAY CONTAIN SENSITIVE INFORMATION ABOUT YOUR ENVIRONMENT **
** PLEASE INSPECT CONTENTS BEFORE SHARING IT ON ANY PUBLIC FORUM **`)
warningMsgHeader := infoText(warningMsgBoundary)
warningMsgTrailer := infoText(warningMsgBoundary)
fmt.Printf("%s\n%s\n%s\n%s\n", warningMsgHeader, warning, warningContents, warningMsgTrailer)
return nil
}
func infoText(s string) string {
console.SetColor("INFO", color.New(color.FgGreen, color.Bold))
return console.Colorize("INFO", s)
}
func greenText(s string) string {
console.SetColor("GREEN", color.New(color.FgGreen))
return console.Colorize("GREEN", s)
}
func warnText(s string) string {
console.SetColor("WARN", color.New(color.FgRed, color.Bold))
return console.Colorize("WARN", s)
}
func mainAdminOBD(ctx *cli.Context) error {
checkAdminOBDSyntax(ctx)
// Get the alias parameter from cli
args := ctx.Args()
aliasedURL := args.Get(0)
// Create a new MinIO Admin Client
client, err := newAdminClient(aliasedURL)
fatalIf(err, "Unable to initialize admin connection.")
spinners := []string{"/", "|", "\\", "--", "|"}
cont, cancel := context.WithCancel(globalContext)
defer cancel()
startSpinner := func(s string) func() {
ctx, cancel := context.WithCancel(cont)
printText := func(t string, sp string, rewind int) {
console.RewindLines(rewind)
dot := infoText(dot)
t = fmt.Sprintf("%s ...", t)
t = greenText(t)
sp = infoText(sp)
toPrint := fmt.Sprintf("%s %s %s ", dot, t, sp)
fmt.Printf("%s\n", toPrint)
}
i := 0
sp := func() string {
i = i + 1
i = i % len(spinners)
return spinners[i]
}
done := make(chan bool)
doneToggle := false
go func() {
printText(s, sp(), 0)
for {
<-time.After(500 * time.Millisecond) //2 fps
if ctx.Err() != nil {
printText(s, check, 1)
done <- true
return
}
printText(s, sp(), 1)
}
}()
return func() {
cancel()
if !doneToggle {
<-done
os.Stdout.Sync()
doneToggle = true
}
}
}
spinner := func(resource string) func(bool) bool {
var spinStopper func()
done := false
if globalJSON {
return func(bool) bool {
return true
}
}
return func(cond bool) bool {
if done {
return done
}
if spinStopper == nil {
spinStopper = startSpinner(resource)
}
if cond {
spinStopper()
done = true
}
return done
}
}
clusterOBDInfo := clusterOBDStruct{}
admin := spinner("Admin Info")
cpu := spinner("CPU")
diskHw := spinner("Disk Hardware")
osInfo := spinner("Os Info")
mem := spinner("Mem Info")
process := spinner("Process Info")
config := spinner("Config")
drive := spinner("Drive")
net := spinner("Net")
progress := func(info madmin.OBDInfo) bool {
return admin(len(info.Minio.Info.Servers) > 0) &&
cpu(len(info.Sys.CPUInfo) > 0) &&
diskHw(len(info.Sys.DiskHwInfo) > 0) &&
osInfo(len(info.Sys.OsInfo) > 0) &&
mem(len(info.Sys.MemInfo) > 0) &&
process(len(info.Sys.ProcInfo) > 0) &&
config(info.Minio.Config != nil) &&
drive(len(info.Perf.DriveInfo) > 0) &&
net(len(info.Perf.Net) > 1)
}
// Fetch info of all servers (cluster or single server)
obdChan := client.ServerOBDInfo(cont, options, ctx.Duration("deadline"))
for adminOBDInfo := range obdChan {
if adminOBDInfo.Error != "" {
clusterOBDInfo.Status = "Error"
clusterOBDInfo.Error = adminOBDInfo.Error
clusterOBDInfo.Info.Error = ""
clusterOBDInfo.Info.Minio.Info = madmin.InfoMessage{}
break
}
clusterOBDInfo.Status = "Success"
clusterOBDInfo.Info = adminOBDInfo
progress(adminOBDInfo)
}
// If MinIO is not a global distXL cluster, net will never stop spinning.
// add this extra check to ensure that doesn't happen
if clusterOBDInfo.Error == "" && !progress(clusterOBDInfo.Info) {
net(true)
}
if globalJSON {
jsonBytes, err := cjson.MarshalIndent(clusterOBDInfo, "", " ")
if err != nil {
return err
}
fmt.Println(string(jsonBytes))
return nil
}
if clusterOBDInfo.Error != "" {
fmt.Println(warnText("Error obtaining obd information:"), clusterOBDInfo.Error)
return nil
}
return tarGZ(clusterOBDInfo, aliasedURL)
}
// OBDDataTypeSlice is a typed list of OBD tests
type OBDDataTypeSlice []madmin.OBDDataType
// Set - sets the flag to the given value
func (d *OBDDataTypeSlice) Set(value string) error {
for _, v := range strings.Split(value, ",") {
if obdData, ok := madmin.OBDDataTypesMap[strings.Trim(v, " ")]; ok {
*d = append(*d, obdData)
} else {
return fmt.Errorf("valid options include %s", options.String())
}
}
return nil
}
// String - returns the string representation of the OBD datatypes
func (d *OBDDataTypeSlice) String() string {
val := ""
for _, obdData := range *d {
formatStr := "%s"
if val != "" {
formatStr = fmt.Sprintf("%s,%%s", formatStr)
} else {
formatStr = fmt.Sprintf("%s%%s", formatStr)
}
val = fmt.Sprintf(formatStr, val, string(obdData))
}
return val
}
// Value - returns the value
func (d *OBDDataTypeSlice) Value() []madmin.OBDDataType {
return *d
}
// Get - returns the value
func (d *OBDDataTypeSlice) Get() interface{} {
return *d
}
// OBDDataTypeFlag is a typed flag to represent OBD datatypes
type OBDDataTypeFlag struct {
Name string
Usage string
EnvVar string
Hidden bool
Value *OBDDataTypeSlice
}
// String - returns the string to be shown in the help message
func (f OBDDataTypeFlag) String() string {
return fmt.Sprintf("--%s %s", f.Name, f.Usage)
}
// GetName - returns the name of the flag
func (f OBDDataTypeFlag) GetName() string {
return f.Name
}
// GetOBDDataTypeSlice - returns the list of set OBD tests
func GetOBDDataTypeSlice(c *cli.Context, name string) *OBDDataTypeSlice {
generic := c.Generic(name)
if generic == nil {
return nil
}
if obdData, ok := generic.(*OBDDataTypeSlice); ok {
return obdData
}
return nil
}
// GetGlobalOBDDataTypeSlice - returns the list of set OBD tests set globally
func GetGlobalOBDDataTypeSlice(c *cli.Context, name string) *OBDDataTypeSlice {
generic := c.GlobalGeneric(name)
if generic == nil {
return nil
}
if obdData, ok := generic.(*OBDDataTypeSlice); ok {
return obdData
}
return nil
}
// Apply - applies the flag
func (f OBDDataTypeFlag) Apply(set *flag.FlagSet) {
f.ApplyWithError(set)
}
// ApplyWithError - applies with error
func (f OBDDataTypeFlag) ApplyWithError(set *flag.FlagSet) error {
if f.EnvVar != "" {
for _, envVar := range strings.Split(f.EnvVar, ",") {
envVar = strings.TrimSpace(envVar)
if envVal, ok := syscall.Getenv(envVar); ok {
newVal := &OBDDataTypeSlice{}
for _, s := range strings.Split(envVal, ",") {
s = strings.TrimSpace(s)
if err := newVal.Set(s); err != nil {
return fmt.Errorf("could not parse %s as OBD datatype value for flag %s: %s", envVal, f.Name, err)
}
}
f.Value = newVal
break
}
}
}
for _, name := range strings.Split(f.Name, ",") {
name = strings.Trim(name, " ")
if f.Value == nil {
f.Value = &OBDDataTypeSlice{}
}
set.Var(f.Value, name, f.Usage)
}
return nil
}
var options = OBDDataTypeSlice(madmin.OBDDataTypesList)
+16 -9
View File
@@ -17,21 +17,23 @@
package cmd
import (
"bytes"
"fmt"
"io/ioutil"
"github.com/fatih/color"
"github.com/minio/cli"
json "github.com/minio/mc/pkg/colorjson"
"github.com/minio/mc/pkg/console"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio/pkg/console"
iampolicy "github.com/minio/minio/pkg/iam/policy"
)
var adminPolicyAddCmd = cli.Command{
Name: "add",
Usage: "add new policy",
Action: mainAdminPolicyAdd,
Before: setGlobalsFromContext,
Before: initBeforeRunningCmd,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
@@ -64,17 +66,19 @@ func checkAdminPolicyAddSyntax(ctx *cli.Context) {
// userPolicyMessage container for content message structure
type userPolicyMessage struct {
op string
Status string `json:"status"`
Policy string `json:"policy,omitempty"`
PolicyJSON []byte `json:"policyJSON,omitempty"`
UserOrGroup string `json:"userOrGroup,omitempty"`
IsGroup bool `json:"isGroup"`
Status string `json:"status"`
Policy string `json:"policy,omitempty"`
PolicyJSON *iampolicy.Policy `json:"policyJSON,omitempty"`
UserOrGroup string `json:"userOrGroup,omitempty"`
IsGroup bool `json:"isGroup"`
}
func (u userPolicyMessage) String() string {
switch u.op {
case "info":
return string(u.PolicyJSON)
buf, e := json.MarshalIndent(u.PolicyJSON, "", " ")
fatalIf(probe.NewError(e), "Unable to parse policy")
return string(buf)
case "list":
policyFieldMaxLen := 20
// Create a new pretty table with cols configuration
@@ -121,7 +125,10 @@ func mainAdminPolicyAdd(ctx *cli.Context) error {
client, err := newAdminClient(aliasedURL)
fatalIf(err, "Unable to initialize admin connection.")
fatalIf(probe.NewError(client.AddCannedPolicy(args.Get(1), string(policy))).Trace(args...), "Cannot add new policy")
iamp, e := iampolicy.ParseConfig(bytes.NewReader(policy))
fatalIf(probe.NewError(e).Trace(args...), "Unable to parse the input policy")
fatalIf(probe.NewError(client.AddCannedPolicy(globalContext, args.Get(1), iamp)).Trace(args...), "Unable to add new policy")
printMsg(userPolicyMessage{
op: "add",
+8 -7
View File
@@ -21,15 +21,15 @@ import (
"github.com/fatih/color"
"github.com/minio/cli"
"github.com/minio/mc/pkg/console"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio/pkg/console"
)
var adminPolicyInfoCmd = cli.Command{
Name: "info",
Usage: "show info on a policy",
Action: mainAdminPolicyInfo,
Before: setGlobalsFromContext,
Before: initBeforeRunningCmd,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
@@ -70,19 +70,20 @@ func mainAdminPolicyInfo(ctx *cli.Context) error {
// Create a new MinIO Admin Client
client, err := newAdminClient(aliasedURL)
fatalIf(err, "Unable to initialize admin connection.")
fatalIf(err, "Unable to initialize admin connection")
policies, e := client.ListCannedPolicies()
policies, e := client.ListCannedPolicies(globalContext)
fatalIf(probe.NewError(e).Trace(args...), "Cannot list policy")
if len(policies[policyName]) != 0 {
iamp, ok := policies[policyName]
if ok {
printMsg(userPolicyMessage{
op: "info",
Policy: policyName,
PolicyJSON: policies[policyName],
PolicyJSON: iamp,
})
} else {
fatalIf(probe.NewError(fmt.Errorf("%s is not found", policyName)), "Cannot list the policy")
fatalIf(probe.NewError(fmt.Errorf("%s is not found", policyName)), "Unable to display policy")
}
return nil
}
+3 -3
View File
@@ -19,15 +19,15 @@ package cmd
import (
"github.com/fatih/color"
"github.com/minio/cli"
"github.com/minio/mc/pkg/console"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio/pkg/console"
)
var adminPolicyListCmd = cli.Command{
Name: "list",
Usage: "list all policies",
Action: mainAdminPolicyList,
Before: setGlobalsFromContext,
Before: initBeforeRunningCmd,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
@@ -66,7 +66,7 @@ func mainAdminPolicyList(ctx *cli.Context) error {
client, err := newAdminClient(aliasedURL)
fatalIf(err, "Unable to initialize admin connection.")
policies, e := client.ListCannedPolicies()
policies, e := client.ListCannedPolicies(globalContext)
fatalIf(probe.NewError(e).Trace(args...), "Cannot list policy")
for k := range policies {
+3 -3
View File
@@ -19,15 +19,15 @@ package cmd
import (
"github.com/fatih/color"
"github.com/minio/cli"
"github.com/minio/mc/pkg/console"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio/pkg/console"
)
var adminPolicyRemoveCmd = cli.Command{
Name: "remove",
Usage: "remove policy",
Action: mainAdminPolicyRemove,
Before: setGlobalsFromContext,
Before: initBeforeRunningCmd,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
@@ -68,7 +68,7 @@ func mainAdminPolicyRemove(ctx *cli.Context) error {
client, err := newAdminClient(aliasedURL)
fatalIf(err, "Unable to initialize admin connection.")
fatalIf(probe.NewError(client.RemoveCannedPolicy(args.Get(1))).Trace(args...), "Cannot remove policy")
fatalIf(probe.NewError(client.RemoveCannedPolicy(globalContext, args.Get(1))).Trace(args...), "Cannot remove policy")
printMsg(userPolicyMessage{
op: "remove",
+3 -3
View File
@@ -22,15 +22,15 @@ import (
"github.com/fatih/color"
"github.com/minio/cli"
"github.com/minio/mc/pkg/console"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio/pkg/console"
)
var adminPolicySetCmd = cli.Command{
Name: "set",
Usage: "set IAM policy on a user or group",
Action: mainAdminPolicySet,
Before: setGlobalsFromContext,
Before: initBeforeRunningCmd,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
@@ -103,7 +103,7 @@ func mainAdminPolicySet(ctx *cli.Context) error {
client, err := newAdminClient(aliasedURL)
fatalIf(err, "Unable to initialize admin connection.")
e := client.SetPolicy(policyName, userOrGroup, isGroup)
e := client.SetPolicy(globalContext, policyName, userOrGroup, isGroup)
if e == nil {
printMsg(userPolicyMessage{
-1
View File
@@ -22,7 +22,6 @@ var adminPolicyCmd = cli.Command{
Name: "policy",
Usage: "manage policies defined in the MinIO server",
Action: mainAdminPolicy,
Before: setGlobalsFromContext,
Flags: globalFlags,
Subcommands: []cli.Command{
adminPolicyAddCmd,
+26 -15
View File
@@ -20,16 +20,17 @@ import (
"strings"
"github.com/minio/cli"
"github.com/minio/mc/pkg/console"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio-go/v6/pkg/set"
"github.com/minio/minio/pkg/console"
"github.com/minio/minio/pkg/madmin"
)
var adminProfileStartFlags = []cli.Flag{
cli.StringFlag{
Name: "type",
Usage: "start profiler type, possible values are 'cpu', 'mem', 'block', 'mutex' and 'trace'",
Value: "mem",
Usage: "start profiler type, possible values are 'cpu', 'mem', 'block', 'mutex', 'trace', 'threads' and 'goroutines'",
Value: "cpu,mem,block",
},
}
@@ -37,7 +38,7 @@ var adminProfileStartCmd = cli.Command{
Name: "start",
Usage: "start recording profile data",
Action: mainAdminProfileStart,
Before: setGlobalsFromContext,
Before: initBeforeRunningCmd,
Flags: append(adminProfileStartFlags, globalFlags...),
HideHelpCommand: true,
CustomHelpTemplate: `NAME:
@@ -50,9 +51,11 @@ FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Start CPU profile
1. Start CPU profiling only
{{.Prompt}} {{.HelpName}} --type cpu myminio/
2. Start CPU, Memory and Block profiling concurrently
{{.Prompt}} {{.HelpName}} --type cpu,mem,block myminio/
`,
}
@@ -62,25 +65,33 @@ func checkAdminProfileStartSyntax(ctx *cli.Context) {
cli.ShowCommandHelpAndExit(ctx, "start", 1) // last argument is exit code
}
profilerTypes := []madmin.ProfilerType{
s := set.NewStringSet()
supportedProfilerTypes := []madmin.ProfilerType{
madmin.ProfilerCPU,
madmin.ProfilerMEM,
madmin.ProfilerBlock,
madmin.ProfilerMutex,
madmin.ProfilerTrace,
madmin.ProfilerThreads,
madmin.ProfilerGoroutines,
}
for _, profilerType := range supportedProfilerTypes {
s.Add(string(profilerType))
}
// Check if the provided profiler type is known and supported
supportedProfiler := false
profilerType := strings.ToLower(ctx.String("type"))
for _, profiler := range profilerTypes {
if profilerType == string(profiler) {
supportedProfiler = true
break
profilers := strings.Split(strings.ToLower(ctx.String("type")), ",")
for _, profiler := range profilers {
if profiler != "" {
if s.Contains(profiler) {
supportedProfiler = true
break
}
}
}
if !supportedProfiler {
fatalIf(errDummy(), "Profiler type unrecognized. Possible values are: %v.", profilerTypes)
fatalIf(errDummy().Trace(ctx.String("type")),
"Profiler type unrecognized. Possible values are: %v.", supportedProfilerTypes)
}
}
@@ -93,7 +104,7 @@ func mainAdminProfileStart(ctx *cli.Context) error {
args := ctx.Args()
aliasedURL := args.Get(0)
profilerType := ctx.String("type")
profilers := ctx.String("type")
// Create a new MinIO Admin Client
client, err := newAdminClient(aliasedURL)
@@ -103,7 +114,7 @@ func mainAdminProfileStart(ctx *cli.Context) error {
}
// Start profile
_, cmdErr := client.StartProfiling(madmin.ProfilerType(profilerType))
_, cmdErr := client.StartProfiling(globalContext, madmin.ProfilerType(profilers))
fatalIf(probe.NewError(cmdErr), "Unable to start profile.")
console.Infoln("Profile data successfully started.")
+3 -3
View File
@@ -23,15 +23,15 @@ import (
"time"
"github.com/minio/cli"
"github.com/minio/mc/pkg/console"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio/pkg/console"
)
var adminProfileStopCmd = cli.Command{
Name: "stop",
Usage: "stop and download profile data",
Action: mainAdminProfileStop,
Before: setGlobalsFromContext,
Before: initBeforeRunningCmd,
Flags: globalFlags,
HideHelpCommand: true,
CustomHelpTemplate: `NAME:
@@ -103,7 +103,7 @@ func mainAdminProfileStop(ctx *cli.Context) error {
fatalIf(probe.NewError(e), "Unable to download profile data.")
// Ask for profile data, which will come compressed with zip format
zippedData, adminErr := client.DownloadProfilingData()
zippedData, adminErr := client.DownloadProfilingData(globalContext)
fatalIf(probe.NewError(adminErr), "Unable to download profile data.")
// Copy zip content to target download file
+1 -2
View File
@@ -1,5 +1,5 @@
/*
* MinIO Client (C) 2018 MinIO, Inc.
* MinIO Client (C) 2018-2020 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -24,7 +24,6 @@ var adminProfileCmd = cli.Command{
Name: "profile",
Usage: "generate profile data for debugging purposes",
Action: mainAdminProfile,
Before: setGlobalsFromContext,
Flags: globalFlags,
Subcommands: []cli.Command{
adminProfileStartCmd,
+4 -3
View File
@@ -23,8 +23,8 @@ import (
"github.com/fatih/color"
"github.com/minio/cli"
"github.com/minio/mc/pkg/console"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio/pkg/console"
jwtgo "github.com/dgrijalva/jwt-go"
json "github.com/minio/mc/pkg/colorjson"
@@ -40,7 +40,7 @@ var adminPrometheusGenerateCmd = cli.Command{
Name: "generate",
Usage: "generates prometheus config",
Action: mainAdminPrometheusGenerate,
Before: setGlobalsFromContext,
Before: initBeforeRunningCmd,
Flags: globalFlags,
HideHelpCommand: true,
CustomHelpTemplate: `NAME:
@@ -138,7 +138,7 @@ func checkAdminPrometheusSyntax(ctx *cli.Context) {
func generatePrometheusConfig(ctx *cli.Context) error {
// Get the alias parameter from cli
args := ctx.Args()
alias := args.Get(0)
alias := cleanAlias(args.Get(0))
if !isValidAlias(alias) {
fatalIf(errInvalidAlias(alias), "Invalid alias.")
@@ -147,6 +147,7 @@ func generatePrometheusConfig(ctx *cli.Context) error {
hostConfig := mustGetHostConfig(alias)
if hostConfig == nil {
fatalIf(errInvalidAliasedURL(alias), "No such alias `"+alias+"` found.")
return nil
}
u, err := url.Parse(hostConfig.URL)
-1
View File
@@ -22,7 +22,6 @@ var adminPrometheusCmd = cli.Command{
Name: "prometheus",
Usage: "manages prometheus config",
Action: mainAdminPrometheus,
Before: setGlobalsFromContext,
Flags: globalFlags,
HideHelpCommand: true,
Subcommands: []cli.Command{
+4 -4
View File
@@ -22,15 +22,15 @@ import (
"github.com/fatih/color"
"github.com/minio/cli"
json "github.com/minio/mc/pkg/colorjson"
"github.com/minio/mc/pkg/console"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio/pkg/console"
)
var adminServiceRestartCmd = cli.Command{
Name: "restart",
Usage: "restart all MinIO servers",
Action: mainAdminServiceRestart,
Before: setGlobalsFromContext,
Before: initBeforeRunningCmd,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
@@ -113,7 +113,7 @@ func mainAdminServiceRestart(ctx *cli.Context) error {
fatalIf(err, "Unable to initialize admin connection.")
// Restart the specified MinIO server
fatalIf(probe.NewError(client.ServiceRestart()), "Cannot restart the server.")
fatalIf(probe.NewError(client.ServiceRestart(globalContext)), "Cannot restart the server.")
// Success..
printMsg(serviceRestartCommand{Status: "success", ServerURL: aliasedURL})
@@ -125,7 +125,7 @@ func mainAdminServiceRestart(ctx *cli.Context) error {
time.Sleep(6 * time.Second)
// Fetch the service status of the specified MinIO server
_, e := client.ServerInfo()
_, e := client.ServerInfo(globalContext)
if e != nil {
printMsg(serviceRestartMessage{Status: "failure", Err: e, ServerURL: aliasedURL})
+3 -3
View File
@@ -20,15 +20,15 @@ import (
"github.com/fatih/color"
"github.com/minio/cli"
json "github.com/minio/mc/pkg/colorjson"
"github.com/minio/mc/pkg/console"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio/pkg/console"
)
var adminServiceStopCmd = cli.Command{
Name: "stop",
Usage: "stop MinIO server",
Action: mainAdminServiceStop,
Before: setGlobalsFromContext,
Before: initBeforeRunningCmd,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
@@ -87,7 +87,7 @@ func mainAdminServiceStop(ctx *cli.Context) error {
fatalIf(err, "Unable to initialize admin connection.")
// Stop the specified MinIO server
fatalIf(probe.NewError(client.ServiceStop()), "Unable to stop the server.")
fatalIf(probe.NewError(client.ServiceStop(globalContext)), "Unable to stop the server.")
// Success..
printMsg(serviceStopMessage{Status: "success", ServerURL: aliasedURL})
-1
View File
@@ -22,7 +22,6 @@ var adminServiceCmd = cli.Command{
Name: "service",
Usage: "restart and stop all MinIO servers",
Action: mainAdminService,
Before: setGlobalsFromContext,
Flags: globalFlags,
HideHelpCommand: true,
Subcommands: []cli.Command{
+3 -3
View File
@@ -23,15 +23,15 @@ import (
"github.com/fatih/color"
"github.com/minio/cli"
json "github.com/minio/mc/pkg/colorjson"
"github.com/minio/mc/pkg/console"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio/pkg/console"
"github.com/minio/minio/pkg/madmin"
)
var adminTopLocksCmd = cli.Command{
Name: "locks",
Usage: "Get a list of the 10 oldest locks on a MinIO cluster.",
Before: setGlobalsFromContext,
Before: initBeforeRunningCmd,
Action: mainAdminTopLocks,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
@@ -114,7 +114,7 @@ func mainAdminTopLocks(ctx *cli.Context) error {
fatalIf(err, "Unable to initialize admin connection.")
// Call top locks API
entries, e := client.TopLocks()
entries, e := client.TopLocks(globalContext)
fatalIf(probe.NewError(e), "Cannot get server locks list.")
console.SetColor("StaleLock", color.New(color.FgRed, color.Bold))
-1
View File
@@ -22,7 +22,6 @@ var adminTopCmd = cli.Command{
Name: "top",
Usage: "provide top like statistics for MinIO",
Action: mainAdminTop,
Before: setGlobalsFromContext,
Flags: globalFlags,
Subcommands: []cli.Command{
adminTopLocksCmd,
+10 -8
View File
@@ -18,6 +18,7 @@ package cmd
import (
"bytes"
"context"
"fmt"
"hash/fnv"
"net/http"
@@ -28,8 +29,8 @@ import (
"github.com/fatih/color"
"github.com/minio/cli"
json "github.com/minio/mc/pkg/colorjson"
"github.com/minio/mc/pkg/console"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio/pkg/console"
"github.com/minio/minio/pkg/madmin"
)
@@ -52,7 +53,7 @@ var adminTraceCmd = cli.Command{
Name: "trace",
Usage: "show http trace for MinIO server",
Action: mainAdminTrace,
Before: setGlobalsFromContext,
Before: initBeforeRunningCmd,
Flags: append(adminTraceFlags, globalFlags...),
HideHelpCommand: true,
CustomHelpTemplate: `NAME:
@@ -117,11 +118,12 @@ func mainAdminTrace(ctx *cli.Context) error {
fatalIf(err.Trace(aliasedURL), "Cannot initialize admin client.")
return nil
}
doneCh := make(chan struct{})
defer close(doneCh)
ctxt, cancel := context.WithCancel(globalContext)
defer cancel()
// Start listening on all trace activity.
traceCh := client.ServiceTrace(all, errfltr, doneCh)
traceCh := client.ServiceTrace(ctxt, all, errfltr)
for traceInfo := range traceCh {
if traceInfo.Err != nil {
fatalIf(probe.NewError(traceInfo.Err), "Cannot listen to http trace")
@@ -238,9 +240,9 @@ func (s shortTraceMsg) String() string {
fmt.Fprint(b, console.Colorize("HeaderValue", fmt.Sprintf(" %2s", s.CallStats.Duration.Round(time.Microsecond))))
spaces = 12 - len(fmt.Sprintf("%2s", s.CallStats.Duration.Round(time.Microsecond)))
fmt.Fprintf(b, "%*s", spaces, " ")
fmt.Fprint(b, console.Colorize("Stat", fmt.Sprintf(" ↑ ")))
fmt.Fprint(b, console.Colorize("Stat", " ↑ "))
fmt.Fprint(b, console.Colorize("HeaderValue", humanize.IBytes(uint64(s.CallStats.Rx))))
fmt.Fprint(b, console.Colorize("Stat", fmt.Sprintf(" ↓ ")))
fmt.Fprint(b, console.Colorize("Stat", " ↓ "))
fmt.Fprint(b, console.Colorize("HeaderValue", humanize.IBytes(uint64(s.CallStats.Tx))))
return b.String()
@@ -331,7 +333,7 @@ func (t traceMessage) String() string {
}
fmt.Fprintf(b, "%s%s", nodeNameStr, console.Colorize("Body", fmt.Sprintf("%s\n", string(ri.Body))))
fmt.Fprintf(b, "%s%s", nodeNameStr, console.Colorize("Response", fmt.Sprintf("[RESPONSE] ")))
fmt.Fprintf(b, "%s%s", nodeNameStr, console.Colorize("Response", "[RESPONSE] "))
fmt.Fprintf(b, "[%s] ", rs.Time.Format(timeFormat))
fmt.Fprint(b, console.Colorize("Stat", fmt.Sprintf("[ Duration %2s ↑ %s ↓ %s ]\n", trc.CallStats.Latency.Round(time.Microsecond), humanize.IBytes(uint64(trc.CallStats.InputBytes)), humanize.IBytes(uint64(trc.CallStats.OutputBytes)))))
+3 -3
View File
@@ -22,15 +22,15 @@ import (
"github.com/fatih/color"
"github.com/minio/cli"
json "github.com/minio/mc/pkg/colorjson"
"github.com/minio/mc/pkg/console"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio/pkg/console"
)
var adminServerUpdateCmd = cli.Command{
Name: "update",
Usage: "update all MinIO servers",
Action: mainAdminServerUpdate,
Before: setGlobalsFromContext,
Before: initBeforeRunningCmd,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
@@ -103,7 +103,7 @@ func mainAdminServerUpdate(ctx *cli.Context) error {
// Update the specified MinIO server, optionally also
// with the provided update URL.
us, e := client.ServerUpdate(updateURL)
us, e := client.ServerUpdate(globalContext, updateURL)
fatalIf(probe.NewError(e), "Unable to update the server.")
// Success..
+58 -7
View File
@@ -17,21 +17,24 @@
package cmd
import (
"bufio"
"fmt"
"os"
"strings"
"github.com/fatih/color"
"github.com/minio/cli"
json "github.com/minio/mc/pkg/colorjson"
"github.com/minio/mc/pkg/console"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio/pkg/console"
"golang.org/x/crypto/ssh/terminal"
)
var adminUserAddCmd = cli.Command{
Name: "add",
Usage: "add a new user",
Action: mainAdminUserAdd,
Before: setGlobalsFromContext,
Before: initBeforeRunningCmd,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
@@ -53,13 +56,23 @@ EXAMPLES:
{{.DisableHistory}}
{{.Prompt}} {{.HelpName}} myminio foobar foo12345
{{.EnableHistory}}
2. Add a new user 'foobar' to MinIO server, prompting for keys.
{{.Prompt}} {{.HelpName}} myminio
Enter Access Key: foobar
Enter Secret Key: foobar12345
3. Add a new user 'foobar' to MinIO server using piped keys.
{{.DisableHistory}}
{{.Prompt}} echo -e "foobar\nfoobar12345" | {{.HelpName}} myminio
{{.EnableHistory}}
`,
}
// checkAdminUserAddSyntax - validate all the passed arguments
func checkAdminUserAddSyntax(ctx *cli.Context) {
if len(ctx.Args()) != 3 {
cli.ShowCommandHelpAndExit(ctx, "add", 1) // last argument is exit code
argsNr := len(ctx.Args())
if argsNr > 3 || argsNr < 1 {
fatalIf(errInvalidArgument().Trace(ctx.Args().Tail()...),
"Incorrect number of arguments for user add command.")
}
}
@@ -115,6 +128,43 @@ func (u userMessage) JSON() string {
return string(jsonMessageBytes)
}
// fetchUserKeys - returns the access and secret key
func fetchUserKeys(args cli.Args) (string, string) {
accessKey := ""
secretKey := ""
console.SetColor(cred, color.New(color.FgYellow, color.Italic))
isTerminal := terminal.IsTerminal(int(os.Stdin.Fd()))
reader := bufio.NewReader(os.Stdin)
argCount := len(args)
if argCount == 1 {
if isTerminal {
fmt.Printf("%s", console.Colorize(cred, "Enter Access Key: "))
}
value, _, _ := reader.ReadLine()
accessKey = string(value)
} else {
accessKey = args.Get(1)
}
if argCount == 1 || argCount == 2 {
if isTerminal {
fmt.Printf("%s", console.Colorize(cred, "Enter Secret Key: "))
bytePassword, _ := terminal.ReadPassword(int(os.Stdin.Fd()))
fmt.Printf("\n")
secretKey = string(bytePassword)
} else {
value, _, _ := reader.ReadLine()
secretKey = string(value)
}
} else {
secretKey = args.Get(2)
}
return accessKey, secretKey
}
// mainAdminUserAdd is the handle for "mc admin user add" command.
func mainAdminUserAdd(ctx *cli.Context) error {
checkAdminUserAddSyntax(ctx)
@@ -124,17 +174,18 @@ func mainAdminUserAdd(ctx *cli.Context) error {
// Get the alias parameter from cli
args := ctx.Args()
aliasedURL := args.Get(0)
accessKey, secretKey := fetchUserKeys(args)
// Create a new MinIO Admin Client
client, err := newAdminClient(aliasedURL)
fatalIf(err, "Unable to initialize admin connection.")
fatalIf(probe.NewError(client.AddUser(args.Get(1), args.Get(2))).Trace(args...), "Cannot add new user")
fatalIf(probe.NewError(client.AddUser(globalContext, accessKey, secretKey)).Trace(args...), "Cannot add new user")
printMsg(userMessage{
op: "add",
AccessKey: args.Get(1),
SecretKey: args.Get(2),
AccessKey: accessKey,
SecretKey: secretKey,
UserStatus: "enabled",
})
+3 -3
View File
@@ -19,8 +19,8 @@ package cmd
import (
"github.com/fatih/color"
"github.com/minio/cli"
"github.com/minio/mc/pkg/console"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio/pkg/console"
"github.com/minio/minio/pkg/madmin"
)
@@ -28,7 +28,7 @@ var adminUserDisableCmd = cli.Command{
Name: "disable",
Usage: "disable user",
Action: mainAdminUserDisable,
Before: setGlobalsFromContext,
Before: initBeforeRunningCmd,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
@@ -66,7 +66,7 @@ func mainAdminUserDisable(ctx *cli.Context) error {
client, err := newAdminClient(aliasedURL)
fatalIf(err, "Unable to initialize admin connection.")
e := client.SetUserStatus(args.Get(1), madmin.AccountDisabled)
e := client.SetUserStatus(globalContext, args.Get(1), madmin.AccountDisabled)
fatalIf(probe.NewError(e).Trace(args...), "Cannot disable user")
printMsg(userMessage{
+3 -3
View File
@@ -19,8 +19,8 @@ package cmd
import (
"github.com/fatih/color"
"github.com/minio/cli"
"github.com/minio/mc/pkg/console"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio/pkg/console"
"github.com/minio/minio/pkg/madmin"
)
@@ -28,7 +28,7 @@ var adminUserEnableCmd = cli.Command{
Name: "enable",
Usage: "enable user",
Action: mainAdminUserEnable,
Before: setGlobalsFromContext,
Before: initBeforeRunningCmd,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
@@ -66,7 +66,7 @@ func mainAdminUserEnable(ctx *cli.Context) error {
client, err := newAdminClient(aliasedURL)
fatalIf(err, "Unable to initialize admin connection.")
e := client.SetUserStatus(args.Get(1), madmin.AccountEnabled)
e := client.SetUserStatus(globalContext, args.Get(1), madmin.AccountEnabled)
fatalIf(probe.NewError(e).Trace(args...), "Cannot enable user")
printMsg(userMessage{
+3 -3
View File
@@ -19,15 +19,15 @@ package cmd
import (
"github.com/fatih/color"
"github.com/minio/cli"
"github.com/minio/mc/pkg/console"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio/pkg/console"
)
var adminUserInfoCmd = cli.Command{
Name: "info",
Usage: "display info of a user",
Action: mainAdminUserInfo,
Before: setGlobalsFromContext,
Before: initBeforeRunningCmd,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
@@ -65,7 +65,7 @@ func mainAdminUserInfo(ctx *cli.Context) error {
client, err := newAdminClient(aliasedURL)
fatalIf(err, "Unable to initialize admin connection.")
user, e := client.GetUserInfo(args.Get(1))
user, e := client.GetUserInfo(globalContext, args.Get(1))
fatalIf(probe.NewError(e).Trace(args...), "Cannot get user info")
printMsg(userMessage{
+3 -3
View File
@@ -19,15 +19,15 @@ package cmd
import (
"github.com/fatih/color"
"github.com/minio/cli"
"github.com/minio/mc/pkg/console"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio/pkg/console"
)
var adminUserListCmd = cli.Command{
Name: "list",
Usage: "list all users",
Action: mainAdminUserList,
Before: setGlobalsFromContext,
Before: initBeforeRunningCmd,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
@@ -69,7 +69,7 @@ func mainAdminUserList(ctx *cli.Context) error {
client, err := newAdminClient(aliasedURL)
fatalIf(err, "Unable to initialize admin connection.")
users, e := client.ListUsers()
users, e := client.ListUsers(globalContext)
fatalIf(probe.NewError(e).Trace(args...), "Cannot list user")
for k, v := range users {
+3 -3
View File
@@ -19,15 +19,15 @@ package cmd
import (
"github.com/fatih/color"
"github.com/minio/cli"
"github.com/minio/mc/pkg/console"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio/pkg/console"
)
var adminUserRemoveCmd = cli.Command{
Name: "remove",
Usage: "remove user",
Action: mainAdminUserRemove,
Before: setGlobalsFromContext,
Before: initBeforeRunningCmd,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
@@ -65,7 +65,7 @@ func mainAdminUserRemove(ctx *cli.Context) error {
client, err := newAdminClient(aliasedURL)
fatalIf(err, "Unable to initialize admin connection.")
e := client.RemoveUser(args.Get(1))
e := client.RemoveUser(globalContext, args.Get(1))
fatalIf(probe.NewError(e).Trace(args...), "Cannot remove %s", args.Get(1))
printMsg(userMessage{
-1
View File
@@ -22,7 +22,6 @@ var adminUserCmd = cli.Command{
Name: "user",
Usage: "manage users",
Action: mainAdminUser,
Before: setGlobalsFromContext,
Flags: globalFlags,
Subcommands: []cli.Command{
adminUserAddCmd,
+39 -18
View File
@@ -29,7 +29,31 @@ import (
// fsComplete knows how to complete file/dir names by the given path
type fsComplete struct{}
func (fs fsComplete) Predict(a complete.Args) (prediction []string) {
// predictPathWithTilde completes an FS path which starts with a `~/`
func (fs fsComplete) predictPathWithTilde(a complete.Args) []string {
homeDir, err := os.UserHomeDir()
if err != nil || homeDir == "" {
return nil
}
// Clean the home directory path
homeDir = strings.TrimRight(homeDir, "/")
// Replace the first occurrence of ~ with the real path and complete
a.Last = strings.Replace(a.Last, "~", homeDir, 1)
predictions := complete.PredictFiles("*").Predict(a)
// Restore ~ to avoid disturbing the completion user experience
for i := range predictions {
predictions[i] = strings.Replace(predictions[i], homeDir, "~", 1)
}
return predictions
}
func (fs fsComplete) Predict(a complete.Args) []string {
if strings.HasPrefix(a.Last, "~/") {
return fs.predictPathWithTilde(a)
}
return complete.PredictFiles("*").Predict(a)
}
@@ -41,7 +65,7 @@ func completeAdminConfigKeys(aliasPath string, keyPrefix string) (prediction []s
return nil
}
h, e := clnt.HelpConfigKV("", "", false)
h, e := clnt.HelpConfigKV(globalContext, "", "", false)
if e != nil {
return nil
}
@@ -72,7 +96,7 @@ func completeS3Path(s3Path string) (prediction []string) {
// List dirPath content and only pick elements that corresponds
// to the path that we want to complete
for content := range clnt.List(false, false, false, DirFirst) {
for content := range clnt.List(globalContext, false, false, false, DirFirst) {
cmplS3Path := alias + getKey(content)
if content.Type.IsDir() {
if !strings.HasSuffix(cmplS3Path, "/") {
@@ -228,6 +252,10 @@ var completeCmds = map[string]complete.Predictor{
"/event/list": aliasCompleter,
"/event/remove": aliasCompleter,
"/tag/list": s3Completer,
"/tag/remove": s3Completer,
"/tag/set": s3Completer,
"/share/download": s3Completer,
"/share/list": nil,
"/share/upload": s3Completer,
@@ -235,18 +263,15 @@ var completeCmds = map[string]complete.Predictor{
// Admin API commands MinIO only.
"/admin/heal": s3Completer,
"/admin/info/server": aliasCompleter,
"/admin/info/cpu": aliasCompleter,
"/admin/info/mem": aliasCompleter,
"/admin/info": aliasCompleter,
"/admin/config/get": adminConfigCompleter,
"/admin/config/set": adminConfigCompleter,
"/admin/config/del": adminConfigCompleter,
"/admin/config/import": aliasCompleter,
"/admin/config/export": aliasCompleter,
"/admin/config/history/restore": aliasCompleter,
"/admin/config/history/list": aliasCompleter,
"/admin/config/history/clear": aliasCompleter,
"/admin/config/get": adminConfigCompleter,
"/admin/config/set": adminConfigCompleter,
"/admin/config/reset": adminConfigCompleter,
"/admin/config/import": aliasCompleter,
"/admin/config/export": aliasCompleter,
"/admin/config/history": aliasCompleter,
"/admin/config/restore": aliasCompleter,
"/admin/trace": aliasCompleter,
"/admin/console": aliasCompleter,
@@ -281,10 +306,6 @@ var completeCmds = map[string]complete.Predictor{
"/admin/group/remove": aliasCompleter,
"/admin/group/info": aliasCompleter,
"/session/clear": nil,
"/session/list": nil,
"/session/resume": nil,
"/config/host/add": nil,
"/config/host/list": aliasCompleter,
"/config/host/remove": aliasCompleter,
+16 -12
View File
@@ -18,6 +18,7 @@ package cmd
import (
"bytes"
"context"
"errors"
"fmt"
"io"
@@ -43,7 +44,7 @@ var catCmd = cli.Command{
Name: "cat",
Usage: "display object contents",
Action: mainCat,
Before: setGlobalsFromContext,
Before: initBeforeRunningCmd,
Flags: append(append(catFlags, ioFlags...), globalFlags...),
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
@@ -139,7 +140,7 @@ func checkCatSyntax(ctx *cli.Context) {
}
// catURL displays contents of a URL to stdout.
func catURL(sourceURL string, encKeyDB map[string][]prefixSSEPair) *probe.Error {
func catURL(ctx context.Context, sourceURL string, encKeyDB map[string][]prefixSSEPair) *probe.Error {
var reader io.ReadCloser
size := int64(-1)
switch sourceURL {
@@ -152,11 +153,11 @@ func catURL(sourceURL string, encKeyDB map[string][]prefixSSEPair) *probe.Error
// downloaded object is equal to the original one. FS files
// are ignored since some of them have zero size though they
// have contents like files under /proc.
client, content, err := url2Stat(sourceURL, false, false, encKeyDB)
client, content, err := url2Stat(ctx, sourceURL, false, encKeyDB)
if err == nil && client.GetURL().Type == objectStorage {
size = content.Size
}
if reader, err = getSourceStreamFromURL(sourceURL, encKeyDB); err != nil {
if reader, err = getSourceStreamFromURL(ctx, sourceURL, encKeyDB); err != nil {
return err.Trace(sourceURL)
}
defer reader.Close()
@@ -210,17 +211,20 @@ func catOut(r io.Reader, size int64) *probe.Error {
}
// mainCat is the main entry point for cat command.
func mainCat(ctx *cli.Context) error {
func mainCat(cliCtx *cli.Context) error {
ctx, cancelCat := context.WithCancel(globalContext)
defer cancelCat()
// Parse encryption keys per command.
encKeyDB, err := getEncKeys(ctx)
encKeyDB, err := getEncKeys(cliCtx)
fatalIf(err, "Unable to parse encryption keys.")
// check 'cat' cli arguments.
checkCatSyntax(ctx)
checkCatSyntax(cliCtx)
// Set command flags from context.
stdinMode := false
if !ctx.Args().Present() {
if !cliCtx.Args().Present() {
stdinMode = true
}
@@ -231,11 +235,11 @@ func mainCat(ctx *cli.Context) error {
}
// if Args contain `-`, we need to preserve its order specially.
args := []string(ctx.Args())
if ctx.Args().First() == "-" {
args := []string(cliCtx.Args())
if cliCtx.Args().First() == "-" {
for i, arg := range os.Args {
if arg == "cat" {
// Overwrite ctx.Args with os.Args.
// Overwrite cliCtx.Args with os.Args.
args = os.Args[i+1:]
break
}
@@ -244,7 +248,7 @@ func mainCat(ctx *cli.Context) error {
// Convert arguments to URLs: expand alias, fix format.
for _, url := range args {
fatalIf(catURL(url, encKeyDB).Trace(url), "Unable to read from `"+url+"`.")
fatalIf(catURL(ctx, url, encKeyDB).Trace(url), "Unable to read from `"+url+"`.")
}
return nil
+33 -12
View File
@@ -1,5 +1,5 @@
/*
* MinIO Client (C) 2017 MinIO, Inc.
* MinIO Client (C) 2017-2020 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -26,13 +26,15 @@ import (
"sync"
"time"
"github.com/mattn/go-ieproxy"
"github.com/minio/mc/pkg/httptracer"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio-go/v6/pkg/credentials"
"github.com/minio/minio/pkg/madmin"
)
// newAdminFactory encloses New function with client cache.
func newAdminFactory() func(config *Config) (*madmin.AdminClient, *probe.Error) {
// NewAdminFactory encloses New function with client cache.
func NewAdminFactory() func(config *Config) (*madmin.AdminClient, *probe.Error) {
clientCache := make(map[uint32]*madmin.AdminClient)
mutex := &sync.Mutex{}
@@ -63,30 +65,49 @@ func newAdminFactory() func(config *Config) (*madmin.AdminClient, *probe.Error)
var api *madmin.AdminClient
var found bool
if api, found = clientCache[confSum]; !found {
// Admin API only supports signature v4.
creds := credentials.NewStaticV4(config.AccessKey, config.SecretKey, config.SessionToken)
// Not found. Instantiate a new MinIO
var e error
api, e = madmin.New(hostName, config.AccessKey, config.SecretKey, useTLS)
api, e = madmin.NewWithOptions(hostName, &madmin.Options{
Creds: creds,
Secure: useTLS,
})
if e != nil {
return nil, probe.NewError(e)
}
// Keep TLS config.
tlsConfig := &tls.Config{RootCAs: globalRootCAs}
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
}
var transport http.RoundTripper = &http.Transport{
Proxy: http.ProxyFromEnvironment,
Proxy: ieproxy.GetProxyFunc(),
DialContext: (&net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second,
Timeout: 10 * time.Second,
KeepAlive: 15 * time.Second,
}).DialContext,
MaxIdleConns: 100,
MaxIdleConnsPerHost: 256,
IdleConnTimeout: 90 * time.Second,
TLSHandshakeTimeout: 10 * time.Second,
ExpectContinueTimeout: 1 * 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`.
//
// Refer:
// https://golang.org/src/net/http/transport.go?h=roundTrip#L1843
DisableCompression: true,
}
if config.Debug {
@@ -124,7 +145,7 @@ func newAdminClient(aliasedURL string) (*madmin.AdminClient, *probe.Error) {
return nil, probe.NewError(fmt.Errorf("No valid configuration found for '%s' host alias", urlStrFull))
}
s3Config := newS3Config(urlStrFull, hostCfg)
s3Config := NewS3Config(urlStrFull, hostCfg)
s3Client, err := s3AdminNew(s3Config)
if err != nil {
@@ -135,4 +156,4 @@ func newAdminClient(aliasedURL string) (*madmin.AdminClient, *probe.Error) {
// s3AdminNew returns an initialized minioAdmin structure. If debug is enabled,
// it also enables an internal trace transport.
var s3AdminNew = newAdminFactory()
var s3AdminNew = NewAdminFactory()
+7
View File
@@ -56,6 +56,13 @@ func (e BucketNameEmpty) Error() string {
return "Bucket name cannot be empty."
}
// ObjectNameEmpty - object name empty.
type ObjectNameEmpty struct{}
func (e ObjectNameEmpty) Error() string {
return "Object name cannot be empty."
}
// BucketInvalid - bucket name invalid.
type BucketInvalid struct {
Bucket string
+258 -325
View File
@@ -1,5 +1,5 @@
/*
* MinIO Client (C) 2015 MinIO, Inc.
* MinIO Client (C) 2015-2020 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this fs except in compliance with the License.
@@ -18,8 +18,8 @@ package cmd
import (
"context"
"errors"
"io"
"io/ioutil"
"os"
"path"
"path/filepath"
@@ -33,28 +33,31 @@ import (
"github.com/pkg/xattr"
"github.com/rjeczalik/notify"
"github.com/minio/mc/cmd/ilm"
"github.com/minio/mc/pkg/disk"
"github.com/minio/mc/pkg/hookreader"
"github.com/minio/mc/pkg/ioutils"
"github.com/minio/mc/pkg/probe"
minio "github.com/minio/minio-go/v6"
"github.com/minio/minio-go/v6/pkg/encrypt"
"github.com/minio/minio-go/v6/pkg/tags"
)
// filesystem client
type fsClient struct {
PathURL *clientURL
PathURL *ClientURL
}
const (
partSuffix = ".part.minio"
slashSeperator = "/"
metaDataKey = "X-Amz-Meta-Mc-Attrs"
)
var ( // GOOS specific ignore list.
ignoreFiles = map[string][]string{
"darwin": {"*.DS_Store"},
"default": {""},
"default": {"lost+found"},
}
)
@@ -111,12 +114,12 @@ func isIgnoredFile(filename string) bool {
}
// URL get url.
func (f *fsClient) GetURL() clientURL {
func (f *fsClient) GetURL() ClientURL {
return *f.PathURL
}
// Select replies a stream of query results.
func (f *fsClient) Select(expression string, sse encrypt.ServerSide, opts SelectObjectOpts) (io.ReadCloser, *probe.Error) {
func (f *fsClient) Select(ctx context.Context, expression string, sse encrypt.ServerSide, opts SelectObjectOpts) (io.ReadCloser, *probe.Error) {
return nil, probe.NewError(APINotImplemented{
API: "Select",
APIType: "filesystem",
@@ -124,16 +127,16 @@ func (f *fsClient) Select(expression string, sse encrypt.ServerSide, opts Select
}
// Watches for all fs events on an input path.
func (f *fsClient) Watch(params watchParams) (*watchObject, *probe.Error) {
eventChan := make(chan EventInfo)
func (f *fsClient) Watch(ctx context.Context, options WatchOptions) (*WatchObject, *probe.Error) {
eventChan := make(chan []EventInfo)
errorChan := make(chan *probe.Error)
doneChan := make(chan bool)
doneChan := make(chan struct{})
// Make the channel buffered to ensure no event is dropped. Notify will drop
// an event if the receiver is not able to keep up the sending pace.
in, out := PipeChan(1000)
var fsEvents []notify.Event
for _, event := range params.events {
for _, event := range options.Events {
switch event {
case "put":
fsEvents = append(fsEvents, EventTypePut...)
@@ -149,7 +152,7 @@ func (f *fsClient) Watch(params watchParams) (*watchObject, *probe.Error) {
// Set up a watchpoint listening for events within a directory tree rooted
// at current working directory. Dispatch remove events to c.
recursivePath := f.PathURL.Path
if params.recursive {
if options.Recursive {
recursivePath = f.PathURL.Path + "..."
}
if e := notify.Watch(recursivePath, in, fsEvents...); e != nil {
@@ -190,52 +193,89 @@ func (f *fsClient) Watch(params watchParams) (*watchObject, *probe.Error) {
// we want files
continue
}
eventChan <- EventInfo{
eventChan <- []EventInfo{{
Time: UTCNow().Format(timeFormatFS),
Size: i.Size(),
Path: event.Path(),
Type: EventCreate,
}
}}
} else if IsDeleteEvent(event.Event()) {
eventChan <- EventInfo{
eventChan <- []EventInfo{{
Time: UTCNow().Format(timeFormatFS),
Path: event.Path(),
Type: EventRemove,
}
}}
} else if IsGetEvent(event.Event()) {
eventChan <- EventInfo{
eventChan <- []EventInfo{{
Time: UTCNow().Format(timeFormatFS),
Path: event.Path(),
Type: EventAccessed,
}
}}
}
}
}()
return &watchObject{
eventInfoChan: eventChan,
errorChan: errorChan,
doneChan: doneChan,
return &WatchObject{
EventInfoChan: eventChan,
ErrorChan: errorChan,
DoneChan: doneChan,
}, nil
}
func isStreamFile(objectPath string) bool {
switch objectPath {
case os.DevNull:
fallthrough
case os.Stdin.Name():
fallthrough
case os.Stdout.Name():
fallthrough
case os.Stderr.Name():
return true
func preserveAttributes(fd *os.File, attr map[string]string) *probe.Error {
if val, ok := attr["mode"]; ok {
mode, e := strconv.ParseUint(val, 0, 32)
if e != nil {
return probe.NewError(e)
}
// Attempt to change the file mode.
if e := fd.Chmod(os.FileMode(mode)); e != nil {
return probe.NewError(e)
}
}
return false
var uid, gid int
var gidExists, uidExists bool
var e error
if val, ok := attr["uid"]; ok {
uid, e = strconv.Atoi(val)
if e != nil {
return probe.NewError(e)
}
uidExists = true
}
if val, ok := attr["gid"]; ok {
gid, e = strconv.Atoi(val)
if e != nil {
return probe.NewError(e)
}
gidExists = true
}
// Attempt to change the owner.
if gidExists && uidExists {
if e := fd.Chown(uid, gid); e != nil {
return probe.NewError(e)
}
} else if uidExists {
if e := fd.Chown(uid, -1); e != nil {
return probe.NewError(e)
}
} else {
if e := fd.Chown(-1, gid); e != nil {
return probe.NewError(e)
}
}
return nil
}
/// Object operations.
func (f *fsClient) put(reader io.Reader, size int64, metadata map[string][]string, progress io.Reader) (int64, *probe.Error) {
func (f *fsClient) put(ctx context.Context, reader io.Reader, size int64, metadata map[string][]string, progress io.Reader, preserve bool) (int64, *probe.Error) {
// ContentType is not handled on purpose.
// For filesystem this is a redundant information.
@@ -256,68 +296,52 @@ func (f *fsClient) put(reader io.Reader, size int64, metadata map[string][]strin
}
objectPath := f.PathURL.Path
avoidResumeUpload := isStreamFile(objectPath)
// Write to a temporary file "object.part.minio" before commit.
objectPartPath := objectPath + partSuffix
if avoidResumeUpload {
objectPartPath = objectPath
}
// If exists, open in append mode. If not create it the part file.
partFile, e := os.OpenFile(objectPartPath, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0666)
// We cannot resume this operation, then we
// should remove any partial download if any.
defer os.Remove(objectPartPath)
tmpFile, e := os.OpenFile(objectPartPath, os.O_CREATE|os.O_WRONLY, 0666)
if e != nil {
err := f.toClientError(e, f.PathURL.Path)
return 0, err.Trace(f.PathURL.Path)
}
// Get stat to get the current size.
partSt, e := os.Stat(objectPartPath)
if e != nil {
err := f.toClientError(e, objectPartPath)
return 0, err.Trace(objectPartPath)
}
var totalWritten int64
// Current file offset.
var currentOffset = partSt.Size()
if !isStdIO(reader) && size > 0 {
reader = hookreader.NewHook(reader, progress)
if seeker, ok := reader.(io.Seeker); ok {
if _, e = seeker.Seek(currentOffset, 0); e != nil {
return 0, probe.NewError(e)
}
// Discard bytes until currentOffset.
if _, e = io.CopyN(ioutil.Discard, progress, currentOffset); e != nil {
return 0, probe.NewError(e)
}
}
} else {
reader = hookreader.NewHook(reader, progress)
// Discard bytes until currentOffset.
if _, e = io.CopyN(ioutil.Discard, reader, currentOffset); e != nil {
attr := make(map[string]string)
if len(metadata[metaDataKey]) != 0 && preserve {
attr, e = parseAttribute(metadata[metaDataKey][0])
if e != nil {
tmpFile.Close()
return 0, probe.NewError(e)
}
if err := preserveAttributes(tmpFile, attr); err != nil {
tmpFile.Close()
return 0, err.Trace(objectPath)
}
}
n, e := io.Copy(partFile, reader)
totalWritten, e := io.Copy(tmpFile, hookreader.NewHook(reader, progress))
if e != nil {
tmpFile.Close()
return 0, probe.NewError(e)
}
// Save currently copied total into totalWritten.
totalWritten = n + currentOffset
// Close the input reader as well, if possible.
closer, ok := reader.(io.Closer)
if ok {
if e = closer.Close(); e != nil {
tmpFile.Close()
return totalWritten, probe.NewError(e)
}
}
// Close the file before rename.
if e = partFile.Close(); e != nil {
// Close the file before renaming, we need to do this
// specifically for windows users - windows explicitly
// disallows renames on Open() fd's by default.
if e = tmpFile.Close(); e != nil {
return totalWritten, probe.NewError(e)
}
@@ -338,82 +362,56 @@ func (f *fsClient) put(reader io.Reader, size int64, metadata map[string][]strin
})
}
}
if !avoidResumeUpload {
// Safely completed put. Now commit by renaming to actual filename.
if e = os.Rename(objectPartPath, objectPath); e != nil {
err := f.toClientError(e, objectPath)
return totalWritten, err.Trace(objectPartPath, objectPath)
// Safely completed put. Now commit by renaming to actual filename.
if e = os.Rename(objectPartPath, objectPath); e != nil {
err := f.toClientError(e, objectPath)
return totalWritten, err.Trace(objectPartPath, objectPath)
}
if len(attr) != 0 && preserve {
var atime, mtime int64
var e error
var atimeChanged, mtimeChanged bool
if val, ok := attr["atime"]; ok {
atime, e = strconv.ParseInt(val, 10, 64)
if e != nil {
return totalWritten, probe.NewError(e)
}
atimeChanged = true
}
if len(metadata["mc-attrs"]) != 0 {
attr, e := parseAttribute(metadata["mc-attrs"][0])
if val, ok := attr["mtime"]; ok {
mtime, e = strconv.ParseInt(val, 10, 64)
if e != nil {
return totalWritten, probe.NewError(e)
}
mtimeChanged = true
}
mode, e := strconv.ParseUint(attr["mode"], 10, 32)
if e != nil {
// Attempt to change the access and modify time
if atimeChanged && mtimeChanged {
if e := os.Chtimes(objectPath, time.Unix(atime, 0), time.Unix(mtime, 0)); e != nil {
return totalWritten, probe.NewError(e)
}
// Change the mode of file
if e := os.Chmod(objectPath, os.FileMode(mode)); e != nil {
if !os.IsPermission(e) {
return totalWritten, probe.NewError(e)
}
}
uid, e := strconv.Atoi(attr["uid"])
if e != nil {
return totalWritten, probe.NewError(e)
}
gid, e := strconv.Atoi(attr["gid"])
if e != nil {
return totalWritten, probe.NewError(e)
}
// Change the owner
if e := os.Chown(objectPath, uid, gid); e != nil {
if !os.IsPermission(e) {
return totalWritten, probe.NewError(e)
}
}
atime, e := strconv.ParseInt(attr["atime"], 10, 64)
if e != nil {
return totalWritten, probe.NewError(e)
}
ctime, e := strconv.ParseInt(attr["ctime"], 10, 64)
if e != nil {
return totalWritten, probe.NewError(e)
}
// Change the access, modify and change time
if e := os.Chtimes(objectPath, time.Unix(atime, 0), time.Unix(ctime, 0)); e != nil {
if !os.IsPermission(e) {
return totalWritten, probe.NewError(e)
}
}
}
}
return totalWritten, nil
}
// Put - create a new file with metadata.
func (f *fsClient) Put(ctx context.Context, reader io.Reader, size int64, metadata map[string]string, progress io.Reader, sse encrypt.ServerSide) (int64, *probe.Error) {
if metadata["mc-attrs"] != "" {
func (f *fsClient) Put(ctx context.Context, reader io.Reader, size int64, metadata map[string]string, progress io.Reader, sse encrypt.ServerSide, md5, disableMultipart, preserve bool) (int64, *probe.Error) {
if metadata[metaDataKey] != "" {
meta := make(map[string][]string)
meta["mc-attrs"] = append(meta["mc-attrs"], metadata["mc-attrs"])
return f.put(reader, size, meta, progress)
meta[metaDataKey] = append(meta[metaDataKey], metadata[metaDataKey])
return f.put(ctx, reader, size, meta, progress, preserve)
}
return f.put(reader, size, nil, progress)
return f.put(ctx, reader, size, nil, progress, preserve)
}
// ShareDownload - share download not implemented for filesystem.
func (f *fsClient) ShareDownload(expires time.Duration) (string, *probe.Error) {
func (f *fsClient) ShareDownload(ctx context.Context, expires time.Duration) (string, *probe.Error) {
return "", probe.NewError(APINotImplemented{
API: "ShareDownload",
APIType: "filesystem",
@@ -428,57 +426,24 @@ func (f *fsClient) ShareUpload(startsWith bool, expires time.Duration, contentTy
})
}
// readFile reads and returns the data inside the file located
// at the provided filepath.
func readFile(fpath string) (io.ReadCloser, error) {
// Golang strips trailing / if you clean(..) or
// EvalSymlinks(..). Adding '.' prevents it from doing so.
if strings.HasSuffix(fpath, "/") {
fpath = fpath + "."
}
fpath, e := filepath.EvalSymlinks(fpath)
if e != nil {
return nil, e
}
fileData, e := os.Open(fpath)
if e != nil {
return nil, e
}
return fileData, nil
}
// Copy - copy data from source to destination
func (f *fsClient) Copy(source string, size int64, progress io.Reader, srcSSE, tgtSSE encrypt.ServerSide, metadata map[string]string) *probe.Error {
destination := f.PathURL.Path
rc, e := readFile(source)
func (f *fsClient) Copy(ctx context.Context, source string, size int64, progress io.Reader, srcSSE, tgtSSE encrypt.ServerSide, metadata map[string]string, disableMultipart, preserve bool) *probe.Error {
rc, e := os.Open(source)
if e != nil {
err := f.toClientError(e, destination)
return err.Trace(destination)
err := f.toClientError(e, source)
return err.Trace(source)
}
defer rc.Close()
_, err := f.put(rc, size, map[string][]string{}, progress)
if err != nil {
destination := f.PathURL.Path
if _, err := f.put(ctx, rc, size, map[string][]string{}, progress, preserve); err != nil {
return err.Trace(destination, source)
}
return nil
}
// get - get wrapper returning object reader.
func (f *fsClient) get() (io.ReadCloser, *probe.Error) {
tmppath := f.PathURL.Path
// Golang strips trailing / if you clean(..) or
// EvalSymlinks(..). Adding '.' prevents it from doing so.
if strings.HasSuffix(tmppath, string(f.PathURL.Separator)) {
tmppath = tmppath + "."
}
// Resolve symlinks.
_, e := filepath.EvalSymlinks(tmppath)
if e != nil {
err := f.toClientError(e, f.PathURL.Path)
return nil, err.Trace(f.PathURL.Path)
}
// Get returns reader and any additional metadata.
func (f *fsClient) Get(ctx context.Context, sse encrypt.ServerSide) (io.ReadCloser, *probe.Error) {
fileData, e := os.Open(f.PathURL.Path)
if e != nil {
err := f.toClientError(e, f.PathURL.Path)
@@ -487,11 +452,6 @@ func (f *fsClient) get() (io.ReadCloser, *probe.Error) {
return fileData, nil
}
// Get returns reader and any additional metadata.
func (f *fsClient) Get(sse encrypt.ServerSide) (io.ReadCloser, *probe.Error) {
return f.get()
}
// Check if the given error corresponds to ENOTEMPTY for unix
// and ERROR_DIR_NOT_EMPTY for windows (directory not empty).
func isSysErrNotEmpty(err error) bool {
@@ -537,7 +497,7 @@ func deleteFile(deletePath string) error {
}
// Remove - remove entry read from clientContent channel.
func (f *fsClient) Remove(isIncomplete, isRemoveBucket bool, contentCh <-chan *clientContent) <-chan *probe.Error {
func (f *fsClient) Remove(ctx context.Context, isIncomplete, isRemoveBucket, isBypass bool, contentCh <-chan *ClientContent) <-chan *probe.Error {
errorCh := make(chan *probe.Error)
// Goroutine reads from contentCh and removes the entry in content.
@@ -545,22 +505,29 @@ func (f *fsClient) Remove(isIncomplete, isRemoveBucket bool, contentCh <-chan *c
defer close(errorCh)
for content := range contentCh {
if content.Err != nil {
errorCh <- content.Err
continue
}
name := content.URL.Path
// Add partSuffix for incomplete uploads.
if isIncomplete {
name += partSuffix
}
if e := deleteFile(name); e != nil {
if os.IsPermission(e) {
// Ignore permission error.
errorCh <- probe.NewError(PathInsufficientPermission{Path: content.URL.Path})
} else if os.IsNotExist(e) && isRemoveBucket {
// ignore PathNotFound for dir removal.
return
} else {
errorCh <- probe.NewError(e)
return
}
e := deleteFile(name)
if e == nil {
continue
}
if os.IsNotExist(e) && isRemoveBucket {
// ignore PathNotFound for dir removal.
return
}
if os.IsPermission(e) {
// Ignore permission error.
errorCh <- probe.NewError(PathInsufficientPermission{Path: content.URL.Path})
} else {
errorCh <- probe.NewError(e)
return
}
}
}()
@@ -569,9 +536,9 @@ func (f *fsClient) Remove(isIncomplete, isRemoveBucket bool, contentCh <-chan *c
}
// List - list files and folders.
func (f *fsClient) List(isRecursive, isIncomplete, isMetadata bool, showDir DirOpt) <-chan *clientContent {
contentCh := make(chan *clientContent)
filteredCh := make(chan *clientContent)
func (f *fsClient) List(ctx context.Context, isRecursive, isIncomplete, isMetadata bool, showDir DirOpt) <-chan *ClientContent {
contentCh := make(chan *ClientContent)
filteredCh := make(chan *ClientContent)
if isRecursive {
if showDir == DirNone {
@@ -646,17 +613,16 @@ func readDir(dirname string) ([]os.FileInfo, error) {
}
// listPrefixes - list all files for any given prefix.
func (f *fsClient) listPrefixes(prefix string, contentCh chan<- *clientContent) {
func (f *fsClient) listPrefixes(prefix string, contentCh chan<- *ClientContent) {
dirName := filepath.Dir(prefix)
files, e := readDir(dirName)
if e != nil {
err := f.toClientError(e, dirName)
contentCh <- &clientContent{
contentCh <- &ClientContent{
Err: err.Trace(dirName),
}
return
}
pathURL := *f.PathURL
for _, fi := range files {
// Skip ignored files.
if isIgnoredFile(fi.Name()) {
@@ -667,31 +633,11 @@ func (f *fsClient) listPrefixes(prefix string, contentCh chan<- *clientContent)
if fi.Mode()&os.ModeSymlink == os.ModeSymlink {
st, e := os.Stat(file)
if e != nil {
if os.IsPermission(e) {
contentCh <- &clientContent{
Err: probe.NewError(PathInsufficientPermission{
Path: pathURL.Path,
}),
}
continue
}
if os.IsNotExist(e) {
contentCh <- &clientContent{
Err: probe.NewError(BrokenSymlink{
Path: pathURL.Path,
}),
}
continue
}
if e != nil {
contentCh <- &clientContent{
Err: probe.NewError(e),
}
continue
}
// Ignore any errors on symlink
continue
}
if strings.HasPrefix(file, prefix) {
contentCh <- &clientContent{
contentCh <- &ClientContent{
URL: *newClientURL(file),
Time: st.ModTime(),
Size: st.Size(),
@@ -702,7 +648,7 @@ func (f *fsClient) listPrefixes(prefix string, contentCh chan<- *clientContent)
}
}
if strings.HasPrefix(file, prefix) {
contentCh <- &clientContent{
contentCh <- &ClientContent{
URL: *newClientURL(file),
Time: fi.ModTime(),
Size: fi.Size(),
@@ -713,7 +659,7 @@ func (f *fsClient) listPrefixes(prefix string, contentCh chan<- *clientContent)
}
}
func (f *fsClient) listInRoutine(contentCh chan<- *clientContent, isMetadata bool) {
func (f *fsClient) listInRoutine(contentCh chan<- *ClientContent, isMetadata bool) {
// close the channel when the function returns.
defer close(contentCh)
@@ -730,7 +676,7 @@ func (f *fsClient) listInRoutine(contentCh chan<- *clientContent, isMetadata boo
return
}
// For all other errors we return genuine error back to the caller.
contentCh <- &clientContent{Err: err.Trace(fpath)}
contentCh <- &ClientContent{Err: err.Trace(fpath)}
return
}
@@ -746,7 +692,7 @@ func (f *fsClient) listInRoutine(contentCh chan<- *clientContent, isMetadata boo
case true:
files, e := readDir(fpath)
if err != nil {
contentCh <- &clientContent{Err: probe.NewError(e)}
contentCh <- &ClientContent{Err: probe.NewError(e)}
return
}
for _, file := range files {
@@ -754,26 +700,8 @@ func (f *fsClient) listInRoutine(contentCh chan<- *clientContent, isMetadata boo
if fi.Mode()&os.ModeSymlink == os.ModeSymlink {
fp := filepath.Join(fpath, fi.Name())
fi, e = os.Stat(fp)
if os.IsPermission(e) {
contentCh <- &clientContent{
Err: probe.NewError(PathInsufficientPermission{Path: pathURL.Path}),
}
continue
}
if os.IsNotExist(e) {
// Lstat makes no attempt to follow the broken link.
_, e = os.Lstat(fp)
contentCh <- &clientContent{
URL: pathURL,
Size: -1,
Err: probe.NewError(e),
}
continue
}
if e != nil {
contentCh <- &clientContent{
Err: probe.NewError(e),
}
// Ignore all errors on symlinks
continue
}
}
@@ -786,7 +714,7 @@ func (f *fsClient) listInRoutine(contentCh chan<- *clientContent, isMetadata boo
continue
}
contentCh <- &clientContent{
contentCh <- &ClientContent{
URL: pathURL,
Time: fi.ModTime(),
Size: fi.Size(),
@@ -796,7 +724,7 @@ func (f *fsClient) listInRoutine(contentCh chan<- *clientContent, isMetadata boo
}
}
default:
contentCh <- &clientContent{
contentCh <- &ClientContent{
URL: pathURL,
Time: fst.ModTime(),
Size: fst.Size(),
@@ -807,7 +735,7 @@ func (f *fsClient) listInRoutine(contentCh chan<- *clientContent, isMetadata boo
}
// List files recursively using non-recursive mode.
func (f *fsClient) listDirOpt(contentCh chan *clientContent, isIncomplete bool, isMetadata bool, dirOpt DirOpt) {
func (f *fsClient) listDirOpt(contentCh chan *ClientContent, isIncomplete bool, isMetadata bool, dirOpt DirOpt) {
defer close(contentCh)
// Trim trailing / or \.
@@ -823,7 +751,7 @@ func (f *fsClient) listDirOpt(contentCh chan *clientContent, isIncomplete bool,
files, e := readDir(currentPath)
if e != nil {
if os.IsPermission(e) {
contentCh <- &clientContent{
contentCh <- &ClientContent{
Err: probe.NewError(PathInsufficientPermission{
Path: currentPath,
}),
@@ -831,13 +759,13 @@ func (f *fsClient) listDirOpt(contentCh chan *clientContent, isIncomplete bool,
return false
}
contentCh <- &clientContent{Err: probe.NewError(e)}
contentCh <- &ClientContent{Err: probe.NewError(e)}
return true
}
for _, file := range files {
name := filepath.Join(currentPath, file.Name())
content := clientContent{
content := ClientContent{
URL: *newClientURL(name),
Time: file.ModTime(),
Size: file.Size(),
@@ -867,17 +795,17 @@ func (f *fsClient) listDirOpt(contentCh chan *clientContent, isIncomplete bool,
// listDir() does not send currentPath to contentCh. We send it here depending on dirOpt.
if dirOpt == DirFirst && !isIncomplete {
contentCh <- &clientContent{URL: *newClientURL(currentPath), Type: os.ModeDir}
contentCh <- &ClientContent{URL: *newClientURL(currentPath), Type: os.ModeDir}
}
listDir(currentPath)
if dirOpt == DirLast && !isIncomplete {
contentCh <- &clientContent{URL: *newClientURL(currentPath), Type: os.ModeDir}
contentCh <- &ClientContent{URL: *newClientURL(currentPath), Type: os.ModeDir}
}
}
func (f *fsClient) listRecursiveInRoutine(contentCh chan *clientContent, isMetadata bool) {
func (f *fsClient) listRecursiveInRoutine(contentCh chan *ClientContent, isMetadata bool) {
// close channels upon return.
defer close(contentCh)
var dirName string
@@ -925,13 +853,13 @@ func (f *fsClient) listRecursiveInRoutine(contentCh chan *clientContent, isMetad
if e != nil {
// If operation is not permitted, we throw quickly back.
if strings.Contains(e.Error(), "operation not permitted") {
contentCh <- &clientContent{
contentCh <- &ClientContent{
Err: probe.NewError(e),
}
return nil
}
if os.IsPermission(e) {
contentCh <- &clientContent{
contentCh <- &ClientContent{
Err: probe.NewError(PathInsufficientPermission{Path: fp}),
}
return nil
@@ -941,34 +869,12 @@ func (f *fsClient) listRecursiveInRoutine(contentCh chan *clientContent, isMetad
if fi.Mode()&os.ModeSymlink == os.ModeSymlink {
fi, e = os.Stat(fp)
if e != nil {
if os.IsPermission(e) {
contentCh <- &clientContent{
Err: probe.NewError(e),
}
return nil
}
if os.IsNotExist(e) {
// Lstat makes no attempt to follow the broken link.
_, e = os.Lstat(fp)
contentCh <- &clientContent{
URL: *newClientURL(fp),
Size: -1,
Err: probe.NewError(e),
}
return nil
}
// Ignore symlink loops.
if strings.Contains(e.Error(), "too many levels of symbolic links") {
contentCh <- &clientContent{
Err: probe.NewError(TooManyLevelsSymlink{Path: fp}),
}
return nil
}
return e
// Ignore any errors for symlink
return nil
}
}
if fi.Mode().IsRegular() {
contentCh <- &clientContent{
contentCh <- &ClientContent{
URL: *newClientURL(fp),
Time: fi.ModTime(),
Size: fi.Size(),
@@ -997,14 +903,14 @@ func (f *fsClient) listRecursiveInRoutine(contentCh chan *clientContent, isMetad
// walks invokes our custom function.
e := ioutils.FTW(dirName, visitFS)
if e != nil {
contentCh <- &clientContent{
contentCh <- &ClientContent{
Err: probe.NewError(e),
}
}
}
// MakeBucket - create a new bucket.
func (f *fsClient) MakeBucket(region string, ignoreExisting, withLock bool) *probe.Error {
func (f *fsClient) MakeBucket(ctx context.Context, region string, ignoreExisting, withLock bool) *probe.Error {
// TODO: ignoreExisting has no effect currently. In the future, we want
// to call os.Mkdir() when ignoredExisting is disabled and os.MkdirAll()
// otherwise.
@@ -1017,7 +923,7 @@ func (f *fsClient) MakeBucket(region string, ignoreExisting, withLock bool) *pro
}
// Set object lock configuration of bucket.
func (f *fsClient) SetObjectLockConfig(mode *minio.RetentionMode, validity *uint, unit *minio.ValidityUnit) *probe.Error {
func (f *fsClient) SetObjectLockConfig(ctx context.Context, mode minio.RetentionMode, validity uint64, unit minio.ValidityUnit) *probe.Error {
return probe.NewError(APINotImplemented{
API: "SetObjectLockConfig",
APIType: "filesystem",
@@ -1025,15 +931,15 @@ func (f *fsClient) SetObjectLockConfig(mode *minio.RetentionMode, validity *uint
}
// Get object lock configuration of bucket.
func (f *fsClient) GetObjectLockConfig() (mode *minio.RetentionMode, validity *uint, unit *minio.ValidityUnit, perr *probe.Error) {
return nil, nil, nil, probe.NewError(APINotImplemented{
func (f *fsClient) GetObjectLockConfig(ctx context.Context) (mode minio.RetentionMode, validity uint64, unit minio.ValidityUnit, err *probe.Error) {
return "", 0, "", probe.NewError(APINotImplemented{
API: "GetObjectLockConfig",
APIType: "filesystem",
})
}
// GetAccessRules - unsupported API
func (f *fsClient) GetAccessRules() (map[string]string, *probe.Error) {
func (f *fsClient) GetAccessRules(ctx context.Context) (map[string]string, *probe.Error) {
return map[string]string{}, probe.NewError(APINotImplemented{
API: "GetBucketPolicy",
APIType: "filesystem",
@@ -1041,15 +947,23 @@ func (f *fsClient) GetAccessRules() (map[string]string, *probe.Error) {
}
// Set object retention for a given object.
func (f *fsClient) PutObjectRetention(mode *minio.RetentionMode, retainUntilDate *time.Time) *probe.Error {
func (f *fsClient) PutObjectRetention(ctx context.Context, mode minio.RetentionMode, retainUntilDate time.Time, bypassGovernance bool) *probe.Error {
return probe.NewError(APINotImplemented{
API: "PutObjectRetention",
APIType: "filesystem",
})
}
// Set object legal hold for a given object.
func (f *fsClient) PutObjectLegalHold(ctx context.Context, lhold minio.LegalHoldStatus) *probe.Error {
return probe.NewError(APINotImplemented{
API: "PutObjectLegalHold",
APIType: "filesystem",
})
}
// GetAccess - get access policy permissions.
func (f *fsClient) GetAccess() (access string, policyJSON string, err *probe.Error) {
func (f *fsClient) GetAccess(ctx context.Context) (access string, policyJSON string, err *probe.Error) {
// For windows this feature is not implemented.
if runtime.GOOS == "windows" {
return "", "", probe.NewError(APINotImplemented{API: "GetAccess", APIType: "filesystem"})
@@ -1074,7 +988,7 @@ func (f *fsClient) GetAccess() (access string, policyJSON string, err *probe.Err
}
// SetAccess - set access policy permissions.
func (f *fsClient) SetAccess(access string, isJSON bool) *probe.Error {
func (f *fsClient) SetAccess(ctx context.Context, access string, isJSON bool) *probe.Error {
// For windows this feature is not implemented.
// JSON policy for fs is not yet implemented.
if runtime.GOOS == "windows" || isJSON {
@@ -1106,13 +1020,13 @@ func (f *fsClient) SetAccess(access string, isJSON bool) *probe.Error {
}
// Stat - get metadata from path.
func (f *fsClient) Stat(isIncomplete, isFetchMeta, isPreserve bool, sse encrypt.ServerSide) (content *clientContent, err *probe.Error) {
func (f *fsClient) Stat(ctx context.Context, isIncomplete, isPreserve bool, sse encrypt.ServerSide) (content *ClientContent, err *probe.Error) {
st, err := f.fsStat(isIncomplete)
if err != nil {
return nil, err.Trace(f.PathURL.String())
}
content = &clientContent{}
content = &ClientContent{}
content.URL = *f.PathURL
content.Size = st.Size()
content.Time = st.ModTime()
@@ -1121,26 +1035,22 @@ func (f *fsClient) Stat(isIncomplete, isFetchMeta, isPreserve bool, sse encrypt.
"Content-Type": guessURLContentType(f.PathURL.Path),
}
// isFetchMeta is true only in the case of mc stat command which lists any extended attributes
// present for this object.
if isFetchMeta {
path := f.PathURL.String()
metaData, pErr := getAllXattrs(path)
if pErr != nil {
path := f.PathURL.String()
metaData, pErr := getAllXattrs(path)
if pErr != nil {
return content, nil
}
for k, v := range metaData {
content.Metadata[k] = v
}
// Populates meta data with file system attribute only in case of
// when preserve flag is passed.
if isPreserve {
fileAttr, err := disk.GetFileSystemAttrs(path)
if err != nil {
return content, nil
}
for k, v := range metaData {
content.Metadata[k] = v
}
// Populates meta data with file system attribute only in case of
// when preserve flag is passed.
if isPreserve {
fileAttr, err := disk.GetFileSystemAttrs(path)
if err != nil {
return content, nil
}
content.Metadata["mc-attrs"] = fileAttr
}
content.Metadata[metaDataKey] = fileAttr
}
return content, nil
@@ -1154,6 +1064,9 @@ func (f *fsClient) toClientError(e error, fpath string) *probe.Error {
if os.IsNotExist(e) {
return probe.NewError(PathNotFound{Path: fpath})
}
if errors.Is(e, syscall.ELOOP) {
return probe.NewError(TooManyLevelsSymlink{Path: fpath})
}
return probe.NewError(e)
}
@@ -1172,32 +1085,52 @@ func (f *fsClient) fsStat(isIncomplete bool) (os.FileInfo, *probe.Error) {
fpath += partSuffix
}
// Golang strips trailing / if you clean(..) or
// EvalSymlinks(..). Adding '.' prevents it from doing so.
if strings.HasSuffix(fpath, string(f.PathURL.Separator)) {
fpath = fpath + "."
}
fpath, e = filepath.EvalSymlinks(fpath)
if e != nil {
if os.IsPermission(e) {
return nil, probe.NewError(PathInsufficientPermission{Path: f.PathURL.Path})
}
err := f.toClientError(e, f.PathURL.Path)
return nil, err.Trace(fpath)
}
st, e = os.Stat(fpath)
if e != nil {
if os.IsPermission(e) {
return nil, probe.NewError(PathInsufficientPermission{Path: f.PathURL.Path})
}
if os.IsNotExist(e) {
return nil, probe.NewError(PathNotFound{Path: f.PathURL.Path})
}
return nil, probe.NewError(e)
return nil, f.toClientError(e, fpath)
}
return st, nil
}
func (f *fsClient) AddUserAgent(app, version string) {
func (f *fsClient) AddUserAgent(_, _ string) {
}
// Get Object Tags
func (f *fsClient) GetTags(ctx context.Context) (*tags.Tags, *probe.Error) {
return nil, probe.NewError(APINotImplemented{
API: "GetObjectTagging",
APIType: "filesystem",
})
}
// Set Object tags
func (f *fsClient) SetTags(ctx context.Context, tags string) *probe.Error {
return probe.NewError(APINotImplemented{
API: "SetObjectTagging",
APIType: "filesystem",
})
}
// Delete object tags
func (f *fsClient) DeleteTags(ctx context.Context) *probe.Error {
return probe.NewError(APINotImplemented{
API: "DeleteObjectTagging",
APIType: "filesystem",
})
}
// Get lifecycle configuration for a given bucket, not implemented.
func (f *fsClient) GetLifecycle(ctx context.Context) (ilm.LifecycleConfiguration, *probe.Error) {
return ilm.LifecycleConfiguration{}, probe.NewError(APINotImplemented{
API: "GetLifecycle",
APIType: "filesystem",
})
}
// Set lifecycle configuration for a given bucket, not implemented.
func (f *fsClient) SetLifecycle(ctx context.Context, _ ilm.LifecycleConfiguration) *probe.Error {
return probe.NewError(APINotImplemented{
API: "SetLifecycle",
APIType: "filesystem",
})
}
+25 -26
View File
@@ -45,7 +45,7 @@ func (s *TestSuite) TestList(c *C) {
var n int64
n, err = fsClient.Put(context.Background(), reader, int64(len(data)), map[string]string{
"Content-Type": "application/octet-stream",
}, nil, nil)
}, nil, nil, false, false, false)
c.Assert(err, IsNil)
c.Assert(n, Equals, int64(len(data)))
@@ -56,7 +56,7 @@ func (s *TestSuite) TestList(c *C) {
reader = bytes.NewReader([]byte(data))
n, err = fsClient.Put(context.Background(), reader, int64(len(data)), map[string]string{
"Content-Type": "application/octet-stream",
}, nil, nil)
}, nil, nil, false, false, false)
c.Assert(err, IsNil)
c.Assert(n, Equals, int64(len(data)))
@@ -64,8 +64,8 @@ func (s *TestSuite) TestList(c *C) {
c.Assert(err, IsNil)
// Verify previously create files and list them.
var contents []*clientContent
for content := range fsClient.List(false, false, false, DirNone) {
var contents []*ClientContent
for content := range fsClient.List(globalContext, false, false, false, DirNone) {
if content.Err != nil {
err = content.Err
break
@@ -84,7 +84,7 @@ func (s *TestSuite) TestList(c *C) {
reader = bytes.NewReader([]byte(data))
n, err = fsClient.Put(context.Background(), reader, int64(len(data)), map[string]string{
"Content-Type": "application/octet-stream",
}, nil, nil)
}, nil, nil, false, false, false)
c.Assert(err, IsNil)
c.Assert(n, Equals, int64(len(data)))
@@ -93,7 +93,7 @@ func (s *TestSuite) TestList(c *C) {
contents = nil
// List non recursive to list only top level files.
for content := range fsClient.List(false, false, false, DirNone) {
for content := range fsClient.List(globalContext, false, false, false, DirNone) {
if content.Err != nil {
err = content.Err
break
@@ -109,7 +109,7 @@ func (s *TestSuite) TestList(c *C) {
contents = nil
// List recursively all files and verify.
for content := range fsClient.List(true, false, false, DirNone) {
for content := range fsClient.List(globalContext, true, false, false, DirNone) {
if content.Err != nil {
err = content.Err
break
@@ -144,7 +144,7 @@ func (s *TestSuite) TestList(c *C) {
reader = bytes.NewReader([]byte(data))
n, err = fsClient.Put(context.Background(), reader, int64(len(data)), map[string]string{
"Content-Type": "application/octet-stream",
}, nil, nil)
}, nil, nil, false, false, false)
c.Assert(err, IsNil)
c.Assert(n, Equals, int64(len(data)))
@@ -153,7 +153,7 @@ func (s *TestSuite) TestList(c *C) {
contents = nil
// List recursively all files and verify.
for content := range fsClient.List(true, false, false, DirNone) {
for content := range fsClient.List(globalContext, true, false, false, DirNone) {
if content.Err != nil {
err = content.Err
break
@@ -194,7 +194,7 @@ func (s *TestSuite) TestPutBucket(c *C) {
bucketPath := filepath.Join(root, "bucket")
fsClient, err := fsNew(bucketPath)
c.Assert(err, IsNil)
err = fsClient.MakeBucket("us-east-1", true, false)
err = fsClient.MakeBucket(context.Background(), "us-east-1", true, false)
c.Assert(err, IsNil)
}
@@ -208,9 +208,9 @@ func (s *TestSuite) TestStatBucket(c *C) {
fsClient, err := fsNew(bucketPath)
c.Assert(err, IsNil)
err = fsClient.MakeBucket("us-east-1", true, false)
err = fsClient.MakeBucket(context.Background(), "us-east-1", true, false)
c.Assert(err, IsNil)
_, err = fsClient.Stat(false, false, false, nil)
_, err = fsClient.Stat(context.Background(), false, false, nil)
c.Assert(err, IsNil)
}
@@ -223,15 +223,15 @@ func (s *TestSuite) TestBucketACLFails(c *C) {
bucketPath := filepath.Join(root, "bucket")
fsClient, err := fsNew(bucketPath)
c.Assert(err, IsNil)
err = fsClient.MakeBucket("us-east-1", true, false)
err = fsClient.MakeBucket(context.Background(), "us-east-1", true, false)
c.Assert(err, IsNil)
// On windows setting permissions is not supported.
if runtime.GOOS != "windows" {
err = fsClient.SetAccess("readonly", false)
err = fsClient.SetAccess(context.Background(), "readonly", false)
c.Assert(err, IsNil)
_, _, err = fsClient.GetAccess()
_, _, err = fsClient.GetAccess(context.Background())
c.Assert(err, IsNil)
}
}
@@ -251,7 +251,7 @@ func (s *TestSuite) TestPut(c *C) {
var n int64
n, err = fsClient.Put(context.Background(), reader, int64(len(data)), map[string]string{
"Content-Type": "application/octet-stream",
}, nil, nil)
}, nil, nil, false, false, false)
c.Assert(err, IsNil)
c.Assert(n, Equals, int64(len(data)))
}
@@ -271,11 +271,11 @@ func (s *TestSuite) TestGet(c *C) {
reader = bytes.NewReader([]byte(data))
n, err := fsClient.Put(context.Background(), reader, int64(len(data)), map[string]string{
"Content-Type": "application/octet-stream",
}, nil, nil)
}, nil, nil, false, false, false)
c.Assert(err, IsNil)
c.Assert(n, Equals, int64(len(data)))
reader, err = fsClient.Get(nil)
reader, err = fsClient.Get(context.Background(), nil)
c.Assert(err, IsNil)
var results bytes.Buffer
_, e = io.Copy(&results, reader)
@@ -299,11 +299,11 @@ func (s *TestSuite) TestGetRange(c *C) {
reader = bytes.NewReader([]byte(data))
n, err := fsClient.Put(context.Background(), reader, int64(len(data)), map[string]string{
"Content-Type": "application/octet-stream",
}, nil, nil)
}, nil, nil, false, false, false)
c.Assert(err, IsNil)
c.Assert(n, Equals, int64(len(data)))
reader, err = fsClient.Get(nil)
reader, err = fsClient.Get(context.Background(), nil)
c.Assert(err, IsNil)
var results bytes.Buffer
buf := make([]byte, 5)
@@ -330,11 +330,11 @@ func (s *TestSuite) TestStatObject(c *C) {
reader := bytes.NewReader([]byte(data))
n, err := fsClient.Put(context.Background(), reader, int64(dataLen), map[string]string{
"Content-Type": "application/octet-stream",
}, nil, nil)
}, nil, nil, false, false, false)
c.Assert(err, IsNil)
c.Assert(n, Equals, int64(len(data)))
content, err := fsClient.Stat(false, false, false, nil)
content, err := fsClient.Stat(context.Background(), false, false, nil)
c.Assert(err, IsNil)
c.Assert(content.Size, Equals, int64(dataLen))
}
@@ -352,14 +352,13 @@ func (s *TestSuite) TestCopy(c *C) {
c.Assert(err, IsNil)
data := "hello world"
var reader io.Reader
reader = bytes.NewReader([]byte(data))
reader := bytes.NewReader([]byte(data))
n, err := fsClientSource.Put(context.Background(), reader, int64(len(data)), map[string]string{
"Content-Type": "application/octet-stream",
}, nil, nil)
}, nil, nil, false, false, false)
c.Assert(err, IsNil)
c.Assert(n, Equals, int64(len(data)))
err = fsClientTarget.Copy(sourcePath, int64(len(data)), nil, nil, nil, nil)
err = fsClientTarget.Copy(context.Background(), sourcePath, int64(len(data)), nil, nil, nil, nil, false, false)
c.Assert(err, IsNil)
}
+5 -2
View File
@@ -22,7 +22,7 @@ import "github.com/rjeczalik/notify"
var (
// EventTypePut contains the notify events that will cause a put (writer)
EventTypePut = []notify.Event{notify.Create, notify.Write, notify.Rename}
EventTypePut = []notify.Event{notify.Create, notify.Write, notify.Rename, notify.FileNotifyChangeFileName, notify.FileNotifyChangeDirName}
// EventTypeDelete contains the notify events that will cause a delete (remove)
EventTypeDelete = []notify.Event{notify.Remove}
// EventTypeGet contains the notify events that will cause a get (read)
@@ -36,6 +36,9 @@ func IsGetEvent(event notify.Event) bool {
// IsPutEvent checks if the event returned is a put event
func IsPutEvent(event notify.Event) bool {
if event&notify.FileActionRenamedOldName != 0 {
return false
}
for _, ev := range EventTypePut {
if event&ev != 0 {
return true
@@ -46,7 +49,7 @@ func IsPutEvent(event notify.Event) bool {
// IsDeleteEvent checks if the event returned is a delete event
func IsDeleteEvent(event notify.Event) bool {
return event&notify.Remove != 0
return event&notify.Remove != 0 || event&notify.FileActionRenamedOldName != 0
}
// getAllXattrs returns the extended attributes for a file if supported
+1 -1
View File
@@ -21,8 +21,8 @@ import (
"net/http/httputil"
"strings"
"github.com/minio/mc/pkg/console"
"github.com/minio/mc/pkg/httptracer"
"github.com/minio/minio/pkg/console"
)
// traceV2 - tracing structure for signature version '2'.
+1 -1
View File
@@ -22,8 +22,8 @@ import (
"regexp"
"strings"
"github.com/minio/mc/pkg/console"
"github.com/minio/mc/pkg/httptracer"
"github.com/minio/minio/pkg/console"
)
// traceV4 - tracing structure for signature version '4'.
+721 -494
View File
File diff suppressed because it is too large Load Diff
+11 -11
View File
@@ -168,35 +168,35 @@ func (s *TestSuite) TestBucketOperations(c *C) {
conf.AccessKey = "WLGDGYAQYIGI833EV05A"
conf.SecretKey = "BYvgJM101sHngl2uzjXS/OBF/aMxAN06JrJ3qJlF"
conf.Signature = "S3v4"
s3c, err := s3New(conf)
s3c, err := S3New(conf)
c.Assert(err, IsNil)
err = s3c.MakeBucket("us-east-1", true, false)
err = s3c.MakeBucket(context.Background(), "us-east-1", true, false)
c.Assert(err, IsNil)
conf.HostURL = server.URL + string(s3c.GetURL().Separator)
s3c, err = s3New(conf)
s3c, err = S3New(conf)
c.Assert(err, IsNil)
for content := range s3c.List(false, false, false, DirNone) {
for content := range s3c.List(globalContext, false, false, false, DirNone) {
c.Assert(content.Err, IsNil)
c.Assert(content.Type.IsDir(), Equals, true)
}
conf.HostURL = server.URL + "/bucket"
s3c, err = s3New(conf)
s3c, err = S3New(conf)
c.Assert(err, IsNil)
for content := range s3c.List(false, false, false, DirNone) {
for content := range s3c.List(globalContext, false, false, false, DirNone) {
c.Assert(content.Err, IsNil)
c.Assert(content.Type.IsDir(), Equals, true)
}
conf.HostURL = server.URL + "/bucket/"
s3c, err = s3New(conf)
s3c, err = S3New(conf)
c.Assert(err, IsNil)
for content := range s3c.List(false, false, false, DirNone) {
for content := range s3c.List(globalContext, false, false, false, DirNone) {
c.Assert(content.Err, IsNil)
c.Assert(content.Type.IsRegular(), Equals, true)
}
@@ -216,18 +216,18 @@ func (s *TestSuite) TestObjectOperations(c *C) {
conf.AccessKey = "WLGDGYAQYIGI833EV05A"
conf.SecretKey = "BYvgJM101sHngl2uzjXS/OBF/aMxAN06JrJ3qJlF"
conf.Signature = "S3v4"
s3c, err := s3New(conf)
s3c, err := S3New(conf)
c.Assert(err, IsNil)
var reader io.Reader
reader = bytes.NewReader(object.data)
n, err := s3c.Put(context.Background(), reader, int64(len(object.data)), map[string]string{
"Content-Type": "application/octet-stream",
}, nil, nil)
}, nil, nil, false, false, false)
c.Assert(err, IsNil)
c.Assert(n, Equals, int64(len(object.data)))
reader, err = s3c.Get(nil)
reader, err = s3c.Get(context.Background(), nil)
c.Assert(err, IsNil)
var buffer bytes.Buffer
{
+26 -13
View File
@@ -18,6 +18,7 @@ package cmd
import (
"bytes"
"context"
"path/filepath"
"regexp"
"runtime"
@@ -27,9 +28,9 @@ import (
"github.com/minio/minio/pkg/mimedb"
)
// url client url structure
type clientURL struct {
Type clientURLType
// ClientURL url client url structure
type ClientURL struct {
Type ClientURLType
Scheme string
Host string
Path string
@@ -37,8 +38,8 @@ type clientURL struct {
Separator rune
}
// clientURLType - enum of different url types
type clientURLType int
// ClientURLType - enum of different url types
type ClientURLType int
// enum types
const (
@@ -91,7 +92,7 @@ func getHost(authority string) (host string) {
}
// newClientURL returns an abstracted URL for filesystems and object storage.
func newClientURL(urlStr string) *clientURL {
func newClientURL(urlStr string) *ClientURL {
scheme, rest := getScheme(urlStr)
if strings.HasPrefix(rest, "//") {
// if rest has '//' prefix, skip them
@@ -102,7 +103,7 @@ func newClientURL(urlStr string) *clientURL {
}
host := getHost(authority)
if host != "" && (scheme == "http" || scheme == "https") {
return &clientURL{
return &ClientURL{
Scheme: scheme,
Type: objectStorage,
Host: host,
@@ -112,7 +113,7 @@ func newClientURL(urlStr string) *clientURL {
}
}
}
return &clientURL{
return &ClientURL{
Type: fileSystem,
Path: rest,
Separator: filepath.Separator,
@@ -120,7 +121,7 @@ func newClientURL(urlStr string) *clientURL {
}
// joinURLs join two input urls and returns a url
func joinURLs(url1, url2 *clientURL) *clientURL {
func joinURLs(url1, url2 *ClientURL) *ClientURL {
var url1Path, url2Path string
url1Path = filepath.ToSlash(url1.Path)
url2Path = filepath.ToSlash(url2.Path)
@@ -132,8 +133,20 @@ func joinURLs(url1, url2 *clientURL) *clientURL {
return url1
}
// Clone the url into a new object.
func (u ClientURL) Clone() ClientURL {
return ClientURL{
Type: u.Type,
Scheme: u.Scheme,
Host: u.Host,
Path: u.Path,
SchemeSeparator: u.SchemeSeparator,
Separator: u.Separator,
}
}
// String convert URL into its canonical form.
func (u clientURL) String() string {
func (u ClientURL) String() string {
var buf bytes.Buffer
// if fileSystem no translation needed, return as is.
if u.Type == fileSystem {
@@ -171,7 +184,7 @@ func urlJoinPath(url1, url2 string) string {
}
// url2Stat returns stat info for URL.
func url2Stat(urlStr string, isFetchMeta, fileAttr bool, encKeyDB map[string][]prefixSSEPair) (client Client, content *clientContent, err *probe.Error) {
func url2Stat(ctx context.Context, urlStr string, fileAttr bool, encKeyDB map[string][]prefixSSEPair) (client Client, content *ClientContent, err *probe.Error) {
client, err = newClient(urlStr)
if err != nil {
return nil, nil, err.Trace(urlStr)
@@ -179,7 +192,7 @@ func url2Stat(urlStr string, isFetchMeta, fileAttr bool, encKeyDB map[string][]p
alias, _ := url2Alias(urlStr)
sse := getSSE(urlStr, encKeyDB[alias])
content, err = client.Stat(false, isFetchMeta, fileAttr, sse)
content, err = client.Stat(ctx, false, fileAttr, sse)
if err != nil {
return nil, nil, err.Trace(urlStr)
}
@@ -219,7 +232,7 @@ func isURLPrefixExists(urlPrefix string, incomplete bool) bool {
isRecursive := false
isIncomplete := incomplete
isFetchMeta := false
for entry := range clnt.List(isRecursive, isIncomplete, isFetchMeta, DirNone) {
for entry := range clnt.List(globalContext, isRecursive, isIncomplete, isFetchMeta, DirNone) {
return entry.Err == nil
}
return false
+53 -34
View File
@@ -22,9 +22,11 @@ import (
"os"
"time"
"github.com/minio/mc/cmd/ilm"
"github.com/minio/mc/pkg/probe"
minio "github.com/minio/minio-go/v6"
"github.com/minio/minio-go/v6/pkg/encrypt"
"github.com/minio/minio-go/v6/pkg/tags"
)
// DirOpt - list directory option.
@@ -45,50 +47,61 @@ const defaultMultipartThreadsNum = 4
// Client - client interface
type Client interface {
// Common operations
Stat(isIncomplete, isFetchMeta, isPreserve bool, sse encrypt.ServerSide) (content *clientContent, err *probe.Error)
List(isRecursive, isIncomplete, isFetchMeta bool, showDir DirOpt) <-chan *clientContent
Stat(ctx context.Context, isIncomplete, isPreserve bool, sse encrypt.ServerSide) (content *ClientContent, err *probe.Error)
List(ctx context.Context, isRecursive, isIncomplete, isFetchMeta bool, showDir DirOpt) <-chan *ClientContent
// Bucket operations
MakeBucket(region string, ignoreExisting, withLock bool) *probe.Error
SetObjectLockConfig(mode *minio.RetentionMode, validity *uint, unit *minio.ValidityUnit) *probe.Error
GetObjectLockConfig() (mode *minio.RetentionMode, validity *uint, unit *minio.ValidityUnit, perr *probe.Error)
MakeBucket(ctx context.Context, region string, ignoreExisting, withLock bool) *probe.Error
// Object lock config
SetObjectLockConfig(ctx context.Context, mode minio.RetentionMode, validity uint64, unit minio.ValidityUnit) *probe.Error
GetObjectLockConfig(ctx context.Context) (mode minio.RetentionMode, validity uint64, unit minio.ValidityUnit, perr *probe.Error)
// Access policy operations.
GetAccess() (access string, policyJSON string, error *probe.Error)
GetAccessRules() (policyRules map[string]string, error *probe.Error)
SetAccess(access string, isJSON bool) *probe.Error
GetAccess(ctx context.Context) (access string, policyJSON string, error *probe.Error)
GetAccessRules(ctx context.Context) (policyRules map[string]string, error *probe.Error)
SetAccess(ctx context.Context, access string, isJSON bool) *probe.Error
// I/O operations
Copy(source string, size int64, progress io.Reader, srcSSE, tgtSSE encrypt.ServerSide, metadata map[string]string) *probe.Error
Copy(ctx context.Context, source string, size int64, progress io.Reader, srcSSE, tgtSSE encrypt.ServerSide, metadata map[string]string, disableMultipart, isPreserve bool) *probe.Error
// Runs select expression on object storage on specific files.
Select(expression string, sse encrypt.ServerSide, opts SelectObjectOpts) (io.ReadCloser, *probe.Error)
Select(ctx context.Context, expression string, sse encrypt.ServerSide, opts SelectObjectOpts) (io.ReadCloser, *probe.Error)
// I/O operations with metadata.
Get(sse encrypt.ServerSide) (reader io.ReadCloser, err *probe.Error)
Put(ctx context.Context, reader io.Reader, size int64, metadata map[string]string, progress io.Reader, sse encrypt.ServerSide) (n int64, err *probe.Error)
Get(ctx context.Context, sse encrypt.ServerSide) (reader io.ReadCloser, err *probe.Error)
Put(ctx context.Context, reader io.Reader, size int64, metadata map[string]string, progress io.Reader, sse encrypt.ServerSide, md5, disableMultipart, isPreserve bool) (n int64, err *probe.Error)
// Object Locking related API
PutObjectRetention(mode *minio.RetentionMode, retainUntilDate *time.Time) *probe.Error
PutObjectRetention(ctx context.Context, mode minio.RetentionMode, retainUntilDate time.Time, bypassGovernance bool) *probe.Error
PutObjectLegalHold(ctx context.Context, hold minio.LegalHoldStatus) *probe.Error
// I/O operations with expiration
ShareDownload(expires time.Duration) (string, *probe.Error)
ShareDownload(ctx context.Context, expires time.Duration) (string, *probe.Error)
ShareUpload(bool, time.Duration, string) (string, map[string]string, *probe.Error)
// Watch events
Watch(params watchParams) (*watchObject, *probe.Error)
Watch(ctx context.Context, options WatchOptions) (*WatchObject, *probe.Error)
// Delete operations
Remove(isIncomplete, isRemoveBucket bool, contentCh <-chan *clientContent) (errorCh <-chan *probe.Error)
Remove(ctx context.Context, isIncomplete, isRemoveBucket, isBypass bool, contentCh <-chan *ClientContent) (errorCh <-chan *probe.Error)
// GetURL returns back internal url
GetURL() clientURL
GetURL() ClientURL
AddUserAgent(app, version string)
// Tagging operations
GetTags(ctx context.Context) (*tags.Tags, *probe.Error)
SetTags(ctx context.Context, tags string) *probe.Error
DeleteTags(ctx context.Context) *probe.Error
// Lifecycle operations
GetLifecycle(ctx context.Context) (ilm.LifecycleConfiguration, *probe.Error)
SetLifecycle(ctx context.Context, lfcCfg ilm.LifecycleConfiguration) *probe.Error
}
// Content container for content metadata
type clientContent struct {
URL clientURL
// ClientContent - Content container for content metadata
type ClientContent struct {
URL ClientURL
Time time.Time
Size int64
Type os.FileMode
@@ -97,23 +110,29 @@ type clientContent struct {
UserMetadata map[string]string
ETag string
Expires time.Time
EncryptionHeaders map[string]string
Retention bool
Err *probe.Error
RetentionEnabled bool
RetentionMode string
RetentionDuration string
BypassGovernance bool
LegalHoldEnabled bool
LegalHold string
Err *probe.Error
}
// Config - see http://docs.amazonwebservices.com/AmazonS3/latest/dev/index.html?RESTAuthentication.html
type Config struct {
AccessKey string
SecretKey string
Signature string
HostURL string
AppName string
AppVersion string
AppComments []string
Debug bool
Insecure bool
Lookup minio.BucketLookupType
AccessKey string
SecretKey string
SessionToken string
Signature string
HostURL string
AppName string
AppVersion string
AppComments []string
Debug bool
Insecure bool
Lookup minio.BucketLookupType
}
// SelectObjectOpts - opts entered for select API
+217 -100
View File
@@ -104,10 +104,10 @@ func getEncKeys(ctx *cli.Context) (map[string][]prefixSSEPair, *probe.Error) {
// Check if the passed URL represents a folder. It may or may not exist yet.
// If it exists, we can easily check if it is a folder, if it doesn't exist,
// we can guess if the url is a folder from how it looks.
func isAliasURLDir(aliasURL string, keys map[string][]prefixSSEPair) bool {
func isAliasURLDir(ctx context.Context, aliasURL string, keys map[string][]prefixSSEPair) bool {
// If the target url exists, check if it is a directory
// and return immediately.
_, targetContent, err := url2Stat(aliasURL, false, false, keys)
_, targetContent, err := url2Stat(ctx, aliasURL, false, keys)
if err == nil {
return targetContent.Type.IsDir()
}
@@ -141,71 +141,127 @@ func isAliasURLDir(aliasURL string, keys map[string][]prefixSSEPair) bool {
}
// getSourceStreamMetadataFromURL gets a reader from URL.
func getSourceStreamMetadataFromURL(urlStr string, encKeyDB map[string][]prefixSSEPair) (reader io.ReadCloser,
func getSourceStreamMetadataFromURL(ctx context.Context, urlStr string, encKeyDB map[string][]prefixSSEPair) (reader io.ReadCloser,
metadata map[string]string, err *probe.Error) {
alias, urlStrFull, _, err := expandAlias(urlStr)
if err != nil {
return nil, nil, err.Trace(urlStr)
}
sseKey := getSSE(urlStr, encKeyDB[alias])
return getSourceStream(alias, urlStrFull, true, sseKey)
return getSourceStream(ctx, alias, urlStrFull, true, sseKey, false)
}
// getSourceStreamFromURL gets a reader from URL.
func getSourceStreamFromURL(urlStr string, encKeyDB map[string][]prefixSSEPair) (reader io.ReadCloser, err *probe.Error) {
func getSourceStreamFromURL(ctx context.Context, urlStr string, encKeyDB map[string][]prefixSSEPair) (reader io.ReadCloser, err *probe.Error) {
alias, urlStrFull, _, err := expandAlias(urlStr)
if err != nil {
return nil, err.Trace(urlStr)
}
sse := getSSE(urlStr, encKeyDB[alias])
reader, _, err = getSourceStream(alias, urlStrFull, false, sse)
reader, _, err = getSourceStream(ctx, alias, urlStrFull, false, sse, false)
return reader, err
}
func probeContentType(reader io.Reader) (ctype string, err *probe.Error) {
ctype = "application/octet-stream"
// Read a chunk to decide between utf-8 text and binary
if s, ok := reader.(io.Seeker); ok {
var buf [512]byte
n, _ := io.ReadFull(reader, buf[:])
if n <= 0 {
return ctype, nil
}
kind, e := filetype.Match(buf[:n])
if e != nil {
return ctype, probe.NewError(e)
}
// rewind to output whole file
if _, e = s.Seek(0, io.SeekStart); e != nil {
return ctype, probe.NewError(e)
}
if kind.MIME.Value != "" {
ctype = kind.MIME.Value
}
}
return ctype, nil
}
// Verify if reader is a generic ReaderAt
func isReadAt(reader io.Reader) (ok bool) {
var v *os.File
v, ok = reader.(*os.File)
if ok {
// Stdin, Stdout and Stderr all have *os.File type
// 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{
"/dev/stdin",
"/dev/stdout",
"/dev/stderr",
} {
if f == v.Name() {
ok = false
break
}
}
}
return
}
// getSourceStream gets a reader from URL.
func getSourceStream(alias string, urlStr string, fetchStat bool, sse encrypt.ServerSide) (reader io.ReadCloser, metadata map[string]string, err *probe.Error) {
func getSourceStream(ctx context.Context, alias string, urlStr string, fetchStat bool, sse encrypt.ServerSide, preserve bool) (reader io.ReadCloser, metadata map[string]string, err *probe.Error) {
sourceClnt, err := newClientFromAlias(alias, urlStr)
if err != nil {
return nil, nil, err.Trace(alias, urlStr)
}
reader, err = sourceClnt.Get(sse)
reader, err = sourceClnt.Get(ctx, sse)
if err != nil {
return nil, nil, err.Trace(alias, urlStr)
}
metadata = make(map[string]string)
if fetchStat {
st, err := sourceClnt.Stat(false, true, false, sse)
if err != nil {
return nil, nil, err.Trace(alias, urlStr)
var st *ClientContent
mo, mok := reader.(*minio.Object)
if mok {
oinfo, e := mo.Stat()
if e != nil {
return nil, nil, probe.NewError(e).Trace(alias, urlStr)
}
st = &ClientContent{}
st.Time = oinfo.LastModified
st.Size = oinfo.Size
st.ETag = oinfo.ETag
st.Expires = oinfo.Expires
st.Type = os.FileMode(0664)
st.Metadata = map[string]string{}
for k := range oinfo.Metadata {
st.Metadata[k] = oinfo.Metadata.Get(k)
}
st.ETag = oinfo.ETag
} else {
st, err = sourceClnt.Stat(ctx, false, preserve, sse)
if err != nil {
return nil, nil, err.Trace(alias, urlStr)
}
}
for k, v := range st.Metadata {
if httpguts.ValidHeaderFieldName(k) &&
httpguts.ValidHeaderFieldValue(v) {
metadata[k] = v
}
}
// If our reader is a seeker try to detect content-type further.
if s, ok := reader.(io.ReadSeeker); ok {
// All unrecognized files have `application/octet-stream`
// So we continue our detection process.
if ctype := metadata["Content-Type"]; ctype == "application/octet-stream" {
// Read a chunk to decide between utf-8 text and binary
var buf [512]byte
n, _ := io.ReadFull(reader, buf[:])
if n > 0 {
kind, e := filetype.Match(buf[:n])
if e != nil {
return nil, nil, probe.NewError(e)
}
// rewind to output whole file
if _, e := s.Seek(0, io.SeekStart); e != nil {
return nil, nil, probe.NewError(e)
}
ctype = kind.MIME.Value
if ctype == "" {
ctype = "application/octet-stream"
}
metadata["Content-Type"] = ctype
// All unrecognized files have `application/octet-stream`
// So we continue our detection process.
if ctype := metadata["Content-Type"]; ctype == "application/octet-stream" {
// Continue probing content-type if its filesystem stream.
if !mok {
metadata["Content-Type"], err = probeContentType(reader)
if err != nil {
return nil, nil, err.Trace(alias, urlStr)
}
}
}
@@ -234,19 +290,29 @@ func putTargetRetention(ctx context.Context, alias string, urlStr string, metada
retainUntilDate = t.UTC()
}
}
if err := targetClnt.PutObjectRetention(&lockMode, &retainUntilDate); err != nil {
if err := targetClnt.PutObjectRetention(ctx, lockMode, retainUntilDate, false); err != nil {
return err.Trace(alias, urlStr)
}
return nil
}
// putTargetStream writes to URL from Reader.
func putTargetStream(ctx context.Context, alias string, urlStr string, reader io.Reader, size int64, metadata map[string]string, progress io.Reader, sse encrypt.ServerSide) (int64, *probe.Error) {
func putTargetStream(ctx context.Context, alias, urlStr, mode, until, legalHold string, reader io.Reader, size int64, metadata map[string]string, progress io.Reader, sse encrypt.ServerSide, md5, disableMultipart, preserve bool) (int64, *probe.Error) {
targetClnt, err := newClientFromAlias(alias, urlStr)
if err != nil {
return 0, err.Trace(alias, urlStr)
}
n, err := targetClnt.Put(ctx, reader, size, metadata, progress, sse)
if mode != "" {
metadata[AmzObjectLockMode] = mode
}
if until != "" {
metadata[AmzObjectLockRetainUntilDate] = until
}
if legalHold != "" {
metadata[AmzObjectLockLegalHold] = legalHold
}
n, err := targetClnt.Put(ctx, reader, size, metadata, progress, sse, md5, disableMultipart, preserve)
if err != nil {
return n, err.Trace(alias, urlStr)
}
@@ -254,25 +320,32 @@ func putTargetStream(ctx context.Context, alias string, urlStr string, reader io
}
// putTargetStreamWithURL writes to URL from reader. If length=-1, read until EOF.
func putTargetStreamWithURL(urlStr string, reader io.Reader, size int64, sse encrypt.ServerSide) (int64, *probe.Error) {
func putTargetStreamWithURL(urlStr string, reader io.Reader, size int64, sse encrypt.ServerSide, md5, disableMultipart, preserve bool, metadata map[string]string) (int64, *probe.Error) {
alias, urlStrFull, _, err := expandAlias(urlStr)
if err != nil {
return 0, err.Trace(alias, urlStr)
}
contentType := guessURLContentType(urlStr)
metadata := map[string]string{
"Content-Type": contentType,
if metadata == nil {
metadata = map[string]string{}
}
return putTargetStream(context.Background(), alias, urlStrFull, reader, size, metadata, nil, sse)
metadata["Content-Type"] = contentType
return putTargetStream(context.Background(), alias, urlStrFull, "", "", "", reader, size, metadata, nil, sse, md5, disableMultipart, preserve)
}
// copySourceToTargetURL copies to targetURL from source.
func copySourceToTargetURL(alias string, urlStr string, source string, size int64, progress io.Reader, srcSSE, tgtSSE encrypt.ServerSide, metadata map[string]string) *probe.Error {
func copySourceToTargetURL(ctx context.Context, alias, urlStr, source, mode, until, legalHold string, size int64, progress io.Reader, srcSSE, tgtSSE encrypt.ServerSide, metadata map[string]string, disableMultipart bool) *probe.Error {
targetClnt, err := newClientFromAlias(alias, urlStr)
if err != nil {
return err.Trace(alias, urlStr)
}
err = targetClnt.Copy(source, size, progress, srcSSE, tgtSSE, metadata)
metadata[AmzObjectLockMode] = mode
metadata[AmzObjectLockRetainUntilDate] = until
metadata[AmzObjectLockLegalHold] = legalHold
err = targetClnt.Copy(ctx, source, size, progress, srcSSE, tgtSSE, metadata, disableMultipart, false)
if err != nil {
return err.Trace(alias, urlStr)
}
@@ -287,7 +360,7 @@ func filterMetadata(metadata map[string]string) map[string]string {
}
}
for k := range metadata {
if strings.HasPrefix(http.CanonicalHeaderKey(k), "X-Amz-Server-Side-Encryption-") {
if strings.HasPrefix(http.CanonicalHeaderKey(k), http.CanonicalHeaderKey(serverEncryptionKeyPrefix)) {
delete(newMetadata, k)
}
}
@@ -296,23 +369,23 @@ func filterMetadata(metadata map[string]string) map[string]string {
// getAllMetadata - returns a map of user defined function
// by combining the usermetadata of object and values passed by attr keyword
func getAllMetadata(sourceAlias, sourceURLStr string, srcSSE encrypt.ServerSide, urls URLs) (map[string]string, *probe.Error) {
func getAllMetadata(ctx context.Context, sourceAlias, sourceURLStr string, srcSSE encrypt.ServerSide, urls URLs, preserve bool) (map[string]string, *probe.Error) {
metadata := make(map[string]string)
sourceClnt, err := newClientFromAlias(sourceAlias, sourceURLStr)
if err != nil {
return nil, err.Trace(sourceAlias, sourceURLStr)
}
st, err := sourceClnt.Stat(false, true, false, srcSSE)
st, err := sourceClnt.Stat(ctx, false, preserve, srcSSE)
if err != nil {
return nil, err.Trace(sourceAlias, sourceURLStr)
}
for k, v := range st.Metadata {
metadata[k] = v
metadata[http.CanonicalHeaderKey(k)] = v
}
for k, v := range urls.TargetContent.UserMetadata {
metadata[k] = v
metadata[http.CanonicalHeaderKey(k)] = v
}
return filterMetadata(metadata), nil
@@ -321,7 +394,7 @@ func getAllMetadata(sourceAlias, sourceURLStr string, srcSSE encrypt.ServerSide,
// uploadSourceToTargetURL - uploads to targetURL from source.
// optionally optimizes copy for object sizes <= 5GiB by using
// server side copy operation.
func uploadSourceToTargetURL(ctx context.Context, urls URLs, progress io.Reader, encKeyDB map[string][]prefixSSEPair) URLs {
func uploadSourceToTargetURL(ctx context.Context, urls URLs, progress io.Reader, encKeyDB map[string][]prefixSSEPair, preserve bool) URLs {
sourceAlias := urls.SourceAlias
sourceURL := urls.SourceContent.URL
targetAlias := urls.TargetAlias
@@ -335,59 +408,131 @@ func uploadSourceToTargetURL(ctx context.Context, urls URLs, progress io.Reader,
var err *probe.Error
var metadata = map[string]string{}
var mode, until, legalHold string
// add object retention fields in metadata for target, if target wants
// to override defaults from source, usually happens in `cp` command.
// for the most part source metadata is copied over.
if urls.TargetContent.RetentionEnabled {
m := minio.RetentionMode(strings.ToUpper(urls.TargetContent.RetentionMode))
var dur uint64
var unit minio.ValidityUnit
dur, unit, err = parseRetentionValidity(urls.TargetContent.RetentionDuration, m)
if err != nil {
return urls.WithError(err.Trace(targetURL.String()))
}
mode = urls.TargetContent.RetentionMode
until, err = getRetainUntilDate(dur, unit)
if err != nil {
return urls.WithError(err.Trace(sourceURL.String()))
}
}
// add object legal hold fields in metadata for target, if target wants
// to override defaults from source, usually happens in `cp` command.
// for the most part source metadata is copied over.
if urls.TargetContent.LegalHoldEnabled {
switch minio.LegalHoldStatus(urls.TargetContent.LegalHold) {
case minio.LegalHoldDisabled:
case minio.LegalHoldEnabled:
default:
return urls.WithError(errInvalidArgument().Trace(urls.TargetContent.LegalHold))
}
legalHold = urls.TargetContent.LegalHold
}
for k, v := range urls.SourceContent.UserMetadata {
metadata[http.CanonicalHeaderKey(k)] = v
}
for k, v := range urls.SourceContent.Metadata {
metadata[http.CanonicalHeaderKey(k)] = v
}
// Optimize for server side copy if the host is same.
if sourceAlias == targetAlias {
for k, v := range urls.SourceContent.UserMetadata {
metadata[k] = v
}
for k, v := range urls.SourceContent.Metadata {
metadata[k] = v
}
// If no metadata populated already by the caller
// just do a Stat() to obtain the metadata.
if len(metadata) == 0 {
metadata, err = getAllMetadata(sourceAlias, sourceURL.String(), srcSSE, urls)
if len(metadata) == 0 && preserve {
metadata, err = getAllMetadata(ctx, sourceAlias, sourceURL.String(), srcSSE, urls, preserve)
if err != nil {
return urls.WithError(err.Trace(sourceURL.String()))
}
}
// Get metadata from target content as well
for k, v := range urls.TargetContent.Metadata {
metadata[http.CanonicalHeaderKey(k)] = v
}
// Get userMetadata from target content as well
for k, v := range urls.TargetContent.UserMetadata {
metadata[http.CanonicalHeaderKey(k)] = v
}
sourcePath := filepath.ToSlash(sourceURL.Path)
if urls.SourceContent.Retention {
if urls.SourceContent.RetentionEnabled {
err = putTargetRetention(ctx, targetAlias, targetURL.String(), metadata)
return urls.WithError(err.Trace(sourceURL.String()))
}
err = copySourceToTargetURL(targetAlias, targetURL.String(), sourcePath, length,
progress, srcSSE, tgtSSE, filterMetadata(metadata))
err = copySourceToTargetURL(ctx, targetAlias, targetURL.String(), sourcePath, mode, until,
legalHold, length, progress, srcSSE, tgtSSE, filterMetadata(metadata), urls.DisableMultipart)
} else {
if len(metadata) == 0 {
metadata, err = getAllMetadata(sourceAlias, sourceURL.String(), srcSSE, urls)
if err != nil {
return urls.WithError(err.Trace(sourceURL.String()))
if urls.SourceContent.RetentionEnabled {
// If no metadata populated already by the caller
// just do a Stat() to obtain the metadata.
if len(metadata) == 0 && preserve {
metadata, err = getAllMetadata(ctx, sourceAlias, sourceURL.String(), srcSSE, urls, preserve)
if err != nil {
return urls.WithError(err.Trace(sourceURL.String()))
}
}
}
if urls.SourceContent.Retention {
// Get metadata from target content as well
for k, v := range urls.TargetContent.Metadata {
metadata[http.CanonicalHeaderKey(k)] = v
}
// Get userMetadata from target content as well
for k, v := range urls.TargetContent.UserMetadata {
metadata[http.CanonicalHeaderKey(k)] = v
}
err = putTargetRetention(ctx, targetAlias, targetURL.String(), metadata)
return urls.WithError(err.Trace(sourceURL.String()))
}
var reader io.ReadCloser
// Proceed with regular stream copy.
reader, metadata, err = getSourceStream(sourceAlias, sourceURL.String(), true, srcSSE)
reader, metadata, err = getSourceStream(ctx, sourceAlias, sourceURL.String(), true, srcSSE, preserve)
if err != nil {
return urls.WithError(err.Trace(sourceURL.String()))
}
defer reader.Close()
// Get metadata from target content as well
for k, v := range urls.TargetContent.Metadata {
metadata[k] = v
metadata[http.CanonicalHeaderKey(k)] = v
}
// Get userMetadata from target content as well
for k, v := range urls.TargetContent.UserMetadata {
metadata[k] = v
metadata[http.CanonicalHeaderKey(k)] = v
}
if isReadAt(reader) {
_, err = putTargetStream(ctx, targetAlias, targetURL.String(), mode, until,
legalHold, reader, length, filterMetadata(metadata),
progress, tgtSSE, urls.MD5, urls.DisableMultipart, preserve)
} else {
_, err = putTargetStream(ctx, targetAlias, targetURL.String(), mode, until,
legalHold, io.LimitReader(reader, length),
length, filterMetadata(metadata), progress, tgtSSE, urls.MD5,
urls.DisableMultipart, preserve)
}
_, err = putTargetStream(ctx, targetAlias, targetURL.String(), reader, length, filterMetadata(metadata),
progress, tgtSSE)
}
if err != nil {
return urls.WithError(err.Trace(sourceURL.String()))
@@ -415,9 +560,9 @@ func newClientFromAlias(alias, urlStr string) (Client, *probe.Error) {
return fsClient, nil
}
s3Config := newS3Config(urlStr, hostCfg)
s3Config := NewS3Config(urlStr, hostCfg)
s3Client, err := s3New(s3Config)
s3Client, err := S3New(s3Config)
if err != nil {
return nil, err.Trace(alias, urlStr)
}
@@ -440,31 +585,3 @@ func newClient(aliasedURL string) (Client, *probe.Error) {
}
return newClientFromAlias(alias, urlStrFull)
}
// Return the file attribute value present in metadata
func getFileAttrMeta(sURLs URLs, encKeyDB map[string][]prefixSSEPair) (string, *probe.Error) {
sourceAlias := sURLs.SourceAlias
sourceURL := sURLs.SourceContent.URL
sourcePath := filepath.ToSlash(filepath.Join(sourceAlias, sURLs.SourceContent.URL.Path))
srcSSE := getSSE(sourcePath, encKeyDB[sourceAlias])
statSourceURL := sURLs.SourceAlias + getKey(sURLs.SourceContent)
srcClt, err := newClient(statSourceURL)
if err != nil {
return "", err.Trace(sourceURL.String())
}
sourceMeta, err := srcClt.Stat(false, true, true, srcSSE)
if err != nil {
return "", err.Trace(sourceURL.String())
}
attrValue := ""
if sourceMeta.Metadata["X-Amz-Meta-Mc-Attrs"] != "" {
attrValue = sourceMeta.Metadata["X-Amz-Meta-Mc-Attrs"]
} else if sourceMeta.Metadata["X-Amz-Meta-S3cmd-Attrs"] != "" {
attrValue = sourceMeta.Metadata["X-Amz-Meta-S3cmd-Attrs"]
} else if sourceMeta.Metadata["mc-attrs"] != "" {
attrValue = sourceMeta.Metadata["mc-attrs"]
}
return attrValue, nil
}
+8 -4
View File
@@ -23,8 +23,8 @@ import (
"runtime"
"strings"
"github.com/minio/mc/pkg/console"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio/pkg/console"
"github.com/minio/minio/pkg/quick"
)
@@ -137,7 +137,7 @@ func fixConfigV6ForHosts() {
newCfgV6.Aliases[k] = v
}
url := &clientURL{}
url := &ClientURL{}
// Copy hosts.
for host, hostCfgV6 := range brokenMcCfgV6.Data().(*configV6).Hosts {
// Already fixed - Copy and move on.
@@ -259,6 +259,10 @@ func fixConfigLocation() {
// If there is a config at legacyLoc+".exe", rename it.
legacyLoc := mcCustomConfigDir + ".exe"
unusedLoc := mcCustomConfigDir + ".unused"
s, err := os.Stat(legacyLoc)
if err != nil || !s.IsDir() {
return
}
_ = os.Rename(legacyLoc, unusedLoc)
return
}
@@ -269,8 +273,8 @@ func fixConfigLocation() {
wantExists := !os.IsNotExist(err)
legFileName := mcCustomConfigDir + ".exe"
_, err = os.Stat(legFileName)
legExists := !os.IsNotExist(err)
stat, err := os.Stat(legFileName)
legExists := !os.IsNotExist(err) && stat.IsDir()
switch {
case legExists && wantExists:
// Both exist and mc was called with legacy path (.exe)
+113 -49
View File
@@ -17,15 +17,23 @@
package cmd
import (
"bufio"
"context"
"fmt"
"math/rand"
"os"
"time"
"github.com/fatih/color"
"github.com/minio/cli"
"github.com/minio/mc/pkg/console"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio-go/v6"
"github.com/minio/minio/pkg/console"
"golang.org/x/crypto/ssh/terminal"
)
const cred = "YellowItalics"
var hostAddFlags = []cli.Flag{
cli.StringFlag{
Name: "lookup",
@@ -42,7 +50,7 @@ var configHostAddCmd = cli.Command{
ShortName: "a",
Usage: "add a new host to configuration file",
Action: mainConfigHostAdd,
Before: setGlobalsFromContext,
Before: initBeforeRunningCmd,
Flags: append(hostAddFlags, globalFlags...),
HideHelpCommand: true,
CustomHelpTemplate: `NAME:
@@ -71,24 +79,34 @@ EXAMPLES:
{{.Prompt}} {{.HelpName}} mys3 https://s3.amazonaws.com \
BKIKJAA5BMMU2RHO6IBB V8f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12
{{.EnableHistory}}
4. Add Amazon S3 storage service under "mys3" alias, prompting for keys.
{{.Prompt}} {{.HelpName}} mys3 https://s3.amazonaws.com --api "s3v4" --lookup "dns"
Enter Access Key: BKIKJAA5BMMU2RHO6IBB
Enter Secret Key: V8f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12
5. Add Amazon S3 storage service under "mys3" alias using piped keys.
{{.DisableHistory}}
{{.Prompt}} echo -e "BKIKJAA5BMMU2RHO6IBB\nV8f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12" | \
{{.HelpName}} mys3 https://s3.amazonaws.com --api "s3v4" --lookup "dns"
{{.EnableHistory}}
`,
}
// checkConfigHostAddSyntax - verifies input arguments to 'config host add'.
func checkConfigHostAddSyntax(ctx *cli.Context) {
func checkConfigHostAddSyntax(ctx *cli.Context, accessKey string, secretKey string) {
args := ctx.Args()
argsNr := len(args)
if argsNr < 4 || argsNr > 5 {
if argsNr > 4 || argsNr < 2 {
fatalIf(errInvalidArgument().Trace(ctx.Args().Tail()...),
"Incorrect number of arguments for host add command.")
}
alias := args.Get(0)
alias := cleanAlias(args.Get(0))
url := args.Get(1)
accessKey := args.Get(2)
secretKey := args.Get(3)
api := ctx.String("api")
bucketLookup := ctx.String("lookup")
if !isValidAlias(alias) {
fatalIf(errInvalidAlias(alias), "Invalid alias.")
}
@@ -142,7 +160,7 @@ func addHost(alias string, hostCfgV9 hostConfigV9) {
// probeS3Signature - auto probe S3 server signature: issue a Stat call
// using v4 signature then v2 in case of failure.
func probeS3Signature(accessKey, secretKey, url string) (string, *probe.Error) {
func probeS3Signature(ctx context.Context, accessKey, secretKey, url string) (string, *probe.Error) {
probeBucketName := randString(60, rand.NewSource(time.Now().UnixNano()), "probe-bucket-sign-")
// Test s3 connection for API auto probe
s3Config := &Config{
@@ -150,45 +168,51 @@ func probeS3Signature(accessKey, secretKey, url string) (string, *probe.Error) {
Insecure: globalInsecure,
AccessKey: accessKey,
SecretKey: secretKey,
Signature: "s3v4",
HostURL: urlJoinPath(url, probeBucketName),
Debug: globalDebug,
}
s3Client, err := s3New(s3Config)
if err != nil {
return "", err
}
if _, err = s3Client.Stat(false, false, false, nil); err != nil {
switch err.ToGoError().(type) {
case BucketDoesNotExist:
// Bucket doesn't exist, means signature probing worked V4.
default:
// Attempt with signature v2, since v4 seem to have failed.
s3Config.Signature = "s3v2"
s3Client, err = s3New(s3Config)
if err != nil {
return "", err
}
if _, err = s3Client.Stat(false, false, false, nil); err != nil {
switch err.ToGoError().(type) {
case BucketDoesNotExist:
// Bucket doesn't exist, means signature probing worked with V2.
default:
return "", err
}
}
probeSignatureType := func(stype string) (string, *probe.Error) {
s3Config.Signature = stype
s3Client, err := S3New(s3Config)
if err != nil {
return "", err
}
if _, err := s3Client.Stat(ctx, false, false, nil); err != nil {
e := err.ToGoError()
if _, ok := e.(BucketDoesNotExist); ok {
// Bucket doesn't exist, means signature probing worked successfully.
return stype, nil
}
// AccessDenied means Stat() is not allowed but credentials are valid.
// AccessDenied is only returned when policy doesn't allow HeadBucket
// operations.
if minio.ToErrorResponse(err.ToGoError()).Code == "AccessDenied" {
return stype, nil
}
// For any other errors we fail.
return "", err.Trace(s3Config.Signature)
}
return stype, nil
}
return s3Config.Signature, nil
stype, err := probeSignatureType("s3v4")
if err != nil {
if stype, err = probeSignatureType("s3v2"); err != nil {
return "", err.Trace("s3v4", "s3v2")
}
return stype, nil
}
return stype, nil
}
// buildS3Config constructs an S3 Config and does
// BuildS3Config constructs an S3 Config and does
// signature auto-probe when needed.
func buildS3Config(url, accessKey, secretKey, api, lookup string) (*Config, *probe.Error) {
func BuildS3Config(ctx context.Context, url, accessKey, secretKey, api, lookup string) (*Config, *probe.Error) {
s3Config := newS3Config(url, &hostConfigV9{
s3Config := NewS3Config(url, &hostConfigV9{
AccessKey: accessKey,
SecretKey: secretKey,
URL: url,
@@ -202,7 +226,7 @@ func buildS3Config(url, accessKey, secretKey, api, lookup string) (*Config, *pro
return s3Config, nil
}
// Probe S3 signature version
api, err := probeS3Signature(accessKey, secretKey, url)
api, err := probeS3Signature(ctx, accessKey, secretKey, url)
if err != nil {
return nil, err.Trace(url, accessKey, secretKey, api, lookup)
}
@@ -212,23 +236,63 @@ func buildS3Config(url, accessKey, secretKey, api, lookup string) (*Config, *pro
return s3Config, nil
}
func mainConfigHostAdd(ctx *cli.Context) error {
checkConfigHostAddSyntax(ctx)
// fetchHostKeys - returns the user accessKey and secretKey
func fetchHostKeys(args cli.Args) (string, string) {
accessKey := ""
secretKey := ""
console.SetColor(cred, color.New(color.FgYellow, color.Italic))
isTerminal := terminal.IsTerminal(int(os.Stdin.Fd()))
reader := bufio.NewReader(os.Stdin)
argsNr := len(args)
if argsNr == 2 {
if isTerminal {
fmt.Printf("%s", console.Colorize(cred, "Enter Access Key: "))
}
value, _, _ := reader.ReadLine()
accessKey = string(value)
} else {
accessKey = args.Get(2)
}
if argsNr == 2 || argsNr == 3 {
if isTerminal {
fmt.Printf("%s", console.Colorize(cred, "Enter Secret Key: "))
bytePassword, _ := terminal.ReadPassword(int(os.Stdin.Fd()))
fmt.Printf("\n")
secretKey = string(bytePassword)
} else {
value, _, _ := reader.ReadLine()
secretKey = string(value)
}
} else {
secretKey = args.Get(3)
}
return accessKey, secretKey
}
func mainConfigHostAdd(cli *cli.Context) error {
console.SetColor("HostMessage", color.New(color.FgGreen))
var (
args = ctx.Args()
url = trimTrailingSeparator(args.Get(1))
accessKey = args.Get(2)
secretKey = args.Get(3)
api = ctx.String("api")
lookup = ctx.String("lookup")
args = cli.Args()
alias = cleanAlias(args.Get(0))
url = trimTrailingSeparator(args.Get(1))
api = cli.String("api")
lookup = cli.String("lookup")
)
accessKey, secretKey := fetchHostKeys(args)
checkConfigHostAddSyntax(cli, accessKey, secretKey)
s3Config, err := buildS3Config(url, accessKey, secretKey, api, lookup)
fatalIf(err.Trace(ctx.Args()...), "Unable to initialize new config from the provided credentials.")
ctx, cancelHostAdd := context.WithCancel(globalContext)
defer cancelHostAdd()
addHost(ctx.Args().Get(0), hostConfigV9{
s3Config, err := BuildS3Config(ctx, url, accessKey, secretKey, api, lookup)
fatalIf(err.Trace(cli.Args()...), "Unable to initialize new config from the provided credentials.")
addHost(alias, hostConfigV9{
URL: s3Config.HostURL,
AccessKey: s3Config.AccessKey,
SecretKey: s3Config.SecretKey,
+5 -11
View File
@@ -22,7 +22,7 @@ import (
"github.com/fatih/color"
"github.com/minio/cli"
"github.com/minio/mc/pkg/console"
"github.com/minio/minio/pkg/console"
)
var configHostListCmd = cli.Command{
@@ -30,7 +30,7 @@ var configHostListCmd = cli.Command{
ShortName: "ls",
Usage: "list hosts in configuration file",
Action: mainConfigHostList,
Before: setGlobalsFromContext,
Before: initBeforeRunningCmd,
Flags: globalFlags,
HideHelpCommand: true,
CustomHelpTemplate: `NAME:
@@ -59,13 +59,6 @@ func checkConfigHostListSyntax(ctx *cli.Context) {
fatalIf(errInvalidArgument().Trace(args...),
"Incorrect number of arguments to list hosts.")
}
if args.Get(0) != "" {
if !isValidAlias(args.Get(0)) {
fatalIf(errDummy().Trace(args.Get(0)),
"Invalid alias `"+args.Get(0)+"`.")
}
}
}
func mainConfigHostList(ctx *cli.Context) error {
@@ -79,8 +72,9 @@ func mainConfigHostList(ctx *cli.Context) error {
console.SetColor("API", color.New(color.FgBlue))
console.SetColor("Lookup", color.New(color.FgCyan))
args := ctx.Args()
listHosts(args.Get(0)) // List all configured hosts.
alias := cleanAlias(ctx.Args().Get(0))
listHosts(alias) // List all configured hosts.
return nil
}
+5 -5
View File
@@ -19,7 +19,7 @@ package cmd
import (
"github.com/fatih/color"
"github.com/minio/cli"
"github.com/minio/mc/pkg/console"
"github.com/minio/minio/pkg/console"
)
var configHostRemoveCmd = cli.Command{
@@ -27,7 +27,7 @@ var configHostRemoveCmd = cli.Command{
ShortName: "rm",
Usage: "remove a host from configuration file",
Action: mainConfigHostRemove,
Before: setGlobalsFromContext,
Before: initBeforeRunningCmd,
Flags: globalFlags,
HideHelpCommand: true,
CustomHelpTemplate: `NAME:
@@ -55,9 +55,9 @@ func checkConfigHostRemoveSyntax(ctx *cli.Context) {
"Incorrect number of arguments for remove host command.")
}
if !isValidAlias(args.Get(0)) {
fatalIf(errDummy().Trace(args.Get(0)),
"Invalid alias `"+args.Get(0)+"`.")
alias := cleanAlias(args.Get(0))
if !isValidAlias(alias) {
fatalIf(errDummy().Trace(alias), "Invalid alias `"+alias+"`.")
}
}
+1 -2
View File
@@ -19,15 +19,14 @@ package cmd
import (
"github.com/minio/cli"
json "github.com/minio/mc/pkg/colorjson"
"github.com/minio/mc/pkg/console"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio/pkg/console"
)
var configHostCmd = cli.Command{
Name: "host",
Usage: "add, remove and list hosts in configuration file",
Action: mainConfigHost,
Before: setGlobalsFromContext,
Flags: globalFlags,
Subcommands: []cli.Command{
configHostAddCmd,
-1
View File
@@ -37,7 +37,6 @@ var configCmd = cli.Command{
Name: "config",
Usage: "configure MinIO client",
Action: mainConfig,
Before: setGlobalsFromContext,
HideHelpCommand: true,
Flags: append(configFlags, globalFlags...),
Subcommands: []cli.Command{
+1 -1
View File
@@ -20,8 +20,8 @@ import (
"fmt"
"strings"
"github.com/minio/mc/pkg/console"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio/pkg/console"
"github.com/minio/minio/pkg/quick"
)
+6 -5
View File
@@ -37,11 +37,12 @@ var (
// hostConfig configuration of a host.
type hostConfigV9 struct {
URL string `json:"url"`
AccessKey string `json:"accessKey"`
SecretKey string `json:"secretKey"`
API string `json:"api"`
Lookup string `json:"lookup"`
URL string `json:"url"`
AccessKey string `json:"accessKey"`
SecretKey string `json:"secretKey"`
SessionToken string `json:"sessionToken,omitempty"`
API string `json:"api"`
Lookup string `json:"lookup"`
}
// configV8 config version.
+54 -62
View File
@@ -159,6 +159,14 @@ func isMcConfigExists() bool {
return true
}
// cleanAlias removes any forbidden trailing slashes or backslashes
// before any validation to avoid annoying mc complaints.
func cleanAlias(s string) string {
s = strings.TrimSuffix(s, "/")
s = strings.TrimSuffix(s, "\\")
return s
}
// isValidAlias - Check if alias valid.
func isValidAlias(alias string) bool {
return regexp.MustCompile("^[a-zA-Z][a-zA-Z0-9-_]+$").MatchString(alias)
@@ -200,73 +208,56 @@ func mustGetHostConfig(alias string) *hostConfigV9 {
return hostCfg
}
var (
hostKeys = regexp.MustCompile("^(https?://)(.*?):(.*?)@(.*?)$")
hostKeyTokens = regexp.MustCompile("^(https?://)(.*?):(.*?):(.*?)@(.*?)$")
)
// parse url usually obtained from env.
func parseEnvURL(envURL string) (*url.URL, string, string, *probe.Error) {
u, e := url.Parse(envURL)
func parseEnvURLStr(envURL string) (*url.URL, string, string, string, *probe.Error) {
var accessKey, secretKey, sessionToken string
var parsedURL string
if hostKeyTokens.MatchString(envURL) {
parts := hostKeyTokens.FindStringSubmatch(envURL)
if len(parts) != 6 {
return nil, "", "", "", errInvalidArgument().Trace(envURL)
}
accessKey = parts[2]
secretKey = parts[3]
sessionToken = parts[4]
parsedURL = fmt.Sprintf("%s%s", parts[1], parts[5])
} else if hostKeys.MatchString(envURL) {
parts := hostKeys.FindStringSubmatch(envURL)
if len(parts) != 5 {
return nil, "", "", "", errInvalidArgument().Trace(envURL)
}
accessKey = parts[2]
secretKey = parts[3]
parsedURL = fmt.Sprintf("%s%s", parts[1], parts[4])
}
var u *url.URL
var e error
if parsedURL != "" {
u, e = url.Parse(parsedURL)
} else {
u, e = url.Parse(envURL)
}
if e != nil {
return nil, "", "", probe.NewError(e).Trace(envURL)
return nil, "", "", "", probe.NewError(e)
}
var accessKey, secretKey string
// Check if username:password is provided in URL, with no
// access keys or secret we proceed and perform anonymous
// requests.
if u.User != nil {
accessKey = u.User.Username()
secretKey, _ = u.User.Password()
}
// 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 == "") {
return nil, "", "", errInvalidArgument().Trace(u.String())
return nil, "", "", "", errInvalidArgument().Trace(u.String())
}
// Now that we have validated the URL to be in expected style.
u.User = nil
return u, accessKey, secretKey, nil
}
// parse url usually obtained from env.
func parseEnvURLStr(envURL string) (*url.URL, string, string, *probe.Error) {
var envURLStr string
u, accessKey, secretKey, err := parseEnvURL(envURL)
if err != nil {
// url parsing can fail when accessKey/secretKey contains non url encoded values
// such as #. Strip accessKey/secretKey from envURL and parse again.
re := regexp.MustCompile("^(https?://)(.*?):(.*?)@(.*?)$")
res := re.FindAllStringSubmatch(envURL, -1)
// regex will return full match, scheme, accessKey, secretKey and endpoint:port as
// captured groups.
if res == nil || len(res[0]) != 5 {
return nil, "", "", err
}
for k, v := range res[0] {
if k == 2 {
accessKey = v
}
if k == 3 {
secretKey = v
}
if k == 1 || k == 4 {
envURLStr = fmt.Sprintf("%s%s", envURLStr, v)
}
}
u, _, _, err = parseEnvURL(envURLStr)
if err != nil {
return nil, "", "", err
if accessKey == "" && secretKey == "" {
if u.User != nil {
accessKey = u.User.Username()
secretKey, _ = u.User.Password()
}
}
// Check if username:password is provided in URL, with no
// access keys or secret we proceed and perform anonymous
// requests.
if u.User != nil {
accessKey = u.User.Username()
secretKey, _ = u.User.Password()
}
return u, accessKey, secretKey, nil
return u, accessKey, secretKey, sessionToken, nil
}
const (
@@ -275,16 +266,17 @@ const (
)
func expandAliasFromEnv(envURL string) (*hostConfigV9, *probe.Error) {
u, accessKey, secretKey, err := parseEnvURLStr(envURL)
u, accessKey, secretKey, sessionToken, err := parseEnvURLStr(envURL)
if err != nil {
return nil, err.Trace(envURL)
}
return &hostConfigV9{
URL: u.String(),
API: "S3v4",
AccessKey: accessKey,
SecretKey: secretKey,
URL: u.String(),
API: "S3v4",
AccessKey: accessKey,
SecretKey: secretKey,
SessionToken: sessionToken,
}, nil
}
+73 -23
View File
@@ -21,11 +21,12 @@ import "testing"
// Tests valid host URL functionality.
func TestParseEnvURLStr(t *testing.T) {
testCases := []struct {
hostURL string
accessKey string
secretKey string
hostname string
port string
hostURL string
accessKey string
secretKey string
sessionToken string
hostname string
port string
}{
{
hostURL: "https://minio:minio1#23@localhost:9000",
@@ -48,30 +49,79 @@ func TestParseEnvURLStr(t *testing.T) {
hostname: "localhost",
port: "9000",
},
{
hostURL: "https://minio:minio123:token@localhost:9000",
accessKey: "minio",
secretKey: "minio123",
sessionToken: "token",
hostname: "localhost",
port: "9000",
},
{
hostURL: "https://minio@localhost:9000",
accessKey: "minio",
hostname: "localhost",
port: "9000",
},
{
hostURL: "https://minio:@localhost:9000",
accessKey: "minio",
hostname: "localhost",
port: "9000",
},
{
hostURL: "https://:@localhost:9000",
hostname: "localhost",
port: "9000",
},
{
hostURL: "https://:minio123@localhost:9000",
hostname: "localhost",
secretKey: "minio123",
port: "9000",
},
{
hostURL: "https://:minio123:token@localhost:9000",
hostname: "localhost",
secretKey: "minio123",
sessionToken: "token",
port: "9000",
},
{
hostURL: "https://:minio123:@localhost:9000",
hostname: "localhost",
secretKey: "minio123",
port: "9000",
},
}
for i, testCase := range testCases {
url, ak, sk, err := parseEnvURLStr(testCase.hostURL)
if testCase.accessKey != ak {
t.Fatalf("Test %d: Expected %s, got %s", i+1, testCase.accessKey, ak)
}
if testCase.secretKey != sk {
t.Fatalf("Test %d: Expected %s, got %s", i+1, testCase.secretKey, sk)
}
if testCase.hostname != url.Hostname() {
t.Fatalf("Test %d: Expected %s, got %s", i+1, testCase.hostname, url.Hostname())
}
if testCase.port != url.Port() {
t.Fatalf("Test %d: Expected %s, got %s", i+1, testCase.port, url.Port())
}
if err != nil {
t.Fatalf("Test %d: Expected test to pass. Failed with err %s", i+1, err)
}
for _, testCase := range testCases {
t.Run("", func(t *testing.T) {
url, ak, sk, token, err := parseEnvURLStr(testCase.hostURL)
if testCase.accessKey != ak {
t.Fatalf("Expected %s, got %s", testCase.accessKey, ak)
}
if testCase.secretKey != sk {
t.Fatalf("Expected %s, got %s", testCase.secretKey, sk)
}
if testCase.sessionToken != token {
t.Fatalf("Expected %s, got %s", testCase.sessionToken, token)
}
if testCase.hostname != url.Hostname() {
t.Fatalf("Expected %s, got %s", testCase.hostname, url.Hostname())
}
if testCase.port != url.Port() {
t.Fatalf("Expected %s, got %s", testCase.port, url.Port())
}
if err != nil {
t.Fatalf("Expected test to pass. Failed with err %s", err)
}
})
}
}
func TestParseEnvURLStrInvalid(t *testing.T) {
_, _, _, err := parseEnvURLStr("")
_, _, _, _, err := parseEnvURLStr("")
if err == nil {
t.Fatalf("Expected failure")
}
+171 -66
View File
@@ -23,15 +23,15 @@ import (
"errors"
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"strings"
"syscall"
"github.com/fatih/color"
"github.com/minio/cli"
"github.com/minio/mc/pkg/console"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio/pkg/console"
)
// cp command flags.
@@ -69,9 +69,33 @@ var (
Name: "preserve, a",
Usage: "preserve filesystem attributes (mode, ownership, timestamps)",
},
cli.BoolFlag{
Name: "disable-multipart",
Usage: "disable multipart upload feature",
},
cli.BoolFlag{
Name: "md5",
Usage: "force all upload(s) to calculate md5sum checksum",
},
cli.StringFlag{
Name: rmFlag,
Usage: "retention mode to be applied on the object (governance, compliance)",
},
cli.StringFlag{
Name: rdFlag,
Usage: "retention duration for the object in d days or y years",
},
cli.StringFlag{
Name: lhFlag,
Usage: "apply legal hold to the copied object (on, off)",
},
}
)
var rmFlag = "retention-mode"
var rdFlag = "retention-duration"
var lhFlag = "legal-hold"
// ErrInvalidMetadata reflects invalid metadata format
var ErrInvalidMetadata = errors.New("specified metadata should be of form key1=value1;key2=value2;... and so on")
@@ -80,7 +104,7 @@ var cpCmd = cli.Command{
Name: "cp",
Usage: "copy objects",
Action: mainCopy,
Before: setGlobalsFromContext,
Before: initBeforeRunningCmd,
Flags: append(append(cpFlags, ioFlags...), globalFlags...),
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
@@ -127,11 +151,11 @@ EXAMPLES:
base64 encoded string as key.
{{.Prompt}} {{.HelpName}} --recursive --encrypt-key "s3/documents/=MzJieXRlc2xvbmdzZWNyZWFiY2RlZmcJZ2l2ZW5uMjE=,myminio/documents/=MzJieXRlc2xvbmdzZWNyZWFiY2RlZmcJZ2l2ZW5uMjE=" s3/documents/ myminio/documents/
11. Copy a list of objects from local file system to MinIO cloud storage with specified metadata.
{{.Prompt}} {{.HelpName}} --attr key1=value1,key2=value2 Music/*.mp4 play/mybucket/
11. Copy a list of objects from local file system to MinIO cloud storage with specified metadata, separated by ";"
{{.Prompt}} {{.HelpName}} --attr "key1=value1;key2=value2" Music/*.mp4 play/mybucket/
12. Copy a folder recursively from MinIO cloud storage to Amazon S3 cloud storage with specified metadata.
{{.Prompt}} {{.HelpName}} --attr Cache-Control=max-age=90000,min-fresh=9000\;key1=value1\;key2=value2 --recursive play/mybucket/burningman2011/ s3/mybucket/
12. Copy a folder recursively from MinIO cloud storage to Amazon S3 cloud storage with Cache-Control and custom metadata, separated by ";".
{{.Prompt}} {{.HelpName}} --attr "Cache-Control=max-age=90000,min-fresh=9000;key1=value1;key2=value2" --recursive play/mybucket/burningman2011/ s3/mybucket/
13. Copy a text file to an object storage and assign REDUCED_REDUNDANCY storage-class to the uploaded object.
{{.Prompt}} {{.HelpName}} --storage-class REDUCED_REDUNDANCY myobject.txt play/mybucket
@@ -141,6 +165,15 @@ EXAMPLES:
15. Copy a text file to an object storage and preserve the file system attribute as metadata.
{{.Prompt}} {{.HelpName}} -a myobject.txt play/mybucket
16. Copy a text file to an object storage with object lock mode set to 'GOVERNANCE' with retention duration 1 day.
{{.Prompt}} {{.HelpName}} --retention-mode governance --retention-duration 1d locked.txt play/locked-bucket/
17. Copy a text file to an object storage with legal-hold enabled.
{{.Prompt}} {{.HelpName}} --legal-hold on locked.txt play/locked-bucket/
18. Copy a text file to an object storage and disable multipart upload feature.
{{.Prompt}} {{.HelpName}} --disable-multipart myobject.txt play/mybucket
`,
}
@@ -182,8 +215,8 @@ type ProgressReader interface {
Progress
}
// doCopy - Copy a singe file from source to destination
func doCopy(ctx context.Context, cpURLs URLs, pg ProgressReader, encKeyDB map[string][]prefixSSEPair) URLs {
// doCopy - Copy a single file from source to destination
func doCopy(ctx context.Context, cpURLs URLs, pg ProgressReader, encKeyDB map[string][]prefixSSEPair, isMvCmd bool, preserve bool) URLs {
if cpURLs.Error != nil {
cpURLs.Error = cpURLs.Error.Trace()
return cpURLs
@@ -194,11 +227,11 @@ func doCopy(ctx context.Context, cpURLs URLs, pg ProgressReader, encKeyDB map[st
targetAlias := cpURLs.TargetAlias
targetURL := cpURLs.TargetContent.URL
length := cpURLs.SourceContent.Size
sourcePath := filepath.ToSlash(filepath.Join(sourceAlias, sourceURL.Path))
if progressReader, ok := pg.(*progressBar); ok {
progressReader.SetCaption(cpURLs.SourceContent.URL.String() + ": ")
} else {
sourcePath := filepath.ToSlash(filepath.Join(sourceAlias, sourceURL.Path))
targetPath := filepath.ToSlash(filepath.Join(targetAlias, targetURL.Path))
printMsg(copyMessage{
Source: sourcePath,
@@ -208,19 +241,31 @@ func doCopy(ctx context.Context, cpURLs URLs, pg ProgressReader, encKeyDB map[st
TotalSize: cpURLs.TotalSize,
})
}
return uploadSourceToTargetURL(ctx, cpURLs, pg, encKeyDB)
urls := uploadSourceToTargetURL(ctx, cpURLs, pg, encKeyDB, preserve)
if isMvCmd && urls.Error == nil {
bgRemove(ctx, sourcePath)
}
return urls
}
// doCopyFake - Perform a fake copy to update the progress bar appropriately.
func doCopyFake(cpURLs URLs, pg Progress) URLs {
func doCopyFake(ctx context.Context, cpURLs URLs, pg Progress, isMvCmd bool) URLs {
if progressReader, ok := pg.(*progressBar); ok {
progressReader.ProgressBar.Add64(cpURLs.SourceContent.Size)
}
if isMvCmd {
sourcePath := filepath.ToSlash(filepath.Join(cpURLs.SourceAlias, cpURLs.SourceContent.URL.Path))
bgRemove(ctx, sourcePath)
}
return cpURLs
}
// doPrepareCopyURLs scans the source URL and prepares a list of objects for copying.
func doPrepareCopyURLs(session *sessionV8, trapCh <-chan bool, cancelCopy context.CancelFunc) (totalBytes, totalObjects int64) {
func doPrepareCopyURLs(ctx context.Context, session *sessionV8, cancelCopy context.CancelFunc) (totalBytes, totalObjects int64) {
// Separate source and target. 'cp' can take only one target,
// but any number of sources.
sourceURLs := session.Header.CommandArgs[:len(session.Header.CommandArgs)-1]
@@ -244,7 +289,7 @@ func doPrepareCopyURLs(session *sessionV8, trapCh <-chan bool, cancelCopy contex
scanBar = scanBarFactory()
}
URLsCh := prepareCopyURLs(sourceURLs, targetURL, isRecursive, encKeyDB, olderThan, newerThan)
URLsCh := prepareCopyURLs(ctx, sourceURLs, targetURL, isRecursive, encKeyDB, olderThan, newerThan)
done := false
for !done {
select {
@@ -271,15 +316,15 @@ func doPrepareCopyURLs(session *sessionV8, trapCh <-chan bool, cancelCopy contex
session.Delete()
fatalIf(probe.NewError(e), "Unable to prepare URL for copying. Error in JSON marshaling.")
}
fmt.Fprintln(dataFP, string(jsonData))
dataFP.Write(jsonData)
dataFP.Write([]byte{'\n'})
if !globalQuiet && !globalJSON {
scanBar(cpURLs.SourceContent.URL.String())
}
totalBytes += cpURLs.SourceContent.Size
totalObjects++
case <-trapCh:
case <-globalContext.Done():
cancelCopy()
// Print in new line and adjust to top so that we don't print over the ongoing scan bar
if !globalQuiet && !globalJSON {
@@ -296,12 +341,7 @@ func doPrepareCopyURLs(session *sessionV8, trapCh <-chan bool, cancelCopy contex
return
}
func doCopySession(cli *cli.Context, session *sessionV8, encKeyDB map[string][]prefixSSEPair) error {
trapCh := signalTrap(os.Interrupt, syscall.SIGTERM, syscall.SIGKILL)
ctx, cancelCopy := context.WithCancel(context.Background())
defer cancelCopy()
func doCopySession(ctx context.Context, cancelCopy context.CancelFunc, cli *cli.Context, session *sessionV8, encKeyDB map[string][]prefixSSEPair, isMvCmd bool) error {
var isCopied func(string) bool
var totalObjects, totalBytes int64
@@ -323,7 +363,7 @@ func doCopySession(cli *cli.Context, session *sessionV8, encKeyDB map[string][]p
isCopied = isLastFactory(session.Header.LastCopied)
if !session.HasData() {
totalBytes, totalObjects = doPrepareCopyURLs(session, trapCh, cancelCopy)
totalBytes, totalObjects = doPrepareCopyURLs(ctx, session, cancelCopy)
} else {
totalBytes, totalObjects = session.Header.TotalBytes, session.Header.TotalObjects
}
@@ -338,6 +378,7 @@ func doCopySession(cli *cli.Context, session *sessionV8, encKeyDB map[string][]p
close(cpURLsCh)
break
}
var cpURLs URLs
if e := json.Unmarshal([]byte(urlScanner.Text()), &cpURLs); e != nil {
errorIf(probe.NewError(e), "Unable to unmarshal %s", urlScanner.Text())
@@ -359,10 +400,28 @@ func doCopySession(cli *cli.Context, session *sessionV8, encKeyDB map[string][]p
go func() {
totalBytes := int64(0)
for cpURLs := range prepareCopyURLs(sourceURLs, targetURL, isRecursive, encKeyDB, olderThan, newerThan) {
totalBytes += cpURLs.SourceContent.Size
pg.SetTotal(totalBytes)
for cpURLs := range prepareCopyURLs(ctx, sourceURLs, targetURL, isRecursive,
encKeyDB, olderThan, newerThan) {
if cpURLs.Error != nil {
// Print in new line and adjust to top so that we
// don't print over the ongoing scan bar
if !globalQuiet && !globalJSON {
console.Eraseline()
}
if strings.Contains(cpURLs.Error.ToGoError().Error(),
" is a folder.") {
errorIf(cpURLs.Error.Trace(),
"Folder cannot be copied. Please use `...` suffix.")
} else {
errorIf(cpURLs.Error.Trace(),
"Unable to start copying.")
}
break
} else {
totalBytes += cpURLs.SourceContent.Size
pg.SetTotal(totalBytes)
totalObjects++
}
cpURLsCh <- cpURLs
}
close(cpURLsCh)
@@ -409,6 +468,30 @@ func doCopySession(cli *cli.Context, session *sessionV8, encKeyDB map[string][]p
cpURLs.TargetContent.Metadata["X-Amz-Storage-Class"] = storageClass
}
// update Object retention related fields
if session != nil {
cpURLs.TargetContent.RetentionMode = session.Header.CommandStringFlags[rmFlag]
if cpURLs.TargetContent.RetentionMode != "" {
cpURLs.TargetContent.RetentionEnabled = true
}
cpURLs.TargetContent.RetentionDuration = session.Header.CommandStringFlags[rdFlag]
cpURLs.TargetContent.LegalHold = strings.ToUpper(session.Header.CommandStringFlags[lhFlag])
if cpURLs.TargetContent.LegalHold != "" {
cpURLs.TargetContent.LegalHoldEnabled = true
}
} else {
if rm := cli.String(rmFlag); rm != "" {
cpURLs.TargetContent.RetentionMode = rm
cpURLs.TargetContent.RetentionEnabled = true
}
if rd := cli.String(rdFlag); rd != "" {
cpURLs.TargetContent.RetentionDuration = rd
}
if lh := cli.String(lhFlag); lh != "" {
cpURLs.TargetContent.LegalHold = strings.ToUpper(lh)
cpURLs.TargetContent.LegalHoldEnabled = true
}
}
if cli.String("attr") != "" {
userMetaMap, _ := getMetaDataEntry(cli.String("attr"))
for metaDataKey, metaDataVal := range userMetaMap {
@@ -416,26 +499,18 @@ func doCopySession(cli *cli.Context, session *sessionV8, encKeyDB map[string][]p
}
}
// If one needs to store the file system information by passing -a flag
if preserve := cli.Bool("preserve"); preserve {
attrValue, pErr := getFileAttrMeta(cpURLs, encKeyDB)
if pErr != nil {
errorIf(pErr, "Unable to fetch file meta info for %s", cpURLs.SourceAlias)
continue
}
preserve := cli.Bool("preserve")
cpURLs.MD5 = cli.Bool("md5")
cpURLs.DisableMultipart = cli.Bool("disable-multipart")
if attrValue != "" {
cpURLs.TargetContent.Metadata["mc-attrs"] = attrValue
}
}
// Verify if previously copied, notify progress bar.
if isCopied != nil && isCopied(cpURLs.SourceContent.URL.String()) {
queueCh <- func() URLs {
return doCopyFake(cpURLs, pg)
return doCopyFake(ctx, cpURLs, pg, isMvCmd)
}
} else {
queueCh <- func() URLs {
return doCopy(ctx, cpURLs, pg, encKeyDB)
return doCopy(ctx, cpURLs, pg, encKeyDB, isMvCmd, preserve)
}
}
}
@@ -443,11 +518,13 @@ func doCopySession(cli *cli.Context, session *sessionV8, encKeyDB map[string][]p
}()
var retErr error
errSeen := false
cpAllFilesErr := true
loop:
for {
select {
case <-trapCh:
case <-globalContext.Done():
close(quitCh)
cancelCopy()
// Receive interrupt notification.
@@ -457,6 +534,7 @@ loop:
if session != nil {
session.CloseAndDie()
}
break loop
case cpURLs, ok := <-statusCh:
// Status channel is closed, we should return.
if !ok {
@@ -467,6 +545,7 @@ loop:
session.Header.LastCopied = cpURLs.SourceContent.URL.String()
session.Save()
}
cpAllFilesErr = false
} else {
// Set exit status for any copy error
@@ -480,9 +559,23 @@ loop:
errorIf(cpURLs.Error.Trace(cpURLs.SourceContent.URL.String()),
fmt.Sprintf("Failed to copy `%s`.", cpURLs.SourceContent.URL.String()))
if isErrIgnored(cpURLs.Error) {
cpAllFilesErr = false
continue loop
}
errSeen = true
if progressReader, pgok := pg.(*progressBar); pgok {
if progressReader.ProgressBar.Get() > 0 {
writeContSize := (int)(cpURLs.SourceContent.Size)
totalPGSize := (int)(progressReader.ProgressBar.Total)
written := (int)(progressReader.ProgressBar.Get())
if totalPGSize > writeContSize && written > writeContSize {
progressReader.ProgressBar.Set((written - writeContSize))
progressReader.ProgressBar.Update()
}
}
}
if session != nil {
// For critical errors we should exit. Session
// can be resumed after the user figures out
@@ -494,7 +587,9 @@ loop:
}
if progressReader, ok := pg.(*progressBar); ok {
if progressReader.ProgressBar.Get() > 0 {
if (errSeen && totalObjects == 1) || (cpAllFilesErr && totalObjects > 1) {
console.Eraseline()
} else if progressReader.ProgressBar.Get() > 0 {
progressReader.ProgressBar.Finish()
}
} else {
@@ -511,40 +606,45 @@ func getMetaDataEntry(metadataString string) (map[string]string, *probe.Error) {
metaDataMap := make(map[string]string)
for _, metaData := range strings.Split(metadataString, ";") {
metaDataEntry := strings.SplitN(metaData, "=", 2)
if len(metaDataEntry) == 2 {
metaDataMap[metaDataEntry[0]] = metaDataEntry[1]
} else {
if len(metaDataEntry) != 2 {
return nil, probe.NewError(ErrInvalidMetadata)
}
metaDataMap[http.CanonicalHeaderKey(metaDataEntry[0])] = metaDataEntry[1]
}
return metaDataMap, nil
}
// mainCopy is the entry point for cp command.
func mainCopy(ctx *cli.Context) error {
func mainCopy(cliCtx *cli.Context) error {
ctx, cancelCopy := context.WithCancel(globalContext)
defer cancelCopy()
// Parse encryption keys per command.
encKeyDB, err := getEncKeys(ctx)
encKeyDB, err := getEncKeys(cliCtx)
fatalIf(err, "Unable to parse encryption keys.")
// Parse metadata.
userMetaMap := make(map[string]string)
if ctx.String("attr") != "" {
userMetaMap, err = getMetaDataEntry(ctx.String("attr"))
fatalIf(err, "Unable to parse attribute %v", ctx.String("attr"))
if cliCtx.String("attr") != "" {
userMetaMap, err = getMetaDataEntry(cliCtx.String("attr"))
fatalIf(err, "Unable to parse attribute %v", cliCtx.String("attr"))
}
// check 'copy' cli arguments.
checkCopySyntax(ctx, encKeyDB)
checkCopySyntax(ctx, cliCtx, encKeyDB, false)
// Additional command speific theme customization.
// Additional command specific theme customization.
console.SetColor("Copy", color.New(color.FgGreen, color.Bold))
recursive := ctx.Bool("recursive")
olderThan := ctx.String("older-than")
newerThan := ctx.String("newer-than")
storageClass := ctx.String("storage-class")
recursive := cliCtx.Bool("recursive")
olderThan := cliCtx.String("older-than")
newerThan := cliCtx.String("newer-than")
storageClass := cliCtx.String("storage-class")
retentionMode := cliCtx.String(rmFlag)
retentionDuration := cliCtx.String(rdFlag)
legalHold := strings.ToUpper(cliCtx.String(lhFlag))
sseKeys := os.Getenv("MC_ENCRYPT_KEY")
if key := ctx.String("encrypt-key"); key != "" {
if key := cliCtx.String("encrypt-key"); key != "" {
sseKeys = key
}
@@ -552,12 +652,12 @@ func mainCopy(ctx *cli.Context) error {
sseKeys, err = getDecodedKey(sseKeys)
fatalIf(err, "Unable to parse encryption keys.")
}
sse := ctx.String("encrypt")
sse := cliCtx.String("encrypt")
var session *sessionV8
if ctx.Bool("continue") {
sessionID := getHash("cp", ctx.Args())
if cliCtx.Bool("continue") {
sessionID := getHash("cp", cliCtx.Args())
if isSessionExists(sessionID) {
session, err = loadSessionV8(sessionID)
fatalIf(err.Trace(sessionID), "Unable to load session.")
@@ -568,14 +668,19 @@ func mainCopy(ctx *cli.Context) error {
session.Header.CommandStringFlags["older-than"] = olderThan
session.Header.CommandStringFlags["newer-than"] = newerThan
session.Header.CommandStringFlags["storage-class"] = storageClass
session.Header.CommandStringFlags[rmFlag] = retentionMode
session.Header.CommandStringFlags[rdFlag] = retentionDuration
session.Header.CommandStringFlags[lhFlag] = legalHold
session.Header.CommandStringFlags["encrypt-key"] = sseKeys
session.Header.CommandStringFlags["encrypt"] = sse
session.Header.CommandBoolFlags["session"] = ctx.Bool("continue")
session.Header.CommandBoolFlags["session"] = cliCtx.Bool("continue")
if ctx.Bool("preserve") {
session.Header.CommandBoolFlags["preserve"] = ctx.Bool("preserve")
if cliCtx.Bool("preserve") {
session.Header.CommandBoolFlags["preserve"] = cliCtx.Bool("preserve")
}
session.Header.UserMetaData = userMetaMap
session.Header.CommandBoolFlags["md5"] = cliCtx.Bool("md5")
session.Header.CommandBoolFlags["disable-multipart"] = cliCtx.Bool("disable-multipart")
var e error
if session.Header.RootPath, e = os.Getwd(); e != nil {
@@ -584,11 +689,11 @@ func mainCopy(ctx *cli.Context) error {
}
// extract URLs.
session.Header.CommandArgs = ctx.Args()
session.Header.CommandArgs = cliCtx.Args()
}
}
e := doCopySession(ctx, session, encKeyDB)
e := doCopySession(ctx, cancelCopy, cliCtx, session, encKeyDB, false)
if session != nil {
session.Delete()
}

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