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
Harshavardhana 7c9ea88742 Update to latest minio/minio (#3020) 2019-12-24 05:46:13 -08:00
Harshavardhana ee283811a3 fix: ignore APINotImplemented errors from filesystem (#3018) 2019-12-19 15:24:34 -08:00
Harshavardhana d92d2f0d4f Upgrade to new Listen bucket API (#3008) 2019-12-14 08:53:55 -08:00
Anis Elleuch f2f8f858a6 cp: Only use session when -c is passed (#2989) 2019-12-13 10:20:56 -08:00
ebozduman 64e0c36e3b Extraneous line in 'mc admin info' output (#3010) 2019-12-12 12:01:22 -08:00
ebozduman 85f814eb44 Stops showing usage info if Bucket#=0 (#3007) 2019-12-11 20:46:30 -08:00
ebozduman 2616a1d051 New admin info (#2982) 2019-12-11 18:25:55 -08:00
BigUstad 7038207039 Replace Timestamp separator (#3002)
Replace time stamp separator to use `-`
2019-12-11 17:33:17 -08:00
Klaus Post 23aab5b458 mc sql: Use compression parameter (#2996)
The compression parameter is not actually used, but always guessed from the file extension.

Only guess the compression type if it is not explicitly set.

Uploading a file called `out.csv.geezipd`:

Before:
```
λ mc sql -e="SELECT * from s3object LIMIT 1" --compression=GZIP --csv-input "rd=\n,fh=USE,fd=;" local/test/out.csv.geezipd
�""���k↔��Xs��W.v�      ��)��{2#��,r���:�|D▲�.��f♫��→�i�p�2l�♫��ʭ���Q��v▲�5ر�c
```
(content actually not ungzipped)

After:
```
λ mc sql -e="SELECT * from s3object LIMIT 1" --compression=GZIP --csv-input "rd=\n,fh=USE,fd=;" local/test/out.csv.geezipd
"281,1285,159625,159627,2637,20000827.0117590018,1239029,1663,-6.7535419,1533,0.53597438,8"
```

We leave validation of the compression value to the server.
2019-12-11 09:24:45 -08:00
Harshavardhana e109a5370a Multi-master only run single startMirror at a time (#3003)
Also randomize the sleep appropriately based
on Unix() time source.
2019-12-10 23:00:41 -08:00
poornas 871b8da9a6 Fix mirroring of PutObjectRetention event (#3004) 2019-12-10 16:23:42 -08:00
Harshavardhana 34757e2ce2 Mirror with fallback list in multimaster mode, copy missing files (#2999) 2019-12-09 07:56:18 -08:00
Harshavardhana dff0f0318c Avoid mirror fatalIf in multi-master (#2998) 2019-12-09 18:50:11 +05:30
Harshavardhana 45df811a89 update minio-go to master (#2995) 2019-12-09 01:36:25 -08:00
Krishna Srinivas 8a488ba0e4 Do full scan diff+mirror in multi-site mirror mode (#2994) 2019-12-09 01:32:58 -08:00
Krishna Srinivas ea0a4b2142 Fix multi-master setup help text (#2993) 2019-12-09 00:52:47 -08:00
kannappanr 4482063fb9 Retry mirror forever on watch (#2992) 2019-12-08 19:44:46 -08:00
Krishna Srinivas 2d8bd7aecc Support for multi master sites (#2991) 2019-12-08 16:25:50 -08:00
Harshavardhana 69bea2eb96 Continue listing upon error during diff and mirror (#2988) 2019-12-08 14:34:52 -08:00
Anis Elleuch c5112d4a0f watch: Add site wide level support (#2987) 2019-12-08 11:35:35 -08:00
Krishna Srinivas a8064ff644 Continue mirroring inspite of error events (#2986) 2019-12-07 18:00:58 -08:00
Harshavardhana fccdcfe803 fix: Source content can be nil when updating progress bar (#2984) 2019-12-07 10:06:16 +05:30
Harshavardhana 543ea4bd90 change target to name in config help (#2983) 2019-12-07 10:05:32 +05:30
Harshavardhana da47ed8ac4 Avoid re-parsing config history elements (#2981) 2019-12-06 07:17:35 +05:30
Harshavardhana f3b2d5471f Add finalized command line options (#2979) 2019-12-04 21:03:34 -08:00
Harshavardhana 3f426ff7e0 Update export command to print disabled sub-sys as comments (#2978) 2019-12-03 12:10:12 -08:00
Harshavardhana 1e1480f408 Fix progress bar update regression (#2976)
Regression introduced in cf6defe025
2019-11-30 17:19:23 -08:00
poornas 4e316c3a40 Remove duplicated API method(s) for object retention (#2973) 2019-11-27 09:44:39 -08:00
Harshavardhana cb110f7403 Add support for auto-complete in 'mc admin config' commands (#2975) 2019-11-27 09:36:40 -08:00
Harshavardhana 21a79b4a44 Add import/export command (#2974) 2019-11-26 10:08:41 -08:00
Harshavardhana cf6defe025 Fix totalSize and totalCounts calculation (#2969) 2019-11-25 18:27:01 +05:30
kannappanr 6eaf0dd05e Retention command to apply retention to objects with a Prefix (#2963) 2019-11-22 12:39:46 -08:00
poornas c2a771f51c Handle PutObjectRetention notification events correctly (#2966) 2019-11-22 09:38:36 -08:00
Harshavardhana 6cfbc809cf Add mirror command to compare metadata and copy (#2965)
mirror now uses the newly introduced
ListObjectsV2WithMetadata API in minio-go
2019-11-21 22:25:46 -08:00
Harshavardhana 3dc37f1ecd Add default values in 'get' (#2962) 2019-11-21 14:35:40 +05:30
poornas 5dda155f81 mirror object lock configuration to dest bucket (#2964)
if bucket does not exist on the target side.
2019-11-20 16:17:07 -08:00
Harshavardhana c51267871c help command is now part of mc admin config get/set (#2961) 2019-11-19 15:15:10 -08:00
Ashish Kumar Sinha 9a9a6d853d Rectify usage section of policy help (#2959) 2019-11-15 10:37:32 -08:00
Harshavardhana 9aebf1e818 update to latest minio (#2957) 2019-11-13 22:35:23 -08:00
poornas 3df8101903 Fix encrypt-key flag parsing (#2955) 2019-11-12 10:24:00 -08:00
Harshavardhana 94943334d4 update to latest minio (#2956) 2019-11-12 03:26:52 -08:00
Bala FA 27d1131825 add lock command (#2880)
`lock` command enables to set, get and clear object lock configuration
of given bucket.
2019-11-11 11:36:04 -08:00
Harshavardhana e0c6fabda6 Fix config history to list in git style format (#2951)
```
~ mc admin config history list -n 2 myminio
RestoreId: df0ebb1e-69b0-4043-b9dd-ab54508f2897
Date: Mon, 04 Nov 2019 17:27:27 GMT

region name="us-east-1" state="on"
region name="us-east-1" state="on"
region name="us-east-1" state="on"
region name="us-east-1" state="on"

RestoreId: ecc6873a-0ed3-41f9-b03e-a2a1bab48b5f
Date: Mon, 04 Nov 2019 17:28:23 GMT

region name=us-east-1 state=off
```
2019-11-05 14:41:52 -08:00
Praveen raj Mani 71f5a7568f Fix the storage prints for xl/fs disks in admin info server (#2947) 2019-10-31 10:14:53 -07:00
Wesley Collin Wright 2a33d28cb9 print disk usage as a plain integer when formatting as json (#2946) 2019-10-31 10:05:55 -07:00
Harshavardhana 9927c0d5c7 mc admin config set/get/del/history/help (#2835)
Related to https://github.com/minio/minio/pull/8392
2019-10-30 21:36:41 -07:00
Ashish Kumar Sinha 42898064f2 Add options to preserve filesystem attributes (#2938) 2019-10-30 00:35:25 -07:00
kannappanr 810978720f Fix typo in error message (#2945)
Change the error message from `Cannot remove new user` to 
`Cannot remove <User>`, when a non-existent user is removed.
2019-10-30 09:08:00 +05:30
kannappanr 90a60d3b6a Avoid index out of range errors (#2943)
Fixes #2941
2019-10-28 12:01:56 +05:30
Nitish Tiwari f6240587db Fix arrow signs to use more common U+2191 & U+2193 (#2942) 2019-10-27 20:55:36 -07:00
Praveen raj Mani 80aecfddff Adapt new changes in StorageInfo (#2889) 2019-10-23 08:47:38 -07:00
Bala FA 72403ecbd1 fix mc cp termination on signals (#2934) 2019-10-21 22:12:56 +05:30
Ashish Kumar Sinha 16965bc19a continue flag: Fix inconsistent punctuation in usage text (#2933) 2019-10-21 14:32:46 +05:30
Bala FA d7078ae153 Refactor mc cp and make session optional. (#2910)
Now `mc cp --recursive --continue` creates copy session on failure or
resumes if previous failed session is found.

Fixes #2893
2019-10-18 22:52:20 +05:30
Harshavardhana bced96ee98 Update mc to use secure-io package (#2931) 2019-10-17 03:04:05 -07:00
poornas 990a7b6d51 Add --type flag to mc admin console (#2914)
This allows filtering error logs by type
2019-10-15 00:47:09 +05:30
poornas 735aa139b1 Fix removing empty prefixes with mc rm command (#2912)
Fixes: 2909
2019-10-12 09:49:14 +05:30
Klaus Post aa4a4774da Fix Windows config path (#2898)
Remove '.exe' (case insensitive) from executable name for consistent config folder.

Potentially breaking: If people (for whatever reason) used 'mc.exe', this will potentially break their setup.
2019-10-12 00:07:10 +05:30
yiranzai c389ee4aa0 Fix zh_CN doc about policy errors (#2927) 2019-10-11 04:21:20 +05:30
kannappanr f93fe1330a Update minio-go to v6.0.39 (#2924) 2019-10-09 09:08:39 -07:00
ebozduman 3710c443bb No 'Removing ...' messages for prefixes(dirs) (#2925) 2019-10-09 06:58:55 +05:30
poornas 0f8345b207 trace - Add TimeToFirstByte to output in --json mode (#2904) 2019-10-09 01:25:54 +05:30
Oleg Utkin 6f478d0a6f update docker alpine base image to 3.10 (#2920) 2019-10-08 07:16:43 +05:30
Andy Boyett d902705d90 README: update minimum go version (#2923)
PR #2888 bumped the minimum go version from 1.12 to 1.13 but did not
update README.md to reflect the change. This commit updates the readme
to be in line with the code.

Attempting to build `mc` from source on go 1.12 yields this error:
```
$ GO111MODULE=on go get github.com/minio/mc
go: finding github.com/minio/mc latest
package github.com/minio/mc: build constraints exclude all Go files in /home/andy/go/pkg/mod/github.com/minio/mc@v0.0.0-20191004065813-f79aefa79713
```
2019-10-08 01:04:46 +05:30
poornas f79aefa797 mc sql - default to json output if global json flag set (#2921) 2019-10-04 12:28:13 +05:30
kannappanr 196723372c Doc: Remove text on s3V4 incompatibility with GCS (#2916)
GCS right now works with S3V4, so removed the documentation
where it says that GCS only supports s3V2.

Fixes #2915
2019-10-04 10:17:58 +05:30
Harshavardhana f687722587 Add default query for sql (#2919) 2019-10-02 21:09:10 -07:00
kannappanr 26b9044a86 mod: update minio-go package to v6.0.38 (#2917) 2019-10-03 00:47:43 +05:30
ebozduman a9c606f119 Customize service help for Windows/Linux users (#2908) 2019-09-28 08:33:28 +05:30
poornas 26b71711e8 Show server startup messages on admin console cmd (#2897) 2019-09-26 00:27:22 +05:30
Harshavardhana 6438350130 Update minio-go to latest (#2905)
- Change LDAP XML names to follow server changes (#1164)
- Fix listObjects hang when listing special characters (#1165)
2019-09-24 07:00:03 +05:30
Praveen raj Mani 508869e3f1 Prometheus config generation (#2781)
Add `admin promethes --generate` to generate the prometheus config
2019-09-22 20:28:17 +05:30
Harshavardhana 1db7a3bbed Add go.yml github workflow (#2902) 2019-09-20 05:56:49 +05:30
Harshavardhana 57a9c6fab2 Fix mc functional tests to work with new changed behavior (#2901)
- mc rm doesn't fail for SSE-C encrypted objects because
  we use multi-object delete - this behavior is S3 compatible
- changes needed to ensure that keys are set appropriately
  when doing server side copy.
2019-09-20 04:48:02 +05:30
Harshavardhana 93297260be Remove 'mc update' prompt just update automatically (#2900) 2019-09-19 09:01:24 -07:00
Harshavardhana dff077e34b Add support for attr flag in mirror (#2892) 2019-09-19 08:22:45 -07:00
Harshavardhana a8380a00ef Remove codecov for mc builds 2019-09-18 17:43:50 -07:00
Vivian Kong 5afb0a3aa7 Build staticcheck as pre-built binaries are not available on s390x (#2890) 2019-09-12 23:59:34 +05:30
Harshavardhana 54ee3a2800 Migrate to go1.13 (#2888) 2019-09-09 02:54:43 +05:30
poornas 9f75caef55 fix mc rb to accept bucket or alias as valid args (#2886)
Fixes: #2869
2019-09-07 12:13:52 +05:30
poornas bc1c6bde1d admin console - fix output format (#2885) 2019-09-07 06:44:31 +05:30
poornas 1dd2b4494d Fix error message wording in mc admin commands (#2887) 2019-09-06 17:09:44 -07:00
Harshavardhana 5fc35b6682 Fix admin help messages and docs (#2884) 2019-09-06 10:07:30 -07:00
poornas 22ab93da0f Add mc admin console command (#2794)
Also replace thrift package location
2019-09-05 07:04:25 +05:30
Ashish Kumar Sinha 1582b1cf35 Add support for passing non-printable charachter as key (#2851) 2019-08-29 16:57:04 -07:00
Harshavardhana bd7564a2d4 Add 'mc admin update' command (#2857)
Also this PR deprecates `service status` command
2019-08-28 15:57:25 -07:00
Daniel Valdivia af7d551010 Add support for Total Space and Available Space on mc admin info (#2872) 2019-08-23 09:33:38 -07:00
Ashish Kumar Sinha 3acbeda9c2 Merge mc monitor to mc info (#2838) 2019-08-23 00:26:51 +05:30
Praveen raj Mani 89d30e9aa2 Recognise dot prefixed endpoints in admin info (#2868)
Fixes #2867
2019-08-18 10:25:03 +05:30
Sidhartha Mani 64d45ac35a fix formatting for admin trace (#2854) 2019-08-16 16:57:40 -07:00
poornas f8661fd87e Fix broken link to go installation docs (#2866) 2019-08-15 15:23:12 -07:00
Harshavardhana 12add870fc Add missing commands to autocomplete (#2862) 2019-08-15 12:20:31 -07:00
jgkirschbaum 00a2f81589 Clarified the used JSON format (#2864) 2019-08-15 11:33:53 -07:00
jgkirschbaum 617b5e39f5 Clarified the used JSON format (#2863) 2019-08-15 10:51:27 -07:00
Aditya Manthramurthy 1555979f96 Fix help message bug in group disable command (#2860) 2019-08-14 15:04:55 -07:00
Praveen raj Mani 418c8e7182 Remove empty parent directories while mirroring fs (#2849)
Fixes 2826
2019-08-14 09:26:57 -07:00
Aditya Manthramurthy 3b94d4d3e0 Add policy set command (#2852)
This is a BREAKING change.

- This command sets policy for user and group
- `mc admin user set-policy` is now removed.
- `mc admin uesr add` no longer accepts a policy to set on the user.

Add user info command to show groups of a user
2019-08-13 14:11:27 -07:00
Praveen raj Mani e541715e42 Fix error message in mc tree (#2855) 2019-08-13 13:35:47 -07:00
Harshavardhana 37bdbd037e Colorize du output appropriately (#2856) 2019-08-12 18:05:17 -07:00
Bala FA d399b1e70b add du command support (#2802)
This command works like `du` command in unices i.e. summarize disk
usage of given TARGET recursively.
2019-08-07 21:02:09 -07:00
Ashish Kumar Sinha fef437bdd6 Modify policy command (#2768)
Add set, set-json, get , get-json sub-commands.

Example:
mc policy set download s3/mybucket
mc policy set-json path-to-json-file s3/mybucket
mc policy get s3/mybucket
mc policy get-json s3/mybucket
2019-08-06 21:09:28 -07:00
Harshavardhana 809741e161 Update README.md for source builds 2019-08-06 15:46:32 -07:00
Harshavardhana 0f360131cb Remove runtime checks use go build tag (#2848)
Project can be only built with go1.12 or newer
other build related changes to use new go1.12
features.

Fixes #2815
2019-08-06 15:41:04 -07:00
Aditya Manthramurthy cb3ce8fb97 Add mc admin group command (#2841)
This change is in preparation to add user-groups support to MinIO
server.

- Adds add, remove, enable/disable, list and info sub-commands for the
  group command
2019-08-05 11:37:07 -07:00
poornas b56e297be0 fix admin trace crash on 32 bit systems (#2847) 2019-07-31 17:06:42 -07:00
Harshavardhana 81eb54d146 Fix broken functional tests (#2843) 2019-07-30 14:28:13 -07:00
Ashish Kumar Sinha 9fabc08520 Accept metadata of form Cache-Control=max-age=xxxxxxx (#2840) 2019-07-30 06:52:31 -07:00
kannappanr b885d13060 Windows stat: Compare URLs in windows style path (#2774)
Convert user provided URL into windows style to compare in statURL

Fixes #2772
2019-07-25 17:37:52 -07:00
poornas 67dbada736 Minor changes to admin trace output fmt (#2834) 2019-07-23 17:31:31 -07:00
Harshavardhana c25461640b Fix tree docs and error handling (#2833)
Fixes #2832
2019-07-22 13:02:49 -07:00
poornas c727be5a48 Add error filter flag to mc admin trace command (#2824) 2019-07-21 06:30:33 +01:00
Harshavardhana ae098462c9 Fix admin info dot coloring (#2830) 2019-07-19 08:20:14 +01:00
poornas 74a7c3dc9a Show call stats in admin trace command (#2823)
- Add call latency, input and output bytes to trace
2019-07-19 02:20:08 +01:00
Harshavardhana c2fcfe6512 Make sure to error out if depth is -1 (#2828)
Current code silently converts -1 to 0, which
is not needed and we should fail instead.
2019-07-18 14:40:51 +01:00
Praveen raj Mani bdcb9dcb2f Add tree listing (#2804) 2019-07-17 22:23:02 -07:00
Aditya Manthramurthy 6200a34522 Add "mc admin policy info" command to display policy content (#2818) 2019-07-18 01:43:10 +01:00
Ashish Kumar Sinha 9a25e66e87 Add --ignore-existing/-p flag in mc event add command (#2773)
If the event is already present the server throws an error. With the --ignore-existing/ -p flag these error messages are discarded
2019-07-16 10:40:06 +01:00
Harshavardhana 7c454d8f94 Migrate to new minio/cli, fix all extra spaces across commands (#2825) 2019-07-15 19:59:28 +01:00
Harshavardhana ab3e70ae9f Fix escape characters in trace command (#2822) 2019-07-13 09:07:34 +05:30
Mauricio Scheffer 1818191dca Fix inner link (#2820) 2019-07-12 10:21:15 +05:30
Harshavardhana 31e5ac02bd Fix auto-completion code (#2819)
Reverts the code in #2812

Fixes #2816
2019-07-11 10:41:14 -07:00
Harshavardhana aa3c9f58df Remove port 9000 for play.min.io (#2817)
Most corporate environments block port 9000,
since we already allow access from port 80 and
port 443 just default to https port instead.
2019-07-10 21:16:45 +01:00
213 changed files with 34528 additions and 6128 deletions
+2 -2
View File
@@ -4,8 +4,8 @@
## Steps to reproduce the behavior
## mc version
- (paste output of `mc version`)
## mc --version
- (paste output of `mc --version`)
## System information
+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
+47
View File
@@ -0,0 +1,47 @@
name: Go
on:
pull_request:
branches:
- master
push:
branches:
- master
jobs:
build:
name: Test on Go ${{ matrix.go-version }} and ${{ matrix.os }}
runs-on: ${{ matrix.os }}
strategy:
matrix:
go-version: [1.13.x]
os: [ubuntu-latest, windows-latest]
steps:
- name: Set up Go ${{ matrix.go-version }} on ${{ matrix.os }}
uses: actions/setup-go@v1
with:
go-version: ${{ matrix.go-version }}
id: go
- name: Check out code into the Go module directory
uses: actions/checkout@v1
- name: Build on ${{ matrix.os }}
if: matrix.os == 'windows-latest'
env:
GO111MODULE: on
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 -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
-43
View File
@@ -1,43 +0,0 @@
go_import_path: github.com/minio/mc
language: go
# this ensures PRs based on a local branch are not built twice
# the downside is that a PR targeting a different branch is not built
# but as a workaround you can add the branch to this list
branches:
only:
- master
matrix:
include:
- os: linux
dist: trusty
env:
- ARCH=x86_64
- GO111MODULE=on
go: 1.12.1
script:
- diff -au <(gofmt -d *.go) <(printf "")
- diff -au <(gofmt -d cmd) <(printf "")
- diff -au <(gofmt -d pkg) <(printf "")
- for d in $(go list ./...); do go test -v -race "$d"; done
- make coverage
- make verifiers
- os: windows
env:
- ARCH=x86_64
- GO111MODULE=on
go: 1.12.1
script:
- go build --ldflags="$(go run buildscripts/gen-ldflags.go)" -o %GOPATH%\bin\mc.exe
- for d in $(go list ./...); do go test -v -race "$d"; done
- bash buildscripts/go-coverage.sh
before_script:
# Add an IPv6 config - see the corresponding Travis issue
# https://github.com/travis-ci/travis-ci/issues/8361
- if [[ "${TRAVIS_OS_NAME}" == "linux" ]]; then sudo sh -c 'echo 0 > /proc/sys/net/ipv6/conf/all/disable_ipv6'; fi
after_success:
- bash <(curl -s https://codecov.io/bash)
+20083
View File
File diff suppressed because it is too large Load Diff
+5 -5
View File
@@ -1,4 +1,4 @@
FROM golang:1.12-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.9
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"]
+8
View File
@@ -0,0 +1,8 @@
FROM alpine:3.12
COPY mc /usr/bin/
COPY CREDITS /
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.9
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"]
+25 -21
View File
@@ -2,8 +2,14 @@ PWD := $(shell pwd)
GOPATH := $(shell go env GOPATH)
LDFLAGS := $(shell go run buildscripts/gen-ldflags.go)
GOARCH := $(shell go env GOARCH)
GOOS := $(shell go env GOOS)
BUILD_LDFLAGS := '$(LDFLAGS)'
VERSION ?= $(shell git describe --tags)
TAG ?= "minio/mc:$(VERSION)"
all: build
checks:
@@ -12,14 +18,15 @@ checks:
getdeps:
@mkdir -p ${GOPATH}/bin
@which golint 1>/dev/null || (echo "Installing golint" && go get -u golang.org/x/lint/golint)
@which staticcheck 1>/dev/null || (echo "Installing staticcheck" && wget --quiet -O ${GOPATH}/bin/staticcheck https://github.com/dominikh/go-tools/releases/download/2019.1/staticcheck_linux_amd64 && chmod +x ${GOPATH}/bin/staticcheck)
@which misspell 1>/dev/null || (echo "Installing misspell" && wget --quiet https://github.com/client9/misspell/releases/download/v0.3.4/misspell_0.3.4_linux_64bit.tar.gz && tar xf misspell_0.3.4_linux_64bit.tar.gz && mv misspell ${GOPATH}/bin/misspell && chmod +x ${GOPATH}/bin/misspell && rm -f misspell_0.3.4_linux_64bit.tar.gz)
@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
vet:
@echo "Running $@"
@@ -31,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
@@ -53,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 GO_FLAGS="" 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/).
+31 -36
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
@@ -82,14 +85,10 @@ mc.exe --help
```
## Install from Source
Source installation is intended only for developers and advanced users. `mc update` command does not support update notifications for source based installations. Please download official releases from https://min.io/download/#minio-client.
Source installation is only intended for developers and advanced users. If you do not have a working Golang environment, please follow [How to install Golang](https://golang.org/doc/install). Minimum version required is [go1.13](https://golang.org/dl/#stable)
If you do not have a working Golang environment, please follow [How to install Golang](https://docs.min.io/docs/how-to-install-golang).
```
go get -d github.com/minio/mc
cd ${GOPATH}/src/github.com/minio/mc
make
```sh
GO111MODULE=on go get github.com/minio/mc
```
## Add a Cloud Storage Service
@@ -153,14 +152,12 @@ Get your AccessKeyID and SecretAccessKey by following [Google Credentials Guide]
mc config host add gcs https://storage.googleapis.com BKIKJAA5BMMU2RHO6IBB V8f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12
```
NOTE: Google Cloud Storage only supports Legacy Signature Version 2, so you have to pick - S3v2
## Test Your Setup
`mc` is pre-configured with https://play.min.io:9000, aliased as "play". It is a hosted MinIO server for testing and development purpose. To test Amazon S3, simply replace "play" with "s3" or the alias you used at the time of setup.
`mc` is pre-configured with https://play.min.io, aliased as "play". It is a hosted MinIO server for testing and development purpose. To test Amazon S3, simply replace "play" with "s3" or the alias you used at the time of setup.
*Example:*
List all buckets from https://play.min.io:9000
List all buckets from https://play.min.io
```
mc ls play
@@ -207,8 +204,7 @@ alias find='mc find'
```
### Shell autocompletion
In case you are using bash or zsh, the current shell will be automatically setup to use completion feature to suggest or auto-complete your mc commands.
In case you are using bash, zsh or fish. Shell completion is embedded by default in `mc`, to install auto-completion use `mc --autocompletion`. Restart the shell, mc will auto-complete commands as shown below.
```
mc <TAB>
@@ -224,6 +220,5 @@ cat cp event head mb pipe rm share stat
## Contribute to MinIO Project
Please follow MinIO [Contributor's Guide](https://github.com/minio/mc/blob/master/CONTRIBUTING.md)
## License
[![FOSSA Status](https://app.fossa.io/api/projects/git%2Bgithub.com%2Fminio%2Fmc.svg?type=large)](https://app.fossa.io/projects/git%2Bgithub.com%2Fminio%2Fmc?ref=badge_large)
+7 -7
View File
@@ -78,7 +78,7 @@ mc.exe --help
## 通过源码安装
通过源码安装仅适用于开发人员和高级用户。`mc update`命令不支持基于源码安装的更新通知。请从https://min.io/download/#minio-client下载官方版本。
如果您没有Golang环境,请参照[如何安装Golang](https://docs.min.io/docs/how-to-install-golang)。
如果您没有Golang环境,请参照[如何安装Golang](https://golang.org/doc/install)。
```
go get -d github.com/minio/mc
@@ -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,31 +101,31 @@ 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。
## 验证
`mc`预先配置了云存储服务URL:https://play.min.io:9000,别名“play”。它是一个用于研发和测试的MinIO服务。如果想测试Amazon S3,你可以将“play”替换为“s3”。
`mc`预先配置了云存储服务URL:https://play.min.io,别名“play”。它是一个用于研发和测试的MinIO服务。如果想测试Amazon S3,你可以将“play”替换为“s3”。
*示例:*
列出https://play.min.io:9000上的所有存储桶。
列出https://play.min.io上的所有存储桶。
```
mc ls play
+2 -2
View File
@@ -24,7 +24,7 @@ _init() {
## Minimum required versions for build dependencies
GIT_VERSION="1.0"
GO_VERSION="1.12"
GO_VERSION="1.13"
OSX_VERSION="10.8"
KNAME=$(uname -s)
ARCH=$(uname -m)
@@ -97,7 +97,7 @@ assert_is_supported_os() {
assert_check_golang_env() {
if ! which go >/dev/null 2>&1; then
echo "Cannot find go binary in your PATH configuration, please refer to Go installation document at https://docs.min.io/docs/how-to-install-golang"
echo "Cannot find go binary in your PATH configuration, please refer to Go installation document at https://golang.org/doc/install"
exit 1
fi
+2 -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() {
@@ -23,6 +23,7 @@ function _build() {
export GOOS=$os
export GOARCH=$arch
export GO111MODULE=on
export CGO_ENABLED=0
go build -tags kqueue -o /dev/null
}
-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 ./...
+4 -1
View File
@@ -17,13 +17,13 @@
package cmd
import (
"encoding/json"
"fmt"
"sync"
"sync/atomic"
"time"
"github.com/cheggaaa/pb"
json "github.com/minio/mc/pkg/colorjson"
"github.com/minio/mc/pkg/probe"
)
@@ -138,6 +138,9 @@ func (a *accounter) Get() int64 {
return atomic.LoadInt64(&a.current)
}
func (a *accounter) SetTotal(int64) {
}
// Add add to current value atomically.
func (a *accounter) Add(n int64) int64 {
return atomic.AddInt64(&a.current, n)
+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.
}
+95
View File
@@ -0,0 +1,95 @@
/*
* MinIO Client (C) 2019 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"
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: initBeforeRunningCmd,
Action: mainAdminConfigExport,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} TARGET
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Export the current config from MinIO server
{{.Prompt}} {{.HelpName}} play/ > config.txt
`,
}
// configExportMessage container to hold locks information.
type configExportMessage struct {
Status string `json:"status"`
Value []byte `json:"value"`
}
// String colorized service status message.
func (u configExportMessage) String() string {
return string(u.Value)
}
// JSON jsonified service status Message message.
func (u configExportMessage) JSON() string {
u.Status = "success"
statusJSONBytes, e := json.MarshalIndent(u, "", " ")
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
return string(statusJSONBytes)
}
// checkAdminConfigExportSyntax - validate all the passed arguments
func checkAdminConfigExportSyntax(ctx *cli.Context) {
if !ctx.Args().Present() || len(ctx.Args()) > 1 {
cli.ShowCommandHelpAndExit(ctx, "export", 1) // last argument is exit code
}
}
func mainAdminConfigExport(ctx *cli.Context) error {
checkAdminConfigExportSyntax(ctx)
// Export the alias parameter from cli
args := ctx.Args()
aliasedURL := args.Get(0)
// Create a new MinIO Admin Client
client, err := newAdminClient(aliasedURL)
fatalIf(err, "Unable to initialize admin connection.")
// Call get config API
buf, e := client.GetConfig(globalContext)
fatalIf(probe.NewError(e), "Cannot get server config")
// Print
printMsg(configExportMessage{
Value: buf,
})
return nil
}
+37 -20
View File
@@ -1,5 +1,5 @@
/*
* MinIO Client (C) 2017 MinIO, Inc.
* MinIO Client (C) 2017-2019 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -17,6 +17,8 @@
package cmd
import (
"strings"
"github.com/minio/cli"
json "github.com/minio/mc/pkg/colorjson"
"github.com/minio/mc/pkg/probe"
@@ -24,8 +26,8 @@ import (
var adminConfigGetCmd = cli.Command{
Name: "get",
Usage: "get config of a MinIO server/cluster",
Before: setGlobalsFromContext,
Usage: "interactively retrieve a config key parameters",
Before: initBeforeRunningCmd,
Action: mainAdminConfigGet,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
@@ -38,24 +40,29 @@ FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Get server configuration of a MinIO server/cluster.
$ {{.HelpName}} play/
1. Get the current region setting on MinIO server.
{{.Prompt}} {{.HelpName}} play/ region
region name=us-east-1
2. Get the current notification settings for Webhook target on MinIO server
{{.Prompt}} {{.HelpName}} myminio/ notify_webhook
notify_webhook endpoint="http://localhost:8080" auth_token= queue_limit=10000 queue_dir="/home/events"
3. Get the current compression settings on MinIO server
{{.Prompt}} {{.HelpName}} myminio/ compression
compression extensions=".txt,.csv" mime_types="text/*"
`,
}
// configGetMessage container to hold locks information.
type configGetMessage struct {
Status string `json:"status"`
Config map[string]interface{} `json:"config"`
Status string `json:"status"`
Value []byte `json:"value"`
}
// String colorized service status message.
func (u configGetMessage) String() string {
config, e := json.MarshalIndent(u.Config, "", " ")
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
return string(config)
return string(u.Value)
}
// JSON jsonified service status Message message.
@@ -69,7 +76,7 @@ func (u configGetMessage) JSON() string {
// checkAdminConfigGetSyntax - validate all the passed arguments
func checkAdminConfigGetSyntax(ctx *cli.Context) {
if len(ctx.Args()) == 0 || len(ctx.Args()) > 2 {
if !ctx.Args().Present() || len(ctx.Args()) < 1 {
cli.ShowCommandHelpAndExit(ctx, "get", 1) // last argument is exit code
}
}
@@ -84,19 +91,29 @@ func mainAdminConfigGet(ctx *cli.Context) error {
// Create a new MinIO Admin Client
client, err := newAdminClient(aliasedURL)
fatalIf(err, "Cannot get a configured admin connection.")
fatalIf(err, "Unable to initialize admin connection.")
if len(ctx.Args()) == 1 {
// Call get config API
hr, e := client.HelpConfigKV(globalContext, "", "", false)
fatalIf(probe.NewError(e), "Cannot get help for the sub-system")
// Print
printMsg(configHelpMessage{
Value: hr,
envOnly: false,
})
return nil
}
// Call get config API
c, e := client.GetConfig()
fatalIf(probe.NewError(e), "Cannot get server configuration file.")
config := map[string]interface{}{}
e = json.Unmarshal(c, &config)
fatalIf(probe.NewError(e), "Cannot unmarshal server configuration file.")
buf, e := client.GetConfigKV(globalContext, strings.Join(args.Tail(), " "))
fatalIf(probe.NewError(e), "Cannot get server '%s' config", args.Tail())
// Print
printMsg(configGetMessage{
Config: config,
Value: buf,
})
return nil
+83
View File
@@ -0,0 +1,83 @@
/*
* MinIO Client (C) 2019 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 (
"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"
)
// HelpTmpl template used by all sub-systems
const HelpTmpl = `{{if ne .SubSys ""}}{{colorBlueBold "KEY:"}}
{{if .MultipleTargets}}{{colorYellowBold .SubSys}}[:name]{{"\t"}}{{else}}{{colorYellowBold .SubSys}}{{"\t"}}{{end}}{{.Description}}
{{colorBlueBold "ARGS:"}}{{range .KeysHelp}}
{{if .Optional}}{{colorYellowBold .Key}}{{else}}{{colorRedBold .Key}}*{{end}}{{"\t"}}({{.Type}}){{"\t"}}{{.Description}}{{end}}{{else}}{{colorBlueBold "KEYS:"}}{{range .KeysHelp}}
{{colorGreenBold .Key}}{{"\t"}}{{.Description}}{{end}}{{end}}`
var funcMap = template.FuncMap{
"colorBlueBold": color.New(color.FgBlue, color.Bold).SprintfFunc(),
"colorYellowBold": color.New(color.FgYellow, color.Bold).SprintfFunc(),
"colorCyanBold": color.New(color.FgCyan, color.Bold).SprintFunc(),
"colorRedBold": color.New(color.FgRed, color.Bold).SprintfFunc(),
"colorGreenBold": color.New(color.FgGreen, color.Bold).SprintfFunc(),
}
// HelpTemplate - captures config help template
var HelpTemplate = template.Must(template.New("config-help").Funcs(funcMap).Parse(HelpTmpl))
// HelpEnvTemplate - captures config help template
var HelpEnvTemplate = template.Must(template.New("config-help-env").Funcs(funcMap).Parse(HelpTmpl))
// configHelpMessage container to hold locks information.
type configHelpMessage struct {
Status string `json:"status"`
Value madmin.Help `json:"help"`
envOnly bool
}
// String colorized service status message.
func (u configHelpMessage) String() string {
var s strings.Builder
w := tabwriter.NewWriter(&s, 1, 8, 2, ' ', 0)
var e error
if !u.envOnly {
e = HelpTemplate.Execute(w, u.Value)
} else {
e = HelpEnvTemplate.Execute(w, u.Value)
}
fatalIf(probe.NewError(e), "Cannot initialize template writer")
w.Flush()
return s.String()
}
// JSON jsonified service status Message message.
func (u configHelpMessage) JSON() string {
u.Status = "success"
statusJSONBytes, e := json.MarshalIndent(u, "", " ")
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
return string(statusJSONBytes)
}
+155
View File
@@ -0,0 +1,155 @@
/*
* MinIO Client (C) 2019 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 (
"strings"
"text/tabwriter"
"text/template"
"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"
)
var historyListFlags = []cli.Flag{
cli.IntFlag{
Name: "count, n",
Usage: "list only last 'n' entries",
Value: 10,
},
cli.BoolFlag{
Name: "clear, c",
Usage: "clear all history",
},
}
var adminConfigHistoryCmd = cli.Command{
Name: "history",
Usage: "show all historic configuration changes",
Before: initBeforeRunningCmd,
Action: mainAdminConfigHistory,
Flags: append(append([]cli.Flag{}, globalFlags...), historyListFlags...),
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} TARGET
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. List all history entries sorted by time.
{{.Prompt}} {{.HelpName}} play/
`,
}
// History template used by all sub-systems
const History = `{{range .}}{{colorYellowBold "RestoreId:"}} {{colorYellowBold .RestoreID}}
Date: {{.CreateTime}}
{{.Targets}}
{{end}}`
// HistoryTemplate - captures history list template
var HistoryTemplate = template.Must(template.New("history-list").Funcs(funcMap).Parse(History))
type historyEntry struct {
RestoreID string `json:"restoreId"`
CreateTime string `json:"createTime"`
Targets string `json:"targets"`
}
// configHistoryMessage container to hold locks information.
type configHistoryMessage struct {
Status string `json:"status"`
Entries []historyEntry `json:"entries"`
}
// String colorized service status message.
func (u configHistoryMessage) String() string {
var s strings.Builder
w := tabwriter.NewWriter(&s, 1, 8, 2, ' ', 0)
e := HistoryTemplate.Execute(w, u.Entries)
fatalIf(probe.NewError(e), "Cannot initialize template writer")
w.Flush()
return s.String()
}
// JSON jsonified service status Message message.
func (u configHistoryMessage) JSON() string {
u.Status = "success"
statusJSONBytes, e := json.MarshalIndent(u, "", " ")
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
return string(statusJSONBytes)
}
// checkAdminConfigHistorySyntax - validate all the passed arguments
func checkAdminConfigHistorySyntax(ctx *cli.Context) {
if !ctx.Args().Present() || len(ctx.Args()) > 1 {
cli.ShowCommandHelpAndExit(ctx, "history", 1) // last argument is exit code
}
}
func mainAdminConfigHistory(ctx *cli.Context) error {
checkAdminConfigHistorySyntax(ctx)
console.SetColor("ConfigHistoryMessageRestoreID", color.New(color.Bold))
console.SetColor("ConfigHistoryMessageTime", color.New(color.FgGreen))
// Get the alias parameter from cli
args := ctx.Args()
aliasedURL := args.Get(0)
// Create a new MinIO Admin Client
client, err := newAdminClient(aliasedURL)
fatalIf(err, "Unable to initialize admin connection.")
if ctx.IsSet("clear") {
fatalIf(probe.NewError(client.ClearConfigHistoryKV(globalContext, "all")), "Cannot clear server configuration.")
// Print
printMsg(configHistoryMessage{})
return nil
}
chEntries, e := client.ListConfigHistoryKV(globalContext, ctx.Int("count"))
fatalIf(probe.NewError(e), "Cannot list server history configuration.")
hentries := make([]historyEntry, len(chEntries))
for i, chEntry := range chEntries {
hentries[i] = historyEntry{
RestoreID: chEntry.RestoreID,
CreateTime: chEntry.CreateTimeFormatted(),
}
hentries[i].Targets = chEntry.Data
}
// Print
printMsg(configHistoryMessage{
Entries: hentries,
})
return nil
}
+107
View File
@@ -0,0 +1,107 @@
/*
* MinIO Client (C) 2019 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"
"os"
"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"
)
var adminConfigImportCmd = cli.Command{
Name: "import",
Usage: "import multiple config keys from STDIN",
Before: initBeforeRunningCmd,
Action: mainAdminConfigImport,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} TARGET
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Import the new local config and apply to the MinIO server
{{.Prompt}} {{.HelpName}} play/ < config.txt
`,
}
// configImportMessage container to hold locks information.
type configImportMessage struct {
Status string `json:"status"`
targetAlias string
}
// String colorized service status message.
func (u configImportMessage) String() (msg string) {
msg += console.Colorize("SetConfigSuccess",
"Setting new key has been successful.\n")
suggestion := fmt.Sprintf("mc admin service restart %s", u.targetAlias)
msg += console.Colorize("SetConfigSuccess",
fmt.Sprintf("Please restart your server with `%s`.\n", suggestion))
return msg
}
// JSON jsonified service status Message message.
func (u configImportMessage) JSON() string {
u.Status = "success"
statusJSONBytes, e := json.MarshalIndent(u, "", " ")
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
return string(statusJSONBytes)
}
// checkAdminConfigImportSyntax - validate all the passed arguments
func checkAdminConfigImportSyntax(ctx *cli.Context) {
if !ctx.Args().Present() || len(ctx.Args()) > 1 {
cli.ShowCommandHelpAndExit(ctx, "import", 1) // last argument is exit code
}
}
func mainAdminConfigImport(ctx *cli.Context) error {
checkAdminConfigImportSyntax(ctx)
// Set color preference of command outputs
console.SetColor("SetConfigSuccess", color.New(color.FgGreen, color.Bold))
// Import the alias parameter from cli
args := ctx.Args()
aliasedURL := args.Get(0)
// Create a new MinIO Admin Client
client, err := newAdminClient(aliasedURL)
fatalIf(err, "Unable to initialize admin connection.")
// Call set config API
fatalIf(probe.NewError(client.SetConfig(globalContext, os.Stdin)), "Cannot set server config")
// Print
printMsg(configImportMessage{
targetAlias: aliasedURL,
})
return nil
}
+133
View File
@@ -0,0 +1,133 @@
/*
* MinIO Client (C) 2019 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"
"strings"
"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"
)
var adminConfigEnvFlags = []cli.Flag{
cli.BoolFlag{
Name: "env",
Usage: "list all the env only help",
},
}
var adminConfigResetCmd = cli.Command{
Name: "reset",
Usage: "interactively reset a config key parameters",
Before: initBeforeRunningCmd,
Action: mainAdminConfigReset,
Flags: append(adminConfigEnvFlags, globalFlags...),
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} TARGET
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Reset MQTT notifcation target 'name1' settings to default values.
{{.Prompt}} {{.HelpName}} myminio/ notify_mqtt:name1
`,
}
// configResetMessage container to hold locks information.
type configResetMessage struct {
Status string `json:"status"`
targetAlias string
}
// String colorized service status message.
func (u configResetMessage) String() (msg string) {
msg += console.Colorize("ResetConfigSuccess",
"Key is successfully reset.\n")
suggestion := fmt.Sprintf("mc admin service restart %s", u.targetAlias)
msg += console.Colorize("ResetConfigSuccess",
fmt.Sprintf("Please restart your server with `%s`.\n", suggestion))
return
}
// JSON jsonified service status message.
func (u configResetMessage) JSON() string {
u.Status = "success"
statusJSONBytes, e := json.MarshalIndent(u, "", " ")
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
return string(statusJSONBytes)
}
// checkAdminConfigResetSyntax - validate all the passed arguments
func checkAdminConfigResetSyntax(ctx *cli.Context) {
if !ctx.Args().Present() {
cli.ShowCommandHelpAndExit(ctx, "reset", 1) // last argument is exit code
}
}
// main config set function
func mainAdminConfigReset(ctx *cli.Context) error {
// Check command arguments
checkAdminConfigResetSyntax(ctx)
// Reset color preference of command outputs
console.SetColor("ResetConfigSuccess", color.New(color.FgGreen, color.Bold))
console.SetColor("ResetConfigFailure", color.New(color.FgRed, color.Bold))
// Get the alias parameter from cli
args := ctx.Args()
aliasedURL := args.Get(0)
// Create a new MinIO Admin Client
client, err := newAdminClient(aliasedURL)
fatalIf(err, "Unable to initialize admin connection.")
if len(ctx.Args()) == 1 {
// Call get config API
hr, e := client.HelpConfigKV(globalContext, "", "", ctx.IsSet("env"))
fatalIf(probe.NewError(e), "Cannot get help for the sub-system")
// Print
printMsg(configHelpMessage{
Value: hr,
envOnly: ctx.IsSet("env"),
})
return nil
}
// Call reset config API
input := strings.Join(args.Tail(), " ")
fatalIf(probe.NewError(client.DelConfigKV(globalContext, input)),
"Cannot reset '%s' on the server", input)
// Print set config result
printMsg(configResetMessage{
targetAlias: aliasedURL,
})
return nil
}
+106
View File
@@ -0,0 +1,106 @@
/*
* MinIO Client (C) 2019 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/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"
)
var adminConfigRestoreCmd = cli.Command{
Name: "restore",
Usage: "rollback back changes to a specific config history",
Before: initBeforeRunningCmd,
Action: mainAdminConfigRestore,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} TARGET RESTOREID
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Restore 'restore-id' history key value on MinIO server.
{{.Prompt}} {{.HelpName}} play/ <restore-id>
`,
}
// configRestoreMessage container to hold locks information.
type configRestoreMessage struct {
Status string `json:"status"`
RestoreID string `json:"restoreID"`
targetAlias string
}
// String colorized service status message.
func (u configRestoreMessage) String() (msg string) {
suggestion := fmt.Sprintf("mc admin service restart %s", u.targetAlias)
msg += console.Colorize("ConfigRestoreMessage",
fmt.Sprintf("Please restart your server with `%s`.\n", suggestion))
msg += console.Colorize("ConfigRestoreMessage", "Restored "+u.RestoreID+" kv successfully.")
return msg
}
// JSON jsonified service status Message message.
func (u configRestoreMessage) JSON() string {
u.Status = "success"
statusJSONBytes, e := json.MarshalIndent(u, "", " ")
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
return string(statusJSONBytes)
}
// checkAdminConfigRestoreSyntax - validate all the passed arguments
func checkAdminConfigRestoreSyntax(ctx *cli.Context) {
if !ctx.Args().Present() || len(ctx.Args()) > 2 {
cli.ShowCommandHelpAndExit(ctx, "restore", 1) // last argument is exit code
}
}
func mainAdminConfigRestore(ctx *cli.Context) error {
checkAdminConfigRestoreSyntax(ctx)
console.SetColor("ConfigRestoreMessage", color.New(color.FgGreen))
// Get the alias parameter from cli
args := ctx.Args()
aliasedURL := args.Get(0)
// Create a new MinIO Admin Client
client, err := newAdminClient(aliasedURL)
fatalIf(err, "Unable to initialize admin connection.")
// Call get config API
fatalIf(probe.NewError(client.RestoreConfigHistoryKV(globalContext, args.Get(1))), "Cannot restore server configuration.")
// Print
printMsg(configRestoreMessage{
RestoreID: args.Get(1),
targetAlias: aliasedURL,
})
return nil
}
+44 -35
View File
@@ -1,5 +1,5 @@
/*
* MinIO Client (C) 2017 MinIO, Inc.
* MinIO Client (C) 2017-2019 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -18,21 +18,22 @@ package cmd
import (
"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"
"github.com/minio/minio/pkg/madmin"
)
var adminConfigSetCmd = cli.Command{
Name: "set",
Usage: "set new config file to a MinIO server/cluster.",
Before: setGlobalsFromContext,
Usage: "interactively set a config key parameters",
Before: initBeforeRunningCmd,
Action: mainAdminConfigSet,
Flags: globalFlags,
Flags: append(adminConfigEnvFlags, globalFlags...),
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
@@ -43,41 +44,33 @@ FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Set server configuration of a MinIO server/cluster.
$ cat myconfig | {{.HelpName}} myminio/
1. Enable webhook notification target for MinIO server.
{{.Prompt}} {{.HelpName}} myminio/ notify_webhook endpoint="http://localhost:8080/minio/events"
2. Change region name for the MinIO server to 'us-west-1'.
{{.Prompt}} {{.HelpName}} myminio/ region name=us-west-1
`,
}
// configSetMessage container to hold locks information.
type configSetMessage struct {
Status string `json:"status"`
setConfigStatus bool
targetAlias string
Status string `json:"status"`
targetAlias string
}
// String colorized service status message.
func (u configSetMessage) String() (msg string) {
// Print the general set config status
if u.setConfigStatus {
msg += console.Colorize("SetConfigSuccess",
"Setting new MinIO configuration file has been successful.\n")
suggestion := fmt.Sprintf("mc admin service restart %s", u.targetAlias)
msg += console.Colorize("SetConfigSuccess",
fmt.Sprintf("Please restart your server with `%s`.\n", suggestion))
} else {
msg += console.Colorize("SetConfigFailure",
"Setting new MinIO configuration file has failed.\n")
}
msg += console.Colorize("SetConfigSuccess",
"Setting new key has been successful.\n")
suggestion := fmt.Sprintf("mc admin service restart %s", u.targetAlias)
msg += console.Colorize("SetConfigSuccess",
fmt.Sprintf("Please restart your server with `%s`.\n", suggestion))
return
}
// JSON jsonified service status Message message.
// JSON jsonified service status message.
func (u configSetMessage) JSON() string {
if u.setConfigStatus {
u.Status = "success"
} else {
u.Status = "error"
}
u.Status = "success"
statusJSONBytes, e := json.MarshalIndent(u, "", " ")
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
@@ -86,7 +79,7 @@ func (u configSetMessage) JSON() string {
// checkAdminConfigSetSyntax - validate all the passed arguments
func checkAdminConfigSetSyntax(ctx *cli.Context) {
if len(ctx.Args()) == 0 || len(ctx.Args()) > 2 {
if !ctx.Args().Present() && len(ctx.Args()) < 1 {
cli.ShowCommandHelpAndExit(ctx, "set", 1) // last argument is exit code
}
}
@@ -99,7 +92,6 @@ func mainAdminConfigSet(ctx *cli.Context) error {
// Set color preference of command outputs
console.SetColor("SetConfigSuccess", color.New(color.FgGreen, color.Bold))
console.SetColor("SetConfigFailure", color.New(color.FgRed, color.Bold))
// Get the alias parameter from cli
args := ctx.Args()
@@ -107,15 +99,32 @@ func mainAdminConfigSet(ctx *cli.Context) error {
// Create a new MinIO Admin Client
client, err := newAdminClient(aliasedURL)
fatalIf(err, "Cannot get a configured admin connection.")
fatalIf(err, "Unable to initialize admin connection.")
// Call get config API
fatalIf(probe.NewError(client.SetConfig(os.Stdin)), "Cannot set server configuration file.")
input := strings.Join(args.Tail(), " ")
if !strings.Contains(input, madmin.KvSeparator) {
// Call get config API
hr, e := client.HelpConfigKV(globalContext, args.Get(1), args.Get(2), ctx.IsSet("env"))
fatalIf(probe.NewError(e), "Cannot get help for the sub-system")
// Print
printMsg(configHelpMessage{
Value: hr,
envOnly: ctx.IsSet("env"),
})
return nil
}
// Call set config API
fatalIf(probe.NewError(client.SetConfigKV(globalContext, input)),
"Cannot set '%s' to server", input)
// Print set config result
printMsg(configSetMessage{
setConfigStatus: true,
targetAlias: aliasedURL,
targetAlias: aliasedURL,
})
return nil
+7 -3
View File
@@ -1,5 +1,5 @@
/*
* MinIO Client (C) 2017, 2018 MinIO, Inc.
* MinIO Client (C) 2017-2019 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -20,13 +20,17 @@ import "github.com/minio/cli"
var adminConfigCmd = cli.Command{
Name: "config",
Usage: "manage configuration file",
Usage: "manage MinIO server configuration",
Action: mainAdminConfig,
Before: setGlobalsFromContext,
Flags: globalFlags,
Subcommands: []cli.Command{
adminConfigGetCmd,
adminConfigSetCmd,
adminConfigResetCmd,
adminConfigHistoryCmd,
adminConfigRestoreCmd,
adminConfigExportCmd,
adminConfigImportCmd,
},
HideHelpCommand: true,
}
+215
View File
@@ -0,0 +1,215 @@
/*
* MinIO Client (C) 2019 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"
"fmt"
"strings"
"time"
"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"
)
const logTimeFormat string = "15:04:05 MST 01/02/2006"
var adminConsoleFlags = []cli.Flag{
cli.IntFlag{
Name: "limit, l",
Usage: "show last n log entries",
Value: 10,
},
cli.StringFlag{
Name: "type, t",
Usage: "list error logs by type. Valid options are '[minio, application, all]'",
Value: "all",
},
}
var adminConsoleCmd = cli.Command{
Name: "console",
Usage: "show console logs for MinIO server",
Action: mainAdminConsole,
Before: initBeforeRunningCmd,
Flags: append(adminConsoleFlags, globalFlags...),
HideHelpCommand: true,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} [FLAGS] TARGET [NODENAME]
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Show console logs for a MinIO server with alias 'play'
{{.Prompt}} {{.HelpName}} play
2. Show last 5 log entries for node 'node1' on MinIO server with alias 'cluster1'
{{.Prompt}} {{.HelpName}} --limit 5 cluster1 node1
3. Show application error logs on MinIO server with alias 'play'
{{.Prompt}} {{.HelpName}} --type application play
`,
}
func checkAdminLogSyntax(ctx *cli.Context) {
if len(ctx.Args()) == 0 || len(ctx.Args()) > 3 {
cli.ShowCommandHelpAndExit(ctx, "console", 1) // last argument is exit code
}
}
// Extend madmin.LogInfo to add String() and JSON() methods
type logMessage struct {
madmin.LogInfo
}
// JSON - jsonify loginfo
func (l logMessage) JSON() string {
logJSON, err := json.MarshalIndent(&l, "", " ")
fatalIf(probe.NewError(err), "Unable to marshal into JSON.")
return string(logJSON)
}
func getLogTime(lt string) string {
tm, err := time.Parse(time.RFC3339Nano, lt)
if err != nil {
return lt
}
return tm.Format(logTimeFormat)
}
// String - return colorized loginfo as string.
func (l logMessage) String() string {
var hostStr string
var b = &strings.Builder{}
if l.NodeName != "" {
hostStr = fmt.Sprintf("%s ", colorizedNodeName(l.NodeName))
}
log := l.LogInfo
if log.ConsoleMsg != "" {
if strings.HasPrefix(log.ConsoleMsg, "\n") {
fmt.Fprintf(b, "%s\n", hostStr)
log.ConsoleMsg = strings.TrimPrefix(log.ConsoleMsg, "\n")
}
fmt.Fprintf(b, "%s %s", hostStr, log.ConsoleMsg)
return b.String()
}
if l.API != nil {
apiString := "API: " + l.API.Name + "("
if l.API.Args != nil && l.API.Args.Bucket != "" {
apiString = apiString + "bucket=" + l.API.Args.Bucket
}
if l.API.Args != nil && l.API.Args.Object != "" {
apiString = apiString + ", object=" + l.API.Args.Object
}
apiString += ")"
fmt.Fprintf(b, "\n%s %s", hostStr, console.Colorize("API", apiString))
}
if l.Time != "" {
fmt.Fprintf(b, "\n%s Time: %s", hostStr, getLogTime(l.Time))
}
if l.DeploymentID != "" {
fmt.Fprintf(b, "\n%s DeploymentID: %s", hostStr, l.DeploymentID)
}
if l.RequestID != "" {
fmt.Fprintf(b, "\n%s RequestID: %s", hostStr, l.RequestID)
}
if l.RemoteHost != "" {
fmt.Fprintf(b, "\n%s RemoteHost: %s", hostStr, l.RemoteHost)
}
if l.UserAgent != "" {
fmt.Fprintf(b, "\n%s UserAgent: %s", hostStr, l.UserAgent)
}
if l.Trace != nil {
if l.Trace.Message != "" {
fmt.Fprintf(b, "\n%s Error: %s", hostStr, console.Colorize("LogMessage", l.Trace.Message))
}
if l.Trace.Variables != nil {
for key, value := range l.Trace.Variables {
if value != "" {
fmt.Fprintf(b, "\n%s %s=%s", hostStr, key, value)
}
}
}
if l.Trace.Source != nil {
traceLength := len(l.Trace.Source)
for i, element := range l.Trace.Source {
fmt.Fprintf(b, "\n%s %8v: %s", hostStr, traceLength-i, element)
}
}
}
logMsg := strings.TrimPrefix(b.String(), "\n")
return fmt.Sprintf("%s\n", logMsg)
}
// mainAdminConsole - the entry function of console command
func mainAdminConsole(ctx *cli.Context) error {
// Check for command syntax
checkAdminLogSyntax(ctx)
console.SetColor("LogMessage", color.New(color.Bold, color.FgRed))
console.SetColor("Api", color.New(color.Bold, color.FgWhite))
for _, c := range colors {
console.SetColor(fmt.Sprintf("Node%d", c), color.New(c))
}
aliasedURL := ctx.Args().Get(0)
var node string
if len(ctx.Args()) > 1 {
node = ctx.Args().Get(1)
}
var limit int
if ctx.IsSet("limit") {
limit = ctx.Int("limit")
if limit <= 0 {
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")
}
}
logType := strings.ToLower(ctx.String("type"))
if logType != "minio" && logType != "application" && logType != "all" {
fatalIf(errInvalidArgument().Trace(ctx.Args()...), "Invalid value for --type flag. Valid options are [minio, application, all]")
}
// Create a new MinIO Admin Client
client, err := newAdminClient(aliasedURL)
if err != nil {
fatalIf(err.Trace(aliasedURL), "Cannot initialize admin client.")
return nil
}
ctxt, cancel := context.WithCancel(globalContext)
defer cancel()
// Start listening on all console log activity.
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")
}
// drop nodeName from output if specified as cli arg
if node != "" {
logInfo.NodeName = ""
}
printMsg(logMessage{logInfo})
}
return nil
}
+143
View File
@@ -0,0 +1,143 @@
/*
* MinIO Client (C) 2019 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"
"strings"
"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 adminGroupAddCmd = cli.Command{
Name: "add",
Usage: "add users to a new or existing group",
Action: mainAdminGroupAdd,
Before: initBeforeRunningCmd,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} TARGET GROUPNAME MEMBERS...
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Add users 'fivecent' and 'tencent' to the group 'allcents':
{{.Prompt}} {{.HelpName}} myminio allcents fivecent tencent
`,
}
// checkAdminGroupAddSyntax - validate all the passed arguments
func checkAdminGroupAddSyntax(ctx *cli.Context) {
if len(ctx.Args()) < 3 {
cli.ShowCommandHelpAndExit(ctx, "add", 1) // last argument is exit code
}
}
// groupMessage container for content message structure
type groupMessage struct {
op string
Status string `json:"status"`
GroupName string `json:"groupName,omitempty"`
Groups []string `json:"groups,omitempty"`
Members []string `json:"members,omitempty"`
GroupStatus string `json:"groupStatus,omitempty"`
GroupPolicy string `json:"groupPolicy,omitempty"`
}
func (u groupMessage) String() string {
switch u.op {
case "list":
var s []string
for _, g := range u.Groups {
s = append(s, console.Colorize("GroupMessage", g))
}
return strings.Join(s, "\n")
case "disable":
return console.Colorize("GroupMessage", "Disabled group `"+u.GroupName+"` successfully.")
case "enable":
return console.Colorize("GroupMessage", "Enabled group `"+u.GroupName+"` successfully.")
case "add":
membersStr := fmt.Sprintf("{%s}", strings.Join(u.Members, ","))
return console.Colorize("GroupMessage", "Added members "+membersStr+" to group "+u.GroupName+" successfully.")
case "remove":
if len(u.Members) > 0 {
membersStr := fmt.Sprintf("{%s}", strings.Join(u.Members, ","))
return console.Colorize("GroupMessage", "Removed members "+membersStr+" from group "+u.GroupName+" successfully.")
}
return console.Colorize("GroupMessage", "Removed group "+u.GroupName+" successfully.")
case "info":
return strings.Join([]string{
console.Colorize("GroupMessage", "Group: "+u.GroupName),
console.Colorize("GroupMessage", "Status: "+u.GroupStatus),
console.Colorize("GroupMessage", "Policy: "+u.GroupPolicy),
console.Colorize("GroupMessage", "Members: "+strings.Join(u.Members, ",")),
}, "\n")
}
return ""
}
func (u groupMessage) JSON() string {
u.Status = "success"
jsonMessageBytes, e := json.MarshalIndent(u, "", " ")
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
return string(jsonMessageBytes)
}
// mainAdminGroupAdd is the handle for "mc admin group add" command.
func mainAdminGroupAdd(ctx *cli.Context) error {
checkAdminGroupAddSyntax(ctx)
console.SetColor("GroupMessage", color.New(color.FgGreen))
// Get the alias parameter from cli
args := ctx.Args()
aliasedURL := args.Get(0)
// Create a new MinIO Admin Client
client, err := newAdminClient(aliasedURL)
fatalIf(err, "Unable to initialize admin connection.")
members := []string{}
for i := 2; i < ctx.NArg(); i++ {
members = append(members, args.Get(i))
}
gAddRemove := madmin.GroupAddRemove{
Group: args.Get(1),
Members: members,
IsRemove: false,
}
fatalIf(probe.NewError(client.UpdateGroupMembers(globalContext, gAddRemove)).Trace(args...), "Cannot add new group")
printMsg(groupMessage{
op: "add",
GroupName: args.Get(1),
Members: members,
})
return nil
}
+42
View File
@@ -0,0 +1,42 @@
/*
* MinIO Client (C) 2019 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 adminGroupDisableCmd = cli.Command{
Name: "disable",
Usage: "Disable a group",
Action: mainAdminGroupEnableDisable,
Before: initBeforeRunningCmd,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} TARGET GROUPNAME
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Disable group 'allcents'.
{{.Prompt}} {{.HelpName}} myminio allcents
`,
}
+92
View File
@@ -0,0 +1,92 @@
/*
* MinIO Client (C) 2019 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 (
"errors"
"github.com/fatih/color"
"github.com/minio/cli"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio/pkg/console"
"github.com/minio/minio/pkg/madmin"
)
var adminGroupEnableCmd = cli.Command{
Name: "enable",
Usage: "Enable a group",
Action: mainAdminGroupEnableDisable,
Before: initBeforeRunningCmd,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} TARGET GROUPNAME
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Enable group 'allcents'.
{{.Prompt}} {{.HelpName}} myminio allcents
`,
}
// checkAdminGroupEnableSyntax - validate all the passed arguments
func checkAdminGroupEnableSyntax(ctx *cli.Context) {
if len(ctx.Args()) != 2 {
cli.ShowCommandHelpAndExit(ctx, ctx.Command.Name, 1) // last argument is exit code
}
}
// mainAdminGroupEnableDisable is the handle for "mc admin group enable|disable" command.
func mainAdminGroupEnableDisable(ctx *cli.Context) error {
checkAdminGroupEnableSyntax(ctx)
console.SetColor("GroupMessage", color.New(color.FgGreen))
// Get the alias parameter from cli
args := ctx.Args()
aliasedURL := args.Get(0)
// Create a new MinIO Admin Client
client, err := newAdminClient(aliasedURL)
fatalIf(err, "Unable to initialize admin connection.")
group := args.Get(1)
var err1 error
var status madmin.GroupStatus
if ctx.Command.Name == "enable" {
status = madmin.GroupEnabled
} else if ctx.Command.Name == "disable" {
status = madmin.GroupDisabled
} else {
err1 = errors.New("cannot happen")
fatalIf(probe.NewError(err1).Trace(args...), "Could not get group enable")
}
err1 = client.SetGroupStatus(globalContext, group, status)
fatalIf(probe.NewError(err1).Trace(args...), "Could not get group enable")
printMsg(groupMessage{
op: ctx.Command.Name,
GroupName: group,
GroupStatus: string(status),
})
return nil
}
+81
View File
@@ -0,0 +1,81 @@
/*
* MinIO Client (C) 2019 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/fatih/color"
"github.com/minio/cli"
"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: initBeforeRunningCmd,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} TARGET GROUPNAME
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Get info on group 'allcents'.
{{.Prompt}} {{.HelpName}} myminio allcents
`,
}
// checkAdminGroupInfoSyntax - validate all the passed arguments
func checkAdminGroupInfoSyntax(ctx *cli.Context) {
if len(ctx.Args()) != 2 {
cli.ShowCommandHelpAndExit(ctx, "info", 1) // last argument is exit code
}
}
// mainAdminGroupInfo is the handle for "mc admin group info" command.
func mainAdminGroupInfo(ctx *cli.Context) error {
checkAdminGroupInfoSyntax(ctx)
console.SetColor("GroupMessage", color.New(color.FgGreen))
// Get the alias parameter from cli
args := ctx.Args()
aliasedURL := args.Get(0)
// Create a new MinIO Admin Client
client, err := newAdminClient(aliasedURL)
fatalIf(err, "Unable to initialize admin connection.")
group := args.Get(1)
gd, err1 := client.GetGroupDescription(globalContext, group)
fatalIf(probe.NewError(err1).Trace(args...), "Could not get group info")
printMsg(groupMessage{
op: "info",
GroupName: group,
GroupStatus: gd.Status,
GroupPolicy: gd.Policy,
Members: gd.Members,
})
return nil
}
+77
View File
@@ -0,0 +1,77 @@
/*
* MinIO Client (C) 2019 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/fatih/color"
"github.com/minio/cli"
"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: initBeforeRunningCmd,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} TARGET
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. List all groups.
{{.Prompt}} {{.HelpName}} myminio
`,
}
// checkAdminGroupListSyntax - validate all the passed arguments
func checkAdminGroupListSyntax(ctx *cli.Context) {
if len(ctx.Args()) != 1 {
cli.ShowCommandHelpAndExit(ctx, "list", 1) // last argument is exit code
}
}
// mainAdminGroupList is the handle for "mc admin group list" command.
func mainAdminGroupList(ctx *cli.Context) error {
checkAdminGroupListSyntax(ctx)
console.SetColor("GroupMessage", color.New(color.FgGreen))
// Get the alias parameter from cli
args := ctx.Args()
aliasedURL := args.Get(0)
// Create a new MinIO Admin Client
client, err := newAdminClient(aliasedURL)
fatalIf(err, "Unable to initialize admin connection.")
gs, err1 := client.ListGroups(globalContext)
fatalIf(probe.NewError(err1).Trace(args...), "Could not get group list")
printMsg(groupMessage{
op: "list",
Groups: gs,
})
return nil
}
+92
View File
@@ -0,0 +1,92 @@
/*
* MinIO Client (C) 2019 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/fatih/color"
"github.com/minio/cli"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio/pkg/console"
"github.com/minio/minio/pkg/madmin"
)
var adminGroupRemoveCmd = cli.Command{
Name: "remove",
Usage: "remove group or members from a group",
Action: mainAdminGroupRemove,
Before: initBeforeRunningCmd,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} TARGET GROUPNAME [USERNAMES...]
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Remove members 'tencent' and 'fivecent' from group 'allcents'.
{{.Prompt}} {{.HelpName}} myminio allcents tencent fivecent
2. Remove group 'allcents'.
{{.Prompt}} {{.HelpName}} myminio allcents
`,
}
// checkAdminGroupRemoveSyntax - validate all the passed arguments
func checkAdminGroupRemoveSyntax(ctx *cli.Context) {
if len(ctx.Args()) < 2 {
cli.ShowCommandHelpAndExit(ctx, "remove", 1) // last argument is exit code
}
}
// mainAdminGroupRemove is the handle for "mc admin group remove" command.
func mainAdminGroupRemove(ctx *cli.Context) error {
checkAdminGroupRemoveSyntax(ctx)
console.SetColor("GroupMessage", color.New(color.FgGreen))
// Get the alias parameter from cli
args := ctx.Args()
aliasedURL := args.Get(0)
// Create a new MinIO Admin Client
client, err := newAdminClient(aliasedURL)
fatalIf(err, "Unable to initialize admin connection.")
members := []string{}
for i := 2; i < ctx.NArg(); i++ {
members = append(members, args.Get(i))
}
gAddRemove := madmin.GroupAddRemove{
Group: args.Get(1),
Members: members,
IsRemove: true,
}
e := client.UpdateGroupMembers(globalContext, gAddRemove)
fatalIf(probe.NewError(e).Trace(args...), "Could not perform remove operation")
printMsg(groupMessage{
op: "remove",
GroupName: args.Get(1),
Members: members,
})
return nil
}
+42
View File
@@ -0,0 +1,42 @@
/*
* MinIO Client (C) 2019 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 adminGroupCmd = cli.Command{
Name: "group",
Usage: "manage groups",
Action: mainAdminGroup,
Flags: globalFlags,
Subcommands: []cli.Command{
adminGroupAddCmd,
adminGroupRemoveCmd,
adminGroupInfoCmd,
adminGroupListCmd,
adminGroupEnableCmd,
adminGroupDisableCmd,
},
HideHelpCommand: true,
}
// mainAdminGroup is the handle for "mc admin config" command.
func mainAdminGroup(ctx *cli.Context) error {
cli.ShowCommandHelp(ctx, ctx.Args().First())
return nil
// Sub-commands like "get", "set" have their own main.
}
+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
+52 -27
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:
@@ -79,35 +79,34 @@ USAGE:
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
SCAN MODES:
normal (default): Heal objects which are missing on one or more disks.
deep : Heal objects which are missing on one or more disks. Also heal objects with silent data corruption.
normal (default): Heal objects which are missing on one or more disks.
deep : Heal objects which are missing or with silent data corruption on one or more disks.
EXAMPLES:
1. To format newly replaced disks in a MinIO server with alias 'myminio'
$ {{.HelpName}} myminio
1. To format newly replaced disks in a MinIO server with alias 'myminio'
{{.Prompt}} {{.HelpName}} myminio
2. Heal 'testbucket' in a MinIO server with alias 'myminio'
$ {{.HelpName}} myminio/testbucket/
2. Heal 'testbucket' in a MinIO server with alias 'myminio'
{{.Prompt}} {{.HelpName}} myminio/testbucket/
3. Heal all objects under 'dir' prefix
$ {{.HelpName}} --recursive myminio/testbucket/dir/
3. Heal all objects under 'dir' prefix
{{.Prompt}} {{.HelpName}} --recursive myminio/testbucket/dir/
4. Issue a dry-run heal operation to inspect objects health but not heal them
$ {{.HelpName}} --dry-run myminio
4. Issue a dry-run heal operation to inspect objects health but not heal them
{{.Prompt}} {{.HelpName}} --dry-run myminio
5. Issue a dry-run heal operation to inspect objects health under 'dir' prefix
$ {{.HelpName}} --recursive --dry-run myminio/testbucket/dir/
5. Issue a dry-run heal operation to inspect objects health under 'dir' prefix
{{.Prompt}} {{.HelpName}} --recursive --dry-run myminio/testbucket/dir/
6. Force start a running heal sequence (meaning it will force kill the running heal sequence and start a new one)
$ {{.HelpName}} --force-start myminio/testbucket/dir/
6. Force start a running heal sequence (meaning it will force kill the running heal sequence and start a new one)
{{.Prompt}} {{.HelpName}} --force-start myminio/testbucket/dir/
7. Force stop a running heal sequence (meaning it will force kill the running heal sequence)
$ {{.HelpName}} --force-stop myminio/testbucket/dir/
7. Force stop a running heal sequence (meaning it will force kill the running heal sequence)
{{.Prompt}} {{.HelpName}} --force-stop myminio/testbucket/dir/
8. Issue a dry-run heal operation to inspect objects health under 'dir' prefix
$ {{.HelpName}} --dry-run myminio/testbucket/dir/
8. Issue a dry-run heal operation to inspect objects health under 'dir' prefix
{{.Prompt}} {{.HelpName}} --dry-run myminio/testbucket/dir/
`,
}
@@ -151,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
}
@@ -186,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))
@@ -203,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
@@ -222,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{
+150 -231
View File
@@ -1,5 +1,5 @@
/*
* MinIO Client (C) 2016, 2017, 2018 MinIO, Inc.
* MinIO Client (C) 2019 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -17,31 +17,29 @@
package cmd
import (
"errors"
"fmt"
"net/url"
"sort"
"reflect"
"strconv"
"strings"
"time"
humanize "github.com/dustin/go-humanize"
"github.com/dustin/go-humanize/english"
"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 (
adminInfoFlags = []cli.Flag{}
)
var adminInfoCmd = cli.Command{
Name: "info",
Usage: "display MinIO server information",
Action: mainAdminInfo,
Before: setGlobalsFromContext,
Flags: append(adminInfoFlags, globalFlags...),
Before: initBeforeRunningCmd,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
@@ -53,266 +51,187 @@ FLAGS:
{{end}}
EXAMPLES:
1. Get server information of the 'play' MinIO server.
$ {{.HelpName}} play/
{{.Prompt}} {{.HelpName}} play/
`,
}
// backendType - indicates the type of backend storage
type backendType string
const (
fsType = backendType("FS")
erasureType = backendType("Erasure")
)
// fsBackend contains specific FS storage information
type fsBackend struct {
Type backendType `json:"backendType"`
// Wrap "Info" message together with fields "Status" and "Error"
type clusterStruct struct {
Status string `json:"status"`
Error string `json:"error,omitempty"`
Info madmin.InfoMessage `json:"info,omitempty"`
}
// xlBackend contains specific erasure storage information
type xlBackend struct {
Type backendType `json:"backendType"`
OnlineDisks int `json:"onlineDisks"`
OfflineDisks int `json:"offlineDisks"`
// Data disks for currently configured Standard storage class.
StandardSCData int `json:"standardSCData"`
// Parity disks for currently configured Standard storage class.
StandardSCParity int `json:"standardSCParity"`
// Data disks for currently configured Reduced Redundancy storage class.
RRSCData int `json:"rrSCData"`
// Parity disks for currently configured Reduced Redundancy storage class.
RRSCParity int `json:"rrSCParity"`
// List of all disk status.
Sets [][]madmin.DriveInfo `json:"sets"`
}
// backendStatus represents the overall information of all backend storage types
type backendStatus struct {
Used uint64 `json:"used"`
Backend interface{} `json:"backend"`
}
// ServerInfo holds the whole server information that will be
// returned by ServerInfo API.
type ServerInfo struct {
StorageInfo backendStatus `json:"storage"`
ConnStats madmin.ServerConnStats `json:"network"`
Properties madmin.ServerProperties `json:"server"`
}
// infoMessage container to hold service status information.
type infoMessage struct {
Status string `json:"status"`
Service string `json:"service"`
Addr string `json:"address"`
Err string `json:"error"`
*ServerInfo
}
// String colorized service status message.
func (u infoMessage) String() (msg string) {
dot := "●"
// When service is offline
if u.Service == "off" {
msg += fmt.Sprintf("%s %s\n", dot, console.Colorize("PrintB", u.Addr))
msg += fmt.Sprintf(" Status : %s", console.Colorize("InfoFail", "offline"))
return
// 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")
}
// Print error if any and exit
if u.Err != "" {
msg += fmt.Sprintf("%s %s\n", dot, console.Colorize("PrintB", u.Addr))
msg += fmt.Sprintf(" Status : %s\n", console.Colorize("InfoFail", "offline"))
e := u.Err
if strings.Trim(e, " ") == "rpc: retry error" {
e = "unreachable"
}
msg += fmt.Sprintf(" Error : %s", console.Colorize("InfoFail", e))
return
// If nothing has been collected, error out
if u.Info.Servers == nil {
fatal(probe.NewError(errors.New("Cannot get service status")), "")
}
// Print server title
msg += fmt.Sprintf("%s %s\n", dot, console.Colorize("PrintB", u.Addr))
// Initialization
var totalOnlineDisksCluster int
var totalOfflineDisksCluster int
// Status
msg += fmt.Sprintf(" Status : %s\n", console.Colorize("Info", "online"))
// Color palette initialization
console.SetColor("Info", color.New(color.FgGreen, color.Bold))
console.SetColor("InfoFail", color.New(color.FgRed, color.Bold))
// Uptime
msg += fmt.Sprintf(" Uptime : %s\n", humanize.RelTime(time.Now(), time.Now().Add(-u.ServerInfo.Properties.Uptime), "", ""))
// Version
version := u.ServerInfo.Properties.Version
if u.ServerInfo.Properties.Version == "DEVELOPMENT.GOGET" {
version = "<development>"
}
msg += fmt.Sprintf(" Version : %s\n", version)
// Region
if u.ServerInfo.Properties.Region != "" {
msg += fmt.Sprintf(" Region : %s\n", u.ServerInfo.Properties.Region)
}
// ARNs
sqsARNs := ""
for _, v := range u.ServerInfo.Properties.SQSARN {
sqsARNs += fmt.Sprintf("%s ", v)
}
if sqsARNs != "" {
msg += fmt.Sprintf(" SQS ARNs : %s\n", sqsARNs)
}
// Incoming/outgoing
msg += fmt.Sprintf(" Storage : Used %s", humanize.IBytes(u.StorageInfo.Used))
if v, ok := u.ServerInfo.StorageInfo.Backend.(xlBackend); ok {
upBackends := 0
downBackends := 0
for _, set := range v.Sets {
for _, s := range set {
if strings.Contains(s.Endpoint, u.Addr) || s.Endpoint[0] == '/' {
if s.State == "ok" {
upBackends++
} else {
downBackends++
}
}
// 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
}
}
upBackendsString := fmt.Sprintf("%d", upBackends)
if downBackends != 0 {
upBackendsString = console.Colorize("InfoFail", fmt.Sprintf("%d", upBackends))
}
msg += fmt.Sprintf("\n Drives : %s/%d OK\n", upBackendsString, upBackends+downBackends)
}
// Loop through each server and put together info for each one
for _, srv := range u.Info.Servers {
// Check if MinIO server is offline ("Mode" field),
// If offline, error out
if srv.State == "offline" {
// "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\n", console.Colorize("InfoFail", "offline"))
// Continue to the next server
continue
}
// Print server title
msg += fmt.Sprintf("%s %s\n", console.Colorize("Info", dot), console.Colorize("PrintB", srv.Endpoint))
// Uptime
msg += fmt.Sprintf(" Uptime: %s\n", console.Colorize("Info",
humanize.RelTime(time.Now(), time.Now().Add(time.Duration(srv.Uptime)*time.Second), "", "")))
// Version
version := srv.Version
if srv.Version == "DEVELOPMENT.GOGET" {
version = "<development>"
}
msg += fmt.Sprintf(" Version: %s\n", version)
// Network info, only available for non-FS types
var connectionAlive int
totalNodes := strconv.Itoa(len(srv.Network))
if srv.Network != nil {
for _, v := range srv.Network {
if v == "online" {
connectionAlive++
}
}
displayNwInfo := strconv.Itoa(connectionAlive) + "/" + totalNodes
msg += fmt.Sprintf(" Network: %s %s\n", displayNwInfo, console.Colorize("Info", "OK "))
}
if backendType != "FS" {
// Info about drives on a server, only available for non-FS types
var OffDisks int
var OnDisks int
var dispNoOfDisks string
for _, disk := range srv.Disks {
if disk.State == "ok" {
OnDisks++
} else {
OffDisks++
}
}
totalDisksPerServer := OnDisks + OffDisks
totalOnlineDisksCluster += OnDisks
totalOfflineDisksCluster += OffDisks
dispNoOfDisks = strconv.Itoa(OnDisks) + "/" + strconv.Itoa(totalDisksPerServer)
msg += fmt.Sprintf(" Drives: %s %s\n", dispNoOfDisks, console.Colorize("Info", "OK "))
}
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\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("%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
}
// JSON jsonified service status Message message.
func (u infoMessage) JSON() string {
u.Status = "success"
statusJSONBytes, e := json.MarshalIndent(u, "", " ")
// JSON jsonifies service status message.
func (u clusterStruct) JSON() string {
statusJSONBytes, e := json.MarshalIndent(u, "", " ")
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
return string(statusJSONBytes)
}
// checkAdminInfoSyntax - validate all the passed arguments
// checkAdminInfoSyntax - validate arguments passed by a user
func checkAdminInfoSyntax(ctx *cli.Context) {
if len(ctx.Args()) == 0 || len(ctx.Args()) > 2 {
if len(ctx.Args()) == 0 || len(ctx.Args()) > 1 {
cli.ShowCommandHelpAndExit(ctx, "info", 1) // last argument is exit code
}
}
func mainAdminInfo(ctx *cli.Context) error {
// Validate service status syntax.
checkAdminInfoSyntax(ctx)
console.SetColor("Info", color.New(color.FgGreen, color.Bold))
console.SetColor("InfoDegraded", color.New(color.FgYellow, color.Bold))
console.SetColor("InfoFail", color.New(color.FgRed, color.Bold))
// Get the alias parameter from cli
args := ctx.Args()
aliasedURL := args.Get(0)
// Create a new MinIO Admin Client
client, err := newAdminClient(aliasedURL)
fatalIf(err, "Cannot get a configured admin connection.")
fatalIf(err, "Unable to initialize admin connection.")
var clusterInfo clusterStruct
// Fetch info of all servers (cluster or single server)
serversInfo, e := client.ServerInfo()
// Check the availability of the server: online or offline. A server is considered
// offline if we can't get any response or we get a bad format response
var serviceOffline bool
switch e.(type) {
case *json.SyntaxError:
serviceOffline = true
case *url.Error:
serviceOffline = true
}
if serviceOffline {
printMsg(infoMessage{Addr: aliasedURL, Service: "off"})
return nil
}
// If the error is not nil and not unrecognizable, just print it and exit
fatalIf(probe.NewError(e), "Cannot get service status.")
infoMessages := []infoMessage{}
for _, serverInfo := range serversInfo {
// Print the error if exists and jump to the next server
if serverInfo.Error != "" {
infoMessages = append(infoMessages, infoMessage{
Service: "on",
Addr: serverInfo.Addr,
Err: serverInfo.Error,
})
continue
}
// Construct the backend status
storageInfo := backendStatus{
Used: serverInfo.Data.StorageInfo.Used,
}
if serverInfo.Data.StorageInfo.Backend.Type == madmin.Erasure {
storageInfo.Backend = xlBackend{
Type: erasureType,
OnlineDisks: serverInfo.Data.StorageInfo.Backend.OnlineDisks,
OfflineDisks: serverInfo.Data.StorageInfo.Backend.OfflineDisks,
StandardSCData: serverInfo.Data.StorageInfo.Backend.StandardSCData,
StandardSCParity: serverInfo.Data.StorageInfo.Backend.StandardSCParity,
RRSCData: serverInfo.Data.StorageInfo.Backend.RRSCData,
RRSCParity: serverInfo.Data.StorageInfo.Backend.RRSCParity,
Sets: serverInfo.Data.StorageInfo.Backend.Sets,
}
} else {
storageInfo.Backend = fsBackend{
Type: fsType,
}
}
infoMessages = append(infoMessages, (infoMessage{
Service: "on",
Addr: serverInfo.Addr,
Err: serverInfo.Error,
ServerInfo: &ServerInfo{
StorageInfo: storageInfo,
ConnStats: serverInfo.Data.ConnStats,
Properties: serverInfo.Data.Properties,
},
}))
}
sort.Stable(&sortInfoWrapper{infoMessages})
for _, s := range infoMessages {
printMsg(s)
admInfo, e := client.ServerInfo(globalContext)
if e != nil {
clusterInfo.Status = "error"
clusterInfo.Error = e.Error()
} else {
clusterInfo.Status = "success"
clusterInfo.Error = ""
}
clusterInfo.Info = admInfo
printMsg(clusterStruct(clusterInfo))
return nil
}
type sortInfoWrapper struct {
infos []infoMessage
}
func (s *sortInfoWrapper) Len() int {
return len(s.infos)
}
func (s *sortInfoWrapper) Swap(i, j int) {
if s.infos != nil {
s.infos[i], s.infos[j] = s.infos[j], s.infos[i]
}
}
func (s *sortInfoWrapper) Less(i, j int) bool {
if s.infos != nil {
return s.infos[i].Addr < s.infos[j].Addr
}
return false
}
+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
}
+16 -2
View File
@@ -22,27 +22,41 @@ 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,
adminServerUpdateCmd,
adminInfoCmd,
adminUserCmd,
adminGroupCmd,
adminPolicyCmd,
adminConfigCmd,
adminHealCmd,
adminProfileCmd,
adminTopCmd,
adminMonitorCmd,
adminTraceCmd,
adminConsoleCmd,
adminPrometheusCmd,
adminKMSCmd,
adminOBDCmd,
adminBucketCmd,
},
}
const dateTimeFormatFilename = "2006-01-02T15-04-05.999999-07-00"
// mainAdmin is the handle for "mc admin" command.
func mainAdmin(ctx *cli.Context) error {
cli.ShowCommandHelp(ctx, ctx.Args().First())
-252
View File
@@ -1,252 +0,0 @@
/*
* MinIO Client (C) 2019 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"
"net/url"
"sort"
"strings"
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/console"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio/pkg/madmin"
)
var (
adminMonitorFlags = []cli.Flag{}
)
const (
monitor = "BoldGreen"
monitorDegraded = "BoldYellow"
monitorFail = "BoldRed"
)
var adminMonitorCmd = cli.Command{
Name: "monitor",
Usage: "monitor cpu and mem statistics",
Action: mainAdminMonitor,
Before: setGlobalsFromContext,
Flags: append(adminMonitorFlags, globalFlags...),
HideHelpCommand: true,
CustomHelpTemplate: `Name:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} TARGET
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Get server cpu and mem statistics of the 'play' server.
$ {{.HelpName}} play/
`,
}
// serverMonitorMessage holds service status info along with
// cpu, mem, net and disk monitoristics
type serverMonitorMessage struct {
Monitor string `json:"status"`
Service string `json:"service"`
Addr string `json:"address"`
Err string `json:"error"`
CPULoad *madmin.ServerCPULoadInfo `json:"cpu,omitempty"`
MemUsage *madmin.ServerMemUsageInfo `json:"mem,omitempty"`
}
func (s serverMonitorMessage) JSON() string {
s.Monitor = "success"
if s.Err != "" {
s.Monitor = "fail"
}
statusJSONBytes, e := json.MarshalIndent(s, "", " ")
fatalIf(probe.NewError(e), "Unable to marshal into JSON")
return string(statusJSONBytes)
}
func (s serverMonitorMessage) String() string {
msg := ""
dot := "●"
if s.Err != "" || s.Service == "off" {
msg += fmt.Sprintf("%s %s\n", console.Colorize(monitorFail, dot), s.Addr)
msg += fmt.Sprintf(" Server is %s\n", console.Colorize(monitorFail, "offline"))
msg += fmt.Sprintf(" Error : %s\n", console.Colorize(monitorFail, s.Err))
return msg
}
// Print server title
msg += fmt.Sprintf("%s %s \n", console.Colorize(monitor, dot), s.Addr)
msg += "\n"
msg += fmt.Sprintf("%s min avg max\n", console.Colorize(monitor, " CPU"))
for i := range s.CPULoad.Load {
msg += fmt.Sprintf(" current %.2f%% %.2f%% %.2f%%\n", s.CPULoad.Load[i].Min, s.CPULoad.Load[i].Avg, s.CPULoad.Load[i].Max)
if len(s.CPULoad.HistoricLoad) > i {
msg += fmt.Sprintf(" historic %.2f%% %.2f%% %.2f%%\n", s.CPULoad.HistoricLoad[i].Min, s.CPULoad.HistoricLoad[i].Avg, s.CPULoad.HistoricLoad[i].Max)
}
msg += "\n"
}
// Mem section
msg += fmt.Sprintf("%s usage\n", console.Colorize(monitor, " MEM"))
for i := range s.MemUsage.Usage {
msg += fmt.Sprintf(" current %s\n", humanize.IBytes(s.MemUsage.Usage[i].Mem))
if len(s.MemUsage.HistoricUsage) > i {
msg += fmt.Sprintf(" historic %s\n", humanize.IBytes(s.MemUsage.HistoricUsage[i].Mem))
}
msg += "\n"
}
return msg
}
func mainAdminMonitor(ctx *cli.Context) error {
checkAdminMonitorSyntax(ctx)
// set the console colors
console.SetColor(monitor, color.New(color.FgGreen, color.Bold))
console.SetColor(monitorDegraded, color.New(color.FgYellow, color.Bold))
console.SetColor(monitorFail, color.New(color.FgRed, color.Bold))
// Get the alias
args := ctx.Args()
aliasedURL := args.Get(0)
// Create a new MinIO admin client
client, err := newAdminClient(aliasedURL)
fatalIf(err, "Cannot get a configured admin connection.")
printOfflineErrorMessage := func(err error) {
errMsg := ""
if err != nil {
errMsg = err.Error()
}
printMsg(serverMonitorMessage{
Addr: aliasedURL,
Service: "off",
Err: errMsg,
})
}
processErr := func(e error) error {
switch e.(type) {
case *json.SyntaxError:
printOfflineErrorMessage(e)
return e
case *url.Error:
printOfflineErrorMessage(e)
return e
default:
// If the error is not nil and unrecognized, just print it and exit
fatalIf(probe.NewError(e), "Cannot get service status.")
}
return nil
}
// Fetch info of all CPU loads (all MinIO server instances)
cpuLoads, e := client.ServerCPULoadInfo()
if err := processErr(e); err != nil {
// exit immediately if error encountered
return nil
}
sort.Stable(&sortWrapper{cpuLoads: cpuLoads})
memUsages, e := client.ServerMemUsageInfo()
if err := processErr(e); err != nil {
// exit immediately if error encountered
return nil
}
sort.Stable(&sortWrapper{memUsages: memUsages})
for i, cpuLoad := range cpuLoads {
memUsage := memUsages[i]
if cpuLoad.Error != "" {
printMsg(serverMonitorMessage{
Service: "off",
Addr: cpuLoad.Addr,
Err: cpuLoad.Error,
})
continue
}
if memUsage.Error != "" {
printMsg(serverMonitorMessage{
Service: "off",
Addr: memUsage.Addr,
Err: memUsage.Error,
})
continue
}
printMsg(serverMonitorMessage{
Service: "on",
Addr: cpuLoad.Addr,
CPULoad: &cpuLoad,
MemUsage: &memUsage,
})
}
return nil
}
type sortWrapper struct {
cpuLoads []madmin.ServerCPULoadInfo
memUsages []madmin.ServerMemUsageInfo
}
func (s *sortWrapper) Len() int {
if s.cpuLoads != nil {
return len(s.cpuLoads)
}
return len(s.memUsages)
}
func (s *sortWrapper) Swap(i, j int) {
if s.cpuLoads != nil {
s.cpuLoads[i], s.cpuLoads[j] = s.cpuLoads[j], s.cpuLoads[i]
return
}
if s.memUsages != nil {
s.memUsages[i], s.memUsages[j] = s.memUsages[j], s.memUsages[i]
}
}
func (s *sortWrapper) Less(i, j int) bool {
if s.cpuLoads != nil {
return strings.Compare(s.cpuLoads[i].Addr, s.cpuLoads[j].Addr) < 0
}
if s.memUsages != nil {
return strings.Compare(s.memUsages[i].Addr, s.memUsages[j].Addr) < 0
}
return false
}
// checkAdminMonitorSyntax - validate all the passed arguments
func checkAdminMonitorSyntax(ctx *cli.Context) {
if len(ctx.Args()) == 0 || len(ctx.Args()) > 1 {
exit := globalErrorExitStatus
cli.ShowCommandHelpAndExit(ctx, "monitor", exit)
}
}
+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)
+28 -12
View File
@@ -17,20 +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}}
@@ -49,7 +52,7 @@ FLAGS:
{{end}}
EXAMPLES:
1. Add a new canned policy 'writeonly'.
$ {{.HelpName}} myminio writeonly /tmp/writeonly.json
{{.Prompt}} {{.HelpName}} myminio writeonly /tmp/writeonly.json
`,
}
@@ -62,18 +65,21 @@ 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"`
op string
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":
buf, e := json.MarshalIndent(u.PolicyJSON, "", " ")
fatalIf(probe.NewError(e), "Unable to parse policy")
return string(buf)
case "list":
if len(u.PolicyJSON) > 0 {
return string(u.PolicyJSON)
}
policyFieldMaxLen := 20
// Create a new pretty table with cols configuration
return newPrettyTable(" ",
@@ -83,6 +89,13 @@ func (u userPolicyMessage) String() string {
return console.Colorize("PolicyMessage", "Removed policy `"+u.Policy+"` successfully.")
case "add":
return console.Colorize("PolicyMessage", "Added policy `"+u.Policy+"` successfully.")
case "set":
fragment := "user"
if u.IsGroup {
fragment = "group"
}
return console.Colorize("PolicyMessage",
fmt.Sprintf("Policy %s is set on %s `%s`", u.Policy, fragment, u.UserOrGroup))
}
return ""
}
@@ -110,9 +123,12 @@ func mainAdminPolicyAdd(ctx *cli.Context) error {
// Create a new MinIO Admin Client
client, err := newAdminClient(aliasedURL)
fatalIf(err, "Cannot get a configured admin connection.")
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",
+89
View File
@@ -0,0 +1,89 @@
/*
* MinIO Client (C) 2019 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/fatih/color"
"github.com/minio/cli"
"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: initBeforeRunningCmd,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} TARGET POLICYNAME
POLICYNAME:
Name of the policy on the MinIO server.
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Show information on a given policy.
{{.Prompt}} {{.HelpName}} myminio writeonly
`,
}
// checkAdminPolicyInfoSyntax - validate all the passed arguments
func checkAdminPolicyInfoSyntax(ctx *cli.Context) {
if len(ctx.Args()) != 2 {
cli.ShowCommandHelpAndExit(ctx, "info", 1) // last argument is exit code
}
}
// mainAdminPolicyInfo is the handler for "mc admin policy info" command.
func mainAdminPolicyInfo(ctx *cli.Context) error {
checkAdminPolicyInfoSyntax(ctx)
console.SetColor("PolicyMessage", color.New(color.FgGreen))
console.SetColor("Policy", color.New(color.FgBlue))
// Get the alias parameter from cli
args := ctx.Args()
aliasedURL := args.Get(0)
policyName := args.Get(1)
// Create a new MinIO Admin Client
client, err := newAdminClient(aliasedURL)
fatalIf(err, "Unable to initialize admin connection")
policies, e := client.ListCannedPolicies(globalContext)
fatalIf(probe.NewError(e).Trace(args...), "Cannot list policy")
iamp, ok := policies[policyName]
if ok {
printMsg(userPolicyMessage{
op: "info",
Policy: policyName,
PolicyJSON: iamp,
})
} else {
fatalIf(probe.NewError(fmt.Errorf("%s is not found", policyName)), "Unable to display policy")
}
return nil
}
+13 -32
View File
@@ -1,5 +1,5 @@
/*
* MinIO Client (C) 2018 MinIO, Inc.
* MinIO Client (C) 2018-2019 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -17,43 +17,36 @@
package cmd
import (
"fmt"
"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}}
USAGE:
{{.HelpName}} TARGET POLICYNAME
POLICYNAME:
Name of the canned policy on MinIO server.
{{.HelpName}} TARGET
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. List all policies on MinIO server.
$ {{.HelpName}} myminio
2. List only one policy on MinIO server.
$ {{.HelpName}} myminio writeonly
{{.Prompt}} {{.HelpName}} myminio
`,
}
// checkAdminPolicyListSyntax - validate all the passed arguments
func checkAdminPolicyListSyntax(ctx *cli.Context) {
if len(ctx.Args()) < 1 || len(ctx.Args()) > 2 {
if len(ctx.Args()) != 1 {
cli.ShowCommandHelpAndExit(ctx, "list", 1) // last argument is exit code
}
}
@@ -71,28 +64,16 @@ func mainAdminPolicyList(ctx *cli.Context) error {
// Create a new MinIO Admin Client
client, err := newAdminClient(aliasedURL)
fatalIf(err, "Cannot get a configured 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 policyName := args.Get(1); policyName != "" {
if len(policies[policyName]) != 0 {
printMsg(userPolicyMessage{
op: "list",
Policy: policyName,
PolicyJSON: policies[policyName],
})
} else {
fatalIf(probe.NewError(fmt.Errorf("%s is not found", policyName)), "Cannot list the policy")
}
} else {
for k := range policies {
printMsg(userPolicyMessage{
op: "list",
Policy: k,
})
}
for k := range policies {
printMsg(userPolicyMessage{
op: "list",
Policy: k,
})
}
return nil
}
+5 -5
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}}
@@ -43,7 +43,7 @@ FLAGS:
{{end}}
EXAMPLES:
1. Remove 'writeonly' policy on MinIO server.
$ {{.HelpName}} myminio writeonly
{{.Prompt}} {{.HelpName}} myminio writeonly
`,
}
@@ -66,9 +66,9 @@ func mainAdminPolicyRemove(ctx *cli.Context) error {
// Create a new MinIO Admin Client
client, err := newAdminClient(aliasedURL)
fatalIf(err, "Cannot get a configured admin connection.")
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",
+119
View File
@@ -0,0 +1,119 @@
/*
* MinIO Client (C) 2019 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 (
"errors"
"strings"
"github.com/fatih/color"
"github.com/minio/cli"
"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: initBeforeRunningCmd,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} TARGET POLICYNAME [ user=username1 | group=groupname1 ]
POLICYNAME:
Name of the policy on the MinIO server.
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Set the "readwrite" policy for user "james".
{{.Prompt}} {{.HelpName}} myminio readwrite user=james
2. Set the "readonly" policy for group "auditors".
{{.Prompt}} {{.HelpName}} myminio readonly group=auditors
`,
}
var (
errBadUserGroupArg = errors.New("Last argument must be of the form user=xx or group=xx")
)
func checkAdminPolicySetSyntax(ctx *cli.Context) {
if len(ctx.Args()) != 3 {
cli.ShowCommandHelpAndExit(ctx, "set", 1) // last argument is exit code
}
}
func parseEntityArg(arg string) (userOrGroup string, isGroup bool, err error) {
parts := strings.Split(arg, "=")
switch {
case len(parts) != 2:
fallthrough
case parts[1] == "":
err = errBadUserGroupArg
case strings.ToLower(parts[0]) == "user":
userOrGroup = parts[1]
isGroup = false
case strings.ToLower(parts[0]) == "group":
userOrGroup = parts[1]
isGroup = true
default:
err = errBadUserGroupArg
}
return
}
// mainAdminPolicySet is the handler for "mc admin policy set" command.
func mainAdminPolicySet(ctx *cli.Context) error {
checkAdminPolicySetSyntax(ctx)
console.SetColor("PolicyMessage", color.New(color.FgGreen))
console.SetColor("Policy", color.New(color.FgBlue))
// Get the alias parameter from cli
args := ctx.Args()
aliasedURL := args.Get(0)
policyName := args.Get(1)
entityArg := args.Get(2)
userOrGroup, isGroup, e1 := parseEntityArg(entityArg)
fatalIf(probe.NewError(e1).Trace(args...), "Bad last argument")
// Create a new MinIO Admin Client
client, err := newAdminClient(aliasedURL)
fatalIf(err, "Unable to initialize admin connection.")
e := client.SetPolicy(globalContext, policyName, userOrGroup, isGroup)
if e == nil {
printMsg(userPolicyMessage{
op: "set",
Policy: policyName,
UserOrGroup: userOrGroup,
IsGroup: isGroup,
})
} else {
fatalIf(probe.NewError(e), "Cannot set the policy")
}
return nil
}
+4 -3
View File
@@ -1,5 +1,5 @@
/*
* MinIO Client (C) 2018 MinIO, Inc.
* MinIO Client (C) 2018-2019 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -20,14 +20,15 @@ import "github.com/minio/cli"
var adminPolicyCmd = cli.Command{
Name: "policy",
Usage: "manage canned policy",
Usage: "manage policies defined in the MinIO server",
Action: mainAdminPolicy,
Before: setGlobalsFromContext,
Flags: globalFlags,
Subcommands: []cli.Command{
adminPolicyAddCmd,
adminPolicyRemoveCmd,
adminPolicyListCmd,
adminPolicyInfoCmd,
adminPolicySetCmd,
},
HideHelpCommand: true,
}
+27 -16
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
$ {{.HelpName}} --type cpu myminio/
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.")
+5 -5
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:
@@ -45,7 +45,7 @@ FLAGS:
{{end}}
EXAMPLES:
2. Download latest profile data in the current directory
$ {{.HelpName}} myminio/
{{.Prompt}} {{.HelpName}} myminio/
`,
}
@@ -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
@@ -118,7 +118,7 @@ func mainAdminProfileStop(ctx *cli.Context) error {
fi, e := os.Stat(downloadPath)
if e == nil && !fi.IsDir() {
e = moveFile(downloadPath, downloadPath+"."+time.Now().Format("2006-01-02T15:04:05.999999-07:00"))
e = moveFile(downloadPath, downloadPath+"."+time.Now().Format(dateTimeFormatFilename))
fatalIf(probe.NewError(e), "Unable to create a backup of profile.zip")
} else {
if !os.IsNotExist(e) {
+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,
+191
View File
@@ -0,0 +1,191 @@
/*
* MinIO Client (C) 2019 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"
"net/url"
"time"
"github.com/fatih/color"
"github.com/minio/cli"
"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"
yaml "gopkg.in/yaml.v2"
)
const (
defaultJobName = "minio-job"
defaultMetricsPath = "/minio/prometheus/metrics"
)
var adminPrometheusGenerateCmd = cli.Command{
Name: "generate",
Usage: "generates prometheus config",
Action: mainAdminPrometheusGenerate,
Before: initBeforeRunningCmd,
Flags: globalFlags,
HideHelpCommand: true,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} TARGET
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Generate a default prometheus config.
{{.Prompt}} {{.HelpName}} myminio
`,
}
// PrometheusConfig - container to hold the top level scrape config.
type PrometheusConfig struct {
ScrapeConfigs []ScrapeConfig `yaml:"scrape_configs,omitempty"`
}
// String colorized prometheus config yaml.
func (c PrometheusConfig) String() string {
b, err := yaml.Marshal(c)
if err != nil {
return fmt.Sprintf("error creating config string: %s", err)
}
return console.Colorize("yaml", string(b))
}
// JSON jsonified prometheus config.
func (c PrometheusConfig) JSON() string {
jsonMessageBytes, e := json.MarshalIndent(c.ScrapeConfigs[0], "", " ")
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
return string(jsonMessageBytes)
}
// StatConfig - container to hold the targets config.
type StatConfig struct {
Targets []string `yaml:",flow" json:"targets"`
}
// String colorized stat config yaml.
func (t StatConfig) String() string {
b, err := yaml.Marshal(t)
if err != nil {
return fmt.Sprintf("error creating config string: %s", err)
}
return console.Colorize("yaml", string(b))
}
// JSON jsonified stat config.
func (t StatConfig) JSON() string {
jsonMessageBytes, e := json.MarshalIndent(t.Targets, "", " ")
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
return string(jsonMessageBytes)
}
// ScrapeConfig configures a scraping unit for Prometheus.
type ScrapeConfig struct {
JobName string `yaml:"job_name" json:"jobName"`
BearerToken string `yaml:"bearer_token" json:"bearerToken"`
MetricsPath string `yaml:"metrics_path,omitempty" json:"metricsPath"`
Scheme string `yaml:"scheme,omitempty" json:"scheme"`
StaticConfigs []StatConfig `yaml:"static_configs,omitempty" json:"staticConfigs"`
}
const (
defaultPrometheusJWTExpiry = 100 * 365 * 24 * time.Hour
)
var defaultConfig = PrometheusConfig{
ScrapeConfigs: []ScrapeConfig{
{
JobName: defaultJobName,
MetricsPath: defaultMetricsPath,
StaticConfigs: []StatConfig{
{
Targets: []string{""},
},
},
},
},
}
// checkAdminPrometheusSyntax - validate all the passed arguments
func checkAdminPrometheusSyntax(ctx *cli.Context) {
if len(ctx.Args()) != 1 {
cli.ShowCommandHelpAndExit(ctx, "generate", 1) // last argument is exit code
}
}
func generatePrometheusConfig(ctx *cli.Context) error {
// Get the alias parameter from cli
args := ctx.Args()
alias := cleanAlias(args.Get(0))
if !isValidAlias(alias) {
fatalIf(errInvalidAlias(alias), "Invalid alias.")
}
hostConfig := mustGetHostConfig(alias)
if hostConfig == nil {
fatalIf(errInvalidAliasedURL(alias), "No such alias `"+alias+"` found.")
return nil
}
u, err := url.Parse(hostConfig.URL)
if err != nil {
return err
}
jwt := jwtgo.NewWithClaims(jwtgo.SigningMethodHS512, jwtgo.StandardClaims{
ExpiresAt: UTCNow().Add(defaultPrometheusJWTExpiry).Unix(),
Subject: hostConfig.AccessKey,
Issuer: "prometheus",
})
token, err := jwt.SignedString([]byte(hostConfig.SecretKey))
if err != nil {
return err
}
// Setting the values
defaultConfig.ScrapeConfigs[0].BearerToken = token
defaultConfig.ScrapeConfigs[0].Scheme = u.Scheme
defaultConfig.ScrapeConfigs[0].StaticConfigs[0].Targets[0] = u.Host
printMsg(defaultConfig)
return nil
}
// mainAdminPrometheus is the handle for "mc admin prometheus generate" sub-command.
func mainAdminPrometheusGenerate(ctx *cli.Context) error {
console.SetColor("yaml", color.New(color.FgGreen))
checkAdminPrometheusSyntax(ctx)
if err := generatePrometheusConfig(ctx); err != nil {
return nil
}
return nil
}
+20 -21
View File
@@ -1,5 +1,5 @@
/*
* MinIO Client, (C) 2015 MinIO, Inc.
* MinIO Client (C) 2019 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,32 +16,31 @@
package cmd
import (
"github.com/minio/cli"
)
import "github.com/minio/cli"
var (
sessionFlags = []cli.Flag{}
)
// Resume interrupted operations.
var sessionCmd = cli.Command{
Name: "session",
Usage: "resume interrupted operations",
Action: mainSession,
Flags: append(sessionFlags, globalFlags...),
Before: setGlobalsFromContext,
var adminPrometheusCmd = cli.Command{
Name: "prometheus",
Usage: "manages prometheus config",
Action: mainAdminPrometheus,
Flags: globalFlags,
HideHelpCommand: true,
Subcommands: []cli.Command{
sessionList,
sessionClear,
sessionResume,
adminPrometheusGenerateCmd,
},
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} TARGET
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
`,
}
// mainSession - handle for the 'mc session' command.
func mainSession(ctx *cli.Context) error {
// mainAdminPrometheus is the handle for "mc admin prometheus" command.
func mainAdminPrometheus(ctx *cli.Context) error {
cli.ShowCommandHelp(ctx, ctx.Args().First())
return nil
// Sub-commands like "list", "clear", "resume" have their own main.
}
+8 -11
View File
@@ -22,16 +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/madmin"
"github.com/minio/minio/pkg/console"
)
var adminServiceRestartCmd = cli.Command{
Name: "restart",
Usage: "restart MinIO server",
Usage: "restart all MinIO servers",
Action: mainAdminServiceRestart,
Before: setGlobalsFromContext,
Before: initBeforeRunningCmd,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
@@ -43,9 +42,8 @@ FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Restart MinIO server represented by its alias 'play'.
$ {{.HelpName}} play/
1. Restart MinIO server represented by its alias 'play'.
{{.Prompt}} {{.HelpName}} play/
`,
}
@@ -112,11 +110,10 @@ func mainAdminServiceRestart(ctx *cli.Context) error {
aliasedURL := args.Get(0)
client, err := newAdminClient(aliasedURL)
fatalIf(err, "Cannot get a configured admin connection.")
fatalIf(err, "Unable to initialize admin connection.")
// Restart the specified MinIO server
fatalIf(probe.NewError(client.ServiceSendAction(
madmin.ServiceActionValueRestart)), "Cannot restart server.")
fatalIf(probe.NewError(client.ServiceRestart(globalContext)), "Cannot restart the server.")
// Success..
printMsg(serviceRestartCommand{Status: "success", ServerURL: aliasedURL})
@@ -128,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.ServiceStatus()
_, e := client.ServerInfo(globalContext)
if e != nil {
printMsg(serviceRestartMessage{Status: "failure", Err: e, ServerURL: aliasedURL})
-143
View File
@@ -1,143 +0,0 @@
/*
* MinIO Client (C) 2016, 2017 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"
"net/url"
"time"
"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"
)
var (
adminServiceStatusFlags = []cli.Flag{}
)
var adminServiceStatusCmd = cli.Command{
Name: "status",
Usage: "get the status of MinIO server",
Action: mainAdminServiceStatus,
Before: setGlobalsFromContext,
Flags: append(adminServiceStatusFlags, globalFlags...),
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} TARGET
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Check if the 'play' MinIO server is online and show its uptime.
$ {{.HelpName}} play/
`,
}
// serviceStatusMessage container to hold service status information.
type serviceStatusMessage struct {
Status string `json:"status"`
Service string `json:"service"`
Uptime time.Duration `json:"uptime"`
}
// String colorized service status message.
func (u serviceStatusMessage) String() (msg string) {
defer func() {
msg = console.Colorize("ServiceStatus", msg)
}()
// When service is offline
if u.Service == "off" {
msg = "The server is offline."
return
}
msg = fmt.Sprintf("Uptime: %s.", timeDurationToHumanizedDuration(u.Uptime))
return
}
// JSON jsonified service status Message message.
func (u serviceStatusMessage) JSON() string {
switch u.Service {
case "on":
u.Status = "success"
case "off":
u.Status = "failure"
}
statusJSONBytes, e := json.MarshalIndent(u, "", " ")
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
return string(statusJSONBytes)
}
// checkAdminServiceStatusSyntax - validate all the passed arguments
func checkAdminServiceStatusSyntax(ctx *cli.Context) {
if len(ctx.Args()) == 0 || len(ctx.Args()) > 2 {
cli.ShowCommandHelpAndExit(ctx, "status", 1) // last argument is exit code
}
}
func mainAdminServiceStatus(ctx *cli.Context) error {
// Validate serivce status syntax.
checkAdminServiceStatusSyntax(ctx)
console.SetColor("ServiceStatus", color.New(color.FgGreen, color.Bold))
// Get the alias parameter from cli
args := ctx.Args()
aliasedURL := args.Get(0)
// Create a new MinIO Admin Client
client, err := newAdminClient(aliasedURL)
fatalIf(err, "Cannot get a configured admin connection.")
// Fetch the service status of the specified MinIO server
st, e := client.ServiceStatus()
// Check the availability of the server: online or offline. A server is considered
// offline if we can't get any response or we get a bad format response
var serviceOffline bool
switch v := e.(type) {
case *json.SyntaxError:
serviceOffline = true
case *url.Error:
if v.Timeout() {
serviceOffline = true
}
}
if serviceOffline {
printMsg(serviceStatusMessage{Service: "off"})
return nil
}
// If the error is not nil and not unrecognizable, just print it and exit
fatalIf(probe.NewError(e), "Cannot get service status.")
// Print the whole response
printMsg(serviceStatusMessage{
Service: "on",
Uptime: st.Uptime,
})
return nil
}
+7 -10
View File
@@ -1,5 +1,5 @@
/*
* MinIO Client (C) 2018 MinIO, Inc.
* MinIO Client (C) 2018-2019 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -20,16 +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/madmin"
"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}}
@@ -41,9 +40,8 @@ FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Stop MinIO server represented by its alias 'play'.
$ {{.HelpName}} play/
1. Stop MinIO server represented by its alias 'play'.
{{.Prompt}} {{.HelpName}} play/
`,
}
@@ -86,11 +84,10 @@ func mainAdminServiceStop(ctx *cli.Context) error {
aliasedURL := args.Get(0)
client, err := newAdminClient(aliasedURL)
fatalIf(err, "Cannot get a configured admin connection.")
fatalIf(err, "Unable to initialize admin connection.")
// Stop the specified MinIO server
pErr := client.ServiceSendAction(madmin.ServiceActionValueStop)
fatalIf(probe.NewError(pErr), "Cannot stop server.")
fatalIf(probe.NewError(client.ServiceStop(globalContext)), "Unable to stop the server.")
// Success..
printMsg(serviceStopMessage{Status: "success", ServerURL: aliasedURL})
+1 -3
View File
@@ -20,13 +20,11 @@ import "github.com/minio/cli"
var adminServiceCmd = cli.Command{
Name: "service",
Usage: "stop, restart or get status of MinIO server",
Usage: "restart and stop all MinIO servers",
Action: mainAdminService,
Before: setGlobalsFromContext,
Flags: globalFlags,
HideHelpCommand: true,
Subcommands: []cli.Command{
adminServiceStatusCmd,
adminServiceRestartCmd,
adminServiceStopCmd,
},
+5 -6
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:
@@ -45,8 +45,7 @@ FLAGS:
{{end}}
EXAMPLES:
1. Get a list of the 10 oldest locks on a MinIO cluster.
$ {{.HelpName}} myminio/
{{.Prompt}} {{.HelpName}} myminio/
`,
}
@@ -112,10 +111,10 @@ func mainAdminTopLocks(ctx *cli.Context) error {
// Create a new MinIO Admin Client
client, err := newAdminClient(aliasedURL)
fatalIf(err, "Cannot get a configured admin connection.")
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,
+91 -35
View File
@@ -18,18 +18,19 @@ package cmd
import (
"bytes"
"context"
"fmt"
"hash/fnv"
"net/http"
"strconv"
"strings"
"time"
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/console"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio/pkg/console"
"github.com/minio/minio/pkg/madmin"
)
@@ -42,13 +43,17 @@ var adminTraceFlags = []cli.Flag{
Name: "all, a",
Usage: "trace all traffic (including internode traffic between MinIO servers)",
},
cli.BoolFlag{
Name: "errors, e",
Usage: "trace failed requests only",
},
}
var adminTraceCmd = cli.Command{
Name: "trace",
Usage: "show http trace for minio server",
Usage: "show http trace for MinIO server",
Action: mainAdminTrace,
Before: setGlobalsFromContext,
Before: initBeforeRunningCmd,
Flags: append(adminTraceFlags, globalFlags...),
HideHelpCommand: true,
CustomHelpTemplate: `NAME:
@@ -61,12 +66,15 @@ FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Show console trace for a Minio server with alias 'play'
$ {{.HelpName}} play -v -a
`,
1. Show console trace for a MinIO server with alias 'play'
{{.Prompt}} {{.HelpName}} -v -a play
2. Show trace only for failed requests for a MinIO server with alias 'myminio'
{{.Prompt}} {{.HelpName}} -v -e myminio
`,
}
const timeFormat = "15:04:05.00000"
const timeFormat = "15:04:05.000"
var (
colors = []color.Attribute{color.FgCyan, color.FgWhite, color.FgYellow, color.FgGreen}
@@ -84,7 +92,10 @@ func mainAdminTrace(ctx *cli.Context) error {
checkAdminTraceSyntax(ctx)
verbose := ctx.Bool("verbose")
all := ctx.Bool("all")
errfltr := ctx.Bool("errors")
aliasedURL := ctx.Args().Get(0)
console.SetColor("Stat", color.New(color.FgYellow))
console.SetColor("Request", color.New(color.FgCyan))
console.SetColor("Method", color.New(color.Bold, color.FgWhite))
console.SetColor("Host", color.New(color.Bold, color.FgGreen))
@@ -93,24 +104,26 @@ func mainAdminTrace(ctx *cli.Context) error {
console.SetColor("ReqHeaderKey", color.New(color.Bold, color.FgWhite))
console.SetColor("RespHeaderKey", color.New(color.Bold, color.FgCyan))
console.SetColor("HeaderValue", color.New(color.FgWhite))
console.SetColor("ResponseStatus", color.New(color.Bold, color.FgYellow))
console.SetColor("RespStatus", color.New(color.Bold, color.FgYellow))
console.SetColor("ErrStatus", color.New(color.Bold, color.FgRed))
console.SetColor("Response", color.New(color.FgGreen))
console.SetColor("Body", color.New(color.FgYellow))
for _, c := range colors {
console.SetColor(fmt.Sprintf("Node%d", c), color.New(c))
}
// Create a new Minio Admin Client
// Create a new MinIO Admin Client
client, err := newAdminClient(aliasedURL)
if err != nil {
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.Trace(all, 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")
@@ -129,22 +142,23 @@ type shortTraceMsg struct {
Host string `json:"host"`
Time time.Time `json:"time"`
Client string `json:"client"`
CallStats callStats `json:"callStats"`
FuncName string `json:"api"`
Path string `json:"path"`
Query string `json:"query"`
StatusCode int `json:"statuscode"`
StatusMsg string `json:"statusmsg"`
StatusCode int `json:"statusCode"`
StatusMsg string `json:"statusMsg"`
}
type traceMessage struct {
madmin.TraceInfo
madmin.ServiceTraceInfo
}
type requestInfo struct {
Time time.Time `json:"time"`
Method string `json:"method"`
Path string `json:"path,omitempty"`
RawQuery string `json:"rawquery,omitempty"`
RawQuery string `json:"rawQuery,omitempty"`
Headers map[string]string `json:"headers,omitempty"`
Body string `json:"body,omitempty"`
}
@@ -153,7 +167,13 @@ type responseInfo struct {
Time time.Time `json:"time"`
Headers map[string]string `json:"headers,omitempty"`
Body string `json:"body,omitempty"`
StatusCode int `json:"statuscode,omitempty"`
StatusCode int `json:"statusCode,omitempty"`
}
type callStats struct {
Rx int `json:"rx"`
Tx int `json:"tx"`
Duration time.Duration `json:"duration"`
Ttfb time.Duration `json:"timeToFirstByte"`
}
type trace struct {
@@ -161,10 +181,11 @@ type trace struct {
FuncName string `json:"api"`
RequestInfo requestInfo `json:"request"`
ResponseInfo responseInfo `json:"response"`
CallStats callStats `json:"callStats"`
}
// return a struct with minimal trace info.
func shortTrace(ti madmin.TraceInfo) shortTraceMsg {
func shortTrace(ti madmin.ServiceTraceInfo) shortTraceMsg {
s := shortTraceMsg{}
t := ti.Trace
s.Time = t.ReqInfo.Time
@@ -176,14 +197,23 @@ func shortTrace(ti madmin.TraceInfo) shortTraceMsg {
s.FuncName = t.FuncName
s.StatusCode = t.RespInfo.StatusCode
s.StatusMsg = http.StatusText(t.RespInfo.StatusCode)
s.Client = t.ReqInfo.Client
cSlice := strings.Split(t.ReqInfo.Client, ":")
s.Client = cSlice[0]
s.CallStats.Duration = t.CallStats.Latency
s.CallStats.Rx = t.CallStats.InputBytes
s.CallStats.Tx = t.CallStats.OutputBytes
return s
}
func (s shortTraceMsg) JSON() string {
traceJSONBytes, e := json.MarshalIndent(s, "", " ")
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
return string(traceJSONBytes)
buf := &bytes.Buffer{}
enc := json.NewEncoder(buf)
enc.SetIndent("", " ")
// Disable escaping special chars to display XML tags correctly
enc.SetEscapeHTML(false)
fatalIf(probe.NewError(enc.Encode(s)), "Unable to marshal into JSON.")
return buf.String()
}
func (s shortTraceMsg) String() string {
@@ -193,14 +223,28 @@ func (s shortTraceMsg) String() string {
if s.Host != "" {
hostStr = colorizedNodeName(s.Host)
}
fmt.Fprintf(b, "%s %s %s ", s.Time.Format(timeFormat), s.Client, console.Colorize("FuncName", s.FuncName))
fmt.Fprintf(b, "%s ", s.Time.Format(timeFormat))
statusStr := console.Colorize("RespStatus", fmt.Sprintf("%d %s", s.StatusCode, s.StatusMsg))
if s.StatusCode >= http.StatusBadRequest {
statusStr = console.Colorize("ErrStatus", fmt.Sprintf("%d %s", s.StatusCode, s.StatusMsg))
}
fmt.Fprintf(b, "[%s] %s ", statusStr, console.Colorize("FuncName", s.FuncName))
fmt.Fprintf(b, "%s%s", hostStr, s.Path)
if s.Query != "" {
fmt.Fprintf(b, "?%s", s.Query)
fmt.Fprintf(b, "?%s ", s.Query)
}
fmt.Fprintf(b, " %s", console.Colorize("ResponseStatus",
fmt.Sprintf("\t%s %s", strconv.Itoa(s.StatusCode), s.StatusMsg)))
fmt.Fprintf(b, " %s ", s.Client)
spaces := 15 - len(s.Client)
fmt.Fprintf(b, "%*s", spaces, " ")
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.Fprint(b, console.Colorize("HeaderValue", humanize.IBytes(uint64(s.CallStats.Rx))))
fmt.Fprint(b, console.Colorize("Stat", " ↓ "))
fmt.Fprint(b, console.Colorize("HeaderValue", humanize.IBytes(uint64(s.CallStats.Tx))))
return b.String()
}
@@ -209,7 +253,7 @@ func colorizedNodeName(nodeName string) string {
nodeHash := fnv.New32a()
nodeHash.Write([]byte(nodeName))
nHashSum := nodeHash.Sum32()
idx := int(nHashSum) % len(colors)
idx := uint32(nHashSum) % uint32(len(colors))
return console.Colorize(fmt.Sprintf("Node%d", colors[idx]), nodeName)
}
@@ -241,13 +285,20 @@ func (t traceMessage) JSON() string {
Headers: rspHdrs,
StatusCode: rs.StatusCode,
},
CallStats: callStats{
Duration: t.Trace.CallStats.Latency,
Rx: t.Trace.CallStats.InputBytes,
Tx: t.Trace.CallStats.OutputBytes,
Ttfb: t.Trace.CallStats.TimeToFirstByte,
},
}
buf := &bytes.Buffer{}
enc := json.NewEncoder(buf)
enc.SetIndent("", " ")
// Disable escaping special chars to display XML tags correctly
enc.SetEscapeHTML(false)
enc.Encode(trc)
fatalIf(probe.NewError(enc.Encode(trc)), "Unable to marshal into JSON.")
// strip off extra newline added by json encoder
return strings.TrimSuffix(buf.String(), "\n")
}
@@ -264,8 +315,7 @@ func (t traceMessage) String() string {
ri := trc.ReqInfo
rs := trc.RespInfo
fmt.Fprintf(b, "%s%s", nodeNameStr, console.Colorize("Request", fmt.Sprintf("[REQUEST %s] ", trc.FuncName)))
fmt.Fprintf(b, "[%s]\n", ri.Time.Format(timeFormat))
fmt.Fprintf(b, "%s\n", ri.Time.Format(timeFormat))
fmt.Fprintf(b, "%s%s", nodeNameStr, console.Colorize("Method", fmt.Sprintf("%s %s", ri.Method, ri.Path)))
if ri.RawQuery != "" {
fmt.Fprintf(b, "?%s", ri.RawQuery)
@@ -283,10 +333,16 @@ 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]\n", rs.Time.Format(timeFormat))
fmt.Fprintf(b, "%s%s", nodeNameStr, console.Colorize("ResponseStatus",
fmt.Sprintf("%d %s\n", rs.StatusCode, http.StatusText(rs.StatusCode))))
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)))))
statusStr := console.Colorize("RespStatus", fmt.Sprintf("%d %s", rs.StatusCode, http.StatusText(rs.StatusCode)))
if rs.StatusCode != http.StatusOK {
statusStr = console.Colorize("ErrStatus", fmt.Sprintf("%d %s", rs.StatusCode, http.StatusText(rs.StatusCode)))
}
fmt.Fprintf(b, "%s%s\n", nodeNameStr, statusStr)
for k, v := range rs.Headers {
fmt.Fprintf(b, "%s%s", nodeNameStr, console.Colorize("RespHeaderKey",
fmt.Sprintf("%s: ", k))+console.Colorize("HeaderValue", fmt.Sprintf("%s\n", strings.Join(v, ""))))
+117
View File
@@ -0,0 +1,117 @@
/*
* MinIO Client (C) 2018-2019 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/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"
)
var adminServerUpdateCmd = cli.Command{
Name: "update",
Usage: "update all MinIO servers",
Action: mainAdminServerUpdate,
Before: initBeforeRunningCmd,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} TARGET
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Update MinIO server represented by its alias 'play'.
{{.Prompt}} {{.HelpName}} play/
2. Update all MinIO servers in a distributed setup, represented by its alias 'mydist'.
{{.Prompt}} {{.HelpName}} mydist/
`,
}
// serverUpdateMessage is container for ServerUpdate success and failure messages.
type serverUpdateMessage struct {
Status string `json:"status"`
ServerURL string `json:"serverURL"`
CurrentVersion string `json:"currentVersion"`
UpdatedVersion string `json:"updatedVersion"`
}
// String colorized serverUpdate message.
func (s serverUpdateMessage) String() string {
if s.CurrentVersion != s.UpdatedVersion {
return console.Colorize("ServerUpdate",
fmt.Sprintf("Server `%s` updated successfully from %s to %s",
s.ServerURL, s.CurrentVersion, s.UpdatedVersion))
}
return console.Colorize("ServerUpdate",
fmt.Sprintf("Server `%s` already running the most recent version %s of MinIO",
s.ServerURL, s.CurrentVersion))
}
// JSON jsonified server update message.
func (s serverUpdateMessage) JSON() string {
serverUpdateJSONBytes, e := json.MarshalIndent(s, "", " ")
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
return string(serverUpdateJSONBytes)
}
// checkAdminServerUpdateSyntax - validate all the passed arguments
func checkAdminServerUpdateSyntax(ctx *cli.Context) {
if len(ctx.Args()) == 0 || len(ctx.Args()) > 2 {
cli.ShowCommandHelpAndExit(ctx, "update", 1) // last argument is exit code
}
}
func mainAdminServerUpdate(ctx *cli.Context) error {
// Validate serivce update syntax.
checkAdminServerUpdateSyntax(ctx)
// Set color.
console.SetColor("ServerUpdate", color.New(color.FgGreen, color.Bold))
// Get the alias parameter from cli
args := ctx.Args()
aliasedURL := args.Get(0)
client, err := newAdminClient(aliasedURL)
fatalIf(err, "Unable to initialize admin connection.")
updateURL := args.Get(1)
// Update the specified MinIO server, optionally also
// with the provided update URL.
us, e := client.ServerUpdate(globalContext, updateURL)
fatalIf(probe.NewError(e), "Unable to update the server.")
// Success..
printMsg(serverUpdateMessage{
Status: "success",
ServerURL: aliasedURL,
CurrentVersion: us.CurrentVersion,
UpdatedVersion: us.UpdatedVersion,
})
return nil
}
+86 -24
View File
@@ -17,54 +17,74 @@
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}}
USAGE:
{{.HelpName}} TARGET ACCESSKEY SECRETKEY POLICYNAME
{{.HelpName}} TARGET ACCESSKEY SECRETKEY
POLICYNAME:
Name of the policy available on MinIO server.
ACCESSKEY:
Also called as username.
SECRETKEY:
Also called as password.
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Add a new user 'foobar' to MinIO server with policy 'writeonly'.
$ set +o history
$ {{.HelpName}} myminio foobar foo12345 writeonly
$ set -o history
1. Add a new user 'foobar' to MinIO server.
{{.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()) != 4 {
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.")
}
}
// userMessage container for content message structure
type userMessage struct {
op string
Status string `json:"status"`
AccessKey string `json:"accessKey,omitempty"`
SecretKey string `json:"secretKey,omitempty"`
PolicyName string `json:"policyName,omitempty"`
UserStatus string `json:"userStatus,omitempty"`
Status string `json:"status"` // TODO: remove this?
AccessKey string `json:"accessKey,omitempty"`
SecretKey string `json:"secretKey,omitempty"`
PolicyName string `json:"policyName,omitempty"`
UserStatus string `json:"userStatus,omitempty"`
MemberOf []string `json:"memberOf,omitempty"`
}
func (u userMessage) String() string {
@@ -80,8 +100,14 @@ func (u userMessage) String() string {
Field{"AccessKey", accessFieldMaxLen},
Field{"PolicyName", policyFieldMaxLen},
).buildRow(u.UserStatus, u.AccessKey, u.PolicyName)
case "policy":
return console.Colorize("UserMessage", "Set a policy `"+u.PolicyName+"` for user `"+u.AccessKey+"` successfully.")
case "info":
return console.Colorize("UserMessage", strings.Join(
[]string{
fmt.Sprintf("AccessKey: %s", u.AccessKey),
fmt.Sprintf("Status: %s", u.UserStatus),
fmt.Sprintf("PolicyName: %s", u.PolicyName),
fmt.Sprintf("MemberOf: %s", strings.Join(u.MemberOf, ",")),
}, "\n"))
case "remove":
return console.Colorize("UserMessage", "Removed user `"+u.AccessKey+"` successfully.")
case "disable":
@@ -102,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)
@@ -111,19 +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, "Cannot get a configured admin connection.")
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.SetUserPolicy(args.Get(1), args.Get(3))).Trace(args...), "Cannot set user policy for 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",
})
+5 -5
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}}
@@ -41,7 +41,7 @@ FLAGS:
{{end}}
EXAMPLES:
1. Disable a user 'foobar' on MinIO server.
$ {{.HelpName}} myminio foobar
{{.Prompt}} {{.HelpName}} myminio foobar
`,
}
@@ -64,9 +64,9 @@ func mainAdminUserDisable(ctx *cli.Context) error {
// Create a new MinIO Admin Client
client, err := newAdminClient(aliasedURL)
fatalIf(err, "Cannot get a configured admin connection.")
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{
+5 -5
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}}
@@ -41,7 +41,7 @@ FLAGS:
{{end}}
EXAMPLES:
1. Enable a disabled user 'foobar' on MinIO server.
$ {{.HelpName}} myminio foobar
{{.Prompt}} {{.HelpName}} myminio foobar
`,
}
@@ -64,9 +64,9 @@ func mainAdminUserEnable(ctx *cli.Context) error {
// Create a new MinIO Admin Client
client, err := newAdminClient(aliasedURL)
fatalIf(err, "Cannot get a configured admin connection.")
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{
@@ -19,44 +19,41 @@ 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 adminUserPolicyCmd = cli.Command{
Name: "set-policy",
Usage: "set policy for user",
Action: mainAdminUserPolicy,
Before: setGlobalsFromContext,
var adminUserInfoCmd = cli.Command{
Name: "info",
Usage: "display info of a user",
Action: mainAdminUserInfo,
Before: initBeforeRunningCmd,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} TARGET USERNAME POLICYNAME
POLICYNAME:
Name of the canned policy created on MinIO server.
{{.HelpName}} TARGET USERNAME
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Set a policy 'writeonly' to 'foobar' on MinIO server.
$ {{.HelpName}} myminio foobar writeonly
1. Display the info of a user "foobar".
{{.Prompt}} {{.HelpName}} myminio foobar
`,
}
// checkAdminUserPolicySyntax - validate all the passed arguments
func checkAdminUserPolicySyntax(ctx *cli.Context) {
if len(ctx.Args()) != 3 {
cli.ShowCommandHelpAndExit(ctx, "policy", 1) // last argument is exit code
// checkAdminUserAddSyntax - validate all the passed arguments
func checkAdminUserInfoSyntax(ctx *cli.Context) {
if len(ctx.Args()) != 2 {
cli.ShowCommandHelpAndExit(ctx, "info", 1) // last argument is exit code
}
}
// mainAdminUserPolicy is the handle for "mc admin user policy" command.
func mainAdminUserPolicy(ctx *cli.Context) error {
checkAdminUserPolicySyntax(ctx)
// mainAdminUserInfo is the handler for "mc admin user info" command.
func mainAdminUserInfo(ctx *cli.Context) error {
checkAdminUserInfoSyntax(ctx)
console.SetColor("UserMessage", color.New(color.FgGreen))
@@ -66,15 +63,17 @@ func mainAdminUserPolicy(ctx *cli.Context) error {
// Create a new MinIO Admin Client
client, err := newAdminClient(aliasedURL)
fatalIf(err, "Cannot get a configured admin connection.")
fatalIf(err, "Unable to initialize admin connection.")
fatalIf(probe.NewError(client.SetUserPolicy(args.Get(1), args.Get(2))).Trace(args...), "Cannot set user policy for user")
user, e := client.GetUserInfo(globalContext, args.Get(1))
fatalIf(probe.NewError(e).Trace(args...), "Cannot get user info")
printMsg(userMessage{
op: "policy",
op: "info",
AccessKey: args.Get(1),
PolicyName: args.Get(2),
UserStatus: "enabled",
PolicyName: user.PolicyName,
UserStatus: string(user.Status),
MemberOf: user.MemberOf,
})
return nil
+5 -5
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}}
@@ -40,7 +40,7 @@ FLAGS:
{{end}}
EXAMPLES:
1. List all users on MinIO server.
$ {{.HelpName}} myminio
{{.Prompt}} {{.HelpName}} myminio
`,
}
@@ -67,9 +67,9 @@ func mainAdminUserList(ctx *cli.Context) error {
// Create a new MinIO Admin Client
client, err := newAdminClient(aliasedURL)
fatalIf(err, "Cannot get a configured admin connection.")
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 {
+6 -6
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}}
@@ -40,7 +40,7 @@ FLAGS:
{{end}}
EXAMPLES:
1. Remove a user 'foobar' on MinIO server.
$ {{.HelpName}} myminio foobar
{{.Prompt}} {{.HelpName}} myminio foobar
`,
}
@@ -63,10 +63,10 @@ func mainAdminUserRemove(ctx *cli.Context) error {
// Create a new MinIO Admin Client
client, err := newAdminClient(aliasedURL)
fatalIf(err, "Cannot get a configured admin connection.")
fatalIf(err, "Unable to initialize admin connection.")
e := client.RemoveUser(args.Get(1))
fatalIf(probe.NewError(e).Trace(args...), "Cannot remove new user")
e := client.RemoveUser(globalContext, args.Get(1))
fatalIf(probe.NewError(e).Trace(args...), "Cannot remove %s", args.Get(1))
printMsg(userMessage{
op: "remove",
+1 -2
View File
@@ -22,15 +22,14 @@ var adminUserCmd = cli.Command{
Name: "user",
Usage: "manage users",
Action: mainAdminUser,
Before: setGlobalsFromContext,
Flags: globalFlags,
Subcommands: []cli.Command{
adminUserAddCmd,
adminUserPolicyCmd,
adminUserDisableCmd,
adminUserEnableCmd,
adminUserRemoveCmd,
adminUserListCmd,
adminUserInfoCmd,
},
HideHelpCommand: true,
}
+164 -56
View File
@@ -17,6 +17,7 @@
package cmd
import (
"os"
"path/filepath"
"sort"
"strings"
@@ -28,10 +29,56 @@ 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)
}
func completeAdminConfigKeys(aliasPath string, keyPrefix string) (prediction []string) {
// Convert alias/bucket/incompl to alias/bucket/ to list its contents
parentDirPath := filepath.Dir(aliasPath) + "/"
clnt, err := newAdminClient(parentDirPath)
if err != nil {
return nil
}
h, e := clnt.HelpConfigKV(globalContext, "", "", false)
if e != nil {
return nil
}
for _, hkv := range h.KeysHelp {
if strings.HasPrefix(hkv.Key, keyPrefix) {
prediction = append(prediction, hkv.Key)
}
}
return prediction
}
// Complete S3 path. If the prediction result is only one directory,
// then recursively scans it. This is needed to satisfy posener/complete
// (look at posener/complete.PredictFiles)
@@ -49,15 +96,15 @@ 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, DirFirst) {
completeS3Path := alias + getKey(content)
for content := range clnt.List(globalContext, false, false, false, DirFirst) {
cmplS3Path := alias + getKey(content)
if content.Type.IsDir() {
if !strings.HasSuffix(completeS3Path, "/") {
completeS3Path += "/"
if !strings.HasSuffix(cmplS3Path, "/") {
cmplS3Path += "/"
}
}
if strings.HasPrefix(completeS3Path, s3Path) {
prediction = append(prediction, completeS3Path)
if strings.HasPrefix(cmplS3Path, s3Path) {
prediction = append(prediction, cmplS3Path)
}
}
@@ -69,6 +116,43 @@ func completeS3Path(s3Path string) (prediction []string) {
return
}
type adminConfigComplete struct{}
func (adm adminConfigComplete) Predict(a complete.Args) (prediction []string) {
defer func() {
sort.Strings(prediction)
}()
loadMcConfig = loadMcConfigFactory()
conf, err := loadMcConfig()
if err != nil {
return
}
// We have already predicted the keys, we are done.
if len(a.Completed) == 3 {
return
}
arg := a.Last
lastArg := a.LastCompleted
if _, ok := conf.Hosts[filepath.Clean(a.LastCompleted)]; !ok {
if strings.IndexByte(arg, '/') == -1 {
// Only predict alias since '/' is not found
for alias := range conf.Hosts {
if strings.HasPrefix(alias, arg) {
prediction = append(prediction, alias+"/")
}
}
} else {
prediction = completeAdminConfigKeys(arg, "")
}
} else {
prediction = completeAdminConfigKeys(lastArg, arg)
}
return
}
// s3Complete knows how to complete an mc s3 path
type s3Complete struct {
deepLevel int
@@ -135,6 +219,7 @@ func (al aliasComplete) Predict(a complete.Args) (prediction []string) {
return
}
var adminConfigCompleter = adminConfigComplete{}
var s3Completer = s3Complete{}
var aliasCompleter = aliasComplete{}
var fsCompleter = fsComplete{}
@@ -142,61 +227,84 @@ var fsCompleter = fsComplete{}
// The list of all commands supported by mc with their mapping
// with their bash completer function
var completeCmds = map[string]complete.Predictor{
"/ls": complete.PredictOr(s3Completer, fsCompleter),
"/cp": complete.PredictOr(s3Completer, fsCompleter),
"/rm": complete.PredictOr(s3Completer, fsCompleter),
"/rb": complete.PredictOr(s3Complete{deepLevel: 2}, fsCompleter),
"/cat": complete.PredictOr(s3Completer, fsCompleter),
"/head": complete.PredictOr(s3Completer, fsCompleter),
"/diff": complete.PredictOr(s3Completer, fsCompleter),
"/find": complete.PredictOr(s3Completer, fsCompleter),
"/mirror": complete.PredictOr(s3Completer, fsCompleter),
"/pipe": complete.PredictOr(s3Completer, fsCompleter),
"/stat": complete.PredictOr(s3Completer, fsCompleter),
"/watch": complete.PredictOr(s3Completer, fsCompleter),
"/policy": complete.PredictOr(s3Completer, fsCompleter),
"/mb": aliasCompleter,
"/sql": s3Completer,
"/admin/info": aliasCompleter,
"/admin/heal": s3Completer,
"/admin/credential": aliasCompleter,
"/admin/config/get": aliasCompleter,
"/admin/config/set": aliasCompleter,
"/admin/service/status": aliasCompleter,
"/admin/service/restart": aliasCompleter,
"/admin/service/stop": aliasCompleter,
"/admin/trace": aliasCompleter,
"/admin/profile/start": aliasCompleter,
"/admin/profile/stop": aliasCompleter,
"/admin/policy/add": aliasCompleter,
"/admin/policy/list": aliasCompleter,
"/admin/policy/remove": aliasCompleter,
"/admin/user/add": aliasCompleter,
"/admin/user/policy:": aliasCompleter,
"/admin/user/disable": aliasCompleter,
"/admin/user/enable": aliasCompleter,
"/admin/user/list": aliasCompleter,
"/admin/user/remove": aliasCompleter,
// S3 API level commands
"/ls": complete.PredictOr(s3Completer, fsCompleter),
"/cp": complete.PredictOr(s3Completer, fsCompleter),
"/rm": complete.PredictOr(s3Completer, fsCompleter),
"/rb": complete.PredictOr(s3Complete{deepLevel: 2}, fsCompleter),
"/cat": complete.PredictOr(s3Completer, fsCompleter),
"/head": complete.PredictOr(s3Completer, fsCompleter),
"/diff": complete.PredictOr(s3Completer, fsCompleter),
"/find": complete.PredictOr(s3Completer, fsCompleter),
"/mirror": complete.PredictOr(s3Completer, fsCompleter),
"/pipe": complete.PredictOr(s3Completer, fsCompleter),
"/stat": complete.PredictOr(s3Completer, fsCompleter),
"/watch": complete.PredictOr(s3Completer, fsCompleter),
"/policy": complete.PredictOr(s3Completer, fsCompleter),
"/tree": complete.PredictOr(s3Complete{deepLevel: 2}, fsCompleter),
"/du": complete.PredictOr(s3Complete{deepLevel: 2}, fsCompleter),
"/retention": s3Completer,
"/sql": s3Completer,
"/lock": complete.PredictOr(s3Complete{deepLevel: 2}),
"/mb": aliasCompleter,
"/event/add": aliasCompleter,
"/event/list": aliasCompleter,
"/event/remove": aliasCompleter,
"/session/clear": nil,
"/session/list": nil,
"/session/resume": nil,
"/tag/list": s3Completer,
"/tag/remove": s3Completer,
"/tag/set": s3Completer,
"/share/download": nil,
"/share/download": s3Completer,
"/share/list": nil,
"/share/upload": nil,
"/share/upload": s3Completer,
// Admin API commands MinIO only.
"/admin/heal": s3Completer,
"/admin/info": 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,
"/admin/update": aliasCompleter,
"/admin/top/locks": aliasCompleter,
"/admin/service/stop": aliasCompleter,
"/admin/service/restart": aliasCompleter,
"/admin/prometheus/generate": aliasCompleter,
"/admin/profile/start": aliasCompleter,
"/admin/profile/stop": aliasCompleter,
"/admin/policy/info": aliasCompleter,
"/admin/policy/set": aliasCompleter,
"/admin/policy/add": aliasCompleter,
"/admin/policy/list": aliasCompleter,
"/admin/policy/remove": aliasCompleter,
"/admin/user/add": aliasCompleter,
"/admin/user/disable": aliasCompleter,
"/admin/user/enable": aliasCompleter,
"/admin/user/list": aliasCompleter,
"/admin/user/remove": aliasCompleter,
"/admin/user/info": aliasCompleter,
"/admin/group/add": aliasCompleter,
"/admin/group/disable": aliasCompleter,
"/admin/group/enable": aliasCompleter,
"/admin/group/list": aliasCompleter,
"/admin/group/remove": aliasCompleter,
"/admin/group/info": aliasCompleter,
"/config/host/add": nil,
"/config/host/list": aliasCompleter,
@@ -254,6 +362,6 @@ func mainComplete() error {
GlobalFlags: complFlags,
}
// Answer to bash completion call
complete.New("mc", mcComplete).Run()
complete.New(filepath.Base(os.Args[0]), mcComplete).Run()
return nil
}
+32 -26
View File
@@ -18,6 +18,7 @@ package cmd
import (
"bytes"
"context"
"errors"
"fmt"
"io"
@@ -27,8 +28,6 @@ import (
"unicode"
"unicode/utf8"
"golang.org/x/crypto/ssh/terminal"
"github.com/minio/cli"
"github.com/minio/mc/pkg/probe"
)
@@ -45,32 +44,36 @@ 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}}
USAGE:
{{.HelpName}} [FLAGS] SOURCE [SOURCE...]
{{if .VisibleFlags}}
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
{{end}}{{end}}
ENVIRONMENT VARIABLES:
MC_ENCRYPT_KEY: list of comma delimited prefix=secret values
MC_ENCRYPT_KEY: list of comma delimited prefix=secret values
EXAMPLES:
1. Stream an object from Amazon S3 cloud storage to mplayer standard input.
$ {{.HelpName}} s3/mysql-backups/kubecon-mysql-operator.mpv | mplayer -
1. Stream an object from Amazon S3 cloud storage to mplayer standard input.
{{.Prompt}} {{.HelpName}} s3/mysql-backups/kubecon-mysql-operator.mpv | mplayer -
2. Concatenate contents of file1.txt and stdin to standard output.
$ {{.HelpName}} file1.txt - > file.txt
2. Concatenate contents of file1.txt and stdin to standard output.
{{.Prompt}} {{.HelpName}} file1.txt - > file.txt
3. Concatenate multiple files to one.
$ {{.HelpName}} part.* > complete.img
3. Concatenate multiple files to one.
{{.Prompt}} {{.HelpName}} part.* > complete.img
4. Save an encrypted object from Amazon S3 cloud storage to a local file.
$ {{.HelpName}} --encrypt-key 's3/mysql-backups=32byteslongsecretkeymustbegiven1' s3/mysql-backups/backups-201810.gz > /mnt/data/recent.gz
4. Save an encrypted object from Amazon S3 cloud storage to a local file.
{{.Prompt}} {{.HelpName}} --encrypt-key 's3/mysql-backups=32byteslongsecretkeymustbegiven1' s3/mysql-backups/backups-201810.gz > /mnt/data/recent.gz
5. Display the content of encrypted object. In case the encryption key contains non-printable character like tab, pass the
base64 encoded string as key.
{{.Prompt}} {{.HelpName}} --encrypt-key "play/my-bucket/=MzJieXRlc2xvbmdzZWNyZXRrZQltdXN0YmVnaXZlbjE=" play/my-bucket/my-object
`,
}
@@ -137,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 {
@@ -150,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, 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()
@@ -173,7 +176,7 @@ func catOut(r io.Reader, size int64) *probe.Error {
// In case of a user showing the object content in a terminal,
// avoid printing control and other bad characters to avoid
// terminal session corruption
if terminal.IsTerminal(int(os.Stdout.Fd())) {
if isTerminal() {
stdout = newPrettyStdout(os.Stdout)
} else {
stdout = os.Stdout
@@ -208,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
}
@@ -229,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
}
@@ -242,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
+34 -13
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 {
@@ -121,10 +142,10 @@ func newAdminClient(aliasedURL string) (*madmin.AdminClient, *probe.Error) {
}
if hostCfg == nil {
return nil, probe.NewError(fmt.Errorf("The specified alias: %s not found", urlStrFull))
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
+363 -276
View File
File diff suppressed because it is too large Load Diff
+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, 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, 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, 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, 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)
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)
err = fsClient.MakeBucket(context.Background(), "us-east-1", true, false)
c.Assert(err, IsNil)
_, err = fsClient.Stat(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)
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, 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'.
+853 -496
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)
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, 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, 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, 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
{
+27 -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 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 bool, encKeyDB map[string][]prefixSSEPa
alias, _ := url2Alias(urlStr)
sse := getSSE(urlStr, encKeyDB[alias])
content, err = client.Stat(false, isFetchMeta, sse)
content, err = client.Stat(ctx, false, fileAttr, sse)
if err != nil {
return nil, nil, err.Trace(urlStr)
}
@@ -218,7 +231,8 @@ func isURLPrefixExists(urlPrefix string, incomplete bool) bool {
}
isRecursive := false
isIncomplete := incomplete
for entry := range clnt.List(isRecursive, isIncomplete, DirNone) {
isFetchMeta := false
for entry := range clnt.List(globalContext, isRecursive, isIncomplete, isFetchMeta, DirNone) {
return entry.Err == nil
}
return false
+58 -31
View File
@@ -22,9 +22,11 @@ import (
"os"
"time"
"github.com/minio/mc/cmd/ilm"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio-go/v6"
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,67 +47,92 @@ const defaultMultipartThreadsNum = 4
// Client - client interface
type Client interface {
// Common operations
Stat(isIncomplete, isFetchMeta bool, sse encrypt.ServerSide) (content *clientContent, err *probe.Error)
List(isRecursive, isIncomplete 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 bool) *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(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
StorageClass string
Metadata map[string]string
UserMetadata map[string]string
ETag string
Expires time.Time
EncryptionHeaders map[string]string
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
+327 -78
View File
@@ -1,5 +1,5 @@
/*
* MinIO Client (C) 2015 MinIO, Inc.
* MinIO Client (C) 2015-2019 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -18,20 +18,59 @@ package cmd
import (
"context"
"encoding/base64"
"errors"
"io"
"net/http"
"os"
"path/filepath"
"regexp"
"strings"
"time"
"golang.org/x/net/http/httpguts"
"gopkg.in/h2non/filetype.v1"
"github.com/minio/cli"
"github.com/minio/mc/pkg/probe"
minio "github.com/minio/minio-go/v6"
"github.com/minio/minio-go/v6/pkg/encrypt"
)
// decode if the key is encoded key and returns the key
func getDecodedKey(sseKeys string) (key string, err *probe.Error) {
keyString := ""
for i, sse := range strings.Split(sseKeys, ",") {
if i > 0 {
keyString = keyString + ","
}
sseString, err := parseKey(sse)
if err != nil {
return "", err
}
keyString = keyString + sseString
}
return keyString, nil
}
// Validate the key
func parseKey(sseKeys string) (sse string, err *probe.Error) {
encryptString := strings.SplitN(sseKeys, "=", 2)
if len(encryptString) < 2 {
return "", probe.NewError(errors.New("SSE-C prefix should be of the form prefix1=key1,... "))
}
secretValue := encryptString[1]
if len(secretValue) == 32 {
return sseKeys, nil
}
decodedString, e := base64.StdEncoding.DecodeString(secretValue)
if e != nil || len(decodedString) != 32 {
return "", probe.NewError(errors.New("Encryption key should be 32 bytes plain text key or 44 bytes base64 encoded key"))
}
return encryptString[0] + "=" + string(decodedString), nil
}
// parse and return encryption key pairs per alias.
func getEncKeys(ctx *cli.Context) (map[string][]prefixSSEPair, *probe.Error) {
sseServer := os.Getenv("MC_ENCRYPT")
@@ -46,6 +85,13 @@ func getEncKeys(ctx *cli.Context) (map[string][]prefixSSEPair, *probe.Error) {
}
sseKeys = keyPrefix
}
var err *probe.Error
if sseKeys != "" {
sseKeys, err = getDecodedKey(sseKeys)
if err != nil {
return nil, err.Trace(sseKeys)
}
}
encKeyDB, err := parseAndValidateEncryptionKeys(sseKeys, sseServer)
if err != nil {
@@ -58,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, keys)
_, targetContent, err := url2Stat(ctx, aliasURL, false, keys)
if err == nil {
return targetContent.Type.IsDir()
}
@@ -95,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, 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)
}
}
}
@@ -167,13 +269,50 @@ func getSourceStream(alias string, urlStr string, fetchStat bool, sse encrypt.Se
return reader, metadata, nil
}
// putTargetRetention sets retention headers if any
func putTargetRetention(ctx context.Context, alias string, urlStr string, metadata map[string]string) *probe.Error {
targetClnt, err := newClientFromAlias(alias, urlStr)
if err != nil {
return err.Trace(alias, urlStr)
}
lockModeStr, ok := metadata[AmzObjectLockMode]
lockMode := minio.RetentionMode("")
if ok {
lockMode = minio.RetentionMode(lockModeStr)
delete(metadata, AmzObjectLockMode)
}
retainUntilDateStr, ok := metadata[AmzObjectLockRetainUntilDate]
retainUntilDate := timeSentinel
if ok {
delete(metadata, AmzObjectLockRetainUntilDate)
if t, e := time.Parse(time.RFC3339, retainUntilDateStr); e == nil {
retainUntilDate = t.UTC()
}
}
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)
}
@@ -181,114 +320,224 @@ 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)
}
return nil
}
// createUserMetadata - returns a map of user defined function
// by combining the usermetadata of object and values passed by attr keyword
func createUserMetadata(sourceAlias, sourceURLStr string, srcSSE encrypt.ServerSide, urls URLs) (map[string]string, *probe.Error) {
func filterMetadata(metadata map[string]string) map[string]string {
newMetadata := map[string]string{}
for k, v := range metadata {
if httpguts.ValidHeaderFieldName(k) && httpguts.ValidHeaderFieldValue(v) {
newMetadata[k] = v
}
}
for k := range metadata {
if strings.HasPrefix(http.CanonicalHeaderKey(k), http.CanonicalHeaderKey(serverEncryptionKeyPrefix)) {
delete(newMetadata, k)
}
}
return newMetadata
}
// getAllMetadata - returns a map of user defined function
// by combining the usermetadata of object and values passed by attr keyword
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, srcSSE)
st, err := sourceClnt.Stat(ctx, false, preserve, srcSSE)
if err != nil {
return nil, err.Trace(sourceAlias, sourceURLStr)
}
for k, v := range st.Metadata {
if httpguts.ValidHeaderFieldName(k) && strings.HasPrefix(k, "X-Amz-Meta-") &&
httpguts.ValidHeaderFieldValue(v) {
metadata[k] = v
}
metadata[http.CanonicalHeaderKey(k)] = v
}
for k, v := range urls.TargetContent.UserMetadata {
metadata[k] = v
metadata[http.CanonicalHeaderKey(k)] = v
}
return metadata, nil
return filterMetadata(metadata), nil
}
// 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
targetURL := urls.TargetContent.URL
length := urls.SourceContent.Size
sourcePath := filepath.ToSlash(filepath.Join(sourceAlias, urls.SourceContent.URL.Path))
targetPath := filepath.ToSlash(filepath.Join(targetAlias, urls.TargetContent.URL.Path))
srcSSE := getSSE(sourcePath, encKeyDB[sourceAlias])
tgtSSE := getSSE(targetPath, encKeyDB[targetAlias])
// Optimize for server side copy if the host is same.
if sourceAlias == targetAlias {
var err *probe.Error
var metadata = map[string]string{}
var mode, until, legalHold string
metadata, err := createUserMetadata(sourceAlias, sourceURL.String(), srcSSE, urls)
// 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 {
// 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()))
}
}
// 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)
err = copySourceToTargetURL(targetAlias, targetURL.String(), sourcePath, length, progress, srcSSE, tgtSSE, metadata)
if err != nil {
if urls.SourceContent.RetentionEnabled {
err = putTargetRetention(ctx, targetAlias, targetURL.String(), metadata)
return urls.WithError(err.Trace(sourceURL.String()))
}
} else {
err = copySourceToTargetURL(ctx, targetAlias, targetURL.String(), sourcePath, mode, until,
legalHold, length, progress, srcSSE, tgtSSE, filterMetadata(metadata), urls.DisableMultipart)
} else {
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()))
}
}
// 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
if urls.TargetContent.Metadata != nil {
for k, v := range urls.TargetContent.Metadata {
metadata[k] = v
}
for k, v := range urls.TargetContent.Metadata {
metadata[http.CanonicalHeaderKey(k)] = v
}
// Get userMetadata from target content as well
if urls.TargetContent.UserMetadata != nil {
for k, v := range urls.TargetContent.UserMetadata {
metadata[k] = v
}
for k, v := range urls.TargetContent.UserMetadata {
metadata[http.CanonicalHeaderKey(k)] = v
}
if srcSSE != nil {
delete(metadata, "X-Amz-Server-Side-Encryption-Customer-Algorithm")
delete(metadata, "X-Amz-Server-Side-Encryption-Customer-Key-Md5")
}
_, err = putTargetStream(ctx, targetAlias, targetURL.String(), reader, length, metadata, progress, tgtSSE)
if err != nil {
return urls.WithError(err.Trace(targetURL.String()))
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)
}
}
if err != nil {
return urls.WithError(err.Trace(sourceURL.String()))
}
return urls.WithError(nil)
}
@@ -311,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)
}
+70
View File
@@ -0,0 +1,70 @@
/*
* MinIO Client (C) 2019 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 (
"errors"
"reflect"
"testing"
)
func TestGetDecodedKey(t *testing.T) {
getDecodeCases := []struct {
input string
output string
err error
status bool
}{
//success scenario the key contains non printable (tab) character as key
{"s3/documents/=MzJieXRlc2xvbmdzZWNyZWFiY2RlZmcJZ2l2ZW5uMjE=", "s3/documents/=32byteslongsecreabcdefg givenn21", nil, true},
//success scenario the key contains non printable (tab character) as key
{"s3/documents/=MzJieXRlc2xvbmdzZWNyZWFiY2RlZmcJZ2l2ZW5uMjE=,play/documents/=MzJieXRlc2xvbmdzZWNyZXRrZQltdXN0YmVnaXZlbjE=", "s3/documents/=32byteslongsecreabcdefg givenn21,play/documents/=32byteslongsecretke mustbegiven1", nil, true},
// success scenario using a normal string
{"s3/documents/=32byteslongsecretkeymustbegiven1", "s3/documents/=32byteslongsecretkeymustbegiven1", nil, true},
// success scenario using a normal string
{"s3/documents/=32byteslongsecretkeymustbegiven1,myminio/documents/=32byteslongsecretkeymustbegiven2", "s3/documents/=32byteslongsecretkeymustbegiven1,myminio/documents/=32byteslongsecretkeymustbegiven2", nil, true},
// success scenario using a mix of normal string and encoded string
{"s3/documents/=MzJieXRlc2xvbmdzZWNyZWFiY2RlZmcJZ2l2ZW5uMjE=,play/documents/=32byteslongsecretkeymustbegiven1", "s3/documents/=32byteslongsecreabcdefg givenn21,play/documents/=32byteslongsecretkeymustbegiven1", nil, true},
// success scenario using a mix of normal string and encoded string
{"play/documents/=32byteslongsecretkeymustbegiven1,s3/documents/=MzJieXRlc2xvbmdzZWNyZWFiY2RlZmcJZ2l2ZW5uMjE=", "play/documents/=32byteslongsecretkeymustbegiven1,s3/documents/=32byteslongsecreabcdefg givenn21", nil, true},
// decoded key less than 32 char and conatin non printable (tab) character
{"s3/documents/=MzJieXRlc2xvbmdzZWNyZWFiY2RlZmcJZ2l2ZW5uMjE", "", errors.New("Encryption key should be 32 bytes plain text key or 44 bytes base64 encoded key"), false},
// normal key less than 32 character
{"s3/documents/=32byteslongsecretkeymustbegiven", "", errors.New("Encryption key should be 32 bytes plain text key or 44 bytes base64 encoded key"), false},
}
for idx, testCase := range getDecodeCases {
decodedString, errDecode := getDecodedKey(testCase.input)
if testCase.status == true {
if errDecode != nil {
t.Fatalf("Test %d: generated error not matching, expected = `%s`, found = `%s`", idx+1, testCase.err, errDecode)
}
if !reflect.DeepEqual(decodedString, testCase.output) {
t.Fatalf("Test %d: generated key not matching, expected = `%s`, found = `%s`", idx+1, testCase.input, decodedString)
}
}
if testCase.status == false {
if !reflect.DeepEqual(decodedString, testCase.output) {
t.Fatalf("Test %d: generated Map not matching, expected = `%s`, found = `%s`", idx+1, testCase.input, errDecode)
}
if errDecode.Cause.Error() != testCase.err.Error() {
t.Fatalf("Test %d: generated error not matching, expected = `%s`, found = `%s`", idx+1, testCase.err, errDecode)
}
}
}
}
+53 -2
View File
@@ -18,14 +18,19 @@ package cmd
import (
"fmt"
"os"
"path/filepath"
"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"
)
func fixConfig() {
// Migrate config location on windows
fixConfigLocation()
// Fix config V3
fixConfigV3()
// Fix config V6
@@ -132,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.
@@ -240,3 +245,49 @@ func fixConfigV6() {
console.Infof("Successfully fixed %s broken config for version `6`.\n", mustGetMcConfigPath())
}
}
// fixConfigLocation will resolve the possible duplicate location of Windows config files.
// If there is duplicate configs, it will use the currently enabled config location and
// move it to the 'normalized' location.
// See https://github.com/minio/mc/pull/2898
func fixConfigLocation() {
if runtime.GOOS != "windows" || mcCustomConfigDir != mustGetMcConfigDir() {
return
}
if !strings.HasSuffix(strings.ToLower(filepath.Base(os.Args[0])), ".exe") {
// Most likely scenario, command was called as 'mc'.
// 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
}
// mc was called with '.exe';
// config can have changed location.
_, err := os.Stat(mcCustomConfigDir)
wantExists := !os.IsNotExist(err)
legFileName := mcCustomConfigDir + ".exe"
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)
// Rename the 'mc' config and move the legacy location one to where we want it.
backupdir := fmt.Sprintf("%s.unused\\", mcCustomConfigDir)
_ = os.RemoveAll(backupdir)
err := os.Rename(mcCustomConfigDir, backupdir)
fatalIf(probe.NewError(err), fmt.Sprintln("Renaming unused config", mcCustomConfigDir, "->", backupdir, "failed. Please rename/remove file."))
fallthrough
case !wantExists && legExists:
err := os.Rename(legFileName, mcCustomConfigDir)
fatalIf(probe.NewError(err), fmt.Sprintln("Migrating config location", legFileName, "->", mcCustomConfigDir, "failed. Please move config file."))
default:
// Legacy does not exist.
}
}
+126 -71
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:
@@ -55,49 +63,50 @@ FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Add Amazon S3 storage service under "mys3" alias. For security reasons turn off bash history momentarily.
$ set +o history
$ {{.HelpName}} mys3 https://s3.amazonaws.com \
1. Add MinIO service under "myminio" alias. For security reasons turn off bash history momentarily.
{{.DisableHistory}}
{{.Prompt}} {{.HelpName}} myminio http://localhost:9000 minio minio123
{{.EnableHistory}}
2. Add MinIO service under "myminio" alias, to use dns style bucket lookup. For security reasons
turn off bash history momentarily.
{{.DisableHistory}}
{{.Prompt}} {{.HelpName}} myminio http://localhost:9000 minio minio123 --api "s3v4" --lookup "dns"
{{.EnableHistory}}
3. Add Amazon S3 storage service under "mys3" alias. For security reasons turn off bash history momentarily.
{{.DisableHistory}}
{{.Prompt}} {{.HelpName}} mys3 https://s3.amazonaws.com \
BKIKJAA5BMMU2RHO6IBB V8f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12
$ set -o history
{{.EnableHistory}}
2. Add Amazon S3 accelerated storage service under "mys3-accel" alias. For security reasons turn off bash history momentarily.
$ set +o history
$ {{.HelpName}} mys3-accel https://s3-accelerate.amazonaws.com \
BKIKJAA5BMMU2RHO6IBB V8f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12
$ set -o history
3. Add Amazon S3 IAM temporary credentials with limited access, please make sure to override the signature probe by explicitly
providing the signature type.
$ set +o history
$ {{.HelpName}} mys3-iam https://s3.amazonaws.com \
BKIKJAA5BMMU2RHO6IBB V8f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12 --api "s3v4"
$ set -o history
4. Add S3 API compatible storage service under "myminio" alias, to use dns style bucket lookup. For security reasons turn off bash history momentarily.
$ set +o history
$ {{.HelpName}} myminio http://localhost:9000 \
minio minio123 --api "s3v4" --lookup "dns"
$ set -o history
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.")
}
@@ -151,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{
@@ -159,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, 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, 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,
@@ -211,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)
}
@@ -221,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,
+7 -13
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:
@@ -44,10 +44,10 @@ FLAGS:
{{end}}
EXAMPLES:
1. List all hosts.
$ {{.HelpName}}
{{.Prompt}} {{.HelpName}}
2. List a specific host.
$ {{.HelpName}} s3
{{.Prompt}} {{.HelpName}} s3
`,
}
@@ -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
}
+6 -6
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:
@@ -41,7 +41,7 @@ FLAGS:
{{end}}
EXAMPLES:
1. Remove "goodisk" from config.
$ {{.HelpName}} goodisk
{{.Prompt}} {{.HelpName}} goodisk
`,
}
@@ -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+"`.")
}
}

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