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
Anis Elleuch df9320134b autocompletion: Add control flag and a prompt (#2812)
*) Add --no-autocompletion to disable the automatic install of
the auto completion
*) Add a prompt to ask for permission to install automatic
auto completion when not installed yet
2019-07-04 22:40:56 -07:00
Harshavardhana 6003da8daa update command with json flag shouldn't throw prompt (#2809) 2019-06-27 15:43:14 -07:00
kannappanr 41e3ea5664 Update latest minio-go version in go.mod (#2811) 2019-06-27 12:58:04 -07:00
Krishnan Parthasarathi 8b33b2809c Improve next action suggestion in mc admin config set (#2810) 2019-06-27 12:15:21 -07:00
Ashish Kumar Sinha 56309a4999 mc command cleanup (#2783) 2019-06-27 14:47:08 +05:30
Anis Elleuch 2d691508c2 Show background heal stats in mc admin heal (#2808) 2019-06-26 15:14:20 -07:00
Harshavardhana 98e88c2ff0 Add proper JSON status field for API compatibility (#2807) 2019-06-26 10:51:17 -07:00
poornas 675618574a Change short trace message display format (#2798)
to abridge function name,time format and
add client ip in the output
2019-06-24 15:43:23 -07:00
Harshavardhana d97cfaa55d Fix trace formatting (#2805) 2019-06-19 15:11:03 -07:00
Adara ec76f67668 doc: add info about --attr flag for cp command (#2793) 2019-06-19 12:13:20 -07:00
Harshavardhana a12c507bec Update minio-go to v6.0.29 (#2799) 2019-06-15 10:12:32 -07:00
poornas ca26dac8e2 Add mc admin trace command. (#2655) 2019-06-11 16:25:33 -07:00
Harshavardhana 5d0a9c0803 Make sure to preserve region specific URLs (#2791)
This is to ensure that restricted access
to certain buckets is allowed on certain
regions.

This is a continuation of last commit
2019-06-11 13:59:10 -07:00
Harshavardhana b85dabd6b4 Update to minio-go v6.0.28 (#2790) 2019-06-06 18:11:49 +05:30
Harshavardhana e978c71b7c Add staticcheck based builds (#2788)
Additionally this PR also supports
multi-platform builds to avoid cross
platform build issues.
2019-06-03 11:22:31 -07:00
Anis Elleuch eb9493458e autocomplete: update github.com/posener/complete to include macOS fix (#2784)
https://github.com/posener/complete/commit/afda8e00c6d48e7d20bff281c321bc8aca00699a
is sent to fix a rare macOS issue with installing completion command.

The commit will require a specific commit in posener/complete to have our fix
included.
2019-05-29 17:55:15 -07:00
Harshavardhana f4bb0b8850 Update minio-go to latest release v6.0.26 (#2782) 2019-05-29 08:27:18 -07:00
Aditya Manthramurthy dd4e356c64 Fixup go.mod and go.sum files (#2777) 2019-05-24 20:02:30 -07:00
Harshavardhana c1ed052638 Update madmin API deps with new retry functionality (#2769) 2019-05-11 00:04:08 -07:00
Andreas Auernhammer 88a3c2b1e1 remove admin-credential command (#2767)
This commit removes the admin credentials command
to fix the build since github.com/minio/minio
ae002aa7241bd35d5fd9b47e8b62df2176ad2ab1 removes
the admin API for updating the admin credentials.
2019-05-05 22:32:41 -07:00
Ashish Kumar Sinha f0f156aca8 Skip error upon deletion of non existing object and force flag (#2765)
On the similar lines of standard linux  rm command.
mc retruns exit status as 0 and skips the error message when --force argument is used.
2019-05-02 10:18:15 -07:00
Harshavardhana b1aa2232ef Disable http2.0 for now until upstream bugs are fixed (#2764) 2019-05-01 15:42:36 -07:00
Ashish Kumar Sinha 4b4555b811 Policy list: Return error if policy doesn't exist (#2760) 2019-04-25 13:41:46 -07:00
poornas ecdeb3934d Remove Insufficient permission error from ignored errors (#2755)
Remove Insufficient permission error from ignored list of errors.

Fixes #2752 -  When mirror fails due to insufficient
permissions of user on a bucket, this should be
displayed
2019-04-22 12:22:21 -07:00
fgma abceea8fa1 fix crash when parsing empty/invalid MC_HOST_* env variable (#2757) 2019-04-22 21:53:31 +05:30
ebozduman 83a9d8b91d Adds missing codebase MinIO and min.io changes (#2745) 2019-04-16 22:31:54 -07:00
kannappanr 68a9eeae18 Fix: do not check if object listed equals object being removed (#2748)
List within the statURL function considers object name as a prefix
and lists objects that have the same prefix.
currently, it errors out if the object is a subset of another object.

This PR will fix this.

Fixes #2746
2019-04-16 20:44:57 -07:00
kannappanr 5729a01e69 doc: Document top command (#2672) 2019-04-10 15:48:45 -07:00
kannappanr ea469140d5 Display request header in anonymous mode (#2733)
Currently if authorization header is missing, then request is not displayed
This resulted in just the response being displayed, in anonymous mode.

This PR fixes that issue.
2019-04-05 14:04:16 -07:00
ebozduman b5b7a56eca Replace Minio refs with MinIO and links in mc docs (#2742) 2019-04-05 14:03:18 -07:00
Harshavardhana 66677d7c21 alpine 3.7 is eol'ed migrate (#2743)
Alpine 3.7 is EOL. This PR migrates to Alpine 3.9
2019-04-04 12:07:53 -07:00
Harshavardhana 7805774cf3 Instead of rename use moveFile for cross device renames (#2738) 2019-04-03 12:19:53 -07:00
poornas 8ae04b41b0 mirror: fix 0 byte files not getting mirrored (#2739)
Fixes: #2737
2019-04-03 08:15:17 -07:00
Harshavardhana b27cd5ada8 Make csv-input optional for default cases (#2741)
Fixes #2740
2019-04-03 18:31:23 +05:30
Tufan Barış YILDIRIM a1355e50e2 Documented --json for diff command (#2736) 2019-03-31 20:01:44 -07:00
kannappanr 2ad65c0799 ls: Remove space between size and unit (#2735)
With the move to go.mod, the latest humanize package is being used.
This introduces a space between size and the unit. Manually removing the space
to make it consistent with the older mc releases.
2019-03-29 15:02:26 -07:00
kannappanr 7f2770e68f updating go.mod to use latest sha256-simd pkg (#2732) 2019-03-28 13:02:39 -07:00
Harshavardhana c34dec5495 Set correct compressionType for compression select request (#2730) 2019-03-28 10:52:13 -07:00
Harshavardhana ba92305de0 Migrate to go1.12, deprecate vendor directory (#2727) 2019-03-27 10:08:19 -07:00
poornas 0a790a1a2e ls: consistent output while listing directories on file system (#2723) 2019-03-21 19:19:11 -07:00
Harshavardhana 3ea090fe18 Fix rm to behave properly deleting prefixes (#2720) 2019-03-20 13:08:36 -07:00
poornas 0490231b34 For non-canned policies, show policy status as custom (#2716) 2019-03-19 09:11:16 +05:30
Anis Elleuch 030aa5aba5 Add normal/deep scan flag to admin heal cmd (#2692) 2019-03-15 15:40:51 -07:00
kannappanr 09d04326dc Deprecate MC_HOSTS_ env variable (#2718)
MC_HOSTS_ env variable will be replaced with MC_HOST_ as it is more
appropriate

MC_HOSTS_ will be removed in the near future.
2019-03-14 17:29:07 -07:00
Sidhartha Mani cfb25fe81b mc admin info changes (#2712) 2019-03-14 18:20:29 +05:30
Anis Elleuch ecfd4526a3 tests: Clean per test created buckets (#2717)
In addition to the general bucket name created for functinal tests,
some tests inside this latter creates separated buckets but remove
them using rm command which does not support removing buckets anymore.
2019-03-13 10:38:18 -07:00
Anis Elleuch affc127af0 mirror: Return non-zero exit code for errors occuring during mirror (#2705)
An error, such as, `Bad Request` when copying an object without supplied
keys is not reflected in the exit code.

This commit simplifies a bit the mirror code. It makes mirror before and
after starting to send the status to mj.status.
2019-03-12 16:36:14 -07:00
Anis Elleuch a498b9b3a2 rm: Force removing an object when it is encrypted without key specified (#2700)
Currently, a single remove HEAD an object, but this latter can return
400 Bad Request when the object is encrypted and the user doesn't specify
any encryption key.

So when HEAD fail, this PR will use GET listing to find the object and
remove it if existent.

We can avoid calling HEAD in the first place and use only listing, but this
has some penality on the server.
2019-03-12 14:03:59 -07:00
poornas e684b48cfe Add --dangerous flag for mc rb sitewide removal (#2709)
Also fix mc rb bug while deleting folders on file system
2019-03-11 22:27:35 -07:00
poornas 5b585c4759 Additional flags for mc sql command (#2687)
add sql select options
change flag names and remove parquet option
add csv-output-header option
2019-03-11 22:23:45 -07:00
Ashish Kumar Sinha 2e612b23d6 Add metadata in mc copy (#2671)
Example : mc cp --attr key1=value1,key2=value2 
play/mybucket/burningman2011/ ~/latest/
2019-03-11 12:47:28 +05:30
Anis Elleuch 4a130c60a8 rb: Fix removing an empty bucket when passed as argument (#2703)
rb was relying on client.List() to find all elements that needs to be
removed. However it doesn't include 'alias/bucket' in the listing
when 'alias/bucket' itself is passed as an argument in rb command.

This PR will always attempt to delete the passed argument as this is
what the user wants in the first place.

This PR also fixes teardown() in functional-tests.sh to remove
the bucket using rb instead rm since rm does not remove buckets
anymore.
2019-03-08 17:07:06 +05:30
Anis Elleuch b72d2d9cc5 tests: Use rb instead of rm to clean test bucket (#2708)
rm command is not able to remove buckets anymore, so use the new rb
command instead.
2019-03-07 09:04:32 -08:00
Harshavardhana b3229507a9 Fix functional tests to use --older-than (#2706)
Change missed in previous PR 1761b338f9
2019-03-06 02:33:07 -08:00
Ashish Kumar Sinha 1761b338f9 OlderThan & NewerThan configured for Days, Hours and Minutes (#2614)
Previously OlderThan and NewerThan was configured for day
which has been changed to Days, Hours and minutes.

Also, changed the `flag` in `find` command to be `newer-than` and `older-than` to be consistent with other commands.
2019-03-03 20:18:34 -08:00
poornas c63c5732e9 Fix policy set error (#2701)
When policy is being set,json does not need to be indented - it
is causing a policy has invalid resource error
2019-03-02 10:38:16 -08:00
poornas dba70c0b92 Stat: display Expires header if present (#2697) 2019-03-01 13:03:53 -08:00
Sidhartha Mani c75abbb3f9 use colorjson for all other mc outputs (#2683)
- Update to MarshalIndent instead of Marshal
- Allow unmarshalling
2019-02-28 14:33:13 -08:00
Harshavardhana 19e14db50a Avoid ListBuckets to keep Stat() ops on bucket simpler (#2699)
Due to multi-user feature on Minio and mc adoption in
many different restrictive environments, most users disable
access to ListBuckets() calls. We can avoid such network
operations as they only add marginal value.
2019-02-28 14:23:47 -08:00
Eco bd5372f165 Update mc complete guide with PPC binary link (#2675)
Linux specific
2019-02-22 11:03:35 -08:00
Anis Elleuch a3203d4fe7 complete: Add support of rb completion (#2689)
Add completion for rb command:
- Support filesystem paths
- S3 paths only supports this format: `alias/bucket/`, for that s3Complete{}
has deepLevel parameter to configure maximum path deep level.
2019-02-20 14:35:23 -08:00
poornas e538599e2f Add mc rb command to remove empty bucket (#2662)
Change mc rm --recursive behavior to
delete objects in bucket but not the
bucket itself.

Fixes #2635
2019-02-16 20:12:38 -08:00
Anis Elleuch 4b62f520e8 Add support of bash completion (#2592)
Users of bash/zsh will have completion config enabled in the next
shell session start. This commit provides completion for commands
and all subcommands, their flags and completion of filesystems paths,
mc aliases, buckets and prefixes.
2019-02-14 22:17:43 +05:30
Anis Elleuch bc1a108e5c pb: Do not exceed the specified total transfer bytes (#2685)
mc, via minio-go, can retries some requests for many reasons, such as, network
disconnect. This commit ensures that the progress bar does not show transfered
bytes greater then the total transfered bytes to avoid confusing users.
2019-02-13 11:02:00 -08:00
Anis Elleuch 38965dd432 mirror: Proper exit when preparing diff returns an error (#2681)
A bad synchornization between startMirror() and its caller mirror() happens when preparing the difference of objects between source & target returns an error: mirror() quits when it receives an error from startMirror() without give a chance for that latter to properly stop the parallel mirror manager.

This PR will:
1. Quit mirroring when listing returns an error: this means calculating diff needs to stop and no further action needs to be taken since it can be dangerous especially when --remove flag is passed.
2. Properly stop parallel mirroring manager before quitting.
2019-02-12 14:28:38 -08:00
Eco 30491f369d Update mc quickstart guide with PPC binary link (#2677) 2019-02-11 21:51:40 -08:00
Eco 1941a2532a Update mc admin guide with PPC binary link (#2676)
fixes #2644
2019-02-12 10:26:36 +05:30
Harshavardhana 3a22044471 Vendorize all the latest dependencies with go mod (#2674) 2019-02-08 18:32:17 -08:00
kannappanr da3e027145 Strip trailing separator in URL in config host add (#2680)
Also, in the case of find command for existing configs that has a 
trailing separator in the URL, trim the separator from the URL.

Fixes #2645
2019-02-07 21:10:38 -08:00
Sidhartha Mani 7bc792e745 Add json pretty print (#2661)
Enable jq style color output in github.com/minio/mc/pkg/json
- Drop in replacement of encoding/json
- Bold struct keys in blue
- Strings in green
- Numbers in default color
- Indenting and spacing matches exact jq specifications

Additionally, color coding needs '\x1b[...m' to be whitelisted in encoding/json's parser
2019-02-05 11:52:33 +05:30
Sidhartha Mani 939e1006cc add mc admin monitor command (#2657) 2019-02-02 22:44:21 +05:30
Harshavardhana 57faed2725 Add go mod support and update dependencies (#2668) 2019-01-31 20:37:08 -08:00
Harshavardhana f9a6d70bc0 Add IAM docs about AWS S3 users (#2667) 2019-01-31 15:39:29 -08:00
kannappanr e3854b077a List oldest locks currently used in a distributed XL setup (#2549) 2019-01-31 12:37:04 -08:00
poornas 75a36b4831 Change mc config host list format to record style (#2659) 2019-01-28 16:52:50 -08:00
Praveen raj Mani 30965763d6 Support setting of custom policies from a JSON file (#2649)
Fixes #2633
2019-01-28 13:30:31 -08:00
kannappanr e940856fee Vendorize minio-go (#2660) 2019-01-25 15:19:04 -08:00
Harshavardhana 07169d421e Add sql docs (#2658) 2019-01-24 15:56:09 -08:00
Anis Elleuch a5ea937df2 mirror: Fix double printing of remove object msg (#2639)
Mirror code depends on rm code which naturally prints delete messages,
this PR will make mirror uses its own delete code since it is simple
enough to do.

Also add size information to remove message
2019-01-24 07:13:46 -08:00
kannappanr 539cd245d6 ls: Add Stat call to determine bucket/directory (#2656) 2019-01-23 17:17:35 -08:00
Harshavardhana ede0911de2 Support parquet select implementation (#2643) 2019-01-22 11:13:58 -08:00
Harshavardhana 733d3c5d54 Avoid making Stat calls on listing (#2650) 2019-01-22 16:02:56 +05:30
Harshavardhana 0854af6e6d Migrate to mitchellh/go-homedir from minio/go-homedir (#2641)
We don't use this fork of ours anymore and we don't need
to maintain it anymore as we haven't made any significant
changes to upstream code or fixed bugs.
2019-01-08 00:23:51 -08:00
Harshavardhana d8d3a3dec1 Remove incorrect OutputSerialization 2019-01-07 03:08:41 -08:00
Harshavardhana 59ef9fe468 Support SSE without keys (#2626) 2019-01-04 11:56:43 -08:00
Harshavardhana 9ddc45162a Add new vendored minio-go (#2638)
Fixes https://github.com/minio/mc/issues/2610
2019-01-02 16:42:06 -08:00
Harshavardhana bda754d07f Migrate to go1.11.4 for CI builds (#2634) 2018-12-28 16:47:22 -08:00
Anis Elleuch 124b9fa4d9 Avoid remove freeze when server returns an error (#2631)
Minio can return during deletion sometimes, like missing quorum,
but mc can block in that case. The reason is that Remove() in
client-s3 doesn't actively listen for errors reported by minio-go
RemoveObjects() API  because that would also block this latter.
2018-12-27 17:38:17 -08:00
Harshavardhana 45578f0ed2 Implement head command (#2630) 2018-12-27 13:17:44 -08:00
Praveen raj Mani 4e7eeb0725 Ignore broken symlink durring mirror (#2607)
Fixes #2604
2018-12-21 13:38:12 -08:00
KnutAtteslander f0309e33e1 Fix typo in admin-user-add.go (#2629) 2018-12-20 06:56:50 -08:00
Anis Elleuch 8964876217 error msgs: Add punctuations when needed (#2628)
This commit will automatically add ':' or '.' after scanning
the generic and the detail error messages. This will simplify
maintaining error messages.
2018-12-18 23:18:28 -08:00
Harshavardhana e3b84ac010 With bracket characters in URL, curl requires globbing turned off (#2627)
This PR fixes an issue present when curl commands
are used with IPv6 SERVER_ENDPOINTs
2018-12-17 20:38:27 -08:00
Harshavardhana d541a7f6ef Add support for IPv6 endpoint in functional tests (#2622) 2018-12-12 17:43:48 -08:00
Praveen raj Mani 69f967b3f3 mc mirror should not stop incase of errors (#2624)
Fixes #2623
2018-12-12 10:48:48 -08:00
Harshavardhana 1bb64f0bf0 Fix typo policies to policy (#2621) 2018-12-09 11:21:27 -08:00
Harshavardhana 2073642656 Allow copying file onto itself (#2617)
This allows encrypting an unencrypted file
using server side CopyObject API.
2018-12-06 10:18:16 -08:00
Harshavardhana f3eaa54a32 Breaking change --config-folder is now --config-dir (#2620) 2018-12-05 14:10:36 -08:00
Harshavardhana a91204ea6f Fix typos in complete and README.md (#2616) 2018-11-29 16:52:53 -08:00
Harshavardhana 5117f74fce Allow empty objects to be uploaded (#2613) 2018-11-28 17:14:07 +05:30
Harshavardhana 57414cbb6e Add in-place update feature (#2605) 2018-11-26 20:04:55 +05:30
Harshavardhana 24d4c28aa9 Pass query down on all objects when recursive (#2603) 2018-11-20 08:45:01 +05:30
Harshavardhana cb4f46854b Fix command line names and documentation (#2602) 2018-11-19 17:19:53 -08:00
Harshavardhana 0992c3a50d Fallback detecting filetype from magic numbers (#2598) 2018-11-16 07:45:46 -08:00
Zachary Zhao c5eaa30253 Change USERNAME to ACCESSKEY and PASSWORD to SECRETKEY (#2594)
Since `ACCESSKEY/SECRETKEY` is common knowledge for S3 user,
we should make it clear to avoid confusing people.
2018-11-13 18:19:00 -08:00
Harshavardhana 6faac81eb0 Remove all unused dependencies (#2599) 2018-11-13 15:52:12 -08:00
kannappanr 2fc5413002 Fix: Remove local file during a mirror operation (#2593)
Fixes #2586
2018-11-09 13:31:15 -08:00
Kale Blankenship 8137e79d0c Close readers returned by Client.Get (#2595)
Change Client.Get to return an io.ReadCloser instead of io.Reader
so that it can be closed.
2018-11-08 17:02:14 -08:00
Harshavardhana b827fac635 Fix help message usage for some commands (#2591) 2018-11-05 10:37:33 -08:00
Harshavardhana 4479667d4c Allow resuming and stopping an active heal operation (#2584) 2018-11-04 19:25:14 -08:00
Harshavardhana 9226796558 Fix a typo in config set success message (#2588) 2018-11-01 16:46:44 +05:30
Harshavardhana fd340638bb Update mimedb to set correct content-types (#2587) 2018-10-31 14:45:10 -07:00
Harshavardhana 6ca902d13a Add additional error message in heal (#2583) 2018-10-27 02:53:24 -07:00
kannappanr 73a61b4203 Parse alias set via env variable while prsing encryption key (#2581)
Check MC_HOSTS_ env variable also while looking for the alias to set encryption key
Fixes #2580
2018-10-26 12:51:57 -07:00
Harshavardhana 96378448c5 Fix admin docs add 'mc admin info' (#2578)
Fixes https://github.com/minio/minio/issues/6695
2018-10-25 13:32:03 -07:00
Harshavardhana eab117c07c Allow access key minimum to be 3 characters (#2579) 2018-10-25 19:21:52 +05:30
Harshavardhana 7b69f0064d Add 'mc admin restart' message (#2574) 2018-10-18 17:46:20 -07:00
Anis Elleuch 0dd32c1b26 Add admin profiling command (#2557)
Implement profiling command to start & download profiling data of
a standalone or all nodes of a cluster.

```
1. Start CPU profiling
   $ mc admin profiling start --type "cpu" myminio/

2. Download latest profiling data under save under profiling.zip
   $ mc admin profiling stop myminio/
```
2018-10-17 17:06:12 -07:00
Harshavardhana c707a17f30 Add 'users policy' command(#2573) 2018-10-17 15:21:11 -07:00
Harshavardhana 502e28d2be fix admin docs 2018-10-16 16:49:35 -07:00
Harshavardhana b7e87b623d Add admin users (#2554) 2018-10-16 14:54:25 -07:00
Anis Elleuch 7bbc81ffa4 Change golint import path (#2566) 2018-10-11 15:58:02 -07:00
Praveen raj Mani 449cad0eb8 Migrate from "mime" to "github.com/minio/minio/pkg/mimedb" (#2563)
The content-type resolutions are standardized across platforms.

Fixes #2559
2018-10-02 17:17:44 -07:00
Harshavardhana 7260b0f9ea Ignore errors during mirror (#2562)
S3 lists 1000 objects in batches, but once this batch is being
processed to be copied over there is no way to lock across the
entire batch for mirroring. Due to this we introduce a scenario
when objects might have been deleted in parallel from another
application.

In such a scenario simply ignore such objects and proceed to
copy other files.

Fixes #2537
2018-10-01 15:33:18 +05:30
Harshavardhana a83ffe321c Implement select command (#2538) 2018-09-30 23:18:33 -07:00
Johan Guldmyr a215fbb718 Update docs with --api flag examples (#2555) 2018-09-26 18:30:11 +05:30
Anis Elleuch 87f7e65c4c Disallow copying/mirroring a folder into itself (#2553)
As unix cp command complains when you copy a directory into itself,
(such as `cp -r ~/Desktop/ ~/Desktop/sub/`), mc will follow the
same behavior with this commit.

The main reason is that copy or mirror command can be unpredictable
with the style of copy.

Example:

```
$ mc ls -r myminio/testbucket/
[2018-09-25 19:28:17 CET]     8B dir/object
[2018-09-25 19:28:40 CET]     8B object

$ mc -q cp -r myminio/testbucket/ myminio/testbucket/dir/
`myminio/testbucket/dir/object` -> `myminio/testbucket/dir/dir/object`
`myminio/testbucket/object` -> `myminio/testbucket/dir/object`

```

We can notice that `myminio/testbucket/dir/object` is both source and target
in the copy operation. The last copy operation that will occur will rule the
result of the total copy operation and `myminio/testbucket/dir/dir/object`
will have a different content in each copy operation.

Due to the unpredictability mentionned above, we will disallow copying or
mirroring a folder into itself.
2018-09-25 17:34:40 -07:00
Praveen raj Mani ab31cf97da Remove extraneous bucket on target while mirroring (#2550)
Fixes  #2527
2018-09-25 10:20:14 -07:00
Praveen raj Mani b2d2e09105 mc heal and mc mirror should respond with proper exit code (#2543)
respond with os.exit(0) incase of errors

Fixes #2534 #2474
2018-09-20 15:23:40 -07:00
kannappanr c9f33698fc Display the config in correct format when json flag is used (#2544)
Fixes #2530
2018-09-19 11:48:21 -07:00
Harshavardhana 044a95b6cf update notify library native macOS compilation (#2540)
Fixes #2535
2018-09-13 18:02:27 -07:00
kannappanr c352cadd4b Display restart failures in admin service restart command (#2533)
Fixes #2532
2018-09-10 16:23:17 -07:00
Harshavardhana 40971c0b93 Vendorize updated crypto/blake2b to compile with go1.11 (#2531)
Fixes #2524
2018-09-10 16:21:09 -07:00
Harshavardhana 0d0638b398 vendorize latest minio-go and madmin (#2529) 2018-09-06 16:01:18 -07:00
Harshavardhana 12627c35e4 Fix parallel upload performance issues (#2521)
Tested by transferring 29GiB data, around 246569 files
over 100Gig network.

- master branch
```
time mc mirror /root myminio/testbucket/
real	2m10s
```

- after changes
```
time mc mirror /root myminio/testbucket/
real	1m2s
```

By default runtime.NumCPU() workers are started.
2018-08-30 22:31:08 +05:30
poornas 1d5870b2a2 Fix url parsing of MC_HOSTS_ env variable (#2523) 2018-08-30 22:22:53 +05:30
Nitish Tiwari ae88af8b1b Use go1.10.4 for AppVeyor (#2525) 2018-08-30 08:38:03 -07:00
Harshavardhana bc756e3dbd Fix cp crash when resuming from session (#2520)
We should make sure to handle errors properly
when reading from the session and also parsing.

Current master ignores all these situations
which leads to crash, this PR handles this to avoid
nil pointer crashes.
2018-08-27 12:03:40 -07:00
Aarushi Arya bc679788ac mirror watch: Exit on error while copying. (#2511)
mirror: exit, if copy error occurs while watching.

Fixes #2505
2018-08-23 15:58:14 -07:00
Harshavardhana a1110bc022 Add docs for config get/set commands (#2518) 2018-08-20 22:53:31 +05:30
Harshavardhana 073ed250fe Update madmin API with latest server changes (#2516) 2018-08-17 18:55:05 -07:00
Harshavardhana 3b78c115f6 Remove workaround for http response tracer (#2514) 2018-08-17 17:15:03 -07:00
Harshavardhana f8aafcc774 Vendor pkg/madmin changes in GetConfig/SetConfig (#2513) 2018-08-15 03:06:43 -07:00
Durgadas Kamath 22b8ab43bd ISSUE-2507 : Add s390x support for minio-client (#2508) 2018-08-09 14:53:38 -07:00
Anis Elleuch 5eab7c2698 Updating minio-go library (#2506) 2018-08-07 16:57:32 -07:00
Harshavardhana 26f5102eae Remove/deprecate admin lock commands (#2503) 2018-08-06 12:59:13 -07:00
Ashish Kumar Sinha 9998e077df Remove error statement in mc mirror (#2500)
mc mirror complains about extra file in destination,
but this is not an error so removed the error message.

Fixes: #2470
2018-08-02 22:45:54 +05:30
Nitish Tiwari 480bc8aa2a Use randString() to generate random string for S3 sign probe (#2498)
newRandomID() func may return string with uppercase letters. Such
strings will make invalid bucket name as S3 doesn't allow
uppercase lettes in bucket names.

randString() always returns strings with lowercase letters or
numbers.

Fixes #2496
2018-07-31 20:53:39 +05:30
Ryan Boehning a8c97b467d Replace legacy httplex import with current x/net/httpguts (#2494)
The import path of the httplex package has changed.
2018-07-29 00:45:12 -07:00
Harshavardhana 7f01db2cda create bucket automatically when prefix is created (#2488) 2018-07-27 15:29:53 -07:00
Anis Elleuch d83e73b85b Pick a random bucket name when probing for signature version (#2491)
Probing buckets is a mechanism used to automatically detect supported
S3 signature version. However, it seems that probe-bucket-sign is already
used by someone, the thing that makes probing fails with 403 error. This
PR changes the code to pick a random bucket name when probing.
2018-07-24 20:19:26 -07:00
smouli 7e49e2d519 fix for mc find --ignore option (#2489) 2018-07-22 15:03:09 -07:00
ebozduman 5a962a7cf5 Vendorizing changes required for PR#6067 (#2481) 2018-07-16 08:27:22 -07:00
Harshavardhana 70dcf20d74 Pass down encrypt-key handling across command validators (#2483)
Currently even if the command supports encrypted objects,
the syntax verification would fail on them in certain
cases. Since syntax validation of source/targets doesn't
use the parsed encrypt key pairs.  This PR fixes this
behavior.
2018-07-12 11:13:51 -07:00
Harshavardhana c57a2dc4c2 update minio-go dependency to support single statement policies (#2480) 2018-07-06 11:09:59 -07:00
Harshavardhana 4ab7f30f99 Handle directories properly in cp and mirror (#2478)
Fixes #2477
2018-06-29 16:56:02 -07:00
Harshavardhana 29f2dbca6b Fix 'mc mb' to guide the user when bucket is not passed (#2476)
Additionally this PR also allows for creating
prefixes on S3 compatible object storage backends
in the following form

```
mc mb s3/harshavardhana/object/prefix/
```
2018-06-29 14:56:07 -07:00
Harshavardhana 4070902cda Allow creating directories from S3 to filesystem (#2471)
Fixes #2460
2018-06-20 17:47:26 -07:00
kannappanr 556bbc2de5 Vendorize minio-go inside mc (#2473)
Fixes 2465
2018-06-20 15:25:47 -07:00
ebozduman 7e879edabc Removes unsupported flags and fixes the examples in the doc (#2469)
Removes old flags and fixes the examples in the doc
2018-06-19 12:28:36 -07:00
Rafael Peria de Sene f48ac0de19 Add support for ppc64le (#2468)
Signed-off-by: Rafael Peria de Sene <rpsene@br.ibm.com>
2018-06-19 11:23:28 -07:00
kannappanr 1a5aab3ff4 Makefile: Create bin directory if it doesn't exist (#2466) 2018-06-18 07:42:13 -07:00
Harshavardhana 8cf797da5f Update madmin API changes (#2462) 2018-06-08 18:00:52 -07:00
Arjun Mishra 023b38fe3f Document adding host configuration through environment variable (#2458) 2018-06-08 12:07:14 -07:00
Harshavardhana afcfe758f3 Fix joinPath function to handle directories properly (#2459) 2018-06-06 11:29:05 +05:30
Anis Elleuch c0b89a7aec Add support of empty directories in ls/rm/find commands (#2452) 2018-06-04 17:20:07 -07:00
Nitish Tiwari 4f1f864f64 Fix link to Minio admin complete guide (#2457) 2018-06-01 13:50:14 +05:30
Harshavardhana 2d4346bfe1 Add 'mc admin' complete guide (#2456)
Fixes #2428
2018-06-01 09:16:01 +05:30
Anis Elleuch d566905d7a Properly shutdown parallel copy in cp command (#2448) 2018-05-31 12:38:22 -07:00
Anis Elleuch 743d72ea1a fix: Disable localization to enforce bytewise sorting in functional tests (#2453) 2018-05-30 09:40:42 +05:30
Anis Elleuch 10059459f3 tests: Fix test_find comparaison test (#2455)
`mc find alias/bucket` without trailing slash is actually printing 'alias/bucket' as
first element in the output, the thing which is not taken into consideration in test_find
test. This commit will ask `mc find` to list 'alias/bucket/' instead to have a similar
output as gnu `ls` cmd.
2018-05-29 18:12:27 -07:00
Harshavardhana 376b4ce2f8 Remove deprecated snap mc package (#2454) 2018-05-29 14:51:06 -07:00
Harshavardhana 961c4b5dae Add total used support for mc admin info (#2449) 2018-05-23 17:44:50 -07:00
aarushiarya 1711f0bb46 fix for documentation issue (#2446) 2018-05-16 11:06:42 -07:00
Praveen raj Mani b41b98b04d mc mirror watch fix in darwin (#2445)
The event.Path had few prefixes appended in it (only in darwin).
Instead of taking the trimmed directory path, It takes the full path, say '/private/...".
This disturbs the target URL. Which indeed inserts it as a whole '/private/{target_path}',
So trimming the prefixes in the event.path solved it.

Solves:#2443
2018-05-13 19:34:49 -07:00
Anis Elleuch 1b794a4ae1 Update minio-go to ship new fixes (#2441)
https://github.com/minio/minio-go/commit/c6108c47ba5d86548404ebf9e51c5ca18769fe79
https://github.com/minio/minio-go/commit/92b6411b2475a188f67229f2b6c05dff695433da
2018-04-26 13:40:45 -07:00
Anis Elleuch 182ad295d8 Quit calculating difference for any listing error (#2440)
If we have any listing problem, we should stop comparing difference
between source & target lists because it is already so hard to know
what mc should do next. So, let's inform users and let them deal
with the problem.
2018-04-26 11:21:10 -07:00
Harshavardhana 75e9691616 Support server side copy object with progress (#2438)
Support server side copy object with progress
and also uses a more optimized version to perform
multipart server side copy operation.
2018-04-26 11:02:06 +05:30
Anis Elleuch 1ccf40d1e5 Properly stop parallel work in mirror/cp when the user clicks on Ctrl-C (#2437) 2018-04-25 11:55:07 -07:00
Harshavardhana 2dc48e9dd3 Simplified build system and move to go1.10.1 (#2431)
minio server simplified its build system, this
change borrows the same technique to `mc` as well.

This PR fixes build messages and overall behavior
of our builds on travis and appveyor.
2018-04-13 13:57:07 -07:00
Anis Elleuch 757fff7764 Simplify parallel manager implementation (#2413)
Each 5 seconds, calculate current bandwidth and add new workers as
bandwidth gets increased. Stop adding workers if it is not useful
for increasing bandwidth.
2018-04-06 18:46:35 -07:00
kannappanr 0fe4319e17 Fix display message when list and remove notifications are called (#2424) 2018-04-05 13:19:16 -07:00
poornas 18ddd3925b Config: avoid adding default configs if entries present (#2426) 2018-04-03 13:09:32 -07:00
Dee Koder 8aaf909a08 Remove badges that take too long to render. (#2423) 2018-03-28 10:14:34 +05:30
Harshavardhana da5c19848d vendorize minio-go with fix for reset peer to retry (#2420) 2018-03-24 13:10:23 -07:00
Anis Elleuch 45b32d3985 errors: Add missing ending dot in error & fatal messages (#2418) 2018-03-23 12:22:55 +05:30
Anis Elleuch ae3c123a5c Do not exit mirroring for cannot delete/overwrite errors (#2416)
mc used to show a warning messages during mirroring when it
detects a need to overwrite or remove a remote object but no
flag is specified. This commit efeaf2ee72
changed this behavior but this commit will restablish
the old behavior.
2018-03-22 13:37:32 -07:00
poornas fe82b0381c change encryption key parsing to allow spaces in sse-c key (#2408)
Also vendoring in minio-go updates
2018-03-14 02:47:14 -07:00
poornas 0ede95b65e add encrypt option to cp, mirror,pipe,stat, cat and rm commands (#2400) 2018-03-08 17:18:41 +05:30
Dee Koder 4758556eec Add back wget in the GNU/Linux heading (#2406)
This is nice for usability reasons.
2018-03-07 10:39:57 -08:00
Nitish Tiwari ea580b0b65 Add storage-class support (#2403)
This PR adds storage-class support for mc cp and mirror command.
Storage class values are passed via the -storage-class or
--sc flag.

Fixes #1859
2018-03-03 10:28:53 -08:00
kannappanr b1dd99c94d Detect duplicate config entry in mc add event (#2402)
Fixes #2324
2018-02-26 14:28:33 -08:00
kannappanr 57bf0c0e79 Fix moving standard metadata as user defined header in s3Client's PUT method (#2401)
Standard headers like Content-Disposition, Content-Encoding,
Cache-Control, Content-Language were made part of user metadata
causing it to fail while mirroring, if the source has these headers
set.

Fixes #2358
2018-02-24 15:12:01 -08:00
kannappanr 7ebe7908ea vendorize minio-go to version 4.0.8 (#2399) 2018-02-23 17:39:06 -08:00
Harshavardhana 750644ec4d Fix docker build issues (#2395) 2018-02-21 16:55:58 -08:00
ebozduman efeaf2ee72 Stops removing target bucket content when url.Error (#2377) 2018-02-21 12:22:09 +05:30
Harshavardhana 97c7984bca Large bucket support admin API Changes (#2372) 2018-02-15 18:35:05 -08:00
Aditya Manthramurthy 335a53ad29 Fix flickering in heal dashboard UI (#2391) 2018-02-14 10:15:26 -08:00
Harshavardhana d4981656d3 Remove response timeout for admin operations (#2390) 2018-02-13 15:40:46 -08:00
Harshavardhana 766e04d79d fix crashes on 32bit systems use LoadUint32() instead (#2389) 2018-02-12 10:25:06 -08:00
kannappanr 4e30ca1617 document stat command and additional example for mb command (#2385)
stat command was missing in the mc complete guide doc.
mb command did not have an example for --region flag.

Fixes #2376
2018-02-12 23:34:49 +05:30
poornas 65e22bee24 Add api as option for mc config host add command. (#2381) 2018-02-10 14:39:12 -08:00
ebozduman 3987f1405a Revises 'mc diff' command help menu (#2383) 2018-02-08 16:29:50 +05:30
Krishnan Parthasarathi e1056aa50d Fix admin-info, admin-status json status field (#2293) 2018-02-05 10:09:12 -08:00
A. Elleuch 017dddef97 Add --newer-than & --older-than flags (#2142)
Use --newer-than & --older-than to select newer or older files
in copy, remove and mirroring operations.
2018-02-01 10:32:22 -08:00
Harshavardhana 55f06077e5 Fix heal admin API to honor json/quiet flags correctly (#2370)
Update the madmin updated package as well

Fixes #2369
Fixes #2368
Fixes #2367
2018-01-27 23:19:52 +05:30
A. Elleuch 99ee2a5042 Refactor {build,new}S3Config to remove a duplicate code (#2329) 2018-01-24 12:06:34 -08:00
Aditya Manthramurthy 793cda2ca0 New Admin API client-side implementation (#2350) 2018-01-23 12:32:58 -08:00
ebozduman 83bb797389 Adds stderr and returns exit status of the cmd executed (#2361)
Fixes #2351
2018-01-23 13:17:47 +05:30
Harshavardhana 8fbbd0ee83 Fix and refactor MC_HOSTS_ env handling code (#2365)
Existing MC_HOSTS_<alias> was incorrectly placed
inside s3Config initialization code path which
leads to a situation where we loose the URL path
information.

Fixes #2364
2018-01-19 18:29:28 -08:00
Aditya Manthramurthy b94b8e67e9 Update vendored madmin dep (#2362) 2018-01-19 14:50:55 -08:00
fossabot f93fb55606 Add license scan report and status (#2363) 2018-01-19 13:20:19 +05:30
Harshavardhana 3b4626ea15 Bump max parallel workers to 32 (#2360) 2018-01-18 19:46:31 -08:00
Aditya Manthramurthy d9663e5d96 Improve lock error message (#2353) 2018-01-16 21:25:03 +05:30
poornas 5d703df69d vendorize minio-go to version 4.0.6 (#2357) 2018-01-16 12:43:49 +05:30
Aditya Manthramurthy 5f2f82b5f7 Update heal command - remove upload healing (#2355)
This PR is to keep mc in sync with changes introduced in
https://github.com/minio/minio/pull/5390 to remove upload healing
functionality.
2018-01-12 07:50:04 -08:00
poornas 5dee56d5d0 fix for prefix based rm (#2354)
mc rm --r with prefix not terminated by / doesn't get deleted.
example: mc rm --r --force --older-than=10 play/test/prefix

Fixes: #2341
2018-01-12 09:23:03 +05:30
poornas 722ee94165 fix missing metadata in stat cmd (#2348)
mc stat without --r is missing metadata for stat on objectname
2018-01-10 11:07:21 -08:00
poornas b64c8a3aa9 Copy metadata during mirror and cp peration (#2347)
Validate metadata key/values to filter out custom xattr
set on fs to prevent invalid http headers being sent in http request
by minio-go
2018-01-10 11:03:42 -08:00
Harshavardhana 13259eea21 mirror with --watch should copy and exit for s3 endpoints (#2345)
Current code wouldn't exit unless we press CTRL+C
even if the endpoints do not support --watch, this PR
fixes this behavior.
2018-01-08 10:56:56 -08:00
poornas 9da492975c correct stat behavior and message (#2344)
fix empty stat listing when bucket has only a single object and
cleanup dead code.
2018-01-05 14:18:35 -08:00
Landry Breuil 96dc4f920d Use client-fs_other on OpenBSD (#2342) 2017-12-29 14:14:24 +05:30
poornas 2d221ba8da stat: fix output to show bucket in stat listing (#2340)
Show stat of all buckets at site level, and mimic
mc ls behavior in stat output.
2017-12-25 16:19:24 +05:30
dingjs 87309ebaac Translate mc docs to Chinese. (#2309) 2017-12-18 18:43:07 -08:00
Kaan Kabalak eeb18ff75c Correct typo in mc cat (#2336)
Fixes #2334
2017-12-15 21:45:24 +05:30
A. Elleuch 4cb6e35342 fix: Consider insecure flag in host add cmd (#2331)
--insecure wasn't have an effect when invoked in a `mc host add` cmd. This
PR fixes the behavior.
2017-12-11 15:14:56 -08:00
A. Elleuch 5ddf9728f8 Parallelize upload/remove in cp/mirror commands (#2289)
This PR removes --parallel flag and implements a dynamic way of adding
threads to accelerate mirror/cp command.

After the calculation of objects that need to be copied/removed, mc
sends tasks (upload/remove) to a parallel manager which monitors the
progress of tasks and decide to allocate more threads to it to
accelerate the overall work.

This is very useful when we copy/mirror many relatively small files.
2017-12-07 16:20:34 -08:00
poornas 275db95170 mc: Remove MC_MULTIPART_THREADS env variable (#2326)
Remove this var as PR#2289 will manage threads automatically based on
workload to speed up mc cp/mirror operations.
2017-12-06 09:30:20 -08:00
poornas 399187c4fb ui: consistenly use "flag" instead of "option" in error messages (#2325) 2017-12-06 16:00:10 +05:30
kannappanr 1fd03fb81f Rearrange exclude code to filter source and target URLs (#2322)
Move exclude code handler to mirror-url and mirror-main

Fixes #2319
2017-12-04 15:47:29 -08:00
Harshavardhana 0aa704ad5e Fix typo in find help (#2323) 2017-12-04 23:10:09 +05:30
poornas 1e7b4c9e4a Add mc rm support to recursively remove site (#2265)
This requires --dangerous flag in addition to --recursive and --force

Change namespace identification check to be more robust to user
input errors like mc rm --r --force play//
2017-12-01 18:25:08 -08:00
Harshavardhana 65c582cd5b Fixing find help message and behavior (#2320) 2017-12-01 18:04:09 -08:00
kannappanr 336e7f58bf Add negative test for presigned post policy (#2302)
Append objectname to the URL and make sure that it fails.

This is related to code coverage in minio/minio#5142
2017-12-01 10:05:31 +05:30
Harshavardhana dfffc1e7cc mirror: Deprecate --force instead add --overwrite (#2318)
Fixes #2317
2017-11-30 16:51:17 +05:30
poornas a63a1f7eca Skip color theme for quiet mode (#2313) 2017-11-23 16:35:43 +05:30
poornas b3fe40e113 fix: append XAttr to metadata only if metadata requested (#2310) 2017-11-23 16:35:17 +05:30
kannappanr 093ab6b034 Add success log in "config host add" tests (#2306)
Change the function name "fail" to "show_on_failure"
Add another function called "show_on_success" to handle certain
failure assert scenarios
Add missing Log success message for "test_config_host_add" and
"test_config_host_add_error" functions.

Fixes #2305
2017-11-14 18:44:13 -08:00
Harshavardhana ceb38130fc Fix ENV handling in mc (#2282)
Now ENV supports following style and doesn't require
a pre-requisite to have an entry in `config.json`

MC_HOSTS_myminio=http://minio:minio123@localhost:9000/

Notice signature style is auto-probed if env is set.
2017-11-13 16:29:10 -08:00
Harshavardhana 7498e97182 Relax access key, secret key validation (#2300)
Comply with minio server behavior - fixes #2298
2017-11-13 12:53:11 -08:00
poornas 32a8f34f7d Fix: mc rm to error when nonempty directory is deleted (#2303)
Example: when mc rm play/testbucket/folder1 is attempted and directory
is nonempty, exit with an error message
2017-11-09 18:28:53 -08:00
Harshavardhana 014d09412a Update minio-go (#2299)
- Avoid setting server encryption headers with x-amz-meta (#859)
- Remove redirectHeaders method (#857)
- Honor file pointer set in PutObject method (#856)
- Fix docs and add a validator tool for our api docs (#850)
- requestMetadata should take the md5 and sha256 with expected encodings. (#852)
- Added a new method SetUserMetadata to the PostPolicy (#839)
- Do not need to strictly validate request params in Presign API. (#832)
2017-11-07 16:03:44 -08:00
poornas ab6b2a83ac Add new stat sub command (#2275) 2017-10-31 13:56:40 -07:00
Bala FA 79a51e9afc fix JSON format error in functional test (#2294)
Previously `error` field is not populated properly due to double
formatting error message into JSON string.  This patch fixes the issue
by avoid second time formatting in `printf` command.
2017-10-24 12:21:25 -07:00
Harshavardhana c9448749d0 Fix command line docs and update complete-guide (#2290)
Also re-ordered snap below binary download for windows in priority.w
2017-10-21 07:59:12 +05:30
Harshavardhana aa8d5ed0cc Add newS3Config helper to auto-probe signature type. (#2292) 2017-10-20 13:51:56 -07:00
poornas a86080a0b7 Add context in Put api call for cp/mirror. (#2291) 2017-10-20 13:50:35 -07:00
Harshavardhana 59685e2d6b Fix macOS cross compilation issue. (#2287) 2017-10-17 08:02:32 +05:30
Harshavardhana 582f99b438 Enable mc build tests on go1.9 (#2276) 2017-10-15 19:11:38 -07:00
poornas 26c7c3e500 ls: show ETag in json formatted output (#2285) 2017-10-13 18:23:13 -07:00
Harshavardhana 785e14a725 Add find command in docs, remove deprecated files and entries. (#2286) 2017-10-13 17:28:29 -07:00
Harshavardhana 7ad9a36b9d Add find basic functional test (#2284) 2017-10-13 13:51:12 +05:30
kannappanr 9831612507 Add exclude option to mirror command (#2269)
Added exclude options to exclude unwanted system files.
Exclude option excludes the source files/objects that match
the passed shell file name pattern

Fixes #1903
2017-10-12 14:52:21 -07:00
Krishnan Parthasarathi 207d5cfb61 Bucket events times are in RFC3339 format (#2278) 2017-10-12 11:26:22 -07:00
Harshavardhana c10b429dcb Refactor and fix find bugs (#2273)
- Watch now avoids an unnecessary waitgroup and simplifies overall flow.
- Watch now honors maxDepth parameter as well.
- Parsing logic is fully outside in the mainFind() function.
- Enhance and fix behavior of nameMatch to comply with unix
  find behavior.
- Enhance and fix behavior of maxdepth to comply with unix
  find behavior.

Fixes #2272
2017-10-09 19:44:58 -07:00
A. Elleuch 8f38471e29 fix: Correct some cp/mirror help indentations (#2268) 2017-10-06 09:35:44 -07:00
Harshavardhana 25254c7622 refactor find command to be simpler (#2264) 2017-10-05 15:29:54 -07:00
A. Elleuch 7d062fb08c cat: Print ^? for unprintable characters (#2217)
In terminals, cat avoids directly printing some binary characters, such
as control characters or non printable characters but prints ^? instead,
that way, cat will avoid corrupting terminals
2017-10-04 16:49:35 -07:00
Harshavardhana 37e5a78779 Fix and honor --json flag for find command. (#2263)
Currently `mc find` didn't honor `--json` flag properly,
this PR addresses that.

Additionally also take care of `List` returning errors
and handle them appropriately.

Fixes #2252
2017-10-03 16:49:36 -07:00
Bala FA 07e810fd51 Ignore test_watch_object() for mint in functional test (#2267) 2017-10-03 10:31:47 -07:00
poornas 224e602e59 Allow multipart threads to be configured via environment variable (#2254) 2017-10-02 19:45:08 -07:00
Bala FA be710ecb52 rename assert functions for correct meaning in functional tests (#2266) 2017-10-02 13:22:03 -07:00
A. Elleuch 4810ab8727 tests: Add negative put object & make bucket tests (#2262)
Add new negative tests to functional tests. For that purpose, two functions are
introduced. assert_success makes sure that the passed command returns 0 exit code
and raise an error otherwise. assert_failure makes sure that the passed
command fails and raises an error otherwise.
2017-10-01 11:24:35 -07:00
chibiegg 5a2798dddb Support copy in parallel (#2258) 2017-09-29 14:36:16 -07:00
Nitish Tiwari 36d7d0b9a7 Update quiet flag usage to indicate it only turns off progress bar (#2257)
Fixes https://github.com/minio/mc/issues/2240
2017-09-26 10:17:17 -07:00
Bala FA b1812ebe5a add functional tests (#2253)
Functional tests are automatically run when `make test` is executed.
2017-09-19 12:31:00 -07:00
Leo Arias 683fcf0dd2 Add the install instructions for the snap (#2244) 2017-09-11 08:15:23 -07:00
Carter McClellan 39197ea3ae Fix parsing error with mc find --older, and --newer (#2249) 2017-09-08 10:40:32 -07:00
Harshavardhana 48bd32570f Fix find help text formatting. (#2247) 2017-09-07 11:11:08 -07:00
Carter McClellan 49ef42d36a Implement mc find (#2201) 2017-09-05 15:44:10 -07:00
Harshavardhana fe583468ce Vendorize new changes from minio-go (#2246)
This PR brings in changes for

- PutObjectStream with no content-length is heavily
  optimized so `mc pipe` will not run out of memory
  for large uploads.
- Fixes a bug in Signature v2 for HTTP requests.
- Support us-gov-west-1 region as well.
- Auto region handling is inside minio-go now.
2017-09-03 13:56:22 -07:00
Leo Arias 3f4d3ee1c0 Rename the snap to minio-client (#2243)
In linux, mc is midnight commander. In the traditional
linux distro world, name conflicts are forbidden. Because
we are trying to make this decentralized and self-serving,
we need less strict rules. For this, snap has a concept
of aliases. Then the user can decide what application owns
the mc name.
2017-08-31 14:48:43 -07:00
Aaron Walker dd3b659f9e session: Reimplement using sub-commands (#2225) 2017-08-17 10:55:32 -07:00
Harshavardhana dc47c3819a Enable ubuntu snaps for mc (#2235)
This PR will enable edge channel only.
2017-08-15 10:38:12 -07:00
Krishnan Parthasarathi e6ca983442 Fix credentials argument parsing (#2238) 2017-08-15 10:37:50 -07:00
Aditya Manthramurthy ca96cfc6e6 Move pkg/probe from vendor dir to package dir (#2236)
The probe package is no longer available in the Minio server
repo. This change just moves probe from the vendor directory to its
own dir under `pkg`.

This is a maintenance fix.
2017-08-14 11:13:38 -07:00
Harshavardhana 60681d7fb6 config: Provide meaningful errors for invalid URL and Alias. (#2233)
Fixes #2232
2017-08-06 11:35:01 -07:00
poornas e53ad24e8c Set region for mc from s3 endpoint when its available (#2234) 2017-08-04 14:26:37 -07:00
A. Elleuch b62fa406d8 share: Presign objects under a dir prefix (#2215)
From now on, when the user specifies to share a prefix which represents
a directory, all objects under that directory will be shared without
having to check for --recursive flag. If the latter is specified, all
objects in all subdirs will be shared.
2017-07-31 11:39:19 -07:00
poornas d066ff71f5 diff: reword help message (#2222) 2017-07-30 08:46:39 -07:00
Harshavardhana 3e2c3fc94d vendorize new changes from minio-go (#2227) 2017-07-30 08:44:05 -07:00
Carter McClellan c1b9079b73 Improved experimental log of mc admin heal to only appear on heal specific mc commands (#2230) 2017-07-30 08:43:42 -07:00
Dee Koder b9401d574f Correct typos in mc admin heal warning message. (#2219) 2017-07-27 14:32:19 -07:00
A. Elleuch eba548ca88 Add DisableCompression to override auto-decompress (#2216)
Fixes https://github.com/minio/mc/issues/2209
2017-07-20 11:32:23 -07:00
poornas b4d7ec07f4 Fix typo (#2218) 2017-07-20 11:31:56 -07:00
poornas 4753e1e61b Display watch help [FLAGS] before target (#2220) 2017-07-18 10:39:21 -07:00
Krishnan Parthasarathi 8d7888eb4f Improve mc-cp error message (#2208) 2017-07-15 12:11:21 -07:00
Carter McClellan 54a7460fa0 fix to mc admin (#2207) 2017-07-11 09:39:32 -07:00
Harshavardhana 5c135d25d6 mc: Vendorize minio-go this brings in streaming support. (#2203)
This PR brings following changes

- Brings streaming support for mc uploads.
- Brings support for copying objects upto 5TiB
  as a consequence of ComposeObject implementation
  in minio-go.
2017-07-06 20:41:34 +01:00
Harshavardhana 8391a69dc5 mirror/diff: Ignore errors during objectDifference. (#2200)
Files which are broken in symlink, not accessible
and unsupported should be ignored. We should proceed
to next object.

Fixes #2199
2017-07-06 09:17:34 -07:00
A. Elleuch 1b9beadf2b cat: Ignore Stat() error and pass to Get() (#2166)
* client: Avoid returning metadata with Get()

client-s3.Get() calls Stat() method because Get() is supposed to return
object metadata. This PR makes a change in client interface so metadata
is returned in Stat() method. This is beneficial for us to avoid calling
HEAD method in S3 when run `mc cat`

* cat: Ignore Stat() returned error

In case of cache gateway, HEAD objects returns 404 even though
objects are gettable. This PR ignores Stat() error since its
purpose in case of cat is to check if the download object size
is equal to what the server announced.
2017-07-04 08:13:57 -07:00
Harshavardhana 05f588fd19 mc: Inherit global flags for initialization messages. (#2189)
Fixes #2089
2017-06-26 09:10:14 -07:00
A. Elleuch d01a50d301 minio-go: Revendorize to update (#2194) 2017-06-24 12:03:22 -07:00
Harshavardhana 3b53bbe478 build: Fix release tags of filenames in release. (#2192) 2017-06-23 11:41:30 -07:00
Harshavardhana 685299ab75 mirror: Add timestamp check similar to aws s3 sync (#2188)
Currently `mc mirror` requires source to be
uploaded only if the size is different than the
object on remote server. This PR adds support to
check for last modified time of the source object
as well such that we upload if there are timestamp
differences as well.

Fixes #2187
2017-06-21 16:34:19 -07:00
Harshavardhana 1a8561115b Allow minio-go to validate bucket names. (#2183)
Related change in minio-go https://github.com/minio/minio-go/pull/708

Fixes minio/mc#2157
2017-06-21 21:12:10 +01:00
Minio Trusted c32b1ea48b Add -s -w for gen-ldflags.go 2017-06-14 20:34:56 -07:00
Nitish Tiwari ea05fcbcf5 Add Docker release files for mc (#2182)
- New Dockerfile will be used for mc release images.
- Statically built binary is downloaded from dl.minio.io website and used in the docker image.
2017-06-14 20:01:32 -07:00
Anis Elleuch 2d44e8c85e Fix travis and some code formatting (#2181) 2017-06-13 14:51:20 -07:00
CarterMcClellan 21c677fc2d config: default S3v2 for google endpoints (#2179) 2017-06-13 14:50:17 -07:00
Anis Elleuch 800f0af04e config: Hosts listing cuts fields and adds '...' (#2180)
New host list format when listing several hosts
```
myminiopublic :    http://localhost:9000
myminios      :    https://minio1.duckdns.org:...  Q3AM3UQ867SPQQA43P2F  zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG  S3v4
testazure     :    http://172.17.0.7:9000          myazureac             Gh5543wekitnifILbZam1KYY3TGlswRminio1...  S3v4
```

New host list format when listing one host:

```
azure:  http://localhost:9000  myazureac  Gh5543wekitnifILbZam1KYY3TGlswRminio1u7BJ86wekitnifILbZam1K==  S3v4
```
2017-06-12 14:06:50 -07:00
CarterMcClellan 398bac82d9 Changed install from source instructions. (#2178) 2017-06-08 15:08:49 -07:00
CarterMcClellan cd16de763c Updated build instructions from source. (#2177) 2017-06-08 20:39:34 +00:00
Harshavardhana 694ab27649 build/release: Add sha256sums for minio client releases. (#2171)
Additionally deprecate support for arm6vl platform.

Fixes #2151
2017-06-07 17:09:19 -07:00
Anis Elleuch 61f2595852 fix: Set quiet when term width is unavailable (#2173)
mc was asking the user to provide --quiet flag when terminal
width is not available for any reason. This PR tries to fetch
the terminal width at mc startup and automatically set quiet flag
when it fails to fetch the width.
2017-06-06 21:48:08 -07:00
Harshavardhana be3370396a Remove client instance being sent back in eventInfo() (#2167) 2017-06-05 07:44:22 -07:00
Nitish Tiwari fed9ebe39d - Call the progress bar Finish method once all files are updated (#2165)
- Fixes https://github.com/minio/mc/issues/2161
2017-05-26 18:17:50 +01:00
Anis Elleuch 6c677e0d11 mirror: Sync empty buckets (#2160) 2017-05-22 09:21:45 -07:00
Anis Elleuch 320e29e03f info: Show info of all cluster servers (#2149) 2017-05-22 00:13:35 -07:00
Harshavardhana 7f65ad4957 Add UTCNow() helper function (#2155)
This patch adds UTCNow() function which returns current UTC time.

This is equivalent of UTCNow() == time.Now().UTC()

Refer https://github.com/minio/minio/pull/3931
2017-05-16 18:50:54 +02:00
Anis Elleuch 372e905dad s3: Enforce virtual host style with China endpoint (#2153) 2017-05-11 09:19:12 -07:00
Harshavardhana 7027211e58 docs: Fix bash_autocomplete download link (#2150) 2017-05-10 09:10:04 -07:00
Harshavardhana f0ccc91890 fs: Allow copying to special files if possible. (#2146)
Fixes #2145
2017-05-03 11:21:02 -07:00
Anis Elleuch 136e286ef4 mb: Update pkg to retry mb with unmatched region (#2139) 2017-04-29 00:34:26 -07:00
Anis Elleuch e54962e17f mb: Add -p flag to ignore existing bucket/dir (#2143)
If a remote directory/bucket exists, -p will still make mb cmd
happy if the target already exists.
2017-04-28 13:13:44 -07:00
Marco Liceti 39aa635971 Added configure section with note for Docker users (#2141) 2017-04-26 13:50:32 -07:00
Anis Elleuch 61e511cc3e fs watch: Use a dynamically sized channel (#2109)
Write a growing/shrinking channel to be able to absorb filesystem
notify events even when they come in large numbers.
2017-04-24 01:01:11 -07:00
Scott McClellan dd9e715599 Improved Error Msg For Bucket Names that Contain non-LOWERCASE chars (#2134) (#2135) 2017-04-22 22:15:27 +01:00
Harshavardhana 9bdb7affb1 build: Fix add macOS source work-around for Go bug. (#2138)
Upstream bug https://github.com/golang/go/issues/19734

Fixes #2137
2017-04-20 22:42:10 +01:00
Anis Elleuch 9a881562b9 watch: Fix regression in watch local fs events (#2133) 2017-04-18 12:43:09 -07:00
Anis Elleuch 656f4f13d0 session: Close data session file when migrating (#2126)
Cleanup needed before removing the data file
2017-04-18 12:37:54 -07:00
Scott McClellan 9eb967cabf minor fixes to mc share download command (#2106)
improved error messages and issue with `--recursive` option. 

Fixes  #2099
2017-04-17 17:37:11 -07:00
Anis Elleuch 1bf5ac350f madmin: Update and adapt mc to new lib changes (#2131) 2017-04-16 20:42:55 -07:00
Anis Elleuch 313d0a358f cp: Set exit status to 1 for any error (#2127)
Non fatal errors during copy were not setting mc exit code with 1. This
commit fixes the behavior.
2017-04-15 00:20:13 -07:00
Peter Tribble 81f3ffa3af Fix solaris build (#2122) 2017-04-12 19:55:02 +02:00
Harshavardhana 9ea42680b0 watch/events: Add eventInfo struct for brevity. (#2120) 2017-04-11 09:08:04 -07:00
Harshavardhana 018bcbf629 cli/docs: Fix all cli docs to be consistent in terms of usage. (#2119)
ALIAS should be called as TARGET for all cli commands.
2017-04-11 12:06:02 +01:00
koolhead17 0733d37c67 docs: Fix brew command to install mc. (#2121) 2017-04-11 00:26:05 -07:00
Harshavardhana b0968e29e8 watch/events: Support events on Get/Head operations as well. (#2116)
Fixes #2073
2017-04-10 11:50:52 -07:00
Harshavardhana fac4ef81b2 docs: Fix README.md to reference edge container. (#2118) 2017-04-09 10:43:47 -07:00
Harshavardhana e494e138fe docs: Fix README.md to point to new homebrew tap (#2114) 2017-04-07 03:39:56 -07:00
Anis Elleuch 5805a37d27 alias: Support underscore in alias name (#2113)
my_minio will be supported.
2017-04-05 14:53:57 -07:00
Anis Elleuch ad04a6fcc4 heal: Fix help text (#2111) 2017-04-05 13:58:54 -07:00
Krishnan Parthasarathi 7084a4361e Replace admin-heal-list with admin-heal --fake (#2101)
* Replace admin-heal-list with admin-heal --fake

* Improve admin-heal message for partial healing

* Vendorize pkg/madmin changes to include improved messaging for
  partial healing of objects/uploads.

* Modify message strings to include additional heal result information
  like number of disks where heal was successful.
2017-04-03 12:16:21 -07:00
Anis Elleuch a009299433 Revert "trace: Avoid httputil for less memory consumption (#2102)" (#2104)
This reverts commit eafa942a30.
2017-04-02 14:02:35 -07:00
Anis Elleuch 1c038760ce vendor: Update minio-go package (#2103)
New minio-go commits are introduced:

 sigv2: Do not encode canonical sub-resource value (#636)
 Core.PutObject takes md5 and sha256 sums (#635)
 allow bucket location responses with empty Message (fixes #629) (#630)
 listen: Add support for HEAD/GET bucket events (#634)
 docs:  Remove extra space from code blocks (#632)
 docs: Remove extra space from code blocks. (#631)
 Implement a new NewWithRegion() API for static region. (#627)
 Fix table syntax for SetBucketPolicy parameters (#628)
 Changes needed for implementing "minio gateway s3" (#623)
 Typo in variable name (#625)
 api: Support encryption for Put/Get Object (#613)
 api/retry: Support connection retry for Dial timeout. (#622)
2017-04-02 04:47:42 -07:00
Anis Elleuch eafa942a30 trace: Avoid httputil for less memory consumption (#2102)
Rewrite tracing without httputil since it consumes memory with
requests that have huge data.
2017-03-31 11:17:55 -07:00
Krishnan Parthasarathi 05468dfc8d Improve admin subcommand structure (#2098)
- Rename password subcommand to credentials
- Make clear-lock require --force flag
- Also, fix lock and heal mc-admin subcommand usage text.
2017-03-31 01:12:00 -07:00
Scott McClellan ff7ed00714 Fix for issue #2093 NAME: (#2100)
mc share list COMMAND - List previously shared objects and folders.

COMMAND:
   upload:   list previously shared access to uploads.
   download: list previously shared access to downloads.

USAGE:
   mc share list COMMAND

EXAMPLES:
   1. List previously shared downloads, that haven't expired yet.
       $ mc share list download
   2. List previously shared uploads, that haven't expired yet.
       $ mc share list upload help text misleading...
2017-03-30 18:39:35 -07:00
Anis Elleuch 3c0094a5fe diff: Change output UI (#2097)
Use >, < and ! marks to represent differences between
source and destination.
2017-03-29 15:51:29 -07:00
Anis Elleuch 923c0e24b1 share: Download shares the url of exact prefix (#2096)
When recursive flag is not specified, share download will only
generate download urls for the object which has the exact same
prefix.
2017-03-29 14:43:24 -07:00
Harshavardhana 3b57e86cd3 cli: Add bash and zsh autocomplete (#2095)
Fixes #2094
2017-03-28 16:57:13 -07:00
Harshavardhana 1a6987558a admin: Hide help sub-command from 'mc admin service' (#2091) 2017-03-26 10:30:35 +01:00
Dee Koder a15d54c4a8 docs: Removed space from code blocks. (#2087) 2017-03-23 19:07:02 -07:00
koolhead17 3c4c1222d8 docs: fix for README.md Markdown table. (#2082) 2017-03-23 09:14:35 -07:00
Anis Elleuch 250def49d5 madmin: Update package (#2084)
This brings up the following fix:
https://github.com/minio/minio/commit/181e002c56d6df84576038bab94079c3f1cdf718

Besides, this PR adds removes an uneeded line in admin cmd output.
2017-03-22 20:44:37 +01:00
Anis Elleuch b1e3d147f5 ls: Fix listing incomplete entries result (#2081)
This also factors common code used by several types
of listing routines, by creating a filtering channel
of results returned by these channels.

e.g. Filter out incomplete uploads or vice versa
2017-03-21 10:34:43 -07:00
Anis Elleuch 6c89b81d7b fs: Remove handling of specific windows symlinks (#2080)
Go has fixed the problem of dealing with junction files
(https://github.com/golang/go/issues/9190). This commit
simplifies the code of client fs
2017-03-20 15:51:28 -07:00
Anis Elleuch 7c7969ed55 admin heal: Support for uploads healing (#2076)
mc admin heal supports --incomplete flag to list and heal uploads.
2017-03-20 13:56:52 -07:00
Anis Elleuch 29920f8c9c fs stat(): Return dir stat with incomplete flag (#2078)
fs.Stat() returns an error when the path corresponds to
a directory and incomplete flag is enabled. This PR follows
S3 client behavior and fixes the behavior.
2017-03-20 11:06:43 -07:00
Bala FA 9ebb916902 Use words package from minio for DamerauLevenshteinDistance() (#2075) 2017-03-19 18:25:22 -07:00
Harshavardhana 4369359286 policy/links: Do not list prefixes in recursive mode. (#2070) 2017-03-14 19:41:26 +01:00
Harshavardhana 1dab94c625 Split config-host into remove, list, add commands (#2069)
This PR also adds convenient aliases for

 - remove as `rm`
 - list as `ls`
 - add as `a`

Also brings much needed cleanup.
2017-03-11 18:50:56 -08:00
Harshavardhana 6c0f804f32 vendor update minio-go with new fixes. (#2068) 2017-03-11 00:48:24 +01:00
Anis Elleuch 7991f67863 vendor: Update minio-go to bring #620 fix (#2067)
https://github.com/minio/minio-go/pull/620
2017-03-10 00:14:17 +01:00
Anis Elleuch 22ab1c4901 vendor: Update minio-go to bring #619 fix (#2066)
https://github.com/minio/minio-go/pull/619
2017-03-09 22:15:34 +01:00
Krishna Srinivas 53cb92038a Set secretKeyMaxLen = 100 to accomodate azure's account-key length. (#2054) 2017-03-08 16:53:04 -08:00
Harshavardhana 4425378b37 mc: Code cleanup after running gosimple tool (#2065) 2017-03-08 10:48:45 +01:00
Anis Elleuch 7fda78af40 info: Add sqs ARNs to the output (#2063) 2017-03-07 03:13:49 -08:00
Anis Elleuch 6e8320a6dc cp: Fix guessing if target url is a directory (#2062)
This fixes `mc cp /etc/issue/ /tmp/new_dir/` where
/tmp/new_dir/ doesn't exist yet.
2017-03-07 02:56:14 -08:00
Harshavardhana 99682ecbdb admin: HealObjectInfo can be nil skip it. (#2059)
Fixes #2058
2017-03-03 20:37:04 -08:00
Anis Elleuch bf657a33e3 admin: Add set config command (#2051)
Which works this way: 

```
cat config.json | mc admin config set myminio/
```
2017-03-03 15:18:23 -08:00
Harshavardhana bab1b9302e epoll_wait is not implemented on ARM64 Linux (#2052)
Vendorize the fixes for fsNotify package to avoid
crashes on ARM64 Linux.

Fixes #2047
2017-03-01 15:15:59 -08:00
Anis Elleuch 8ce6f43e35 Stop mirror/diff when difference() sends error (#2049)
The caller of difference() now receives errors so it can
stop mirroring or difference calculation.
2017-03-01 11:06:26 -08:00
Anis Elleuch ecee324c00 admin: Add config get command (#2037) 2017-02-28 14:33:26 -08:00
Harshavardhana 0934a39d73 cli: Fix more commands with inconsistent UI (#2045) 2017-02-28 00:21:46 +01:00
Anis Elleuch 7673ef084d admin: Add info cmd and simplify service status (#2036) 2017-02-27 12:29:12 -08:00
Anis Elleuch 55e010ca52 mirror: Return exit code after mirror/watch error (#2043) 2017-02-27 11:45:16 -08:00
Harshavardhana 1ef242a5c1 Fix all cli commands to have consistent UI (#2040)
Fixes #2038
2017-02-27 11:44:26 -08:00
Harshavardhana 071c71efbc Fix macOS build (#2041)
Fixes #2039
2017-02-27 00:44:09 -08:00
Anis Elleuch 798775775b Use ` instead of unicode single quote (#2033)
‘ is not supported in some dumb terminals, use ` instead
2017-02-25 11:08:32 -08:00
Harshavardhana 2ca601ef22 cli: Remove help sub-command and --version flag (#2030)
This is to bring consistent CLI experience as before.
2017-02-21 23:00:09 +01:00
Nitish Tiwari 1cfb326e2f Update AWS credentials URL (#2031) 2017-02-21 00:55:53 -08:00
Harshavardhana 675fbee1f3 mc: Rewrite update and version command. (#2026)
- Supports docker image
- Supports showing how old your current
  `mc` version is.
2017-02-20 22:04:54 +01:00
Harshavardhana d055f0edac fs: new files and folders created honors umask (#2023)
umask should be honored properly for all write
operations on filesystem. This is in line with
how all unix tools behave.

Fixes #2022
2017-02-19 22:41:56 +01:00
Harshavardhana 1f48b16acb cli: Make sure to add "--help" flag for subcommands. (#2024)
--help is now back and prints properly with command
help template.
2017-02-19 12:30:16 -08:00
Harshavardhana 41d4857d73 Add conflict document regarding midnight commander (#2021) 2017-02-18 21:44:28 -08:00
Harshavardhana f7dbf9a20b Let mc to be compiled with 1.7.5 onwards. 2017-02-18 03:05:34 -08:00
Harshavardhana d7a3a0bce3 Move to go1.8 for all builds. (#2019) 2017-02-17 21:29:53 +01:00
Anis Elleuch 7483cdebfb mirror: Quit after showing all progressbar updates (#2020)
mc can quit when mirror terminates but progress bar is not able
to show all made progress. This commit makes mc waits until all updates
are sent to the status channel.
2017-02-17 12:10:01 -08:00
Harshavardhana e7e44b96ee Avoid printing hidden flags and commands with custom help. (#2015)
Always use .VisibleFlags and .VisibleCommands in templates
to avoid printing hidden flags and commands in the help
template.
2017-02-15 02:05:29 -08:00
Anis Elleuch 43388a06ca client-s3: Recursive List() avoids listing buckets (#2014)
This fixes bug in `mc mirror myminio/ /tmp/dir` since objectDifference() can only
take care of mirroring objects.
2017-02-13 13:47:49 -08:00
Anis Elleuch ace3f452c3 mirror: Mirror buckets if only alias is specified (#2006) 2017-02-12 11:20:05 -08:00
Anis Elleuch fb9d10772a help: Use {{.HelpName}} in help/examples template (#2013)
It is easier to use {{.HelpName}} in help text template to print
the mc binary name plus the whole command hierarchy (binary name +
command + subcommand, etc..)
2017-02-12 09:30:00 -08:00
Bala FA a5014a8c71 trie: use trie package in minio. (#2010) 2017-02-10 19:28:45 -08:00
Anis Elleuch 8ce4b39fed admin: Rename creds to password subcommand (#2009)
Use new command "mc admin password" to change creds
2017-02-09 12:13:45 -08:00
Bala FA f01f94a691 rm: fix multiple args handling (#2008) 2017-02-09 01:18:56 -08:00
janv37 04cd5e80ee Add build support for OpenBSD on i386 and amd64 (#2005) 2017-02-08 09:21:24 -08:00
Harshavardhana 4fd1500312 Fix mc admin restart message. 2017-02-07 01:49:43 -08:00
Harshavardhana 5b74d8c444 Bring --watch option back for mirror to make scripting as default. (#2001) 2017-02-06 11:58:20 -08:00
Harshavardhana 1d683ea83e Fix --watch option 2017-02-05 21:06:29 -08:00
Krishnan Parthasarathi 38652b168a Improve note on setting download policy (#1998) 2017-02-04 10:53:01 -08:00
Harshavardhana cca8c10f33 mirror: For non-s3 make sure we copy and exit properly. (#1995) 2017-02-03 15:55:44 -08:00
Harshavardhana 2ffa265d8c Add docker file as part of the README.md (#1941) 2017-02-02 15:10:04 -08:00
Anis Elleuch ad850412d2 lock: Update madmin pkg and use duration flag name (#1994)
* Use new errors format returned madmin APIs
* Use duration query name in Locks API
2017-02-01 12:19:27 -08:00
Anis Elleuch 4f0c2bf376 mirror: Avoid session and enable continuous mirror (#1992)
* Watch mode is enabled by default without specifying any flag
* Saving session is removed since mirror is incremental
* Remove the use of queue to simpliy the code
2017-01-31 09:39:39 -08:00
Harshavardhana fa75251c76 Allow saving accessKey, secretKey which is empty. (#1990)
Fixes #1989
2017-01-25 17:42:45 -08:00
Anis Elleuch 3fefebd05d heal: Don't print info if heal obj returns an err (#1988)
When heal object returns an error, just print an error and continue with the
next objects.
2017-01-25 13:50:45 -08:00
Harshavardhana 9d7529118e Add build support for pine64 (#1987)
Also update notify package with new fixes.
2017-01-25 13:37:06 -08:00
Anis Elleuch 507e7672c2 madmin: Update vendorized management API (#1986)
Update to fix an ListObjectsHeal() issue
2017-01-25 22:30:21 +01:00
Anis Elleuch 9c81d374b1 heal: Show help when alias is not specified (#1985) 2017-01-25 12:30:22 -08:00
Anis Elleuch 38c3703d08 admin: Heal format in heal command (#1980) 2017-01-24 15:05:32 -08:00
Anis Elleuch 973dc13cc0 admin: Set 5 min timeout for header response (#1982)
For admin management API requests, we set 5 min as default value
2017-01-24 23:05:19 +01:00
Aaron Walker bca93f6c83 Mirror: normalize keys before comparing (#1978)
vendorize golang.org/x/text/unicode/norm dependency

vendorize golang.org/x/text/transform dependency

add example of multiple encodings
2017-01-24 11:51:59 -08:00
Anis Elleuch caf6bfb76f admin: service status uses new response format (#1979)
server & service fields are added to JSON response
2017-01-23 17:01:21 -08:00
Harshavardhana 76180184a5 client: S3 and Admin clients should have TLSConfig. (#1977)
TLSConfig should be allocated regardless of the
URL scheme so that the re-direction works properly.

Without this change if a server is configured with
self signed certs redirection would fail with

```
x509: certificate signed by unknown authority
```

Allocate TLSConfig always with default values.
2017-01-23 14:38:56 -08:00
Anis Elleuch 0e1e954768 Add new admin Heal command (#1958)
e.g.: `mc admin heal list myminio/` and `mc admin heal myminio/testbucket`

Also, some heal files that belong madmin package have been added
2017-01-22 15:19:06 -08:00
Anis Elleuch b031817fce admin: Add creds command (#1976)
mc admin service creds command set new access and secret keys in the specified Minio server
2017-01-22 15:17:55 -08:00
Anis Elleuch 6b2e63e66c locks: Use new json format for list/clear results (#1975)
Also minio-admin package has been updated
2017-01-19 12:07:45 -08:00
Anis Elleuch 085a1e512f flags: use IsSet to fetch for cli flags (#1969)
cli package fails to search for global flags when we use many level of subcommands. This PR uses context.IsSet() instead.
2017-01-19 11:25:35 -08:00
Dee Koder 31cb23f586 updated badges to slack from gitter (#1973) 2017-01-17 11:59:37 -08:00
Harshavardhana 6a7ca4311e cli: update with urfave/cli changes (#1968) 2017-01-16 10:41:56 -08:00
Harshavardhana d87078bee6 service: Remove service stop command. (#1967)
Deprecate and remove `stop` admin command.
2017-01-14 16:38:01 -08:00
Harshavardhana 50228116e1 Fix source code format issues. 2017-01-13 16:55:25 -08:00
koolhead17 95033f3f76 docs: Updated --older-than syntax in doc. (#1966) 2017-01-13 01:06:39 -08:00
poornas a8acbe5cfb sort output of mc config host list (#1959) 2017-01-10 13:42:34 -08:00
poornas f9d4c4dbac fixed formatting for list host (#1955) 2017-01-09 18:48:22 -08:00
Anis Elleuch 17abc6c736 admin service: json output depends on backend type (#1950)
'Type' field in the json output contains 'FS' or 'XL', also read/write quorums information
are hidden and online/offline disks are shown only when the backend storage is XL
2017-01-09 08:49:53 -08:00
Anis Elleuch 94bd9564d0 admin: fatal message for unknown aliases (#1953)
This change issues a fatal message when the provided alias in cli is not known
2017-01-09 08:47:43 -08:00
Anis Elleuch c6cb6595be admin: Simplify client initialization (#1951)
newAdminClient() is added to simplify initialization and take care of ssl connections
and tracing http request
2017-01-07 16:00:22 -08:00
Harshavardhana a2f25c2f3b Remove references for GO15VENDOREXPERIMENT=1 2017-01-06 18:59:55 -08:00
Harshavardhana 5d3c4ed96c admin/lock: list locks defaults to 24hrs and older. 2017-01-06 01:42:47 -08:00
Anis Elleuch 7cec8f2285 Add admin lock command (#1942) 2017-01-06 01:29:49 -08:00
Anis Elleuch 86777e7863 links: Print encoded form of public URLs (#1947) 2017-01-05 12:16:24 -08:00
Harshavardhana 853fea16b4 Enable support for s3 transfer acceleration. (#1946)
Simply use

```
mc config host add s3-accel https://s3-accelerate.amazonaws.com <access_id> <secret_id>
```

This is all is needed, if you have buckets which has s3 acceleration
enabled it just works transparently.

Fixes #1912
2017-01-05 01:36:01 -08:00
Harshavardhana 9cf76b1233 api: StatObject if listing returned missing file. (#1945) 2017-01-04 18:36:09 -08:00
Anis Elleuch 66a65aab02 Add policy links command (#1943) 2017-01-04 08:24:58 -08:00
Harshavardhana 5581915bc0 session: Validate session config header version. (#1940) 2017-01-01 13:30:10 -08:00
Harshavardhana ee7f4e1d52 Simplify loading config and use config loader with version check. (#1939) 2017-01-01 13:02:27 -08:00
Harshavardhana 8c65985cd0 rm: Allow delete of objects with / at the end. (#1937)
Fixes #1931
2017-01-01 10:26:00 -08:00
Harshavardhana 23a58eb5da mc: Introduce new Dockerfile for mc. (#1938)
This is to build `mc` at hub.docker.com

Fixes #1917
2016-12-31 20:49:05 -08:00
Anis Elleuch 9193eef1c9 clientfs: Fix policy mode calc. in GetAccess() (#1936)
Masking target directory file mode to be able to perform correct comparaison with policy standard file permissions in FS mode
2016-12-23 06:54:45 -08:00
Anis Elleuch e90e9bc352 admin: Introduce the new service command (#1922)
Introducing Admin Service cmd to mc
2016-12-22 13:37:55 -08:00
Harshavardhana a1d860f818 Add Solaris/Illumos source installation. 2016-12-22 13:24:25 -08:00
Harshavardhana d733d68b0c enable static build releases with CGO_ENABLED=0 (#1935)
Also removing darwin build, since we do brew install.

Removing solaris since it doesn't build anymore.

Fixes #1933
2016-12-22 12:54:26 -08:00
Aditya Manthramurthy 4a96d65408 gofmt fixes (#1930) 2016-12-16 08:29:00 -08:00
Dee Koder 1e16ed5e55 404fix: Update docs.minio.io/docs/minio to docs.minio.io/minio-quickstart-guide (#1929) 2016-12-15 12:39:41 -08:00
Harshavardhana 782352ae56 mirror/cp/pipe: Preserve metadata while copying s3 to s3. (#1927)
Fixes #1923
2016-12-14 20:06:52 -08:00
koolhead17 d97ba4eb0d docs: Removed $ from code block to make code copy easier. (#1928) 2016-12-14 12:37:58 -08:00
Harshavardhana 282246fff2 mirror: --remove should properly remove files on target. (#1926)
This bug happened after rm-main was refactored.

Fixes https://github.com/minio/minio/issues/3432
2016-12-12 14:31:46 -08:00
Anis Elleuch b3059164aa cli: Fix --version output (#1924) 2016-12-12 10:21:52 -08:00
Harshavardhana 64166319ee cp/diff/mirror: Cleanup code and deprecate unnecessary flags. (#1914)
This fix also fixes an apparent crash found in diff.

```
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x0 pc=0x4bdc07]

goroutine 84 [running]:
panic(0x810ea0, 0xc4200120e0)
        /home/builder/.gimme/versions/go1.7.3.linux.amd64/src/runtime/panic.go:500 +0x1a1
github.com/minio/mc/cmd.objectDifference.func1(0xc4200880a8, 0xc42042ee56, 0xc420315ec0, 0xc4200880b0, 0xc42042ee57, 0xc420315f20, 0xc42042ee54, 0xc42042ee55, 0xc420315501, 0xc4200880a0, ...)
        /home/builder/mygo/src/github.com/minio/mc/cmd/difference.go:109 +0x197
created by github.com/minio/mc/cmd.objectDifference
        /home/builder/mygo/src/github.com/minio/mc/cmd/difference.go:180 +0x2f5
```
2016-12-06 01:41:22 -08:00
Harshavardhana b8e732e526 events: Fix the message printed by events{add,remove} (#1911)
Fixes #1900
2016-12-05 14:14:01 -08:00
Harshavardhana f0d926ebba fs: Enhanced ignore list to do glob match. (#1910)
Fixes #1902
2016-12-05 14:07:18 -08:00
Harshavardhana 1e48d10617 mirror: Avoid flushing session to disk on each i/o operation. (#1909)
The problem was for each read from statusCh we were writing
to session file again and also syncing to disk. This adds
severe performance problems.

Fixes #1908
2016-12-05 13:53:09 -08:00
Anis Elleuch ce9d706716 cat: return err in case s3 object short read (#1907)
cat inspects the size of the downloaded s3 object when specified to
detect a possible short read
2016-12-04 13:59:07 -08:00
Anis Elleuch 81abbca12f Vendorize new minio-go version (#1905) 2016-12-02 16:36:34 -08:00
Anis Elleuch 2cd67b296e tls: load custom public certificates from CAs dir (#1901)
When a user needs to setup his own TLS configuration, he can put his
custom authority certificates in ~/.mc/certs/CAs/. These certificates will
be automatically loaded at startup and will be set to all HTTPS connections
2016-12-02 11:16:01 -08:00
Anis Elleuch 7976d6d805 Continue listing incomplete uploads when we receive an error associated to a specific object (#1899) 2016-11-27 10:33:35 -08:00
Harshavardhana df395786bd mc: Consistent exit codes across all commands. (#1895)
Also brings in much needed CLI changes from
upstream and backporting our custom changes on
top of those changes.

Fixes #1880
2016-11-27 12:35:59 +05:30
Harshavardhana 2412aae68f cp/mirror: Use proper paths for windows during copyObject. (#1897)
Fixes #1857
2016-11-27 12:26:02 +05:30
Harshavardhana 0a42e2969a Relax access/secret key requirements as minio server. (#1894)
Also add tests in the process.
2016-11-24 12:10:28 -08:00
Harshavardhana b51e6b0485 Fix downloading files with exact ranges requested in client FS. (#1892)
This is due to the fact that ReadAt() will not send io.EOF
when reading past the offset, server instead returns
Range error. Handle the error by only reading until the
requested size.
2016-11-21 02:53:24 -08:00
Harshavardhana e1ed7c65e7 Fix a debug message in session close. 2016-11-20 18:41:12 -08:00
Harshavardhana cf89d74561 Vendorize new minio-go code. (#1891)
This fixes #1889.

```sh
mc mirror -w
```

Now runs continous even when the source is not available.
Reconnects indefinitely in a binomially increasing fashion
and also allows jitter so that the retry has a nice
distribution as well.

This allows for 'mc mirror -w' to run continously without
further monitoring.
2016-11-20 16:31:53 -08:00
Harshavardhana 38aec4d875 mirror and cp should print size in --json mode. (#1890)
```sh
mc cp -r --json /usr/bin /tmp | jq .
...
...
{
  "status": "success",
  "source": "/usr/bin/gcm-viewer",
  "target": "/tmp/bin/gcm-viewer",
  "size": 87128,
  "totalCount": 2602,
  "totalSize": 677422730
}
```

This allows scripts to build progress around this data.
2016-11-20 14:46:24 -08:00
Royce Remer 23f0a27acc we removed GOINSTALL.md some time ago, point at new minio docs withe same instructions (#1888) 2016-11-18 18:37:38 -08:00
Royce Remer 447cb7a726 fix regex comparator for GOROOT (#1887) 2016-11-18 18:37:16 -08:00
Harshavardhana fa5a339434 Move to latest x/sys/unix for arm64 fixes. (#1882)
Related to fixes here golang/go#15393
2016-11-18 18:04:09 -08:00
Dee Koder 7a295dd5fa bugfix: Remove sh tag for mc list of commands (#1881) 2016-11-15 15:42:08 -08:00
Anis Elleuch 2895b0acca Put() in client fs avoids reading from input reader when data is zero lengthy (#1879) 2016-11-08 16:59:23 -08:00
Anis Elleuch ab9cdd7fce Fix policy cmd syntax checking (#1878) 2016-11-08 13:32:27 -08:00
Anis Elleuch cc6fa9acbf Rename 'both' policy to 'public' (#1877) 2016-11-08 10:55:55 -08:00
Justin Clift e14dcccd37 Adjust a help text line to match its example description (#1869) 2016-11-03 11:51:11 +05:30
Anis Elleuch 27526399f5 Vendorize new minio-go version as it brings new fixes (#1867) 2016-11-02 02:51:35 -07:00
Harshavardhana 8009e8108b Validating signature type should be case insensitive. (#1866) 2016-10-28 10:50:43 -07:00
Anis Elleuch b45d48f4f1 Update minio-go library (#1864) 2016-10-26 16:39:23 -07:00
Anis Elleuch b9f1950320 Use correct share upload url (#1863) 2016-10-25 13:23:22 -07:00
Bala FA 6de2b4559e Refactor rm command. (#1855)
This patch makes rm command to use minio-go.RemoveObjects() to removeobjects recursively.
2016-10-17 20:24:09 -07:00
Bala FA 0661f537cf update help messages of all commands. (#1856) 2016-10-17 20:18:55 -07:00
Anis Elleuch b737b2e7fc Better error message when trying to monitor a non minio s3 provider (#1854) 2016-10-13 09:16:46 -07:00
Anis Elleuch d9b3f276b8 Fix remote path calcuation when continuously mirroring fs dir to any target (#1853) 2016-10-10 13:03:40 -07:00
Anis Elleuch 53ab0168e4 Correct behavior of listing and removing empty directories (#1851)
* Listing empty directy returns empty entries

* Remove empty directories in rm cmd
2016-10-08 04:16:02 -07:00
koolhead17 01f0c35651 docs: Added newly introduced sub-commands, flags with example. (#1850) 2016-10-07 08:45:17 -07:00
Bala FA 75d55783c0 ls: fix incomplete listing for specific prefix (#1849)
Previously it was failing like below.

```
$ mc ls --incomplete myminio/mybucket
[2016-09-16 09:48:57 PDT] 576MiB 1.iso

$ mc ls --incomplete myminio/mybucket/1.iso
mc: <ERROR> Unable to initialize target ‘myminio/mybucket/1.iso’. Object key is missing, object key cannot be empty
```

This patch fixes this issue.
2016-10-04 17:19:05 -07:00
koolhead17 f03aaef72f docs: modified the guide to add Minio reference instead AWS S3. (#1847) 2016-10-03 00:10:14 -07:00
Anis Elleuch f54e426bb1 Do not return S3 empty directories in recursive listing (#1846) 2016-10-01 21:32:22 -07:00
koolhead17 5b94ddc703 docs: Added note on mc mirror -w that it is minio only command. (#1842) 2016-09-30 09:13:15 -07:00
Harshavardhana 477461325d update: Update link is printed automatically for RELEASE versions. (#1840)
This link is printed only for RELEASE versions when user doesn't
provide any sub commands.

Fixes #1839
2016-09-28 10:50:06 -07:00
Bala FA 3094af8a5e rm: add timebased delete and object list from stdin (#1837)
* Add multi-delete support by taking object list from stdin
* Add support to `rm` to remove objects older than given time
* Add --prefix flag to differenciate prefix and target names.

Fixes #1827 #1828
2016-09-28 10:13:11 -07:00
Harshavardhana add7dcc763 vendor: Update minio-go deps with latest changes (#1836)
- PutObject() parallel uploads
- ListenBucketNotification API change.
- Other misc fixes.
2016-09-27 16:10:24 -07:00
Anis Elleuch df7acbcad4 Upgrade go version requirement to 1.7.1 (#1832) 2016-09-25 12:13:35 -07:00
Anis Elleuch 15b91126d5 More meaningful error messages with unsupported filesystem operations (share and policy) (#1833) 2016-09-25 10:20:56 -07:00
Anis Elleuch 2b24a7b520 Avoid seeking os.Stdin in client-fs Put() (#1834) 2016-09-25 10:19:13 -07:00
koolhead17 b404c7583b docs: added newly introduced --insecure global option. (#1823) 2016-09-08 13:42:28 -07:00
Harshavardhana 6ce337ca38 Bring new fixes from minio-go related to PutObject and GetObject (#1822) 2016-09-09 02:11:53 +05:30
Anis Elleuch d0caa630af isTargetURLDir() returns true for aliased URLs with empty object names (#1805) 2016-09-05 20:38:40 -07:00
Anis Elleuch 8a48d604a8 Add policy list command (#1811) 2016-09-03 05:47:37 -07:00
Anis Elleuch 80b0aa3842 Fix inefficient assignments reported by ineffassign (#1817) 2016-09-02 12:31:52 -07:00
Harshavardhana c6a383590d mc: Do not print accounting with '--json' (#1815) 2016-09-01 20:13:49 -07:00
Anis Elleuch fd34958ffa Add --insecure flag to skip certificate validation (#1814) 2016-09-01 18:36:00 -07:00
Anis Elleuch 530a34a3f3 Fix crash when parallel mc instances try to migrate session files at the same moment (#1812) 2016-08-29 18:58:25 -07:00
koolhead17 90093b5d8c Doc: Added install instructions via brew package manager for Mac. (#1810) 2016-08-29 18:48:22 -07:00
Harshavardhana 939dad5900 Move the notify events to new package - rjeczalik/notify. (#1807)
* Move the notify events to new package - rjeczalik/notify.

* improving handling of notify events on linux specific (#3) @nl5887
2016-08-24 02:11:55 -07:00
Dee Koder 85717527d9 docs: Fix capitalization in heading (#1808)
fixes https://github.com/minio/cookbook/issues/71
2016-08-22 11:58:01 -07:00
Harshavardhana 768be74f74 mirror: Fix progress bar for mirror server to server copy on same host. 2016-08-20 19:41:26 -07:00
Harshavardhana a885ffd64b mirror: Add missing events from mirror watch. (#1804) 2016-08-19 15:26:15 -07:00
koolhead17 e25f1ee72f Doc: Replaced HTML table to Markdown in minio-client-complete-guide.md (#1801) 2016-08-19 13:46:13 -07:00
Harshavardhana 6e943832d5 doc: Add missing '--watch' example for 'mirror' command. 2016-08-19 02:37:18 -07:00
Anis Elleuch 3a3bc2ffb1 Fix typo in default events parameter (#1802) 2016-08-18 10:59:42 -07:00
Harshavardhana 90a421e4af Fix windows builds. 2016-08-18 00:41:41 -07:00
Harshavardhana bc72ffb6b2 doc: Add new watch and events command. 2016-08-17 18:43:51 -07:00
Harshavardhana a30f0aca85 Add build-constants. 2016-08-17 18:30:01 -07:00
Harshavardhana 2ea2ec90d2 Rename mc --> cmd 2016-08-17 18:26:18 -07:00
Harshavardhana 22670acfbe vendor: Update minio-go with new bucket policy changes. 2016-08-17 18:22:19 -07:00
Harshavardhana 358a5af98e Fix table alignment for watch and events. 2016-08-17 18:15:15 -07:00
Harshavardhana c70bd05494 Add colors properly for events. 2016-08-17 18:08:50 -07:00
Anis Elleuch 0b4d52a141 Add events and watch commands (#1800) 2016-08-17 17:59:05 -07:00
Harshavardhana a47c86c54c mirror: Watch() for events based on session time. (#1799)
Enable notification if not already set, avoid overriding
or append to existing notification set - all of this
needs to be done to make this transparent.
2016-08-16 14:32:15 -07:00
koolhead17 082ea3c295 Code: Fixed spelling mistake in files listed. (#1797) 2016-08-16 03:58:08 +05:30
Anis Elleuch a4177ad30b Add notify cmd to listen on bucket notifications (#1791) 2016-08-15 13:35:40 -07:00
Remco Verhoef 3603766f1c changed package command to mc (#1796)
* changed package command to mc

* changed package from command to mc
2016-08-15 09:05:52 -07:00
Harshavardhana 951429fe67 Add code coverage and cleanup CI configs. (#1795) 2016-08-13 14:00:57 -07:00
Harshavardhana f5ff7e15cf mc: Fix release build flags after recent refactor. (#1794) 2016-08-13 13:49:18 -07:00
Harshavardhana c9c95f2e9e vendor: Remove minio-go.v2 from gopkg.in for now. 2016-08-13 12:47:18 -07:00
Remco Verhoef bc79fba49a async replication support for mirror (#1784) 2016-08-13 12:39:21 -07:00
Remco Verhoef b51fb32054 Refacture structure proposal. (#1793) 2016-08-11 15:29:04 -07:00
koolhead17 c9ecd023fa Doc: Added Minio client configuration files guide. (#1789) 2016-08-08 15:08:08 -07:00
koolhead17 c28aa819b6 Doc: This patch will add correct link for downloading 32 bit windows (#1788)
binary.
2016-08-06 10:10:44 -07:00
Anis Elleuch f6ca45c384 Aliases should not start by a slash (#1786) 2016-08-05 09:09:51 -07:00
Krishnan Parthasarathi 75de34de90 Create ISSUE_TEMPLATE.md (#1783) 2016-07-29 19:31:47 -07:00
Anis Elleuch 429a0d00af mc removes incomplete downloads .part.minio when rm is invoked with --incomplete flag (#1769) 2016-07-26 14:20:35 -07:00
koolhead17 acf933646b Doc: minio-client-complete-guide.md (#1781)
Fixed broken link.
2016-07-24 23:52:31 -07:00
koolhead17 b427202237 Doc: Added Gitter channel link (#1780) 2016-07-24 21:54:56 -07:00
Dee Koder 8eaa9463c1 doc: Convert table with empty header to be html table. (#1779)
Fixes https://github.com/minio/cookbook/issues/39
2016-07-24 15:23:42 -07:00
koolhead17 e15f04c01b Doc: Minor changes to appear correctly on Doctor. (#1777) 2016-07-21 15:02:17 -07:00
koolhead17 626baab73d Doc:Changes to reflect on Doctor (#1776) 2016-07-21 12:41:25 -07:00
Anis Elleuch 5e8f861eac Fix typo in session help and remove a comma glued to the access key in config host list (#1775) 2016-07-21 11:21:30 -07:00
Anis Elleuch 9217553a3c Vendorize minio-go 2.0 and make mc use ListObjectsV2 (#1771) 2016-07-20 17:06:15 -07:00
Dee Koder ab20dc98f7 docs : Amend heading to Minio Client Complete Guide (#1773) 2016-07-19 17:19:47 -07:00
Dee Koder 9f1315fa64 space: One extra space was missed. Fixed it. (#1772) 2016-07-19 17:01:16 -07:00
koolhead17 46d158d023 docs: Added new 'doc' directory and moved associated docs related to mc (#1770) 2016-07-19 16:54:12 -07:00
Anis Elleuch acd80370e6 Avoid an error when migrating a session file which is created but then removed by another mc instance (#1768) 2016-07-18 15:00:13 -07:00
Harshavardhana 9ad19bfe52 vendorize: Add new changes from minio-go. (#1766) 2016-07-14 18:36:12 -07:00
Anis Elleuch eed14719db Avoid using white text color for people who has white/bright term background (#1765) 2016-07-14 11:51:04 -07:00
Anis Elleuch 589c821f9b progress: Switch to chegga pb (#1764) 2016-07-13 14:44:23 -07:00
Anis Elleuch a09795c8a7 Fix S3 Stat() dir mode marking (#1763) 2016-07-11 14:13:45 -07:00
Anis Elleuch 52df29917b client-s3 Stat() returns proper error in case of an object or dir are not found (#1762) 2016-07-10 18:16:39 -07:00
Anis Elleuch 16ae081c4c Do not show successful msg in mb command when the latter actually fails (#1761) 2016-07-10 17:04:21 -07:00
Harshavardhana 489d1629fb ls: Listing command should list files as prefixed properly. (#1760)
Fixes #1713
2016-07-10 16:41:41 -07:00
Anis Elleuch 9be8aebfff Avoid creating session when cp detects object exists as directory (#1758) 2016-07-10 16:36:16 -07:00
Anis Elleuch e53fa1a5a2 Simplify and enhance the scan bar rendering (#1759) 2016-07-10 16:36:00 -07:00
Anis Elleuch 92d1e226d3 Fix checking go version under OSX (#1757) 2016-07-10 11:09:50 -07:00
Harshavardhana 64dbb7ed9c docs: Fix docs formatting and remove DOS characters. 2016-07-10 03:23:33 -07:00
Anis Elleuch 21b0f4b0d2 Rename access cmd to policy and permissions to none, download, upload and both (#1755) 2016-07-10 03:23:17 -07:00
Anis Elleuch fc448e49d5 Add support of golang tip (#1756) 2016-07-09 07:36:22 -07:00
David D Lowe 7a21e4bb0d Fix broken documentation links in README.md (#1754)
This is only broken in GitHub, not on the documentation site, but still.
2016-07-08 07:25:40 -07:00
koolhead17 47ca8a61ea doc:README.md/URL path fix. (#1750) 2016-07-04 21:23:10 -07:00
koolhead17 1c3f889f6e doc: README.md/modified to sync with docs.minio.io (#1748) 2016-07-04 10:35:28 -07:00
Aakash Muttineni 6f4a0f9cbb vendor: Bring new minio-go changes for bucket policy related bugs (#1746) 2016-07-04 10:35:15 -07:00
Harshavardhana 67c1957eb0 cli/mb: make bucket takes multiple arguments. (#1745)
As an example

```
$ mc mb /tmp/bc{1..10}
```

It is convenient to have this when 'mc mb' is aliased
to 'mkdir' for everyday use.

Fixes #1743
2016-06-30 02:25:58 -07:00
Krishnan Parthasarathi 3d7796f38c Vendorize recent fixes to minio-go (#1744) 2016-06-29 17:49:09 -07:00
Harshavardhana 2d431dacbc ls/cp/mirror: Ignore objects with StorageClass GLACIER. (#1742)
Fixes #1741
2016-06-23 00:28:17 -07:00
Aakash Muttineni 17468c8863 Vendor update (#1739) 2016-06-14 22:44:33 +05:30
Anand Babu (AB) Periasamy 475670de7d Update play description. (#1735) 2016-05-30 22:51:44 -07:00
Aakash Muttineni f9efb67bc2 Minio-go vendor update (#1734) 2016-05-29 23:44:16 -07:00
Krishnan Parthasarathi 9766ff1805 Append trailing slash to targetURL only if absent (#1731) 2016-05-28 13:16:57 -07:00
Krishnan Parthasarathi cc4227e3f2 Made session list ignore broken sessions (#1728)
* Made session list ignore broken sessions

- `mc session list` - skips partial sessions[1]

- `mc session clear all` - doesn't clear partial sessions.
The idea is to prevent the user from clearing all sessions without
realising that there were partial sessions.

When there is one or more partial sessions, clear each one of them individually
as follows,
 `mc session clear <broken-session-id>` - clears the partial sessions.

[1] - partial session - a session with missing `.data` file in the sessions directory.

N B The presence of partial sessions indicate some underlying bug in session mangement
code. This PR provides relief for users in the event of such a bug.

* Added comments to session helper functions and to be provide context
2016-05-23 23:05:39 -07:00
Krishnan Parthasarathi ba2e8149c8 Ignore BucketEmpty error for top-level listing (#1727)
* Ignore BucketEmpty error for top-level listing

This is relevant in the case of non-fs backend like s3, play etc.

* Used ToGoError() to get Error interface from *probe.Error
2016-05-22 23:04:26 -07:00
Krishnan Parthasarathi b48371e971 Create only one custom transport for all S3 clients (#1722)
* Create only one custom transport for all S3 clients

Closes #1721

* Moved back to http.DefaultTransport

... because ResponseHeaderTimeout may fail `mc mirror` in slow networks
2016-05-21 02:07:18 -07:00
Anis Elleuch 8b074767db ls: list objects inside a directory when this latter is passed without a trailing separator (#1724) 2016-05-20 16:43:06 -07:00
Krishnan Parthasarathi e5bc26c75a Removed setting of http.Client Timeout for mc (#1720)
* Removed setting of http.Client Timeout for mc

Fixes #1719

* Moved mcDefaultTransport closer to use

* Set ResponseHeaderTimeout to 3 secs

* Vendored in changes from github.com/minio/minio-go

* Fixed CI build errors due to API changes, post vendoring

* Fixed unit tests w.r.t the change from insecure to secure in minio.NewV{2,4} API
2016-05-20 00:35:49 -07:00
Harshavardhana 959fa74ca5 profile: Add MC_PROFILER env supporting cpu, mem, block profiling. (#1714)
All profiled outputs are written inside `~/.mc/profile`
2016-05-10 19:10:59 -07:00
Krishna Srinivas ac57970229 Merge pull request #1711 from harshavardhana/signals
session: Signal trap shouldn't panic, close the Notify handler.
2016-05-10 12:39:42 +05:30
Harshavardhana 9fb8cfc1b3 session: Signal trap shouldn't panic, close the Notify handler.
Avoid executing Notify handler again when two SIGINTS are
received which can occur when 'mc' is busy copying a
largefile.

Fixes #1710
2016-05-10 00:05:18 -07:00
Harshavardhana 06ad6c53f7 debug: Tracing should print success response for PUT/POST ops. (#1708)
Due to a golang bug need to add specific code to handle this
properly when the response body has ContentLength of '0'

Ref for more info : https://github.com/golang/go/issues/13942.
2016-05-07 01:11:09 -07:00
Anis Elleuch a9b0b14149 Increase update url fetching timeout to 3 seconds (#1704) 2016-04-28 16:03:09 -07:00
Krishna Srinivas 9a454e714d Merge pull request #1702 from harshavardhana/mirror
mirror/cp: Skip NoSuckKey, NoSuchBucket errors properly in cp/mirror.
2016-04-28 14:40:01 +05:30
Harshavardhana 319b3d8434 mirror/cp: Skip NoSuckKey, NoSuchBucket errors properly in cp/mirror.
Fixes #1693
2016-04-27 20:37:42 -07:00
Harshavardhana 2fec2b4107 session: Close session only if fields have changed. (#1701)
Fixes #1700
2016-04-27 20:10:40 -07:00
Harshavardhana 382aa26859 vendorize: New changes in minio-go. (#1699)
- Fixes listing bug with done channel.
- Fixes retry go-routine leak.
- Adds more to the list of network errors to retry safely.
2016-04-25 01:20:15 -07:00
Anand Babu (AB) Periasamy d7854b6dfa Merge pull request #1698 from harshavardhana/access-msg
access: Change set access perm message.
2016-04-24 00:40:19 -07:00
Harshavardhana e3b6c12925 access: Change set access perm message. 2016-04-24 00:33:39 -07:00
Anand Babu (AB) Periasamy d9224348ce Merge pull request #1697 from harshavardhana/access-docs
access: update docs.
2016-04-23 16:23:44 -07:00
Harshavardhana 6b91c6f430 access: update docs. 2016-04-23 15:15:20 -07:00
Aaron Walker 7e9b96e354 cp/mirror use CopyObject API to enable server side copy (#1686)
Add Copy to s3 and fs methods/enable server side copy
2016-04-23 15:14:31 -07:00
Anand Babu (AB) Periasamy 8a8d4619de Merge pull request #1695 from harshavardhana/ignore
fs: Ignore file in recursive as well.
2016-04-22 01:31:01 -07:00
Harshavardhana 3af0902f28 fs: Ignore file in recursive as well. 2016-04-22 01:23:23 -07:00
Anand Babu (AB) Periasamy 6b4c1a4239 Merge pull request #1694 from harshavardhana/ls
ls: ls should ignore error BucketNameEmpty.
2016-04-21 18:15:12 -07:00
Harshavardhana 783d29794a ls: ls should ignore error BucketNameEmpty.
This is a valid case of 'ls', without this change.

```
$ mc ls localhost
mc: <ERROR> Unable to stat ‘localhost’. Bucket name cannot be empty.
```

What we need to ideally see is if server is not available is
```
$ mc ls localhost
mc: <ERROR> Unable to list folder. Get http://localhost:9000/: dial tcp [::1]:9000: getsockopt: connection refused
```
2016-04-21 17:10:16 -07:00
Anand Babu (AB) Periasamy a094c50f5a Merge pull request #1692 from harshavardhana/is-valid
config: Relax valid access and secret keys.
2016-04-19 18:27:44 -07:00
Harshavardhana 621e8cf0ff config: Relax valid access and secret keys.
Deviating from AWS Standards to support non
AWS Standard keys for Ceph and Exoscale probably
others.

Fixes #1690
2016-04-19 14:52:33 -07:00
Anand Babu (AB) Periasamy 4bd9336139 Merge pull request #1691 from harshavardhana/vendor
vendor: Vendorize minio-go
2016-04-19 02:47:13 -07:00
Harshavardhana c517833663 vendor: Vendorize minio-go
- Bucket policy fixes by Karthik Rao.
- China region fixes.
- Fixes a concurrent crash in Signature V2 code by Anis Elleuch.
2016-04-18 23:15:56 -07:00
Anand Babu (AB) Periasamy 8e4cc8df00 Merge pull request #1687 from harshavardhana/mirror-remove
mirror: Implement '--remove' feature.
2016-04-18 18:29:18 -07:00
Anis Elleuch 94f4c4cd2d Avoid removing session v7 json files by migrateSessionV5ToV6 (#2) 2016-04-18 17:47:39 -07:00
Harshavardhana c4c99999bc session: Add isRemoved() for session to avoid removing last removed files again. 2016-04-18 13:56:14 -07:00
Anis Elleuch 6abd3a4ed6 Avoid a possible crash when an error occurs while removing a file (#1) 2016-04-18 11:41:56 -07:00
Harshavardhana 9e94120d68 mirror: Implement '--remove' feature.
Fixes #1628
2016-04-17 12:21:43 -07:00
Anis Elleuch ba088b8fc0 Move ioutils pkg from minio to mc and fix a sorting list bug (#1688)
* Move ioutils pkg from minio to mc

* Fix an important bug in sorting fs list in recursive mode
2016-04-17 12:20:48 -07:00
Anis Elleuch 98ac1817cb Rewrite diff code (#1681) 2016-04-17 01:18:30 -07:00
Anand Babu (AB) Periasamy 65a31e34c9 check if sources exist (#1685) 2016-04-15 16:59:38 -07:00
Krishna Srinivas 264f1ef992 Merge pull request #1684 from harshavardhana/zip
release: Remove zip, tar.gz release builds.
2016-04-14 13:42:32 +05:30
Harshavardhana b30bbc0e74 release: Remove zip, tar.gz release builds. 2016-04-13 23:48:58 -07:00
Krishna Srinivas 7a77686878 Merge pull request #1680 from harshavardhana/gofmt
url: isURLPrefixExists() should use non-recursive mechanism.
2016-04-12 12:24:04 +05:30
Harshavardhana 0c4200306b url: isURLPrefixExists() should use non-recursive mechanism.
The reason is to avoid generating recursive requests while
we are only concerned about the top level prefix that if
it exists.
2016-04-11 20:44:36 -07:00
Harshavardhana 619b1b4e2a url: There is no reason to split '?' delimiter. (#1679)
The reasoning is that we are not providing query
params through 'mc' and we don't need to handle it
specially. Since all paths are absolute with only
delimiter of '/' all other characters should be allowed
including '?'.

For this same reason now newURL is called newClientURL.

Fixes #1677
2016-04-11 18:20:56 -07:00
Sreeram Boyapati 57d22664f4 config: validate config.json file (#1676)
- Minio Client validates only config host add parameters
    Not the config file. Use the same utils to validate config file

    if HostURL is wrong.
        /storage?googleapis?com for host /storage?googleapis?com is not valid. Could not parse it

    if API is wrong.
        S3v2iasdasd API for host https://www.google.com is not Valid. It is not part of any of the following APIs:
        1. S3v4
        2. S3v2

    If the version is wrong.
        Config version 9 does not match GlobalMCConfiguration 8.

    Example:

    mc: <ERROR> Config version 9 does not match GlobalMCConfiguration 8.

    S3v2asda API for host httpsasdkasd is not Valid. It is not part of any of the following APIs:
    1. S3v4
    2. S3v2

    URL httpsasdkasd for host httpsasdkasd is not valid. Could not parse it.
2016-04-10 21:28:17 -07:00
Anis Elleuch 38339b7cd9 Allow question mark in fs file names (#1678) 2016-04-10 15:28:03 -07:00
Anand Babu (AB) Periasamy d5cb19aeab allow caseless API signature in config (#1675) 2016-04-09 13:24:03 -07:00
karthic rao 3d04e56228 vendor: vendor updates for minio-go 2016-04-07 10:08:09 -07:00
Harshavardhana 3e8f7684f2 build: cmd/vet is deprecated fix the url. 2016-04-06 20:07:57 -07:00
Anand Babu (AB) Periasamy c11527780a implement OS specific file ignore list 2016-04-06 15:44:23 -07:00
Sreeram Boyapati 5a204741b9 config: intialize loadMcConfig later in the app
Go caches the McConfig earlier leading to having no effect on changing config-dir during initialization.
2016-04-05 14:33:34 -07:00
Krishna Srinivas b23e8a77fc Merge pull request #1665 from harshavardhana/mirror-fake
mirror: More fixes for quiet mode, make sure fake is honored.
2016-04-05 13:10:59 +05:30
Harshavardhana e926266c62 mirror: More fixes for quiet mode, make sure fake is honored. 2016-04-04 17:25:15 -07:00
Harshavardhana 1eca4f8c0d mirror: Make sure isFake is set to false properly. 2016-04-04 15:35:25 -07:00
Harshavardhana edb1824006 mc: Simplify, conditional checks across codebase. 2016-04-04 14:58:36 -07:00
Anis Elleuch 6666262e51 Make --json and --quiet work as expected with mc mirror cmd 2016-04-04 11:42:46 -07:00
Harshavardhana 221ee6c26b Merge pull request #1660 from vadmeste/fix_mirror_crash
Fix a crash when --fake is coupled with --quiet in mirror cmd
2016-04-02 10:55:47 -07:00
Anis ELLEUCH d3d4afd223 Fix a crash when --fake is coupled with --quiet in mirror cmd 2016-04-02 15:10:53 +01:00
Krishna Srinivas f55f64b5b9 Merge pull request #1659 from harshavardhana/version
mc: Fix Golang version handling.
2016-04-02 15:28:21 +05:30
Harshavardhana 69fbb9a87d mc: Fix Golang version handling.
Migrate to a better go-version package to handle
version numbers.  Default to 'go1.6' as minimum.
2016-04-02 02:51:27 -07:00
Harshavardhana 8e50e8e8c3 Merge pull request #1657 from vadmeste/fix_realpath_behavior
realpath() alternative implementation doesn't really work under linux and freebsd, use a simpler and more portable method
2016-04-01 13:27:14 -07:00
Anis Elleuch 8cdf71b539 realpath() doesn't really work under linux and freebsd, use a simpler and more portable method 2016-04-01 19:21:01 +01:00
Harshavardhana e7f4b63212 docs: Update readme.md with new links. 2016-03-31 17:53:35 -07:00
Anand Babu (AB) Periasamy 12adf3be32 Merge pull request #1656 from harshavardhana/rel-bz
release: Release binaries will have now .tar.gz and .zip extension.
2016-03-31 17:12:16 -07:00
Harshavardhana 087516a783 release: Release binaries will have now .tar.gz and .zip extension.
The reasoning behind is to preserve permissions of binaries.
2016-03-31 17:04:45 -07:00
Anand Babu (AB) Periasamy 1b2a2fc7f9 Merge pull request #1655 from harshavardhana/global
config: Handle aliases migration from v6 --> v7.
2016-03-31 15:42:20 -07:00
Harshavardhana 3e205dba15 config: Handle aliases migration from v6 --> v7.
Fixes #1652
2016-03-31 15:23:55 -07:00
Anand Babu (AB) Periasamy ff874575e1 Merge pull request #1654 from harshavardhana/object-name
stat: Print proper error messages when bucket name is empty.
2016-03-31 15:22:48 -07:00
Harshavardhana 1e1516c968 stat: Print proper error messages when bucket name is empty.
Handle cases for situations for all commands where target bucket
name is not specified, indicate proper errors in this situation.

Fixes #1629
2016-03-30 18:46:20 -07:00
Harshavardhana aeb6de996c Merge pull request #1653 from krishnasrinivas/timeout-8-minute
ListObjects on a prefix with 10 million entries takes around 8 minutes.
2016-03-30 01:44:58 -07:00
Krishna Srinivas 82d87111fc vendor: vendor update minio-go. Increase http client timeout to 8 minutes. 2016-03-30 14:07:24 +05:30
Anand Babu (AB) Periasamy 49953d53ed Merge pull request #1622 from vadmeste/retrieve_secret_from_env
Retrieve secretKey from the environment first
2016-03-28 12:59:45 -07:00
Anis Elleuch 13a4133da5 Retrieve acessKey/secretKey from the environment first 2016-03-28 19:36:13 +01:00
Anand Babu (AB) Periasamy a02ae19de2 Merge pull request #1651 from harshavardhana/buffer
pipe: Avoid double copy of buffers in minio-go
2016-03-27 20:25:33 -07:00
Harshavardhana 9617f22fcd pipe: Avoid double copy of buffers in minio-go
Disallows multiple copies being referenced internally leads
to OOM conditions on certain low memory devices and systems.

Fixes #1641
2016-03-27 20:08:57 -07:00
Anand Babu (AB) Periasamy e156d62e44 Merge pull request #1640 from harshavardhana/mc-access
access: Access policy command implemented.
2016-03-27 19:55:40 -07:00
Harshavardhana f4e8352f5a access: Access policy command implemented.
This patch implements as decided..

To set a bucket policy.
```
mc access readonly s3/<bucket>
mc access readwrite s3/<bucket>
mc access writeonly s3/<bucket>
mc access none s3/<bucket>
```

To get a bucket policy.
```
mc access s3/<bucket>
```
2016-03-27 19:49:54 -07:00
Harshavardhana deb7f72be2 Merge pull request #1650 from sreeram-boyapati/config_tests
tests: add tests for 'mc cat' and 'mc config host'
2016-03-27 10:12:58 -07:00
Sreeram Boyapati a5a57fa2be tests: add tests for 'mc cat' and 'mc config host' 2016-03-27 21:06:40 +05:30
Harshavardhana c3fb1d52f4 Update README.md 2016-03-23 13:09:45 -07:00
Harshavardhana 9820dce775 config: mcConfigVersion should be '8' 2016-03-22 02:42:31 -07:00
Anand Babu (AB) Periasamy 426df2c9ab Merge pull request #1645 from harshavardhana/config-v8
config: Migrate to new version of config '8'
2016-03-22 02:37:36 -07:00
Harshavardhana 20c7a00af5 config: Migrate to new version of config '8'
This config migration was done to the fact that
play.minio.io:9000 anonymous access has been
removed but instead access keys, while server is
public will not honor anonymous requests anymore.
2016-03-21 15:27:31 -07:00
Anand Babu (AB) Periasamy 00d0f1e9d9 Merge pull request #1644 from harshavardhana/fake-rm
rm: treat --fake option properly and list what its going to do.
2016-03-20 15:42:16 -07:00
Harshavardhana 4cecac4ea4 rm: treat --fake option properly and list what its going to do.
Fixes #1643
2016-03-20 14:43:25 -07:00
Harshavardhana b0e2bde84d Merge pull request #1636 from harshavardhana/vendorize
vendor: Vendorize with new changes to minio-go
2016-03-14 19:03:42 -07:00
Harshavardhana 49851c8795 vendor: Vendorize with new changes to minio-go 2016-03-13 03:22:39 -07:00
Harshavardhana 7bdb39c743 Merge pull request #1635 from hackintoshrao/progress-bar-fix
progress bar: Fixing progress on occurance of non-critical error
2016-03-10 19:35:16 -08:00
Karthic Rao 09495582c4 Adding Get() method to check on currentValue instead of totalFileSize
Adding vendor changes from minio-go and pb, aslo adding minio-go/retry.go changes to solve the race condition
2016-03-11 07:06:24 +05:30
Anand Babu (AB) Periasamy f15be9582a Merge pull request #1634 from harshavardhana/delete-option
diff: Implement url difference with time.
2016-03-10 16:10:34 -08:00
Harshavardhana c022107515 diff: Implement url difference with time.
Also make a 'differType' - fixes #1632
2016-03-09 22:11:07 -08:00
Harshavardhana 373b593c3e Merge pull request #1630 from harshavardhana/fake-option
mirror: Implement --fake option.
2016-03-05 13:20:36 -08:00
Harshavardhana ca06c0e09f Merge pull request #1631 from harshavardhana/difference-factory
diff/mirror: Factory function now refactored to reply function only idiomatic style.
2016-03-05 13:19:36 -08:00
Harshavardhana bd1086c244 diff/mirror: Factory function now refactored to reply function only idiomatic style.
Refactor the current code into more idiomatic style and use
consistent variable names.

ref #1628
2016-03-04 19:52:32 -08:00
Harshavardhana 69c8bf7959 mirror: Implement --fake option.
This option helps users verify what operation 'mirror'
is going to perform without it. It also allows for scripts
to validate what files will be copied etc.

- #1628
2016-03-04 19:14:56 -08:00
Harshavardhana db6b4f1344 Merge pull request #1625 from harshavardhana/bucket-list
ls: Fix bucket date.
2016-02-29 08:42:30 -08:00
Krishna Srinivas 05db6e3981 Merge pull request #1624 from harshavardhana/session-old
session: Remove session backup file if any.
2016-02-29 16:18:03 +05:30
Harshavardhana 2623eeb82e session: Remove session backup file if any.
Fixes #1623
2016-02-29 02:06:25 -08:00
Harshavardhana cbebadc16a ls: Fix bucket date.
While listing buckets 'mc ls s3/bucket' would list the
date incorrectly. Populate it properly from 'ListBuckets()'
2016-02-29 02:00:23 -08:00
Harshavardhana 614d6d81e5 Merge pull request #1620 from vadmeste/make_builder_freebsd_support
Add needed changes to make mc buildable using make under FreeBSD
2016-02-24 12:55:46 -08:00
Anis Elleuch cac451c83e Add needed changes to make mc buildable using make under FreeBSD 2016-02-24 20:54:34 +01:00
Harshavardhana 54a86c69e1 Merge pull request #1618 from harshavardhana/windows
windows: Add progress bar windows fixes.
2016-02-19 15:53:00 -08:00
Harshavardhana ea8f5c0f33 windows: Add progress bar windows fixes. 2016-02-19 15:40:38 -08:00
Harshavardhana 340d576931 Merge pull request #1617 from minio/harshavardhana-patch-1
Update README.md
2016-02-18 20:48:27 -08:00
Harshavardhana 7db8820042 Update README.md 2016-02-18 20:43:41 -08:00
Harshavardhana 54761b22fd Merge pull request #1616 from harshavardhana/tag1
update: Change update tag to verify RELEASE instead of OFFICIAL
2016-02-18 20:05:18 -08:00
Harshavardhana 253f13640c update: Change update tag to verify RELEASE instead of OFFICIAL 2016-02-18 20:01:38 -08:00
Harshavardhana 97110c9676 Merge pull request #1615 from harshavardhana/build
build: Check for gopath and multiple source build locations.
2016-02-18 19:14:40 -08:00
Harshavardhana 9805c4d907 build: Check for gopath and multiple source build locations. 2016-02-18 18:26:47 -08:00
Anand Babu (AB) Periasamy 56d548ad10 Merge pull request #1614 from harshavardhana/fix-shadowing
build/vet: Fix all the shadowed variables.
2016-02-19 07:32:10 +05:30
Harshavardhana c196f6ee08 build/vet: Fix all the shadowed variables. 2016-02-18 17:04:45 -08:00
Harshavardhana db55841e7d Merge pull request #1613 from harshavardhana/go-1.6
build: Default to Golang 1.6
2016-02-18 16:23:24 -08:00
Harshavardhana fb70ef7b1c build: Default to Golang 1.6 2016-02-18 16:08:07 -08:00
Harshavardhana fa82223c50 Merge pull request #1612 from harshavardhana/config-folder
config: Config folder option should be honored.
2016-02-17 16:04:21 -08:00
Harshavardhana 6f3cd87993 config: Config folder option should be honored.
The fix is to load config factory once again, to avoid looking for stale
scoped global variables. For example ``mcCustomConfigDir``

Fixes #1611
2016-02-17 15:59:55 -08:00
Anand Babu (AB) Periasamy 3ca7ac613d Merge pull request #1609 from harshavardhana/fs-s3
fs/s3: move the code for fs and s3 out to the top-level.
2016-02-17 05:53:27 +05:30
Harshavardhana fe5b2f97e3 fs/s3: move the code for fs and s3 out to the top-level.
Now the interface moves to the top level - fixes #1604
2016-02-16 11:27:42 -08:00
Harshavardhana 220bf92a3c Merge pull request #1606 from harshavardhana/solaris
porting: mc now properly works on solaris.
2016-02-15 20:11:35 -08:00
Super-User 5219fd59e8 porting: mc now properly works on solaris.
Fixes #1603
2016-02-15 15:03:40 -08:00
Anand Babu (AB) Periasamy 4832da5cda Merge pull request #1602 from harshavardhana/make-release
build: Now builds for all platforms and builds into 'release/experimental' directory.
2016-02-09 14:22:24 -08:00
Harshavardhana 4ef3dcffc4 build: Now builds for all platforms and builds into 'release/experimental' directory.
Two Makefile options are

- make release
- make experimental

Currently supported OS and arch -

- linux/386
- linux/amd64
- linux/arm
- windows/386
- windows/amd64
- darwin/amd64
2016-02-09 14:18:35 -08:00
Harshavardhana fbe4768658 Merge pull request #1601 from harshavardhana/request-params
mc: update to new changes in minio-go.
2016-02-07 18:09:13 -08:00
Harshavardhana f63de3cc30 mc: update to new changes in minio-go. 2016-02-07 18:03:32 -08:00
Anand Babu (AB) Periasamy 7c7d9e07a2 Merge pull request #1600 from harshavardhana/use-mime
mc: Remove contentdb and use golang pkg/mime instead.
2016-02-06 16:15:51 -08:00
Harshavardhana 708f1e17f4 mc: Remove contentdb and use golang pkg/mime instead.
This is also because golang package sets proper 'charset's
for contentTypes. Also there is no reason for 'mc' to have
its own mimedb.
2016-02-06 10:43:57 -08:00
Krishna Srinivas 8fc48cf24a Merge pull request #1599 from harshavardhana/vendorize
minio-go: Vendorize with new changes.
2016-02-06 13:21:52 +05:30
Harshavardhana 1dea194699 minio-go: Vendorize with new changes. 2016-02-05 23:10:09 -08:00
Krishna Srinivas 4569e519c5 Merge pull request #1598 from harshavardhana/query
rm: List wouldn't progress for files with special characters.
2016-02-02 15:17:04 +05:30
Harshavardhana 0236dcf780 rm: List wouldn't progress for files with special characters.
This patch addresses this problem - fixes #1591
2016-02-02 01:28:04 -08:00
Krishna Srinivas 5e5ad3367d Merge pull request #1597 from harshavardhana/progress-bar
progressBar: Finish progress bar if total is greater than 0
2016-02-02 14:54:59 +05:30
Harshavardhana 744b4728d1 progressBar: Finish progress bar if total is greater than 0
In case of 'mc mirror' => mc prints an erroneous progress bar
with 0bytes.

```
mc mirror /usr/local/Cellar/go/1.5.3/libexec play/test123/libexec
0 B / ?  ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░▓  0.00 % 0
```

This patch fixes #1592
2016-02-01 13:36:23 -08:00
Anand Babu (AB) Periasamy f811b029b1 Merge pull request #1595 from harshavardhana/path-url
url: Error out if the aliased URL has host entry.
2016-02-01 11:44:10 +01:00
Harshavardhana 8b77f918b3 url: Error out if the aliased URL has host entry.
```
mc ls http://localhost:9000/
```

ends up listing `mc ls /`, This is confusing and should be
treated as an error, allow only aliased operations.
2016-02-01 02:41:04 -08:00
Anand Babu (AB) Periasamy c5453d1528 Merge pull request #1590 from harshavardhana/url
urlAlias: Handle forward slashes on windows.
2016-01-27 23:21:48 -08:00
Harshavardhana fc668edadf urlAlias: Handle forward slashes on windows.
On windows
```
> mc ls s3/ --> Fails
```

Since most of our examples talk about '/', we should handle
this cleanly for windows.
2016-01-27 14:34:12 -08:00
Anand Babu (AB) Periasamy 01b0928989 Merge pull request #1588 from harshavardhana/handle-paths
cp/mirror: Handle path constructions properly across operating systems.
2016-01-26 18:27:13 -08:00
Harshavardhana 0a4fce57cf cp/mirror: Handle path constructions properly across operating systems.
```
mc cp -r localhost\testbucket\bin C:\destination
```

Following syntax is supposed to copy only 'bin' inside C:\destination.
Due to url construction issues this leads to 'testbucket' instead being
copied as the top level directory.

With this fix the url construction becomes more cross platform friendly.
2016-01-26 18:21:34 -08:00
Anand Babu (AB) Periasamy 257321c425 Merge pull request #1587 from harshavardhana/fix-listing-order
ls: Make recursive and non-recursive behave the same way
2016-01-26 18:16:27 -08:00
Harshavardhana 3b5dcd478a ls: Make recursive and non-recursive behave the same way
Outputs for recursive today

```
$ mc ls -r /tmp/value/
[2016-01-25 12:27:01 PST]    52B test.go
[2016-01-26 11:36:22 PST] 4.2KiB test.txt
[2016-01-26 11:45:22 PST]   102B test/
[2016-01-26 11:45:22 PST] 4.2KiB test/README.md
```

and Outputs for non recursive today differ lexically.

```
$ mc ls  /tmp/value/
[2016-01-26 11:45:22 PST]   102B test/
[2016-01-25 12:27:01 PST]    52B test.go
[2016-01-26 11:36:22 PST] 4.2KiB test.txt
```

To fix this issue we need to capture the ending '/' as
well part of the names while sorting the output. This
patch addresses this problem.
2016-01-26 18:11:24 -08:00
Anand Babu (AB) Periasamy 5c52a0adae Merge pull request #1586 from harshavardhana/ls-truncate
ls: On windows truncate the directory prefixes properly.
2016-01-26 00:29:19 -08:00
Harshavardhana d572648261 ls: On windows truncate the directory prefixes properly.
Fixes #1585
2016-01-25 21:34:16 -08:00
Anand Babu (AB) Periasamy 85e8b542de Merge pull request #1583 from harshavardhana/make-bucket
re-vendorize minio-go with new URL handling changes
2016-01-25 16:55:45 -08:00
Harshavardhana 3a3dbb2722 minio-go: vendorize to new libs.
Fixes - #1579
2016-01-25 16:39:24 -08:00
Krishna Srinivas 47cd83c71c Merge pull request #1582 from harshavardhana/add-missing
update: Add missing '/' from update url.
2016-01-25 23:19:04 +05:30
Harshavardhana 700f261b86 update: Add missing '/' from update url.
Fixes #1581
2016-01-25 09:39:56 -08:00
Anand Babu (AB) Periasamy 3f3adb1858 Merge pull request #1580 from harshavardhana/re-vendorize
mc: Vendorize to new changes.
2016-01-25 01:04:34 -08:00
Harshavardhana 9a40a67410 mc: Vendorize to new changes.
- Fix 0byte file uploads to be not uploaded as multipart.
- Fix bucket requests to have a '/' at the end
  for path style - fixes #1579
- Handle progress bar, if pb.Total is '0'.
2016-01-25 01:00:47 -08:00
Anand Babu (AB) Periasamy cfac37f53b Merge pull request #1544 from harshavardhana/merge-vendorize
mc: Vendorize to new API changes.
2016-01-23 23:57:59 -08:00
Harshavardhana a769ce6439 mc: Vendorize to new API changes.
This vendorization uses the new set of API changes which
we are brought in.

With this new change Bucket regions are handled transparently
without any region lookup or local map. This makes overall code
seamless and easy to use.

Fixes - #1541 (cp corruption while uploading large files to s3)
Fixes - #1542 (cp checkCopySyntax failed)
Fixes - #1537 (regions will be handled seamelessly now for all buckets)
Fixes - #1538 (fixes access control policy for google cloud storage)
Fixes - #1547 (session resume completes without copying all the files)
Fixes - #1559 (poor network connectivity, causes timing out)
2016-01-23 23:53:27 -08:00
Harshavardhana 951067295e Merge pull request #1575 from fwessels/master
Added alias argument for adding host with config
2016-01-18 08:58:33 -08:00
frankw bd97054b93 Added alias argument for adding host with config 2016-01-18 14:02:34 +01:00
Harshavardhana 796d36083d Merge pull request #1573 from vadmeste/did_you_mean
Add Damerau Levenshtein algo to suggest more alternatives to mistyped…
2016-01-13 12:57:19 -08:00
Anis Elleuch acc4b97483 Add Damerau Levenshtein algo to suggest more alternatives to mistyped commmands 2016-01-13 21:32:23 +01:00
Harshavardhana d92a93566b Merge pull request #1572 from vadmeste/host_add_api_optional
Make API argument in config host add cmd optional
2016-01-10 11:18:21 -08:00
Anis Elleuch 244d377f0a Make API argument in config host add cmd optional 2016-01-10 14:47:48 +01:00
Harshavardhana e958557d28 Merge pull request #1571 from vadmeste/fix_error_reporting_issue
Fix ls error msg
2016-01-09 09:52:35 -08:00
Anis Elleuch 3b35f44eba Fix ls error msg 2016-01-09 15:46:52 +01:00
Anand Babu (AB) Periasamy c26c61d3c4 Merge pull request #1570 from harshavardhana/diff-alias
diff/mirror: Handle aliases properly now.
2016-01-08 21:27:11 -08:00
Harshavardhana b347137d88 diff/mirror: Handle aliases properly now. 2016-01-08 21:24:07 -08:00
Anand Babu (AB) Periasamy 99e12696eb Merge pull request #1569 from harshavardhana/rm-all
rm: Fix alias URL handling in rm.
2016-01-08 20:59:17 -08:00
Harshavardhana f01dc5b60c rm: Fix alias URL handling in rm. 2016-01-08 20:51:28 -08:00
Anand Babu (AB) Periasamy 50240b0a1e Merge pull request #1568 from harshavardhana/mirror
mirror/cp: Remove aliases from being printed in json output. - fixes #1563
2016-01-08 19:23:14 -08:00
Harshavardhana 11b286c149 mirror/cp: Remove aliases from being printed in json output. - fixes #1563
Additionally save expanded targetURL also part of session.
2016-01-08 18:44:39 -08:00
Harshavardhana fa87ad6b37 Merge pull request #1566 from vadmeste/subcommands_has_help_flag
Emphasize that subcommands have a help flag
2016-01-08 11:09:26 -08:00
Harshavardhana dd50ad532e Merge pull request #1565 from koolhead17/patch-4
Update README.md
2016-01-08 10:32:09 -08:00
Anis Elleuch 31b07812cb Emphasize that subcommands have a help flag 2016-01-08 19:14:47 +01:00
koolhead17 e59ba922bd Update README.md
minor change with adding "--help" option
2016-01-08 23:38:34 +05:30
Harshavardhana 008a5f00de Merge pull request #1564 from abperiasamy/as60-exit-bug
return non-zero exit code in case of session failure
2016-01-08 10:00:19 -08:00
Anand Babu (AB) Periasamy 8a91ec65ce return non-zero exit code in case of session failure 2016-01-08 09:55:13 -08:00
Harshavardhana 35cdba2204 Merge pull request #1561 from vadmeste/trivial_fixes
Trivial fix of cmd error message, the same for missing dependencies in checkdeps.sh
2016-01-07 15:04:52 -08:00
Anis Elleuch 664f982833 Trivial fix of cmd error message, the same for missing dependencies in checkdeps.sh 2016-01-07 22:49:47 +01:00
Harshavardhana c08ebb25cd Merge pull request #1558 from abperiasamy/cache-client
cache and re-use minio S3 client
2015-12-31 17:22:53 -08:00
Anand Babu (AB) Periasamy f7cdbc2583 cache and re-use minio S3 client 2015-12-31 17:02:08 -08:00
Harshavardhana d47faa3256 Merge pull request #1556 from koolhead17/patch-3
Update INSTALLGO.md
2015-12-29 23:52:36 -08:00
koolhead17 9cd535a6cd Update INSTALLGO.md
minor fix.
2015-12-30 12:14:35 +05:30
Harshavardhana b6fe0d2529 Merge pull request #1555 from abperiasamy/config-v7
new alias style and numerous cleanups.
2015-12-28 15:35:21 -08:00
Anand Babu (AB) Periasamy 0bd1edfd8f new alias style and numerous cleanups. 2015-12-28 15:31:52 -08:00
462 changed files with 62967 additions and 31482 deletions
+12
View File
@@ -0,0 +1,12 @@
## Expected behavior
## Actual behavior
## Steps to reproduce the behavior
## 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
+10 -1
View File
@@ -1,4 +1,13 @@
cover.out
mc
*~
*.test
release
experimental
coverage.txt
*.tar.bz2
parts/
prime/
stage/
mc
.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
+5 -5
View File
@@ -6,10 +6,10 @@
#
# For explanation on this file format: man git-shortlog
Anand Babu (AB) Periasamy <ab@minio.io> Anand Babu (AB) Periasamy <abperiasamy@users.noreply.github.com>
Anand Babu (AB) Periasamy <ab@minio.io> <ab@unlocksmith.org>
Anand Babu (AB) Periasamy <ab@min.io> Anand Babu (AB) Periasamy <abperiasamy@users.noreply.github.com>
Anand Babu (AB) Periasamy <ab@min.io> <ab@unlocksmith.org>
Anis Elleuch <vadmeste@gmail.com>
Frederick F. Kautz IV <fkautz@minio.io> <fkautz@alumni.cmu.edu>
Harshavardhana <harsha@minio.io> <harsha@harshavardhana.net>
Krishna Srinivas <krishna@minio.io> <krishna.srinivas@gmail.com>
Frederick F. Kautz IV <fkautz@min.io> <fkautz@alumni.cmu.edu>
Harshavardhana <harsha@min.io> <harsha@harshavardhana.net>
Krishna Srinivas <krishna@min.io> <krishna.srinivas@gmail.com>
Bosky <bosky@helpshift.com>
-9
View File
@@ -1,9 +0,0 @@
language: go
script:
- make test GOFLAGS="-race"
go:
- 1.5.1
sudo: false
notifications:
slack:
secure: McinxQ4R/Yu2r/U8lVsdAIQ195Rf+3/Ku6DViWyqLHsTt5fTnVrSfbIKs8vy0t2A0bRLO6zv2xOSMWjfiimZLPMgMbMqLtTFEzUzB8RZyx2n2xgmL8q3gjXcLA3vkBreaRYCzJzX6DjvrxRfhyOg+BQHpLpACWik3FS/7VIdDCI=
+11
View File
@@ -0,0 +1,11 @@
## mc (MinIO Client) v/s Midnight Commander (mc)
There has been some amount of [requests](https://github.com/minio/mc/issues?q=is%3Aissue+midnight+commander+is%3Aclosed) on renaming this project to avoid the conflict with Midnight Commander for Unix distributions. We struggled with this, it is harder to find a name sweeter and shorter than `mc` for MinIO Client.
Besides `mc` is a single static binary and can reside inside your application and is fully self contained. Midnight Commander (mc) is a free software clone of Norton Commander (nc). MinIO and Midnight shares no code or ideas. Only their abbreviation matches.
Package managers are free to choose a different name if they like. One such solution [pointed out](https://github.com/minio/mc/issues/873#issuecomment-267583013) by one of our community members.
```
mv ./mc ./mcli
```
+4 -8
View File
@@ -1,6 +1,6 @@
### Setup your mc Github Repository
Fork [mc upstream](https://github.com/minio/mc/fork) source repository to your own personal repository.
```sh
```
$ mkdir -p $GOPATH/src/github.com/minio
$ cd $GOPATH/src/github.com/minio
$ git clone https://github.com/$USER_ID/mc
@@ -20,20 +20,16 @@ $ mc --help
- Push to the branch (git push origin my-new-feature)
- Create new Pull Request
* If you have additional dependencies for ``mc``, ``mc`` manages its depedencies using [govendor](https://github.com/kardianos/govendor)
* If you have additional dependencies for ``mc``, ``mc`` manages its dependencies using `go mod`
- Run `go get foo/bar`
- Edit your code to import foo/bar
- Run `make pkg-add PKG=foo/bar` from top-level folder
* If you have dependencies which needs to be removed from ``mc``
- Edit your code to not import foo/bar
- Run `make pkg-remove PKG=foo/bar` from top-level folder
- Run `GO111MODULE=on go mod tidy` from top-level folder
* When you're ready to create a pull request, be sure to:
- Have test cases for the new code. If you have questions about how to do it, please ask in your pull request.
- Run `go fmt`
- Squash your commits into a single commit. `git rebase -i`. It's okay to force update your pull request.
- Make sure `make build` completes.
- Make sure `make install` completes.
* Read [Effective Go](https://github.com/golang/go/wiki/CodeReviewComments) article from Golang project
- `mc` project is conformant with Golang style
-9
View File
@@ -1,9 +0,0 @@
## Contributors
<!-- DO NOT EDIT - CONTRIBUTORS.md is autogenerated from git commit log by contributors.sh script. -->
- Anand Babu (AB) Periasamy <ab@minio.io>
- Anis Elleuch <vadmeste@gmail.com>
- Bosky <bosky@helpshift.com>
- Frederick F. Kautz IV <fkautz@minio.io>
- Harshavardhana <harsha@minio.io>
- Krishna Srinivas <krishna@minio.io>
+20083
View File
File diff suppressed because it is too large Load Diff
+22
View File
@@ -0,0 +1,22 @@
FROM golang:1.13-alpine as build
LABEL maintainer="MinIO Inc <dev@min.io>"
ENV GOPATH /go
ENV CGO_ENABLED 0
ENV GO111MODULE on
RUN \
apk add --no-cache git && \
git clone https://github.com/minio/mc && cd mc && \
go install -v -ldflags "$(go run buildscripts/gen-ldflags.go)"
FROM alpine:3.12
COPY --from=build /go/bin/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/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"]
+10
View File
@@ -0,0 +1,10 @@
FROM alpine:3.12
MAINTAINER MinIO Inc <dev@min.io>
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"]
-83
View File
@@ -1,83 +0,0 @@
## Ubuntu (Kylin) 14.04
### Build Dependencies
This installation guide is based on Ubuntu 14.04+ on x86-64 platform.
##### Install Git, GCC
```sh
$ sudo apt-get install git build-essential
```
##### Install Go 1.5+
Download Go 1.5+ from [https://golang.org/dl/](https://golang.org/dl/).
```sh
$ wget https://storage.googleapis.com/golang/go1.5.1.linux-amd64.tar.gz
$ mkdir -p ${HOME}/bin/
$ mkdir -p ${HOME}/go/
$ tar -C ${HOME}/bin/ -xzf go1.5.1.linux-amd64.tar.gz
```
##### Setup GOROOT and GOPATH
Add the following exports to your ``~/.bashrc``. Environment variable GOROOT specifies the location of your golang binaries
and GOPATH specifies the location of your project workspace.
```sh
export GOROOT=${HOME}/bin/go
export GOPATH=${HOME}/go
export PATH=$PATH:${HOME}/bin/go/bin:${GOPATH}/bin
```
```sh
$ source ~/.bashrc
```
##### Testing it all
```sh
$ go env
```
## OS X (Yosemite) 10.10
### Build Dependencies
This installation document assumes OS X Yosemite 10.10+ on x86-64 platform.
##### Install brew
```sh
$ ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
```
##### Install Git, Python
```sh
$ brew install git python
```
##### Install Go 1.5+
Install golang binaries using `brew`
```sh
$ brew install go
$ mkdir -p $HOME/go
```
##### Setup GOROOT and GOPATH
Add the following exports to your ``~/.bash_profile``. Environment variable GOROOT specifies the location of your golang binaries
and GOPATH specifies the location of your project workspace.
```sh
export GOPATH=${HOME}/go
export GOVERSION=$(brew list go | head -n 1 | cut -d '/' -f 6)
export GOROOT=$(brew --prefix)/Cellar/go/${GOVERSION}/libexec
export PATH=$PATH:${GOPATH}/bin
```
##### Source the new enviornment
```sh
$ source ~/.bash_profile
```
##### Testing it all
```sh
$ go env
```
+61 -64
View File
@@ -1,84 +1,81 @@
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)'
all: install
VERSION ?= $(shell git describe --tags)
TAG ?= "minio/mc:$(VERSION)"
checkdeps:
@echo "Checking deps:"
all: build
checks:
@echo "Checking dependencies"
@(env bash $(PWD)/buildscripts/checkdeps.sh)
checkgopath:
@echo "Checking if project is at ${GOPATH}"
@for mcpath in $(echo ${GOPATH} | sed 's/:/\n/g'); do if [ ! -d ${mcpath}/src/github.com/minio/mc ]; then echo "Project not found in ${mcpath}, please follow instructions provided at https://github.com/minio/minio/blob/master/CONTRIBUTING.md#setup-your-minio-github-repository" && exit 1; fi done
@echo "BUILD_LDFLAGS: ${BUILD_LDFLAGS}"
getdeps:
@mkdir -p ${GOPATH}/bin
@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)
getdeps: checkdeps checkgopath
@go get github.com/golang/lint/golint && echo "Installed golint:"
@go get golang.org/x/tools/cmd/vet && echo "Installed vet:"
@go get github.com/fzipp/gocyclo && echo "Installed gocyclo:"
@go get github.com/remyoudompheng/go-misc/deadcode && echo "Installed deadcode:"
crosscompile:
@(env bash $(PWD)/buildscripts/cross-compile.sh)
# verifiers: getdeps vet fmt lint cyclo deadcode
verifiers: getdeps vet fmt lint cyclo deadcode
verifiers: getdeps vet fmt lint
docker: build
@docker build -t $(TAG) . -f Dockerfile.dev
vet:
@echo "Running $@:"
@GO15VENDOREXPERIMENT=1 go tool vet -all *.go
@GO15VENDOREXPERIMENT=1 go tool vet -all ./pkg
@GO15VENDOREXPERIMENT=1 go tool vet -shadow=true *.go
@GO15VENDOREXPERIMENT=1 go tool vet -shadow=true ./pkg
@echo "Running $@"
@GO111MODULE=on go vet github.com/minio/mc/...
fmt:
@echo "Running $@:"
@GO15VENDOREXPERIMENT=1 gofmt -s -l *.go
@GO15VENDOREXPERIMENT=1 gofmt -s -l pkg
@echo "Running $@"
@GO111MODULE=on gofmt -d cmd/
@GO111MODULE=on gofmt -d pkg/
lint:
@echo "Running $@:"
@GO15VENDOREXPERIMENT=1 golint .
@GO15VENDOREXPERIMENT=1 golint github.com/minio/mc/pkg...
@echo "Running $@ check"
@GO111MODULE=on ${GOPATH}/bin/golangci-lint cache clean
@GO111MODULE=on ${GOPATH}/bin/golangci-lint run --timeout=5m --config ./.golangci.yml
cyclo:
@echo "Running $@:"
@GO15VENDOREXPERIMENT=1 gocyclo -over 40 .
# Builds mc, runs the verifiers then runs the tests.
check: test
test: verifiers build
@echo "Running unit tests"
@GO111MODULE=on CGO_ENABLED=0 go test -tags kqueue ./... 1>/dev/null
@echo "Running functional tests"
@(env bash $(PWD)/functional-tests.sh)
deadcode:
@echo "Running $@:"
@GO15VENDOREXPERIMENT=1 deadcode
test-race: verifiers build
@echo "Running unit tests under -race"
@GO111MODULE=on go test -race -v --timeout 20m ./... 1>/dev/null
build: verifiers
@echo "Installing mc:"
# 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)
test: verifiers
@echo "Running all testing:"
@GO15VENDOREXPERIMENT=1 go test $(GOFLAGS) ./
@GO15VENDOREXPERIMENT=1 go test $(GOFLAGS) github.com/minio/mc/pkg...
# Builds mc locally.
build: checks
@echo "Building mc binary to './mc'"
@GO111MODULE=on CGO_ENABLED=0 go build -trimpath -tags kqueue --ldflags $(BUILD_LDFLAGS) -o $(PWD)/mc
gomake-all: build
@GO15VENDOREXPERIMENT=1 go build --ldflags $(BUILD_LDFLAGS) -o $(GOPATH)/bin/mc
@mkdir -p $(HOME)/.mc
coverage:
@GO15VENDOREXPERIMENT=1 go test -race -coverprofile=cover.out ./
@go tool cover -html=cover.out && echo "Visit your browser"
pkg-add:
@GO15VENDOREXPERIMENT=1 govendor add $(PKG)
pkg-update:
@GO15VENDOREXPERIMENT=1 govendor update $(PKG)
pkg-remove:
@GO15VENDOREXPERIMENT=1 govendor remove $(PKG)
install: gomake-all
all-tests: test
# TODO disable them for now.
#@./tests/test-minio.sh
release:
@./release.sh
# Builds MinIO and installs it to $GOPATH/bin.
install: build
@echo "Installing mc binary to '$(GOPATH)/bin/mc'"
@mkdir -p $(GOPATH)/bin && cp -f $(PWD)/mc $(GOPATH)/bin/mc
@echo "Installation successful. To learn more, try \"mc --help\"."
clean:
@rm -fv cover.out
@rm -fv mc
@echo "Cleaning up all the generated files"
@find . -name '*.test' | xargs rm -fv
@find . -name '*~' | xargs rm -fv
@rm -rvf mc
@rm -rvf build
@rm -rvf release
+4 -4
View File
@@ -1,9 +1,9 @@
Minio Client (C) 2014, 2015 Minio, Inc.
MinIO Client (C) 2014-2020 MinIO, Inc.
This product includes software developed at Minio, Inc.
(https://minio.io/).
This product includes software developed at MinIO, Inc.
(https://min.io/).
The Minio project contains unmodified/modified subcomponents too with
The MinIO project contains unmodified/modified subcomponents too with
separate copyright notices and license terms. Your use of the source
code for the these subcomponents is subject to the terms and conditions
of the following licenses.
+190 -72
View File
@@ -1,106 +1,224 @@
# Minio Client (mc) [![Gitter](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/minio/minio?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
# MinIO Client Quickstart Guide
[![Slack](https://slack.min.io/slack?type=svg)](https://slack.min.io) [![Go Report Card](https://goreportcard.com/badge/minio/mc)](https://goreportcard.com/report/minio/mc) [![Docker Pulls](https://img.shields.io/docker/pulls/minio/mc.svg?maxAge=604800)](https://hub.docker.com/r/minio/mc/)
``mc`` provides minimal tools to work with Amazon S3 compatible cloud storage and filesystems. It has features like resumable uploads/downloads, progress bar, parallel copy. ``mc`` is written in golang and released under [Apache license v2](./LICENSE).
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).
## Commands
``mc`` implements the following commands
```
ls List files and folders.
mb Make a bucket or folder.
cat Display contents of a file.
pipe Write contents of stdin to one or more targets. When no target is specified, it writes to stdout.
share Generate URL for sharing.
cp Copy one or more objects to a target.
mirror Mirror folders recursively from a single source to many destinations.
diff Compute differences between two folders.
rm Remove file or bucket [WARNING: Use with care].
access Manage bucket access permissions.
session Manage saved sessions of cp and mirror operations.
config Manage configuration file.
update Check for a new software update.
version Print version.
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
```
## Install [![Build Status](https://api.travis-ci.org/minio/mc.svg?branch=master)](https://travis-ci.org/minio/mc) [![Build status](https://ci.appveyor.com/api/projects/status/3ng8bef7b3e1v763?svg=true)](https://ci.appveyor.com/project/harshavardhana/mc)
## Docker Container
### Stable
```
docker pull minio/mc
docker run minio/mc ls play
```
#### GNU/Linux
### Edge
```
docker pull minio/mc:edge
docker run minio/mc:edge ls play
```
Download ``mc`` for:
**Note:** Above examples run `mc` against MinIO [_play_ environment](#test-your-setup) by default. To run `mc` against other S3 compatible servers, start the container this way:
- ``64-bit Intel`` from https://dl.minio.io/client/mc/release/linux-amd64/mc
- ``32-bit Intel`` from https://dl.minio.io/client/mc/release/linux-386/mc
- ``32-bit ARM`` from https://dl.minio.io/client/mc/release/linux-arm/mc
```
docker run -it --entrypoint=/bin/sh minio/mc
```
~~~
$ chmod +x mc
$ ./mc help
~~~
then use the [`mc config` command](#add-a-cloud-storage-service).
#### OS X
## macOS
### Homebrew
Install mc packages using [Homebrew](http://brew.sh/)
Download ``mc`` from https://dl.minio.io/client/mc/release/darwin-amd64/mc
```
brew install minio/stable/mc
mc --help
```
~~~
$ chmod 755 mc
$ ./mc help
~~~
## GNU/Linux
### Binary Download
| Platform | Architecture | URL |
| ---------- | -------- |------|
|GNU/Linux|64-bit Intel|https://dl.min.io/client/mc/release/linux-amd64/mc |
||64-bit PPC|https://dl.min.io/client/mc/release/linux-ppc64le/mc |
#### Microsoft Windows
```
wget https://dl.min.io/client/mc/release/linux-amd64/mc
chmod +x mc
./mc --help
```
Download ``mc`` for:
## Microsoft Windows
### Binary Download
| Platform | Architecture | URL |
| ---------- | -------- |------|
|Microsoft Windows|64-bit Intel|https://dl.min.io/client/mc/release/windows-amd64/mc.exe |
- ``64-bit`` from https://dl.minio.io/client/mc/release/windows-amd64/mc.exe
- ``32-bit`` from https://dl.minio.io/client/mc/release/windows-386/mc.exe
```
mc.exe --help
```
~~~
C:\Users\Username\Downloads> mc.exe help
~~~
#### Source
<blockquote>
NOTE: Source installation is intended for only developers and advanced users. ‘mc update’ continous delivery mechanism is not supported for ‘go get’ based binary builds. Please download official releases from https://minio.io/#mc.
</blockquote>
If you do not have a working Golang environment, please follow [Install Golang](./INSTALLGO.md).
## Install from Source
Source installation is only intended for developers and advanced users. If you do not have a working Golang environment, please follow [How to install Golang](https://golang.org/doc/install). Minimum version required is [go1.13](https://golang.org/dl/#stable)
```sh
$ GO15VENDOREXPERIMENT=1 go get -u github.com/minio/mc
GO111MODULE=on go get github.com/minio/mc
```
## Public Minio Server
## Add a Cloud Storage Service
If you are planning to use `mc` only on POSIX compatible filesystems, you may skip this step and proceed to [everyday use](#everyday-use).
Minio cloud storage server is hosted at ``https://play.minio.io:9000`` for public use. This service is primarily intended for developers and users to familiarize themselves with Amazon S3 compatible cloud storage. Minio runs with filesystem backend with auto-expiry for objects in about 24 hours. No account signup is required, which means S3 compatible tools and applications can access this service without access and secret keys.
To add one or more Amazon S3 compatible hosts, please follow the instructions below. `mc` stores all its configuration information in ``~/.mc/config.json`` file.
## Configuring mc for Amazon S3
Get your AccessKeyID and SecretAccessKey by following [AWS Credentials Guide](http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSGettingStartedGuide/AWSCredentials.html).
Once you have them update your ``~/.mc/config.json`` configuration file.
```
$ mc config host add <YOUR-S3-ENDPOINT> <YOUR-ACCESS-KEY> <YOUR-SECRET-KEY> S3v4
mc config host add <ALIAS> <YOUR-S3-ENDPOINT> <YOUR-ACCESS-KEY> <YOUR-SECRET-KEY> --api <API-SIGNATURE> --lookup <BUCKET-LOOKUP-TYPE>
```
Example
Alias is simply a short name to your cloud storage service. S3 end-point, access and secret keys are supplied by your cloud storage provider. API signature is an optional argument. By default, it is set to "S3v4".
Lookup is an optional argument. It is used to indicate whether dns or path style url requests are supported by the server. It accepts "dns", "path" or "auto" as valid values. By default, it is set to "auto" and SDK automatically determines the type of url lookup to use.
### Example - MinIO Cloud Storage
MinIO server displays URL, access and secret keys.
```
$ mc config host add https://s3.amazonaws.com BKIKJAA5BMMU2RHO6IBB V7f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12
mc config host add minio http://192.168.1.51 BKIKJAA5BMMU2RHO6IBB V7f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12
```
NOTE: ``S3v4`` is default if not specified.
### Example - Amazon S3 Cloud Storage
Get your AccessKeyID and SecretAccessKey by following [AWS Credentials Guide](http://docs.aws.amazon.com/general/latest/gr/aws-security-credentials.html).
## Configure mc for Google Cloud Storage
Get your AccessKeyID and SecretAccessKey by following [Google Credentials Guide](https://cloud.google.com/storage/docs/migrating?hl=en#keys).
Once you have them update your ``~/.mc/config.json`` configuration file.
```
$ mc config host add https://storage.googleapis.com <YOUR-ACCESS-KEY> <YOUR-SECRET-KEY> S3v2
mc config host add s3 https://s3.amazonaws.com BKIKJAA5BMMU2RHO6IBB V7f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12
```
NOTE: Google Cloud Storage only supports Legacy Signature Version ``2``, so you have to pick - ``S3v2``
**Note**: As an IAM user on Amazon S3 you need to make sure the user has full access to the buckets or set the following restricted policy for your IAM user
## Contribute to Minio Client
Please follow Minio [Contributor's Guide](./CONTRIBUTING.md)
```json
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "AllowBucketStat",
"Effect": "Allow",
"Action": [
"s3:HeadBucket"
],
"Resource": "*"
},
{
"Sid": "AllowThisBucketOnly",
"Effect": "Allow",
"Action": "s3:*",
"Resource": [
"arn:aws:s3:::<your-restricted-bucket>/*",
"arn:aws:s3:::<your-restricted-bucket>"
]
}
]
}
```
### Jobs
If you think in Lisp or Haskell and hack in go, you would blend right in. Send your github link to callhome@minio.io.
### Example - Google Cloud Storage
Get your AccessKeyID and SecretAccessKey by following [Google Credentials Guide](https://cloud.google.com/storage/docs/migrating?hl=en#keys)
```
mc config host add gcs https://storage.googleapis.com BKIKJAA5BMMU2RHO6IBB V8f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12
```
## Test Your Setup
`mc` is pre-configured with https://play.min.io, aliased as "play". It is a hosted MinIO server for testing and development purpose. To test Amazon S3, simply replace "play" with "s3" or the alias you used at the time of setup.
*Example:*
List all buckets from https://play.min.io
```
mc ls play
[2016-03-22 19:47:48 PDT] 0B my-bucketname/
[2016-03-22 22:01:07 PDT] 0B mytestbucket/
[2016-03-22 20:04:39 PDT] 0B mybucketname/
[2016-01-28 17:23:11 PST] 0B newbucket/
[2016-03-20 09:08:36 PDT] 0B s3git-test/
```
Make a bucket
`mb` command creates a new bucket.
*Example:*
```
mc mb play/mybucket
Bucket created successfully `play/mybucket`.
```
Copy Objects
`cp` command copies data from one or more sources to a target.
*Example:*
```
mc cp myobject.txt play/mybucket
myobject.txt: 14 B / 14 B ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ 100.00 % 41 B/s 0
```
<a name="everyday-use"></a>
## Everyday Use
### Shell aliases
You may add shell aliases to override your common Unix tools.
```
alias ls='mc ls'
alias cp='mc cp'
alias cat='mc cat'
alias mkdir='mc mb'
alias pipe='mc pipe'
alias find='mc find'
```
### Shell autocompletion
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>
admin config diff find ls mirror policy session sql update watch
cat cp event head mb pipe rm share stat version
```
## Explore Further
- [MinIO Client Complete Guide](https://docs.min.io/docs/minio-client-complete-guide)
- [MinIO Quickstart Guide](https://docs.min.io/docs/minio-quickstart-guide)
- [The MinIO documentation website](https://docs.min.io)
## 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)
+173
View File
@@ -0,0 +1,173 @@
# MinIO客户端快速入门指南
[![Slack](https://slack.min.io/slack?type=svg)](https://slack.min.io) [![Go Report Card](https://goreportcard.com/badge/minio/mc)](https://goreportcard.com/report/minio/mc) [![Docker Pulls](https://img.shields.io/docker/pulls/minio/mc.svg?maxAge=604800)](https://hub.docker.com/r/minio/mc/)
MinIO Client (mc)为ls,cat,cp,mirror,diff,find等UNIX命令提供了一种替代方案。它支持文件系统和兼容Amazon S3的云存储服务(AWS Signature v2和v4)。
```
ls 列出文件和文件夹。
mb 创建一个存储桶或一个文件夹。
cat 显示文件和对象内容。
pipe 将一个STDIN重定向到一个对象或者文件或者STDOUT。
share 生成用于共享的URL。
cp 拷贝文件和对象。
mirror 给存储桶和文件夹做镜像。
find 基于参数查找文件。
diff 对两个文件夹或者存储桶比较差异。
rm 删除文件和对象。
events 管理对象通知。
watch 监听文件和对象的事件。
policy 管理访问策略。
session 为cp命令管理保存的会话。
config 管理mc配置文件。
update 检查软件更新。
version 输出版本信息。
```
## Docker容器
### 稳定版
```
docker pull minio/mc
docker run minio/mc ls play
```
### 尝鲜版
```
docker pull minio/mc:edge
docker run minio/mc:edge ls play
```
**注意:** 上述示例默认使用MinIO[演示环境](#test-your-setup)做演示,如果想用`mc`操作其它S3兼容的服务,采用下面的方式来启动容器:
```
docker run -it --entrypoint=/bin/sh minio/mc
```
然后使用[`mc config`命令](#add-a-cloud-storage-service)。
## macOS
### Homebrew
使用[Homebrew](http://brew.sh/)安装mc。
```
brew install minio/stable/mc
mc --help
```
## GNU/Linux
### 下载二进制文件
| 平台 | CPU架构 | URL |
| ---------- | -------- |------|
|GNU/Linux|64-bit Intel|https://dl.min.io/client/mc/release/linux-amd64/mc |
```
chmod +x mc
./mc --help
```
## Microsoft Windows
### 下载二进制文件
| 平台 | CPU架构 | URL |
| ---------- | -------- |------|
|Microsoft Windows|64-bit Intel|https://dl.min.io/client/mc/release/windows-amd64/mc.exe |
```
mc.exe --help
```
## 通过源码安装
通过源码安装仅适用于开发人员和高级用户。`mc update`命令不支持基于源码安装的更新通知。请从https://min.io/download/#minio-client下载官方版本。
如果您没有Golang环境,请参照[如何安装Golang](https://golang.org/doc/install)。
```
go get -d github.com/minio/mc
cd ${GOPATH}/src/github.com/minio/mc
make
```
## 添加一个云存储服务
如果你打算仅在POSIX兼容文件系统中使用`mc`,那你可以直接略过本节,跳到[日常使用](#everyday-use)。
添加一个或多个S3兼容的服务,请参考下面说明。`mc`将所有的配置信息都存储在``~/.mc/config.json``文件中。
```
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"。
### 示例-MinIO云存储
从MinIO服务获得URL、access key和secret key。
```
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 --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 --api s3v2
```
注意:Google云存储只支持旧版签名版本V2,所以你需要选择S3v2。
## 验证
`mc`预先配置了云存储服务URL:https://play.min.io,别名“play”。它是一个用于研发和测试的MinIO服务。如果想测试Amazon S3,你可以将“play”替换为“s3”。
*示例:*
列出https://play.min.io上的所有存储桶。
```
mc ls play
[2016-03-22 19:47:48 PDT] 0B my-bucketname/
[2016-03-22 22:01:07 PDT] 0B mytestbucket/
[2016-03-22 20:04:39 PDT] 0B mybucketname/
[2016-01-28 17:23:11 PST] 0B newbucket/
[2016-03-20 09:08:36 PDT] 0B s3git-test/
```
<a name="everyday-use"></a>
## 日常使用
### Shell别名
你可以添加shell别名来覆盖默认的Unix工具命令。
```
alias ls='mc ls'
alias cp='mc cp'
alias cat='mc cat'
alias mkdir='mc mb'
alias pipe='mc pipe'
alias find='mc find'
```
### Shell自动补全
你也可以下载[`autocomplete/bash_autocomplete`](https://raw.githubusercontent.com/minio/mc/master/autocomplete/bash_autocomplete)到`/etc/bash_completion.d/`,然后将其重命名为`mc`。别忘了在这个文件运行source命令让其在你的当前shell上可用。
```
sudo wget https://raw.githubusercontent.com/minio/mc/master/autocomplete/bash_autocomplete -O /etc/bash_completion.d/mc
source /etc/bash_completion.d/mc
```
```
mc <TAB>
admin config diff ls mirror policy session update watch
cat cp events mb pipe rm share version
```
## 了解更多
- [MinIO Client完全指南](https://docs.min.io/docs/minio-client-complete-guide)
- [MinIO快速入门](https://docs.min.io/docs/minio-quickstart-guide)
- [MinIO官方文档](https://docs.min.io)
## 贡献
请遵守MinIO[贡献者指南](https://github.com/minio/mc/blob/master/docs/zh_CN/CONTRIBUTING.md)
-210
View File
@@ -1,210 +0,0 @@
/*
* Minio Client, (C) 2015 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 main
import (
"encoding/json"
"strings"
"github.com/fatih/color"
"github.com/minio/cli"
"github.com/minio/mc/pkg/console"
"github.com/minio/minio-xl/pkg/probe"
)
var (
accessFlags = []cli.Flag{
cli.BoolFlag{
Name: "help, h",
Usage: "Help of access.",
},
}
)
// Set access permissions.
var accessCmd = cli.Command{
Name: "access",
Usage: "Manage bucket access permissions.",
Action: mainAccess,
Flags: append(accessFlags, globalFlags...),
CustomHelpTemplate: `Name:
mc {{.Name}} - {{.Usage}}
USAGE:
mc {{.Name}} [FLAGS] set PERMISSION TARGET [TARGET...]
mc {{.Name}} [FLAGS] get TARGET [TARGET...]
PERMISSION:
Allowed permissions are: [private, readonly, public, authorized].
FLAGS:
{{range .Flags}}{{.}}
{{end}}
EXAMPLES:
1. Set bucket to "private" on Amazon S3 cloud storage.
$ mc {{.Name}} set private s3.amazonaws.com/burningman2011
2. Set bucket to "public" on Amazon S3 cloud storage.
$ mc {{.Name}} set public s3.amazonaws.com/shared
3. Set bucket to "authenticated" on Amazon S3 cloud storage to provide read access to IAM Authenticated Users group.
$ mc {{.Name}} set authorized s3.amazonaws.com/shared-authenticated
4. Get bucket permissions.
$ mc {{.Name}} get s3.amazonaws.com/shared
5. Get bucket permissions.
$ mc {{.Name}} get storage.googleapis.com/miniocloud
`,
}
// accessMessage is container for access command on bucket success and failure messages.
type accessMessage struct {
Operation string `json:"operation"`
Status string `json:"status"`
Bucket string `json:"bucket"`
Perms accessPerms `json:"permission"`
}
// String colorized access message.
func (s accessMessage) String() string {
if s.Operation == "set" {
return console.Colorize("Access",
"Set access permission ‘"+string(s.Perms)+"’ updated successfully for ‘"+s.Bucket+"’")
}
if s.Operation == "get" {
return console.Colorize("Access",
"Access permission for ‘"+s.Bucket+"’"+" is ‘"+string(s.Perms)+"’")
}
// nothing to print
return ""
}
// JSON jsonified access message.
func (s accessMessage) JSON() string {
accessJSONBytes, err := json.Marshal(s)
fatalIf(probe.NewError(err), "Unable to marshal into JSON.")
return string(accessJSONBytes)
}
// checkAccessSyntax check for incoming syntax.
func checkAccessSyntax(ctx *cli.Context) {
if !ctx.Args().Present() {
cli.ShowCommandHelpAndExit(ctx, "access", 1) // last argument is exit code.
}
if len(ctx.Args()) < 2 {
cli.ShowCommandHelpAndExit(ctx, "access", 1) // last argument is exit code.
}
switch ctx.Args().First() {
case "set":
if len(ctx.Args().Tail()) < 2 {
cli.ShowCommandHelpAndExit(ctx, "access", 1) // last argument is exit code.
}
perms := accessPerms(ctx.Args().Tail().Get(0))
if !perms.isValidAccessPERM() {
fatalIf(errDummy().Trace(),
"Unrecognized permission ‘"+perms.String()+"’. Allowed values are [private, public, readonly, authorized].")
}
for _, arg := range ctx.Args().Tail().Tail() {
if strings.TrimSpace(arg) == "" {
fatalIf(errInvalidArgument().Trace(), "Unable to validate empty argument.")
}
}
case "get":
if len(ctx.Args().Tail()) < 1 {
cli.ShowCommandHelpAndExit(ctx, "access", 1) // last argument is exit code.
}
}
}
// doSetAccess do set access.
func doSetAccess(targetURL string, targetPERMS accessPerms) *probe.Error {
clnt, err := url2Client(targetURL)
if err != nil {
return err.Trace(targetURL)
}
if err = clnt.SetBucketAccess(targetPERMS.String()); err != nil {
return err.Trace(targetURL, targetPERMS.String())
}
return nil
}
// doGetAccess do get access.
func doGetAccess(targetURL string) (perms accessPerms, err *probe.Error) {
clnt, err := url2Client(targetURL)
if err != nil {
return "", err.Trace(targetURL)
}
acl, err := clnt.GetBucketAccess()
if err != nil {
return "", err.Trace(targetURL)
}
return aclToPerms(acl), nil
}
func mainAccess(ctx *cli.Context) {
// Set global flags from context.
setGlobalsFromContext(ctx)
// check 'access' cli arguments.
checkAccessSyntax(ctx)
// Additional command speific theme customization.
console.SetColor("Access", color.New(color.FgGreen, color.Bold))
switch ctx.Args().First() {
case "set":
perms := accessPerms(ctx.Args().Tail().First())
URLs, err := args2URLs(ctx.Args().Tail().Tail())
fatalIf(err.Trace(ctx.Args().Tail().Tail()...), "Unable to convert args 2 URLs.")
for _, targetURL := range URLs {
err := doSetAccess(targetURL, perms)
// Upon error, print and continue.
if err != nil {
errorIf(err.Trace(targetURL, string(perms)),
"Unable to set access permission ‘"+string(perms)+"’ for ‘"+targetURL+"’.")
continue
}
printMsg(accessMessage{
Status: "success",
Operation: "set",
Bucket: targetURL,
Perms: perms,
})
}
case "get":
URLs, err := args2URLs(ctx.Args().Tail())
fatalIf(err.Trace(ctx.Args().Tail()...), "Unable to convert args 2 URLs.")
for _, targetURL := range URLs {
perms, err := doGetAccess(targetURL)
if err != nil {
errorIf(err.Trace(targetURL), "Unable to get access permission for ‘"+targetURL+"’.")
continue
}
printMsg(accessMessage{
Status: "success",
Operation: "get",
Bucket: targetURL,
Perms: perms,
})
}
}
}
-96
View File
@@ -1,96 +0,0 @@
/*
* Minio Client (C) 2015 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 main
// isValidAccessPERM - is provided access perm string supported.
func (b accessPerms) isValidAccessPERM() bool {
switch true {
case b.isPrivate():
fallthrough
case b.isReadOnly():
fallthrough
case b.isPublic():
fallthrough
case b.isAuthorized():
return true
default:
return false
}
}
// accessPerms - access level.
type accessPerms string
// different types of Access perm's currently supported by accesss command.
const (
accessPrivate = accessPerms("private")
accessReadOnly = accessPerms("readonly")
accessPublic = accessPerms("public")
accessAuthorized = accessPerms("authorized")
)
func (b accessPerms) String() string {
if !b.isValidAccessPERM() {
return string(b)
}
if b.isReadOnly() {
return "public-read"
}
if b.isPublic() {
return "public-read-write"
}
if b.isAuthorized() {
return "authenticated-read"
}
return "private"
}
// convert acl's to access perms
func aclToPerms(acl string) accessPerms {
switch acl {
case "private":
return accessPerms("private")
case "public-read":
return accessPerms("readonly")
case "public-read-write":
return accessPerms("public")
case "authenticated-read":
return accessPerms("authorized")
default:
return accessPerms(acl)
}
}
// isPrivate - is acl Private.
func (b accessPerms) isPrivate() bool {
return b == accessPrivate
}
// isPublicRead - is acl PublicRead.
func (b accessPerms) isReadOnly() bool {
return b == accessReadOnly
}
// isPublicReadWrite - is acl PublicReadWrite.
func (b accessPerms) isPublic() bool {
return b == accessPublic
}
// isAuthorized - is acl AuthorizedRead.
func (b accessPerms) isAuthorized() bool {
return b == accessAuthorized
}
-74
View File
@@ -1,74 +0,0 @@
/*
* Minio Client (C) 2015 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 main
import (
"os"
"regexp"
"runtime"
"strings"
"github.com/minio/mc/pkg/client"
"github.com/minio/minio-xl/pkg/probe"
)
// isValidAliasName - Check if aliasName is a valid alias.
func isValidAliasName(aliasName string) bool {
return regexp.MustCompile("^[a-zA-Z][a-zA-Z0-9-]+$").MatchString(aliasName)
}
// normalizeAliasedURL - remove any preceding separators.
func normalizeAliasedURL(aliasedURL string) string {
if runtime.GOOS == "windows" {
aliasedURL = strings.Replace(aliasedURL, "/", "\\", -1)
}
aliasedURL = strings.TrimPrefix(aliasedURL, string(os.PathSeparator))
return aliasedURL
}
// getAliasURL expands aliased (name/path) to full URL, used by url-parser.
func getAliasURL(aliasedURL string) (string, *probe.Error) {
config, err := loadMcConfig()
if err != nil {
return aliasedURL, err.Trace(aliasedURL)
}
if strings.HasPrefix(aliasedURL, "https") || strings.HasPrefix(aliasedURL, "http") {
return aliasedURL, nil
}
for hostURL := range config.Hosts {
url := client.NewURL(hostURL)
if strings.Contains(aliasedURL, url.Host) {
return url.Scheme + url.SchemeSeparator + aliasedURL, nil
}
}
normalizedAliasURL := normalizeAliasedURL(aliasedURL)
for aliasName, aliasValue := range config.Aliases {
if strings.HasPrefix(normalizedAliasURL, aliasName) {
// Match found. Expand it.
if !strings.Contains(normalizedAliasURL, string(os.PathSeparator)) {
return aliasValue, nil
}
splits := strings.SplitN(normalizedAliasURL, string(os.PathSeparator), 2)
if len(splits) == 1 {
return aliasedURL, nil // Not an aliased URL. Return as is.
}
// Matched, but path needs to be joined.
return urlJoinPath(aliasValue, splits[1]), nil
}
}
return aliasedURL, nil // No matching alias found. Return as is.
}
-168
View File
@@ -1,168 +0,0 @@
/*
* Minio Client (C) 2015 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 main
import (
"bytes"
"io"
"net/http"
"path/filepath"
"regexp"
"strconv"
"strings"
"sync"
"time"
)
type objectAPIHandler struct {
lock *sync.Mutex
bucket string
object map[string][]byte
}
func (h objectAPIHandler) getHandler(w http.ResponseWriter, r *http.Request) {
h.lock.Lock()
defer h.lock.Unlock()
switch {
case r.URL.Path == "/":
response := []byte("<ListAllMyBucketsResult xmlns=\"http://doc.s3.amazonaws.com/2006-03-01\"><Buckets><Bucket><Name>bucket</Name><CreationDate>2015-05-20T23:05:09.230Z</CreationDate></Bucket></Buckets><Owner><ID>minio</ID><DisplayName>minio</DisplayName></Owner></ListAllMyBucketsResult>")
w.Header().Set("Content-Length", strconv.Itoa(len(response)))
w.Write(response)
return
case r.URL.Path == "/bucket":
_, ok := r.URL.Query()["acl"]
if ok {
response := []byte("<?xml version=\"1.0\" encoding=\"UTF-8\"?><AccessControlPolicy><Owner><ID>75aa57f09aa0c8caeab4f8c24e99d10f8e7faeebf76c078efc7c6caea54ba06a</ID><DisplayName>CustomersName@amazon.com</DisplayName></Owner><AccessControlList><Grant><Grantee xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"CanonicalUser\"><ID>75aa57f09aa0c8caeab4f8c24e99d10f8e7faeebf76c078efc7c6caea54ba06a</ID><DisplayName>CustomersName@amazon.com</DisplayName></Grantee><Permission>FULL_CONTROL</Permission></Grant></AccessControlList></AccessControlPolicy>")
w.Header().Set("Content-Length", strconv.Itoa(len(response)))
w.Write(response)
return
}
fallthrough
case r.URL.Path == "/bucket":
response := []byte("<ListBucketResult xmlns=\"http://doc.s3.amazonaws.com/2006-03-01\"><Contents><ETag>b1946ac92492d2347c6235b4d2611184</ETag><Key>object0</Key><LastModified>2015-05-21T18:24:21.097Z</LastModified><Size>22061</Size><Owner><ID>minio</ID><DisplayName>minio</DisplayName></Owner><StorageClass>STANDARD</StorageClass></Contents><Contents><ETag>b1946ac92492d2347c6235b4d2611184</ETag><Key>object1</Key><LastModified>2015-05-21T18:24:21.097Z</LastModified><Size>22061</Size><Owner><ID>minio</ID><DisplayName>minio</DisplayName></Owner><StorageClass>STANDARD</StorageClass></Contents><Contents><ETag>b1946ac92492d2347c6235b4d2611184</ETag><Key>object2</Key><LastModified>2015-05-21T18:24:21.097Z</LastModified><Size>22061</Size><Owner><ID>minio</ID><DisplayName>minio</DisplayName></Owner><StorageClass>STANDARD</StorageClass></Contents><Contents><ETag>b1946ac92492d2347c6235b4d2611184</ETag><Key>object3</Key><LastModified>2015-05-21T18:24:21.097Z</LastModified><Size>22061</Size><Owner><ID>minio</ID><DisplayName>minio</DisplayName></Owner><StorageClass>STANDARD</StorageClass></Contents><Contents><ETag>b1946ac92492d2347c6235b4d2611184</ETag><Key>object4</Key><LastModified>2015-05-21T18:24:21.097Z</LastModified><Size>22061</Size><Owner><ID>minio</ID><DisplayName>minio</DisplayName></Owner><StorageClass>STANDARD</StorageClass></Contents><Contents><ETag>b1946ac92492d2347c6235b4d2611184</ETag><Key>object5</Key><LastModified>2015-05-21T18:24:21.097Z</LastModified><Size>22061</Size><Owner><ID>minio</ID><DisplayName>minio</DisplayName></Owner><StorageClass>STANDARD</StorageClass></Contents><Contents><ETag>b1946ac92492d2347c6235b4d2611184</ETag><Key>object6</Key><LastModified>2015-05-21T18:24:21.097Z</LastModified><Size>22061</Size><Owner><ID>minio</ID><DisplayName>minio</DisplayName></Owner><StorageClass>STANDARD</StorageClass></Contents><Contents><ETag>b1946ac92492d2347c6235b4d2611184</ETag><Key>object7</Key><LastModified>2015-05-21T18:24:21.097Z</LastModified><Size>22061</Size><Owner><ID>minio</ID><DisplayName>minio</DisplayName></Owner><StorageClass>STANDARD</StorageClass></Contents><Delimiter></Delimiter><EncodingType></EncodingType><IsTruncated>false</IsTruncated><Marker></Marker><MaxKeys>1000</MaxKeys><Name>testbucket</Name><NextMarker></NextMarker><Prefix></Prefix></ListBucketResult>")
w.Header().Set("Content-Length", strconv.Itoa(len(response)))
w.Write(response)
return
case r.URL.Path != "":
if _, ok := h.object[filepath.Base(r.URL.Path)]; !ok {
w.WriteHeader(http.StatusNotFound)
return
}
w.Header().Set("Content-Length", strconv.Itoa(len(h.object[filepath.Base(r.URL.Path)])))
w.Header().Set("Last-Modified", time.Now().UTC().Format(http.TimeFormat))
w.Header().Set("ETag", "b1946ac92492d2347c6235b4d2611184")
w.WriteHeader(http.StatusOK)
io.Copy(w, bytes.NewReader(h.object[filepath.Base(r.URL.Path)]))
return
}
}
func (h objectAPIHandler) headHandler(w http.ResponseWriter, r *http.Request) {
h.lock.Lock()
defer h.lock.Unlock()
switch {
case r.URL.Path == "/":
w.WriteHeader(http.StatusOK)
return
case r.URL.Path == "/bucket":
w.WriteHeader(http.StatusOK)
return
case r.URL.Path != "":
w.Header().Set("Content-Length", strconv.Itoa(len(h.object[filepath.Base(r.URL.Path)])))
w.Header().Set("Last-Modified", time.Now().UTC().Format(http.TimeFormat))
w.Header().Set("ETag", "b1946ac92492d2347c6235b4d2611184")
w.WriteHeader(http.StatusOK)
return
}
}
func isValidBucket(bucket string) bool {
if len(bucket) < 3 || len(bucket) > 63 {
return false
}
if bucket[0] == '.' || bucket[len(bucket)-1] == '.' {
return false
}
if match, _ := regexp.MatchString("\\.\\.", bucket); match == true {
return false
}
// We don't support buckets with '.' in them
match, _ := regexp.MatchString("^[a-zA-Z][a-zA-Z0-9\\-]+[a-zA-Z0-9]$", bucket)
return match
}
func (h objectAPIHandler) putHandler(w http.ResponseWriter, r *http.Request) {
h.lock.Lock()
defer h.lock.Unlock()
switch {
case r.URL.Path == "/":
w.WriteHeader(http.StatusBadRequest)
return
case r.URL.Path == "/bucket":
_, ok := r.URL.Query()["acl"]
if ok {
switch r.Header.Get("x-amz-acl") {
case "public-read-write":
fallthrough
case "public-read":
fallthrough
case "private":
fallthrough
case "authenticated-read":
w.WriteHeader(http.StatusOK)
return
default:
w.WriteHeader(http.StatusNotImplemented)
return
}
}
w.WriteHeader(http.StatusOK)
return
case r.URL.Path != "":
if !isValidBucket(strings.Split(r.URL.Path, "/")[1]) {
w.WriteHeader(http.StatusBadRequest)
return
}
length, err := strconv.Atoi(r.Header.Get("Content-Length"))
if err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
var buffer bytes.Buffer
_, err = io.CopyN(&buffer, r.Body, int64(length))
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
h.object[filepath.Base(r.URL.Path)] = buffer.Bytes()
w.Header().Set("ETag", "b1946ac92492d2347c6235b4d2611184")
w.WriteHeader(http.StatusOK)
return
}
}
func (h objectAPIHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
switch {
case r.Method == "GET":
h.getHandler(w, r)
case r.Method == "HEAD":
h.headHandler(w, r)
case r.Method == "PUT":
h.putHandler(w, r)
}
}
-44
View File
@@ -1,44 +0,0 @@
# version format
version: "{build}"
# Operating system (build VM template)
os: Windows Server 2012 R2
clone_folder: c:\gopath\src\github.com\minio\mc
# environment variables
environment:
GOPATH: c:\gopath
GO15VENDOREXPERIMENT: 1
# scripts that run after cloning repository
install:
- set PATH=%GOPATH%\bin;c:\go\bin;%PATH%
- go version
- go env
- go get -u github.com/golang/lint/golint
- go get -u golang.org/x/tools/cmd/vet
- go get -u github.com/fzipp/gocyclo
- go get -u github.com/remyoudompheng/go-misc/deadcode
# to run your custom scripts instead of automatic MSBuild
build_script:
- go tool vet -all ./pkg
- go tool vet -shadow=true ./pkg
- gofmt -s -l pkg
- golint .
- golint github.com/minio/mc/pkg...
- gocyclo -over 40 .
- deadcode
- go test -race .
- go test -race github.com/minio/mc/pkg...
- go run buildscripts/gen-ldflags.go > temp.txt
- set /p LDFLAGS=<temp.txt
- go build -ldflags="%LDFLAGS%" -o %GOPATH%\bin\mc.exe
- mc version
# to disable automatic tests
test: off
# to disable deployment
deploy: off
+25
View File
@@ -0,0 +1,25 @@
## FIXME:
## In OSX, 'sort -V' option does not exist, hence
## we have our own version compare function.
## Once OSX has the option, below function is good enough.
##
## check_minimum_version() {
## versions=($(echo -e "$1\n$2" | sort -V))
## return [ "$1" == "${versions[0]}" ]
## }
##
check_minimum_version() {
IFS='.' read -r -a varray1 <<< "$1"
IFS='.' read -r -a varray2 <<< "$2"
for i in "${!varray1[@]}"; do
if [[ ${varray1[i]} -lt ${varray2[i]} ]]; then
return 0
elif [[ ${varray1[i]} -gt ${varray2[i]} ]]; then
return 1
fi
done
return 0
}
+110
View File
@@ -0,0 +1,110 @@
#!/bin/bash
_init() {
# Save release LDFLAGS
LDFLAGS=$(go run buildscripts/gen-ldflags.go)
# Extract release tag
release_tag=$(echo $LDFLAGS | awk {'print $6'} | cut -f2 -d=)
# Verify release tag.
if [ -z "$release_tag" ]; then
echo "Release tag cannot be empty. Please check return value of \`go run buildscripts/gen-ldflags.go\`"
exit 1;
fi
# Extract release string.
release_str=$(echo $MC_RELEASE | tr '[:upper:]' '[:lower:]')
# Verify release string.
if [ -z "$release_str" ]; then
echo "Release string cannot be empty. Please set \`MC_RELEASE\` env variable."
exit 1;
fi
# List of supported architectures
SUPPORTED_OSARCH='linux/amd64 linux/ppc64le windows/amd64 darwin/amd64'
## System binaries
CP=`which cp`
SHASUM=`which shasum`
SHA256SUM="${SHASUM} -a 256"
SED=`which sed`
}
go_build() {
local osarch=$1
os=$(echo $osarch | cut -f1 -d'/')
arch=$(echo $osarch | cut -f2 -d'/')
package=$(go list -f '{{.ImportPath}}')
echo -n "-->"
printf "%15s:%s\n" "${osarch}" "${package}"
# Release binary name
release_bin="$release_str/$os-$arch/$(basename $package).$release_tag"
# Release binary downloadable name
release_real_bin="$release_str/$os-$arch/$(basename $package)"
# Release sha1sum name
release_shasum="$release_str/$os-$arch/$(basename $package).${release_tag}.shasum"
# Release sha1sum default
release_shasum_default="$release_str/$os-$arch/$(basename $package).shasum"
# Release sha256sum name
release_sha256sum="$release_str/$os-$arch/$(basename $package).${release_tag}.sha256sum"
# Release sha256sum default
release_sha256sum_default="$release_str/$os-$arch/$(basename $package).sha256sum"
# Go build to build the binary.
CGO_ENABLED=0 GOOS=$os GOARCH=$arch go build -tags kqueue --ldflags "${LDFLAGS}" -o $release_bin
# Create copy
if [ $os == "windows" ]; then
$CP -p $release_bin ${release_real_bin}.exe
else
$CP -p $release_bin $release_real_bin
fi
# Calculate sha1sum
shasum_str=$(${SHASUM} ${release_bin})
echo ${shasum_str} | $SED "s/$release_str\/$os-$arch\///g" > $release_shasum
$CP -p $release_shasum $release_shasum_default
# Calculate sha256sum
sha256sum_str=$(${SHA256SUM} ${release_bin})
echo ${sha256sum_str} | $SED "s/$release_str\/$os-$arch\///g" > $release_sha256sum
$CP -p $release_sha256sum $release_sha256sum_default
}
main() {
# Build releases.
echo "Executing $release_str builds for OS: ${SUPPORTED_OSARCH}"
echo "Choose an OS Arch from the below"
for osarch in ${SUPPORTED_OSARCH}; do
echo ${osarch}
done
read -p "If you want to build for all, Just press Enter: " chosen_osarch
if [ "$chosen_osarch" = "" ] || [ "$chosen_osarch" = "all" ]; then
for each_osarch in ${SUPPORTED_OSARCH}; do
go_build ${each_osarch}
done
else
local found=0
for each_osarch in ${SUPPORTED_OSARCH}; do
if [ "$chosen_osarch" = "$each_osarch" ]; then
found=1
fi
done
if [ ${found} -eq 1 ]; then
go_build ${chosen_osarch}
else
echo "Unknown architecture \"${chosen_osarch}\""
exit 1
fi
fi
}
# Run main.
_init && main
+72 -177
View File
@@ -1,6 +1,6 @@
#!/usr/bin/env bash
#
# Minio Client, (C) 2015 Minio, Inc.
# MinIO Client, (C) 2015, 2016, 2017, 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.
@@ -15,23 +15,35 @@
# limitations under the License.
#
# shellcheck source=buildscripts/build.env
. "$(pwd)/buildscripts/build.env"
_init() {
shopt -s extglob
## Minimum required versions for build dependencies
GCC_VERSION="4.0"
CLANG_VERSION="7.0.0"
YASM_VERSION="1.2.0"
GIT_VERSION="1.0"
GO_VERSION="1.5.1"
GO_VERSION="1.13"
OSX_VERSION="10.8"
UNAME=$(uname -sm)
## Check all dependencies are present
MISSING=""
KNAME=$(uname -s)
ARCH=$(uname -m)
case "${KNAME}" in
SunOS )
ARCH=$(isainfo -k)
;;
esac
}
## FIXME:
## In OSX, 'readlink -f' option does not exist, hence
## we have our own readlink -f behavior here.
## Once OSX has the option, below function is good enough.
##
## readlink() {
## return /bin/readlink -f "$1"
## }
##
readlink() {
TARGET_FILE=$1
@@ -53,187 +65,70 @@ readlink() {
echo $RESULT
}
###
#
# Takes two arguments
# arg1: version number in `x.x.x` format
# arg2: version number in `x.x.x` format
#
# example: check_version "$version1" "$version2"
#
# returns:
# 0 - Installed version is equal to required
# 1 - Installed version is greater than required
# 2 - Installed version is lesser than required
# 3 - If args have length zero
#
####
check_version() {
## validate args
[[ -z "$1" ]] && return 3
[[ -z "$2" ]] && return 3
if [[ $1 == $2 ]]; then
return 0
fi
local IFS=.
local i ver1=($1) ver2=($2)
# fill empty fields in ver1 with zeros
for ((i=${#ver1[@]}; i<${#ver2[@]}; i++)); do
ver1[i]=0
done
for ((i=0; i<${#ver1[@]}; i++)); do
if [[ -z ${ver2[i]} ]]; then
# fill empty fields in ver2 with zeros
ver2[i]=0
fi
if ((10#${ver1[i]} > 10#${ver2[i]})); then
return 1
fi
if ((10#${ver1[i]} < 10#${ver2[i]})); then
## Installed version is lesser than required - Bad condition
return 2
fi
done
return 0
}
check_golang_env() {
echo ${GOROOT:?} 2>&1 >/dev/null
if [ $? -eq 1 ]; then
echo "ERROR"
echo "GOROOT environment variable missing, please refer to Go installation document"
echo "https://github.com/minio/mc/blob/master/INSTALLGO.md#install-go-13"
exit 1
fi
echo ${GOPATH:?} 2>&1 >/dev/null
if [ $? -eq 1 ]; then
echo "ERROR"
echo "GOPATH environment variable missing, please refer to Go installation document"
echo "https://github.com/minio/mc/blob/master/INSTALLGO.md#install-go-13"
exit 1
fi
local go_binary_path=$(which go)
if [ -z "${go_binary_path}" ] ; then
echo "Cannot find go binary in your PATH configuration, please refer to Go installation document"
echo "https://github.com/minio/mc/blob/master/INSTALLGO.md#install-go-13"
exit -1
fi
local new_go_binary_path=${go_binary_path}
if [ -h "${go_binary_path}" ]; then
new_go_binary_path=$(readlink ${go_binary_path})
fi
if [[ !"$(dirname ${new_go_binary_path})" =~ *"${GOROOT%%*(/)}"* ]] ; then
echo "The go binary found in your PATH configuration does not belong to the Go installation pointed by your GOROOT environment," \
"please refer to Go installation document"
echo "https://github.com/minio/mc/blob/master/INSTALLGO.md#install-go-13"
exit -1
fi
}
is_supported_os() {
case ${UNAME%% *} in
"Linux")
os="linux"
;;
"Darwin")
osx_host_version=$(env sw_vers -productVersion)
check_version "${osx_host_version}" "${OSX_VERSION}"
[[ $? -ge 2 ]] && die "Minimum OSX version supported is ${OSX_VERSION}"
;;
"*")
echo "Exiting.. unsupported operating system found"
exit 1;
esac
}
is_supported_arch() {
local supported
case ${UNAME##* } in
"x86_64")
supported=1
;;
"arm"*)
supported=1
assert_is_supported_arch() {
case "${ARCH}" in
x86_64 | amd64 | ppc64le | aarch64 | arm* | s390x )
return
;;
*)
supported=0
;;
echo "Arch '${ARCH}' is not supported. Supported Arch: [x86_64, amd64, ppc64le, aarch64, arm*, s390x]"
exit 1
esac
if [ $supported -eq 0 ]; then
echo "Invalid arch: ${UNAME} not supported, please use x86_64/amd64"
exit 1;
}
assert_is_supported_os() {
case "${KNAME}" in
Linux | FreeBSD | OpenBSD | NetBSD | DragonFly | SunOS )
return
;;
Darwin )
osx_host_version=$(env sw_vers -productVersion)
if ! check_minimum_version "${OSX_VERSION}" "${osx_host_version}"; then
echo "OSX version '${osx_host_version}' is not supported. Minimum supported version: ${OSX_VERSION}"
exit 1
fi
return
;;
*)
echo "OS '${KNAME}' is not supported. Supported OS: [Linux, FreeBSD, OpenBSD, NetBSD, Darwin, DragonFly]"
exit 1
esac
}
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://golang.org/doc/install"
exit 1
fi
installed_go_version=$(go version | sed 's/^.* go\([0-9.]*\).*$/\1/')
if ! check_minimum_version "${GO_VERSION}" "${installed_go_version}"; then
echo "Go runtime version '${installed_go_version}' is unsupported. Minimum supported version: ${GO_VERSION} to compile."
exit 1
fi
}
check_deps() {
check_version "$(env go version 2>/dev/null | sed 's/^.* go\([0-9.]*\).*$/\1/')" "${GO_VERSION}"
if [ $? -ge 2 ]; then
MISSING="${MISSING} golang(${GO_VERSION})"
assert_check_deps() {
# support unusual Git versions such as: 2.7.4 (Apple Git-66)
installed_git_version=$(git version | perl -ne '$_ =~ m/git version (.*?)( |$)/; print "$1\n";')
if ! check_minimum_version "${GIT_VERSION}" "${installed_git_version}"; then
echo "Git version '${installed_git_version}' is not supported. Minimum supported version: ${GIT_VERSION}"
exit 1
fi
check_version "$(env git --version 2>/dev/null | sed -e 's/^.* \([0-9.\].*\).*$/\1/' -e 's/^\([0-9.\]*\).*/\1/g')" "${GIT_VERSION}"
if [ $? -ge 2 ]; then
MISSING="${MISSING} git(${GIT_VERSION})"
fi
case ${UNAME%% *} in
"Linux")
check_version "$(env gcc --version 2>/dev/null | sed 's/^.* \([0-9.]*\).*$/\1/' | head -1)" "${GCC_VERSION}"
if [ $? -ge 2 ]; then
MISSING="${MISSING} build-essential(${GCC_VERSION})"
fi
;;
"Darwin")
check_version "$(env gcc --version 2>/dev/null | awk '{print $4}' | head -1)" "${CLANG_VERSION}"
if [ $? -ge 2 ]; then
MISSING="${MISSING} xcode-cli(${CLANG_VERSION})"
fi
;;
"*")
;;
esac
}
main() {
echo -n "Check for supported arch.. "
is_supported_arch
## Check for supported arch
assert_is_supported_arch
echo -n "Check for supported os.. "
is_supported_os
## Check for supported os
assert_is_supported_os
echo -n "Checking if proper environment variables are set.. "
check_golang_env
## Check for Go environment
assert_check_golang_env
echo "Done"
echo "Using GOPATH=${GOPATH} and GOROOT=${GOROOT}"
echo -n "Checking dependencies for Minio Client.. "
check_deps
## If dependencies are missing, warn the user and abort
if [ "x${MISSING}" != "x" ]; then
echo "ERROR"
echo
echo "The following build tools are missing:"
echo
echo "** ${MISSING} **"
echo
echo "Please install them "
echo "${MISSING}"
echo
echo "Follow https://github.com/minio/mc/blob/master/INSTALLGO.md for further instructions"
exit 1
fi
echo "Done"
## Check for dependencies
assert_check_deps
}
_init && main "$@"
+37
View File
@@ -0,0 +1,37 @@
#!/bin/bash
# Enable tracing if set.
[ -n "$BASH_XTRACEFD" ] && set -ex
function _init() {
## All binaries are static make sure to disable CGO.
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 linux/arm linux/386 windows/amd64"
}
function _build() {
local osarch=$1
IFS=/ read -r -a arr <<<"$osarch"
os="${arr[0]}"
arch="${arr[1]}"
package=$(go list -f '{{.ImportPath}}')
printf -- "--> %15s:%s\n" "${osarch}" "${package}"
# Go build to build the binary.
export GOOS=$os
export GOARCH=$arch
export GO111MODULE=on
export CGO_ENABLED=0
go build -tags kqueue -o /dev/null
}
function main() {
echo "Testing builds for OS/Arch: ${SUPPORTED_OSARCH}"
for each_osarch in ${SUPPORTED_OSARCH}; do
_build "${each_osarch}"
done
}
_init && main "$@"
+6 -6
View File
@@ -1,7 +1,7 @@
// +build ignore
/*
* Mc Client (C) 2014, 2015 Mc, Inc.
* MinIO Client (C) 2014, 2015, 2016, 2017, 2018 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -28,16 +28,16 @@ import (
func genLDFlags(version string) string {
var ldflagsStr string
ldflagsStr = "-X main.mcVersion=" + version + " "
ldflagsStr = ldflagsStr + "-X main.mcReleaseTag=" + releaseTag(version) + " "
ldflagsStr = ldflagsStr + "-X main.mcCommitID=" + commitID() + " "
ldflagsStr = ldflagsStr + "-X main.mcShortCommitID=" + commitID()[:12]
ldflagsStr = "-s -w -X github.com/minio/mc/cmd.Version=" + version + " "
ldflagsStr = ldflagsStr + "-X github.com/minio/mc/cmd.ReleaseTag=" + releaseTag(version) + " "
ldflagsStr = ldflagsStr + "-X github.com/minio/mc/cmd.CommitID=" + commitID() + " "
ldflagsStr = ldflagsStr + "-X github.com/minio/mc/cmd.ShortCommitID=" + commitID()[:12]
return ldflagsStr
}
// genReleaseTag prints release tag to the console for easy git tagging.
func releaseTag(version string) string {
relPrefix := "UNOFFICIAL"
relPrefix := "DEVELOPMENT"
if prefix := os.Getenv("MC_RELEASE"); prefix != "" {
relPrefix = prefix
}
-159
View File
@@ -1,159 +0,0 @@
/*
* Minio Client, (C) 2015 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 main
import (
"errors"
"fmt"
"io"
"os"
"strings"
"syscall"
"github.com/minio/cli"
"github.com/minio/minio-xl/pkg/probe"
)
var (
catFlags = []cli.Flag{
cli.BoolFlag{
Name: "help, h",
Usage: "Help of cat",
},
}
)
// Display contents of a file.
var catCmd = cli.Command{
Name: "cat",
Usage: "Display contents of a file.",
Action: mainCat,
Flags: append(catFlags, globalFlags...),
CustomHelpTemplate: `NAME:
mc {{.Name}} - {{.Usage}}
USAGE:
mc {{.Name}} [FLAGS] SOURCE [SOURCE...]
FLAGS:
{{range .Flags}}{{.}}
{{end}}
EXAMPLES:
1. Stream an object from Amazon S3 cloud storage to mplayer standard input.
$ mc {{.Name}} s3.amazonaws.com/ferenginar/klingon_opera_aktuh_maylotah.ogg | mplayer -
2. Concantenate contents of file1.txt and stdin to standard output.
$ mc {{.Name}} file1.txt - > file.txt
3. Concantenate multiple files to one.
$ mc {{.Name}} part.* > complete.img
`,
}
// checkCatSyntax performs command-line input validation for cat command.
func checkCatSyntax(ctx *cli.Context) {
args := ctx.Args()
if !args.Present() {
args = []string{"-"}
}
for _, arg := range args {
if strings.HasPrefix(arg, "-") && len(arg) > 1 {
fatalIf(probe.NewError(errors.New("")), fmt.Sprintf("Unknown flag ‘%s’ passed.", arg))
}
}
}
// catURL displays contents of a URL to stdout.
func catURL(sourceURL string) *probe.Error {
var reader io.ReadSeeker
switch sourceURL {
case "-":
reader = os.Stdin
default:
sourceClnt, err := url2Client(sourceURL)
if err != nil {
return err.Trace(sourceURL)
}
// Ignore size, since os.Stat() would not return proper size all the
// time for local filesystem for example /proc files.
reader, err = sourceClnt.Get(0, 0)
if err != nil {
return err.Trace(sourceURL)
}
}
return catOut(reader).Trace(sourceURL)
}
// catOut reads from reader stream and writes to stdout.
func catOut(r io.Reader) *probe.Error {
// Read till EOF.
if _, err := io.Copy(os.Stdout, r); err != nil {
switch e := err.(type) {
case *os.PathError:
if e.Err == syscall.EPIPE {
// stdout closed by the user. Gracefully exit.
return nil
}
return probe.NewError(err)
default:
return probe.NewError(err)
}
}
return nil
}
// mainCat is the main entry point for cat command.
func mainCat(ctx *cli.Context) {
// Set global flags from context.
setGlobalsFromContext(ctx)
// check 'cat' cli arguments.
checkCatSyntax(ctx)
// Set command flags from context.
stdinMode := false
if !ctx.Args().Present() {
stdinMode = true
}
// handle std input data.
if stdinMode {
fatalIf(catOut(os.Stdin).Trace(), "Unable to read from standard input.")
return
}
// if Args contain ‘-’, we need to preserve its order specially.
args := []string(ctx.Args())
if ctx.Args().First() == "-" {
for i, arg := range os.Args {
if arg == "cat" {
// Overwrite ctx.Args with os.Args.
args = os.Args[i+1:]
break
}
}
}
// Convert arguments to URLs: expand alias, fix format.
URLs, err := args2URLs(args)
fatalIf(err.Trace(args...), "Unable to parse arguments.")
for _, url := range URLs {
fatalIf(catURL(url).Trace(url), "Unable to read from ‘"+url+"’.")
}
}
-54
View File
@@ -1,54 +0,0 @@
/*
* Minio Client (C) 2015 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 main
import (
"bytes"
"io/ioutil"
"os"
"path/filepath"
"github.com/minio/minio-xl/pkg/probe"
. "gopkg.in/check.v1"
)
func (s *TestSuite) TestCat(c *C) {
/// filesystem
root, e := ioutil.TempDir(os.TempDir(), "cmd-")
c.Assert(e, IsNil)
defer os.RemoveAll(root)
objectPath := filepath.Join(root, "object1")
objectPathServer := server.URL + "/bucket/object1"
data := "hello"
var err *probe.Error
err = putTarget(objectPath, bytes.NewReader([]byte(data)), int64(len(data)))
c.Assert(err, IsNil)
err = putTarget(objectPathServer, bytes.NewReader([]byte(data)), int64(len(data)))
c.Assert(err, IsNil)
var sourceURLs []string
sourceURLs = append(sourceURLs, objectPath)
sourceURLs = append(sourceURLs, objectPathServer)
for _, sourceURL := range sourceURLs {
c.Assert(catURL(sourceURL), IsNil)
}
objectPath = filepath.Join(root, "object2")
c.Assert(catURL(objectPath), Not(IsNil))
}
+44
View File
@@ -0,0 +1,44 @@
/*
* MinIO Client (C) 2015 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 "path/filepath"
// isValidAccessPERM - is provided access perm string supported.
func (b accessPerms) isValidAccessPERM() bool {
switch b {
case accessNone, accessDownload, accessUpload, accessPublic:
return true
}
return false
}
func (b accessPerms) isValidAccessFile() bool {
return filepath.Ext(string(b)) == ".json"
}
// accessPerms - access level.
type accessPerms string
// different types of Access perm's currently supported by policy command.
const (
accessNone = accessPerms("none")
accessDownload = accessPerms("download")
accessUpload = accessPerms("upload")
accessPublic = accessPerms("public")
accessCustom = accessPerms("custom")
)
@@ -1,5 +1,5 @@
/*
* Minio Client (C) 2014, 2015 Minio, Inc.
* MinIO Client (C) 2014, 2015 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -14,20 +14,18 @@
* limitations under the License.
*/
package main
package cmd
import (
"io"
"fmt"
"sync"
"sync/atomic"
"time"
)
// accountingReader - implements and inherits io.ReadCloser interface for accounter.
type accountingReader struct {
io.ReadSeeker
acct *accounter
}
"github.com/cheggaaa/pb"
json "github.com/minio/mc/pkg/colorjson"
"github.com/minio/mc/pkg/probe"
)
// accounter keeps tabs of ongoing data transfer information.
type accounter struct {
@@ -58,7 +56,7 @@ func newAccounter(total int64) *accounter {
// write calculate the final speed.
func (a *accounter) write(current int64) float64 {
fromStart := time.Now().Sub(a.startTime)
fromStart := time.Since(a.startTime)
currentFromStart := current - a.startValue
if currentFromStart > 0 {
speed := float64(currentFromStart) / (float64(fromStart) / float64(time.Second))
@@ -82,9 +80,30 @@ func (a *accounter) writer() {
// accountStat cantainer for current stats captured.
type accountStat struct {
Total int64
Transferred int64
Speed float64
Status string `json:"status"`
Total int64 `json:"total"`
Transferred int64 `json:"transferred"`
Speed float64 `json:"speed"`
}
func (c accountStat) JSON() string {
c.Status = "success"
accountMessageBytes, e := json.MarshalIndent(c, "", " ")
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
return string(accountMessageBytes)
}
func (c accountStat) String() string {
speedBox := pb.Format(int64(c.Speed)).To(pb.U_BYTES).String()
if speedBox == "" {
speedBox = "0 MB"
} else {
speedBox = speedBox + "/s"
}
message := fmt.Sprintf("Total: %s, Transferred: %s, Speed: %s", pb.Format(c.Total).To(pb.U_BYTES),
pb.Format(c.Transferred).To(pb.U_BYTES), speedBox)
return message
}
// Stat provides current stats captured.
@@ -93,7 +112,7 @@ func (a *accounter) Stat() accountStat {
a.finishOnce.Do(func() {
close(a.isFinished)
acntStat.Total = a.Total
acntStat.Transferred = a.current
acntStat.Transferred = atomic.LoadInt64(&a.current)
acntStat.Speed = a.write(atomic.LoadInt64(&a.current))
})
return acntStat
@@ -108,32 +127,28 @@ func (a *accounter) Update() {
}
}
// Add add to current values atomically.
// Set sets the current value atomically.
func (a *accounter) Set(n int64) *accounter {
atomic.StoreInt64(&a.current, n)
return a
}
// Get gets current value atomically
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)
}
// Instantiate a new proxy reader for accounter.
func (a *accounter) NewProxyReader(r io.ReadSeeker) *accountingReader {
return &accountingReader{r, a}
}
// Read implement Reader which internally updates current value.
func (a *accountingReader) Read(p []byte) (n int, err error) {
n, err = a.ReadSeeker.Read(p)
if err != nil {
return
}
a.acct.Add(int64(n))
return
}
// Seek implement Seeker.
func (a *accountingReader) Seek(offset int64, whence int) (n int64, err error) {
n, err = a.ReadSeeker.Seek(offset, whence)
if err != nil {
return
}
a.acct.Add(n)
// Read implements Reader which internally updates current value.
func (a *accounter) Read(p []byte) (n int, err error) {
n = len(p)
a.Add(int64(n))
return
}
+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
}
+120
View File
@@ -0,0 +1,120 @@
/*
* 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.
* 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"
"github.com/minio/cli"
json "github.com/minio/mc/pkg/colorjson"
"github.com/minio/mc/pkg/probe"
)
var adminConfigGetCmd = cli.Command{
Name: "get",
Usage: "interactively retrieve a config key parameters",
Before: initBeforeRunningCmd,
Action: mainAdminConfigGet,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} TARGET
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
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"`
Value []byte `json:"value"`
}
// String colorized service status message.
func (u configGetMessage) String() string {
return string(u.Value)
}
// JSON jsonified service status Message message.
func (u configGetMessage) JSON() string {
u.Status = "success"
statusJSONBytes, e := json.MarshalIndent(u, "", " ")
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
return string(statusJSONBytes)
}
// checkAdminConfigGetSyntax - validate all the passed arguments
func checkAdminConfigGetSyntax(ctx *cli.Context) {
if !ctx.Args().Present() || len(ctx.Args()) < 1 {
cli.ShowCommandHelpAndExit(ctx, "get", 1) // last argument is exit code
}
}
func mainAdminConfigGet(ctx *cli.Context) error {
checkAdminConfigGetSyntax(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.")
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
buf, e := client.GetConfigKV(globalContext, strings.Join(args.Tail(), " "))
fatalIf(probe.NewError(e), "Cannot get server '%s' config", args.Tail())
// Print
printMsg(configGetMessage{
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
}
+131
View File
@@ -0,0 +1,131 @@
/*
* 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.
* 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 adminConfigSetCmd = cli.Command{
Name: "set",
Usage: "interactively set a config key parameters",
Before: initBeforeRunningCmd,
Action: mainAdminConfigSet,
Flags: append(adminConfigEnvFlags, globalFlags...),
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} TARGET
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
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"`
targetAlias string
}
// String colorized service status message.
func (u configSetMessage) 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
}
// JSON jsonified service status message.
func (u configSetMessage) JSON() string {
u.Status = "success"
statusJSONBytes, e := json.MarshalIndent(u, "", " ")
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
return string(statusJSONBytes)
}
// checkAdminConfigSetSyntax - validate all the passed arguments
func checkAdminConfigSetSyntax(ctx *cli.Context) {
if !ctx.Args().Present() && len(ctx.Args()) < 1 {
cli.ShowCommandHelpAndExit(ctx, "set", 1) // last argument is exit code
}
}
// main config set function
func mainAdminConfigSet(ctx *cli.Context) error {
// Check command arguments
checkAdminConfigSetSyntax(ctx)
// Set color preference of command outputs
console.SetColor("SetConfigSuccess", 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, "Unable to initialize admin connection.")
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{
targetAlias: aliasedURL,
})
return nil
}
+43
View File
@@ -0,0 +1,43 @@
/*
* 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.
* 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 adminConfigCmd = cli.Command{
Name: "config",
Usage: "manage MinIO server configuration",
Action: mainAdminConfig,
Flags: globalFlags,
Subcommands: []cli.Command{
adminConfigGetCmd,
adminConfigSetCmd,
adminConfigResetCmd,
adminConfigHistoryCmd,
adminConfigRestoreCmd,
adminConfigExportCmd,
adminConfigImportCmd,
},
HideHelpCommand: true,
}
// mainAdminConfig is the handle for "mc admin config" command.
func mainAdminConfig(ctx *cli.Context) error {
cli.ShowCommandHelp(ctx, ctx.Args().First())
return nil
// Sub-commands like "get", "set" have their own main.
}
+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.
}
+117
View File
@@ -0,0 +1,117 @@
/*
* MinIO Client (C) 2018 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/minio/pkg/madmin"
)
type hri struct {
*madmin.HealResultItem
}
func newHRI(i *madmin.HealResultItem) *hri {
return &hri{i}
}
// getObjectHCCChange - returns before and after color change for
// objects
func (h hri) getObjectHCCChange() (b, a col, err error) {
parityShards := h.ParityBlocks
dataShards := h.DataBlocks
onlineBefore, onlineAfter := h.GetOnlineCounts()
surplusShardsBeforeHeal := onlineBefore - dataShards
surplusShardsAfterHeal := onlineAfter - dataShards
b, err = getHColCode(surplusShardsBeforeHeal, parityShards)
if err != nil {
return
}
a, err = getHColCode(surplusShardsAfterHeal, parityShards)
return
}
// getReplicatedFileHCCChange - fetches health color code for metadata
// files that are replicated.
func (h hri) getReplicatedFileHCCChange() (b, a col, err error) {
getColCode := func(numAvail int) (c col, err error) {
// calculate color code for replicated object similar
// to erasure coded objects
quorum := h.DiskCount/h.SetCount/2 + 1
surplus := numAvail/h.SetCount - quorum
parity := h.DiskCount/h.SetCount - quorum
c, err = getHColCode(surplus, parity)
return
}
onlineBefore, onlineAfter := h.GetOnlineCounts()
b, err = getColCode(onlineBefore)
if err != nil {
return
}
a, err = getColCode(onlineAfter)
return
}
func (h hri) makeHealEntityString() string {
switch h.Type {
case madmin.HealItemObject:
return h.Bucket + "/" + h.Object
case madmin.HealItemBucket:
return h.Bucket
case madmin.HealItemMetadata:
return "[disk-format]"
case madmin.HealItemBucketMetadata:
return fmt.Sprintf("[bucket-metadata]%s/%s", h.Bucket, h.Object)
}
return "** unexpected **"
}
func (h hri) getHRTypeAndName() (typ, name string) {
name = fmt.Sprintf("%s/%s", h.Bucket, h.Object)
switch h.Type {
case madmin.HealItemMetadata:
typ = "system"
name = h.Detail
case madmin.HealItemBucketMetadata:
typ = "system"
name = "bucket-metadata:" + name
case madmin.HealItemBucket:
typ = "bucket"
case madmin.HealItemObject:
typ = "object"
default:
typ = fmt.Sprintf("!! Unknown heal result record %#v !!", h)
name = typ
}
return
}
func (h hri) getHealResultStr() string {
typ, name := h.getHRTypeAndName()
switch h.Type {
case madmin.HealItemMetadata, madmin.HealItemBucketMetadata:
return typ + ":" + name
default:
return name
}
}
+446
View File
@@ -0,0 +1,446 @@
/*
* MinIO Client (C) 2018 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"
"fmt"
"math"
"strings"
"time"
humanize "github.com/dustin/go-humanize"
"github.com/fatih/color"
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 (
lineWidth = 80
)
var (
hColOrder = []col{colRed, colYellow, colGreen}
hColTable = map[int][]int{
1: {0, -1, 1},
2: {0, 1, 2},
3: {1, 2, 3},
4: {1, 2, 4},
5: {1, 3, 5},
6: {2, 4, 6},
7: {2, 4, 7},
8: {2, 5, 8},
}
)
func getHColCode(surplusShards, parityShards int) (c col, err error) {
if parityShards < 1 || parityShards > 8 || surplusShards > parityShards {
return c, fmt.Errorf("Invalid parity shard count/surplus shard count given")
}
if surplusShards < 0 {
return colGrey, err
}
colRow := hColTable[parityShards]
for index, val := range colRow {
if val != -1 && surplusShards <= val {
return hColOrder[index], err
}
}
return c, fmt.Errorf("cannot get a heal color code")
}
type uiData struct {
Bucket, Prefix string
Client *madmin.AdminClient
ClientToken string
ForceStart bool
HealOpts *madmin.HealOpts
LastItem *hri
// Total time since heal start
HealDuration time.Duration
// Accumulated statistics of heal result records
BytesScanned int64
// Counter for objects, and another counter for all kinds of
// items
ObjectsScanned, ItemsScanned int64
// Counters for healed objects and all kinds of healed items
ObjectsHealed, ItemsHealed int64
// Map from online drives to number of objects with that many
// online drives.
ObjectsByOnlineDrives map[int]int64
// Map of health color code to number of objects with that
// health color code.
HealthCols map[col]int64
// channel to receive a prompt string to indicate activity on
// the terminal
CurChan (<-chan string)
}
func (ui *uiData) updateStats(i madmin.HealResultItem) error {
if i.Type == madmin.HealItemObject {
// Objects whose size could not be found have -1 size
// returned.
if i.ObjectSize >= 0 {
ui.BytesScanned += i.ObjectSize
}
ui.ObjectsScanned++
}
ui.ItemsScanned++
beforeUp, afterUp := i.GetOnlineCounts()
if afterUp > beforeUp {
if i.Type == madmin.HealItemObject {
ui.ObjectsHealed++
}
ui.ItemsHealed++
}
ui.ObjectsByOnlineDrives[afterUp]++
// Update health color stats:
// Fetch health color after heal:
var err error
var afterCol col
h := newHRI(&i)
switch h.Type {
case madmin.HealItemMetadata, madmin.HealItemBucket:
_, afterCol, err = h.getReplicatedFileHCCChange()
default:
_, afterCol, err = h.getObjectHCCChange()
}
if err != nil {
return err
}
ui.HealthCols[afterCol]++
return nil
}
func (ui *uiData) updateDuration(s *madmin.HealTaskStatus) {
ui.HealDuration = UTCNow().Sub(s.StartTime)
}
func (ui *uiData) getProgress() (oCount, objSize, duration string) {
oCount = humanize.Comma(ui.ObjectsScanned)
duration = ui.HealDuration.Round(time.Second).String()
bytesScanned := float64(ui.BytesScanned)
// Compute unit for object size
magnitudes := []float64{1 << 10, 1 << 20, 1 << 30, 1 << 40, 1 << 50, 1 << 60}
units := []string{"B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB"}
var i int
for i = 0; i < len(magnitudes); i++ {
if bytesScanned <= magnitudes[i] {
break
}
}
numUnits := int(bytesScanned * (1 << 10) / magnitudes[i])
objSize = fmt.Sprintf("%d %s", numUnits, units[i])
return
}
func (ui *uiData) getPercentsNBars() (p map[col]float64, b map[col]string) {
// barChar, emptyBarChar := "█", "░"
barChar, emptyBarChar := "█", " "
barLen := 12
sum := float64(ui.ItemsScanned)
cols := []col{colGrey, colRed, colYellow, colGreen}
p = make(map[col]float64, len(cols))
b = make(map[col]string, len(cols))
var filledLen int
for _, col := range cols {
v := float64(ui.HealthCols[col])
if sum == 0 {
p[col] = 0
filledLen = 0
} else {
p[col] = v * 100 / sum
// round up the filled part
filledLen = int(math.Ceil(float64(barLen) * v / sum))
}
b[col] = strings.Repeat(barChar, filledLen) +
strings.Repeat(emptyBarChar, barLen-filledLen)
}
return
}
func (ui *uiData) printItemsQuietly(s *madmin.HealTaskStatus) (err error) {
lpad := func(s col) string {
return fmt.Sprintf("%-6s", string(s))
}
rpad := func(s col) string {
return fmt.Sprintf("%6s", string(s))
}
printColStr := func(before, after col) {
console.PrintC("[" + lpad(before) + " -> " + rpad(after) + "] ")
}
var b, a col
for _, item := range s.Items {
h := newHRI(&item)
switch h.Type {
case madmin.HealItemMetadata, madmin.HealItemBucket:
b, a, err = h.getReplicatedFileHCCChange()
default:
b, a, err = h.getObjectHCCChange()
}
if err != nil {
return err
}
printColStr(b, a)
hrStr := h.getHealResultStr()
switch h.Type {
case madmin.HealItemMetadata, madmin.HealItemBucketMetadata:
console.PrintC(fmt.Sprintln("**", hrStr, "**"))
default:
console.PrintC(hrStr, "\n")
}
}
return nil
}
func (ui *uiData) printStatsQuietly(s *madmin.HealTaskStatus) {
totalObjects, totalSize, totalTime := ui.getProgress()
healedStr := fmt.Sprintf("Healed:\t%s/%s objects; %s in %s\n",
humanize.Comma(ui.ObjectsHealed), totalObjects,
totalSize, totalTime)
console.PrintC(healedStr)
}
func (ui *uiData) printItemsJSON(s *madmin.HealTaskStatus) (err error) {
type healRec struct {
Status string `json:"status"`
Error string `json:"error,omitempty"`
Type string `json:"type"`
Name string `json:"name"`
Before struct {
Color string `json:"color"`
Offline int `json:"offline"`
Online int `json:"online"`
Missing int `json:"missing"`
Corrupted int `json:"corrupted"`
Drives []madmin.HealDriveInfo `json:"drives"`
} `json:"before"`
After struct {
Color string `json:"color"`
Offline int `json:"offline"`
Online int `json:"online"`
Missing int `json:"missing"`
Corrupted int `json:"corrupted"`
Drives []madmin.HealDriveInfo `json:"drives"`
} `json:"after"`
Size int64 `json:"size"`
}
makeHR := func(h *hri) (r healRec, err error) {
r.Status = "success"
r.Type, r.Name = h.getHRTypeAndName()
var b, a col
switch h.Type {
case madmin.HealItemMetadata, madmin.HealItemBucket:
b, a, err = h.getReplicatedFileHCCChange()
default:
if h.Type == madmin.HealItemObject {
r.Size = h.ObjectSize
}
b, a, err = h.getObjectHCCChange()
}
if err != nil {
return r, err
}
r.Before.Color = strings.ToLower(string(b))
r.After.Color = strings.ToLower(string(a))
r.Before.Online, r.After.Online = h.GetOnlineCounts()
r.Before.Missing, r.After.Missing = h.GetMissingCounts()
r.Before.Corrupted, r.After.Corrupted = h.GetCorruptedCounts()
r.Before.Offline, r.After.Offline = h.GetOfflineCounts()
r.Before.Drives = h.Before.Drives
r.After.Drives = h.After.Drives
return r, nil
}
for _, item := range s.Items {
h := newHRI(&item)
r, err := makeHR(h)
if err != nil {
return err
}
jsonBytes, err := json.MarshalIndent(r, "", " ")
fatalIf(probe.NewError(err), "Unable to marshal to JSON.")
console.Println(string(jsonBytes))
}
return nil
}
func (ui *uiData) printStatsJSON(s *madmin.HealTaskStatus) {
var summary struct {
Status string `json:"status"`
Error string `json:"error,omitempty"`
Type string `json:"type"`
ObjectsScanned int64 `json:"objects_scanned"`
ObjectsHealed int64 `json:"objects_healed"`
ItemsScanned int64 `json:"items_scanned"`
ItemsHealed int64 `json:"items_healed"`
Size int64 `json:"size"`
ElapsedTime int64 `json:"duration"`
}
summary.Status = "success"
summary.Type = "summary"
summary.ObjectsScanned = ui.ObjectsScanned
summary.ObjectsHealed = ui.ObjectsHealed
summary.ItemsScanned = ui.ItemsScanned
summary.ItemsHealed = ui.ItemsHealed
summary.Size = ui.BytesScanned
summary.ElapsedTime = int64(ui.HealDuration.Round(time.Second).Seconds())
jBytes, err := json.MarshalIndent(summary, "", " ")
fatalIf(probe.NewError(err), "Unable to marshal to JSON.")
console.Println(string(jBytes))
}
func (ui *uiData) updateUI(s *madmin.HealTaskStatus) (err error) {
itemCount := len(s.Items)
h := ui.LastItem
if itemCount > 0 {
item := s.Items[itemCount-1]
h = newHRI(&item)
ui.LastItem = h
}
scannedStr := "** waiting for status from server **"
if h != nil {
scannedStr = lineTrunc(h.makeHealEntityString(), lineWidth-len("Scanned: "))
}
totalObjects, totalSize, totalTime := ui.getProgress()
healedStr := fmt.Sprintf("%s/%s objects; %s in %s",
humanize.Comma(ui.ObjectsHealed), totalObjects,
totalSize, totalTime)
console.Print(console.Colorize("HealUpdateUI", fmt.Sprintf(" %s", <-ui.CurChan)))
console.PrintC(fmt.Sprintf(" %s\n", scannedStr))
console.PrintC(fmt.Sprintf(" %s\n", healedStr))
dspOrder := []col{colGreen, colYellow, colRed, colGrey}
printColors := []*color.Color{}
for _, c := range dspOrder {
printColors = append(printColors, getPrintCol(c))
}
t := console.NewTable(printColors, []bool{false, true, true}, 4)
percentMap, barMap := ui.getPercentsNBars()
cellText := make([][]string, len(dspOrder))
for i := range cellText {
cellText[i] = []string{
string(dspOrder[i]),
fmt.Sprint(humanize.Comma(ui.HealthCols[dspOrder[i]])),
fmt.Sprintf("%5.1f%% %s", percentMap[dspOrder[i]], barMap[dspOrder[i]]),
}
}
t.DisplayTable(cellText)
return nil
}
func (ui *uiData) UpdateDisplay(s *madmin.HealTaskStatus) (err error) {
// Update state
ui.updateDuration(s)
for _, i := range s.Items {
ui.updateStats(i)
}
// Update display
switch {
case globalJSON:
err = ui.printItemsJSON(s)
case globalQuiet:
err = ui.printItemsQuietly(s)
default:
err = ui.updateUI(s)
}
return
}
func (ui *uiData) healResumeMsg(aliasedURL string) string {
var flags string
if ui.HealOpts.Recursive {
flags += "--recursive "
}
if ui.HealOpts.DryRun {
flags += "--dry-run "
}
return fmt.Sprintf("Healing is backgrounded, to resume watching use `mc admin heal %s %s`", flags, aliasedURL)
}
func (ui *uiData) DisplayAndFollowHealStatus(aliasedURL string) (res madmin.HealTaskStatus, err error) {
quitMsg := ui.healResumeMsg(aliasedURL)
firstIter := true
for {
select {
case <-globalContext.Done():
return res, errors.New(quitMsg)
default:
_, res, err = ui.Client.Heal(globalContext, ui.Bucket, ui.Prefix, *ui.HealOpts,
ui.ClientToken, ui.ForceStart, false)
if err != nil {
return res, err
}
if firstIter {
firstIter = false
} else {
if !globalQuiet && !globalJSON {
console.RewindLines(8)
}
}
err = ui.UpdateDisplay(&res)
if err != nil {
return res, err
}
if res.Summary == "finished" {
if globalJSON {
ui.printStatsJSON(&res)
} else if globalQuiet {
ui.printStatsQuietly(&res)
}
return res, nil
}
if res.Summary == "stopped" {
return res, fmt.Errorf("Heal had an error - %s", res.FailureDetail)
}
time.Sleep(time.Second)
}
}
}
+282
View File
@@ -0,0 +1,282 @@
/*
* MinIO Client (C) 2017, 2018 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"
"path/filepath"
"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 (
scanNormalMode = "normal"
scanDeepMode = "deep"
)
var adminHealFlags = []cli.Flag{
cli.StringFlag{
Name: "scan",
Usage: "select the healing scan mode (normal/deep)",
Value: scanNormalMode,
},
cli.BoolFlag{
Name: "recursive, r",
Usage: "heal recursively",
},
cli.BoolFlag{
Name: "dry-run, n",
Usage: "only inspect data, but do not mutate",
},
cli.BoolFlag{
Name: "force-start, f",
Usage: "force start a new heal sequence",
},
cli.BoolFlag{
Name: "force-stop, s",
Usage: "Force stop a running heal sequence",
},
cli.BoolFlag{
Name: "remove",
Usage: "remove dangling objects in heal sequence",
},
}
var adminHealCmd = cli.Command{
Name: "heal",
Usage: "heal disks, buckets and objects on MinIO server",
Action: mainAdminHeal,
Before: initBeforeRunningCmd,
Flags: append(adminHealFlags, globalFlags...),
HideHelpCommand: true,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} [FLAGS] TARGET
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
SCAN MODES:
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'
{{.Prompt}} {{.HelpName}} myminio
2. Heal 'testbucket' in a MinIO server with alias 'myminio'
{{.Prompt}} {{.HelpName}} myminio/testbucket/
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
{{.Prompt}} {{.HelpName}} --dry-run myminio
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)
{{.Prompt}} {{.HelpName}} --force-start 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
{{.Prompt}} {{.HelpName}} --dry-run myminio/testbucket/dir/
`,
}
func checkAdminHealSyntax(ctx *cli.Context) {
if len(ctx.Args()) != 1 {
cli.ShowCommandHelpAndExit(ctx, "heal", 1) // last argument is exit code
}
// Check for scan argument
scanArg := ctx.String("scan")
scanArg = strings.ToLower(scanArg)
if scanArg != scanNormalMode && scanArg != scanDeepMode {
cli.ShowCommandHelpAndExit(ctx, "heal", 1) // last argument is exit code
}
}
// stopHealMessage is container for stop heal success and failure messages.
type stopHealMessage struct {
Status string `json:"status"`
Alias string `json:"alias"`
}
// String colorized stop heal message.
func (s stopHealMessage) String() string {
return console.Colorize("HealStopped", "Heal stopped successfully at `"+s.Alias+"`.")
}
// JSON jsonified stop heal message.
func (s stopHealMessage) JSON() string {
stopHealJSONBytes, e := json.MarshalIndent(s, "", " ")
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
return string(stopHealJSONBytes)
}
// backgroundHealStatusMessage is container for stop heal success and failure messages.
type backgroundHealStatusMessage struct {
Status string `json:"status"`
HealInfo madmin.BgHealState
}
// 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 += dot + fmt.Sprintf("%s item(s) scanned in total\n",
console.Colorize("HealBackground", s.HealInfo.ScannedItemsCount))
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
}
// JSON jsonified stop heal message.
func (s backgroundHealStatusMessage) JSON() string {
healJSONBytes, e := json.MarshalIndent(s, "", " ")
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
return string(healJSONBytes)
}
func transformScanArg(scanArg string) madmin.HealScanMode {
switch scanArg {
case "deep":
return madmin.HealDeepScan
}
return madmin.HealNormalScan
}
// mainAdminHeal - the entry function of heal command
func mainAdminHeal(ctx *cli.Context) error {
// Check for command syntax
checkAdminHealSyntax(ctx)
// Get the alias parameter from cli
args := ctx.Args()
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))
console.SetColor("HealStopped", color.New(color.FgGreen, color.Bold))
// Create a new MinIO Admin Client
client, err := newAdminClient(aliasedURL)
if err != nil {
fatalIf(err.Trace(aliasedURL), "Cannot initialize admin client.")
return nil
}
// Compute bucket and object from the aliased URL
aliasedURL = filepath.ToSlash(aliasedURL)
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(globalContext)
fatalIf(probe.NewError(berr), "Failed to get the status of the background heal.")
printMsg(backgroundHealStatusMessage{Status: "success", HealInfo: bgHealStatus})
return nil
}
opts := madmin.HealOpts{
ScanMode: transformScanArg(ctx.String("scan")),
Remove: ctx.Bool("remove"),
Recursive: ctx.Bool("recursive"),
DryRun: ctx.Bool("dry-run"),
}
forceStart := ctx.Bool("force-start")
forceStop := ctx.Bool("force-stop")
if 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(globalContext, bucket, prefix, opts, "", forceStart, false)
fatalIf(probe.NewError(herr), "Failed to start heal sequence.")
ui := uiData{
Bucket: bucket,
Prefix: prefix,
Client: client,
ClientToken: healStart.ClientToken,
ForceStart: forceStart,
HealOpts: &opts,
ObjectsByOnlineDrives: make(map[int]int64),
HealthCols: make(map[col]int64),
CurChan: cursorAnimate(),
}
res, e := ui.DisplayAndFollowHealStatus(aliasedURL)
if e != nil {
if res.FailureDetail != "" {
data, _ := json.MarshalIndent(res, "", " ")
traceStr := string(data)
fatalIf(probe.NewError(e).Trace(aliasedURL, traceStr), "Unable to display heal status.")
} else {
fatalIf(probe.NewError(e).Trace(aliasedURL), "Unable to display heal status.")
}
}
return nil
}
+237
View File
@@ -0,0 +1,237 @@
/*
* 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"
"fmt"
"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/probe"
"github.com/minio/minio/pkg/console"
"github.com/minio/minio/pkg/madmin"
)
var adminInfoCmd = cli.Command{
Name: "info",
Usage: "display MinIO server information",
Action: mainAdminInfo,
Before: initBeforeRunningCmd,
Flags: 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/
`,
}
// 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"`
}
// String provides colorized info messages depending on the type of a server
// FS server non-FS server
// ============================== ===================================
// ● <ip>:<port> ● <ip>:<port>
// Uptime: xxx Uptime: xxx
// Version: xxx Version: xxx
// Network: X/Y OK Network: X/Y OK
//
// U Used, B Buckets, O Objects Drives: N/N OK
//
// U Used, B Buckets, O Objects
// N drives online, K drives offline
//
func (u clusterStruct) String() (msg string) {
// Check cluster level "Status" field for error
if u.Status == "error" {
fatal(probe.NewError(errors.New(u.Error)), "Cannot get service status")
}
// If nothing has been collected, error out
if u.Info.Servers == nil {
fatal(probe.NewError(errors.New("Cannot get service status")), "")
}
// Initialization
var totalOnlineDisksCluster int
var totalOfflineDisksCluster int
// Color palette initialization
console.SetColor("Info", color.New(color.FgGreen, color.Bold))
console.SetColor("InfoFail", color.New(color.FgRed, color.Bold))
// MinIO server type default
backendType := "Unknown"
// Set the type of MinIO server ("FS", "Erasure", "Unknown")
v := reflect.ValueOf(u.Info.Backend)
if v.Kind() == reflect.Map {
for _, key := range v.MapKeys() {
val := v.MapIndex(key)
switch t := val.Interface().(type) {
case string:
backendType = t
}
}
}
// Loop through each server and put together info for each one
for _, srv := range u.Info.Servers {
// Check if MinIO server is offline ("Mode" field),
// If offline, error out
if 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 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 arguments passed by a user
func checkAdminInfoSyntax(ctx *cli.Context) {
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 {
checkAdminInfoSyntax(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.")
var clusterInfo clusterStruct
// Fetch info of all servers (cluster or single server)
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
}
+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)
}
+19 -17
View File
@@ -1,5 +1,5 @@
/*
* Minio Client (C) 2015 Minio, Inc.
* 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.
@@ -14,21 +14,23 @@
* limitations under the License.
*/
package main
package cmd
// commonPrefix returns the longest common prefix between two strings.
func commonPrefix(first, second string) string {
if first == "" || second == "" {
return ""
}
if first > second {
// Pick the shorter one for looping.
first, second = second, first
}
for i := range first {
if first[i] != second[i] {
return first[:i]
}
}
return first
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
}
@@ -1,5 +1,5 @@
/*
* Minio Client (C) 2015 Minio, Inc.
* 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.
@@ -14,29 +14,23 @@
* limitations under the License.
*/
package console
package cmd
import (
"testing"
import "github.com/minio/cli"
"github.com/fatih/color"
. "gopkg.in/check.v1"
)
func Test(t *testing.T) { TestingT(t) }
type MySuite struct{}
var _ = Suite(&MySuite{})
func (s *MySuite) TestSetColor(c *C) {
SetColor("unknown", color.New(color.FgWhite))
_, ok := Theme["unknown"]
c.Assert(ok, Equals, true)
var adminKMSCmd = cli.Command{
Name: "kms",
Usage: "perform KMS management operations",
Action: mainAdminKMS,
Flags: globalFlags,
Subcommands: []cli.Command{
adminKMSKeyCmd,
},
HideHelpCommand: true,
}
func (s *MySuite) TestLock(c *C) {
Lock()
Print("") // Test for deadlocks.
Unlock()
// mainAdminKMS is the handle for the "mc admin kms" command.
func mainAdminKMS(ctx *cli.Context) error {
cli.ShowCommandHelp(ctx, ctx.Args().First())
return nil
}
+65
View File
@@ -0,0 +1,65 @@
/*
* 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 "github.com/minio/cli"
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,
Flags: append(adminFlags, globalFlags...),
Subcommands: []cli.Command{
adminServiceCmd,
adminServerUpdateCmd,
adminInfoCmd,
adminUserCmd,
adminGroupCmd,
adminPolicyCmd,
adminConfigCmd,
adminHealCmd,
adminProfileCmd,
adminTopCmd,
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())
return nil
// Sub-commands like "service", "heal", "top" have their own main.
}
+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)
+139
View File
@@ -0,0 +1,139 @@
/*
* MinIO Client (C) 2018 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 (
"bytes"
"fmt"
"io/ioutil"
"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"
iampolicy "github.com/minio/minio/pkg/iam/policy"
)
var adminPolicyAddCmd = cli.Command{
Name: "add",
Usage: "add new policy",
Action: mainAdminPolicyAdd,
Before: initBeforeRunningCmd,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} TARGET POLICYNAME POLICYFILE
POLICYNAME:
Name of the canned policy on MinIO server.
POLICYFILE:
Name of the policy file associated with the policy name.
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Add a new canned policy 'writeonly'.
{{.Prompt}} {{.HelpName}} myminio writeonly /tmp/writeonly.json
`,
}
// checkAdminPolicyAddSyntax - validate all the passed arguments
func checkAdminPolicyAddSyntax(ctx *cli.Context) {
if len(ctx.Args()) != 3 {
cli.ShowCommandHelpAndExit(ctx, "add", 1) // last argument is exit code
}
}
// userPolicyMessage container for content message structure
type userPolicyMessage struct {
op string
Status string `json:"status"`
Policy string `json:"policy,omitempty"`
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":
policyFieldMaxLen := 20
// Create a new pretty table with cols configuration
return newPrettyTable(" ",
Field{"Policy", policyFieldMaxLen},
).buildRow(u.Policy)
case "remove":
return console.Colorize("PolicyMessage", "Removed policy `"+u.Policy+"` successfully.")
case "add":
return console.Colorize("PolicyMessage", "Added policy `"+u.Policy+"` successfully.")
case "set":
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 ""
}
func (u userPolicyMessage) JSON() string {
u.Status = "success"
jsonMessageBytes, e := json.MarshalIndent(u, "", " ")
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
return string(jsonMessageBytes)
}
// mainAdminPolicyAdd is the handle for "mc admin policy add" command.
func mainAdminPolicyAdd(ctx *cli.Context) error {
checkAdminPolicyAddSyntax(ctx)
console.SetColor("PolicyMessage", color.New(color.FgGreen))
// Get the alias parameter from cli
args := ctx.Args()
aliasedURL := args.Get(0)
policy, e := ioutil.ReadFile(args.Get(2))
fatalIf(probe.NewError(e).Trace(args...), "Unable to get policy")
// Create a new MinIO Admin Client
client, err := newAdminClient(aliasedURL)
fatalIf(err, "Unable to initialize admin connection.")
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",
Policy: args.Get(1),
})
return nil
}
+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
}
+79
View File
@@ -0,0 +1,79 @@
/*
* 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 (
"github.com/fatih/color"
"github.com/minio/cli"
"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: initBeforeRunningCmd,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} TARGET
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. List all policies on MinIO server.
{{.Prompt}} {{.HelpName}} myminio
`,
}
// checkAdminPolicyListSyntax - validate all the passed arguments
func checkAdminPolicyListSyntax(ctx *cli.Context) {
if len(ctx.Args()) != 1 {
cli.ShowCommandHelpAndExit(ctx, "list", 1) // last argument is exit code
}
}
// mainAdminPolicyList is the handle for "mc admin policy add" command.
func mainAdminPolicyList(ctx *cli.Context) error {
checkAdminPolicyListSyntax(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)
// 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")
for k := range policies {
printMsg(userPolicyMessage{
op: "list",
Policy: k,
})
}
return nil
}
+79
View File
@@ -0,0 +1,79 @@
/*
* MinIO Client (C) 2018 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 adminPolicyRemoveCmd = cli.Command{
Name: "remove",
Usage: "remove policy",
Action: mainAdminPolicyRemove,
Before: initBeforeRunningCmd,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} TARGET POLICYNAME
POLICYNAME:
Name of the canned policy on MinIO server.
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Remove 'writeonly' policy on MinIO server.
{{.Prompt}} {{.HelpName}} myminio writeonly
`,
}
// checkAdminPolicyRemoveSyntax - validate all the passed arguments
func checkAdminPolicyRemoveSyntax(ctx *cli.Context) {
if len(ctx.Args()) != 2 {
cli.ShowCommandHelpAndExit(ctx, "remove", 1) // last argument is exit code
}
}
// mainAdminPolicyRemove is the handle for "mc admin policy remove" command.
func mainAdminPolicyRemove(ctx *cli.Context) error {
checkAdminPolicyRemoveSyntax(ctx)
console.SetColor("PolicyMessage", 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.")
fatalIf(probe.NewError(client.RemoveCannedPolicy(globalContext, args.Get(1))).Trace(args...), "Cannot remove policy")
printMsg(userPolicyMessage{
op: "remove",
Policy: args.Get(1),
})
return nil
}
+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
}
+41
View File
@@ -0,0 +1,41 @@
/*
* 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 "github.com/minio/cli"
var adminPolicyCmd = cli.Command{
Name: "policy",
Usage: "manage policies defined in the MinIO server",
Action: mainAdminPolicy,
Flags: globalFlags,
Subcommands: []cli.Command{
adminPolicyAddCmd,
adminPolicyRemoveCmd,
adminPolicyListCmd,
adminPolicyInfoCmd,
adminPolicySetCmd,
},
HideHelpCommand: true,
}
// mainAdminPolicy is the handle for "mc admin policy" command.
func mainAdminPolicy(ctx *cli.Context) error {
cli.ShowCommandHelp(ctx, ctx.Args().First())
return nil
// Sub-commands like "get", "set" have their own main.
}
+122
View File
@@ -0,0 +1,122 @@
/*
* MinIO Client (C) 2018 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"
"github.com/minio/cli"
"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', 'trace', 'threads' and 'goroutines'",
Value: "cpu,mem,block",
},
}
var adminProfileStartCmd = cli.Command{
Name: "start",
Usage: "start recording profile data",
Action: mainAdminProfileStart,
Before: initBeforeRunningCmd,
Flags: append(adminProfileStartFlags, globalFlags...),
HideHelpCommand: true,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} [FLAGS] TARGET
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
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/
`,
}
func checkAdminProfileStartSyntax(ctx *cli.Context) {
// Check flags combinations
if len(ctx.Args()) != 1 {
cli.ShowCommandHelpAndExit(ctx, "start", 1) // last argument is exit code
}
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
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().Trace(ctx.String("type")),
"Profiler type unrecognized. Possible values are: %v.", supportedProfilerTypes)
}
}
// mainAdminProfileStart - the entry function of profile command
func mainAdminProfileStart(ctx *cli.Context) error {
// Check for command syntax
checkAdminProfileStartSyntax(ctx)
// Get the alias parameter from cli
args := ctx.Args()
aliasedURL := args.Get(0)
profilers := ctx.String("type")
// Create a new MinIO Admin Client
client, err := newAdminClient(aliasedURL)
if err != nil {
fatalIf(err.Trace(aliasedURL), "Cannot initialize admin client.")
return nil
}
// Start profile
_, cmdErr := client.StartProfiling(globalContext, madmin.ProfilerType(profilers))
fatalIf(probe.NewError(cmdErr), "Unable to start profile.")
console.Infoln("Profile data successfully started.")
return nil
}
+133
View File
@@ -0,0 +1,133 @@
/*
* MinIO Client (C) 2018 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 (
"io"
"io/ioutil"
"os"
"time"
"github.com/minio/cli"
"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: initBeforeRunningCmd,
Flags: globalFlags,
HideHelpCommand: true,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} [FLAGS] TARGET
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
2. Download latest profile data in the current directory
{{.Prompt}} {{.HelpName}} myminio/
`,
}
func checkAdminProfileStopSyntax(ctx *cli.Context) {
if len(ctx.Args()) != 1 {
cli.ShowCommandHelpAndExit(ctx, "stop", 1) // last argument is exit code
}
}
// moveFile - os.Rename cannot handle cross device renames, in our situation
// it is possible that /tmp is mounted from a separate partition and current
// working directory is a different partition. To allow all situations to
// be handled appropriately use this function instead of os.Rename()
func moveFile(sourcePath, destPath string) error {
inputFile, err := os.Open(sourcePath)
if err != nil {
return err
}
outputFile, err := os.Create(destPath)
if err != nil {
inputFile.Close()
return err
}
defer outputFile.Close()
_, err = io.Copy(outputFile, inputFile)
inputFile.Close()
if err != nil {
return err
}
// The copy was successful, so now delete the original file
return os.Remove(sourcePath)
}
// mainAdminProfileStop - the entry function of profile stop command
func mainAdminProfileStop(ctx *cli.Context) error {
// Check for command syntax
checkAdminProfileStopSyntax(ctx)
// Get the alias parameter from cli
args := ctx.Args()
aliasedURL := args.Get(0)
// Create a new MinIO Admin Client
client, err := newAdminClient(aliasedURL)
if err != nil {
fatalIf(err.Trace(aliasedURL), "Cannot initialize admin client.")
return nil
}
// Create profile zip file
tmpFile, e := ioutil.TempFile("", "mc-profile-")
fatalIf(probe.NewError(e), "Unable to download profile data.")
// Ask for profile data, which will come compressed with zip format
zippedData, adminErr := client.DownloadProfilingData(globalContext)
fatalIf(probe.NewError(adminErr), "Unable to download profile data.")
// Copy zip content to target download file
_, e = io.Copy(tmpFile, zippedData)
fatalIf(probe.NewError(e), "Unable to download profile data.")
// Close everything
zippedData.Close()
tmpFile.Close()
downloadPath := "profile.zip"
fi, e := os.Stat(downloadPath)
if e == nil && !fi.IsDir() {
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) {
fatal(probe.NewError(e), "Unable to download profile data.")
}
}
fatalIf(probe.NewError(moveFile(tmpFile.Name(), downloadPath)), "Unable to download profile data.")
console.Infof("Profile data successfully downloaded as %s\n", downloadPath)
return nil
}
+39
View File
@@ -0,0 +1,39 @@
/*
* 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.
* 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 adminProfileCmd = cli.Command{
Name: "profile",
Usage: "generate profile data for debugging purposes",
Action: mainAdminProfile,
Flags: globalFlags,
Subcommands: []cli.Command{
adminProfileStartCmd,
adminProfileStopCmd,
},
HideHelpCommand: true,
}
// mainAdminProfile is the handle for "mc admin profile" command.
func mainAdminProfile(ctx *cli.Context) error {
cli.ShowCommandHelp(ctx, ctx.Args().First())
return nil
}
+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
}
+46
View File
@@ -0,0 +1,46 @@
/*
* 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 adminPrometheusCmd = cli.Command{
Name: "prometheus",
Usage: "manages prometheus config",
Action: mainAdminPrometheus,
Flags: globalFlags,
HideHelpCommand: true,
Subcommands: []cli.Command{
adminPrometheusGenerateCmd,
},
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} TARGET
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
`,
}
// mainAdminPrometheus is the handle for "mc admin prometheus" command.
func mainAdminPrometheus(ctx *cli.Context) error {
cli.ShowCommandHelp(ctx, ctx.Args().First())
return nil
}
+137
View File
@@ -0,0 +1,137 @@
/*
* MinIO Client (C) 2016 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 (
"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"
)
var adminServiceRestartCmd = cli.Command{
Name: "restart",
Usage: "restart all MinIO servers",
Action: mainAdminServiceRestart,
Before: initBeforeRunningCmd,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} TARGET
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Restart MinIO server represented by its alias 'play'.
{{.Prompt}} {{.HelpName}} play/
`,
}
// serviceRestartCommand is container for service restart command success and failure messages.
type serviceRestartCommand struct {
Status string `json:"status"`
ServerURL string `json:"serverURL"`
}
// String colorized service restart command message.
func (s serviceRestartCommand) String() string {
return console.Colorize("ServiceRestart", "Restart command successfully sent to `"+s.ServerURL+"`.")
}
// JSON jsonified service restart command message.
func (s serviceRestartCommand) JSON() string {
serviceRestartJSONBytes, e := json.MarshalIndent(s, "", " ")
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
return string(serviceRestartJSONBytes)
}
// serviceRestartMessage is container for service restart success and failure messages.
type serviceRestartMessage struct {
Status string `json:"status"`
ServerURL string `json:"serverURL"`
Err error `json:"error,omitempty"`
}
// String colorized service restart message.
func (s serviceRestartMessage) String() string {
if s.Err == nil {
return console.Colorize("ServiceRestart", "Restarted `"+s.ServerURL+"` successfully.")
}
return console.Colorize("FailedServiceRestart", "Failed to restart `"+s.ServerURL+"`. error: "+s.Err.Error())
}
// JSON jsonified service restart message.
func (s serviceRestartMessage) JSON() string {
serviceRestartJSONBytes, e := json.MarshalIndent(s, "", " ")
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
return string(serviceRestartJSONBytes)
}
// checkAdminServiceRestartSyntax - validate all the passed arguments
func checkAdminServiceRestartSyntax(ctx *cli.Context) {
if len(ctx.Args()) == 0 || len(ctx.Args()) > 2 {
cli.ShowCommandHelpAndExit(ctx, "restart", 1) // last argument is exit code
}
}
func mainAdminServiceRestart(ctx *cli.Context) error {
// Validate serivce restart syntax.
checkAdminServiceRestartSyntax(ctx)
// Set color.
console.SetColor("ServiceRestart", color.New(color.FgGreen, color.Bold))
console.SetColor("FailedServiceRestart", color.New(color.FgRed, 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.")
// Restart the specified MinIO server
fatalIf(probe.NewError(client.ServiceRestart(globalContext)), "Cannot restart the server.")
// Success..
printMsg(serviceRestartCommand{Status: "success", ServerURL: aliasedURL})
// Max. time taken by the server to shutdown is 5 seconds.
// This can happen when there are lot of s3 requests pending when the server
// receives a restart command.
// Sleep for 6 seconds and then check if the server is online.
time.Sleep(6 * time.Second)
// Fetch the service status of the specified MinIO server
_, e := client.ServerInfo(globalContext)
if e != nil {
printMsg(serviceRestartMessage{Status: "failure", Err: e, ServerURL: aliasedURL})
} else {
printMsg(serviceRestartMessage{Status: "success", ServerURL: aliasedURL})
}
return nil
}
+95
View File
@@ -0,0 +1,95 @@
/*
* 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 (
"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 adminServiceStopCmd = cli.Command{
Name: "stop",
Usage: "stop MinIO server",
Action: mainAdminServiceStop,
Before: initBeforeRunningCmd,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} TARGET
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Stop MinIO server represented by its alias 'play'.
{{.Prompt}} {{.HelpName}} play/
`,
}
// serviceStopMessage is container for make bucket success and failure messages.
type serviceStopMessage struct {
Status string `json:"status"`
ServerURL string `json:"serverURL"`
}
// String colorized make bucket message.
func (s serviceStopMessage) String() string {
return console.Colorize("ServiceStop", "Stopped `"+s.ServerURL+"` successfully.")
}
// JSON jsonified make bucket message.
func (s serviceStopMessage) JSON() string {
serviceStopJSONBytes, e := json.MarshalIndent(s, "", " ")
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
return string(serviceStopJSONBytes)
}
// checkAdminServiceStopSyntax - validate all the passed arguments
func checkAdminServiceStopSyntax(ctx *cli.Context) {
if len(ctx.Args()) == 0 || len(ctx.Args()) > 2 {
cli.ShowCommandHelpAndExit(ctx, "stop", 1) // last argument is exit code
}
}
func mainAdminServiceStop(ctx *cli.Context) error {
// Validate serivce stop syntax.
checkAdminServiceStopSyntax(ctx)
// Set color.
console.SetColor("ServiceStop", 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.")
// Stop the specified MinIO server
fatalIf(probe.NewError(client.ServiceStop(globalContext)), "Unable to stop the server.")
// Success..
printMsg(serviceStopMessage{Status: "success", ServerURL: aliasedURL})
return nil
}
+38
View File
@@ -0,0 +1,38 @@
/*
* MinIO Client (C) 2016, 2017, 2018 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 adminServiceCmd = cli.Command{
Name: "service",
Usage: "restart and stop all MinIO servers",
Action: mainAdminService,
Flags: globalFlags,
HideHelpCommand: true,
Subcommands: []cli.Command{
adminServiceRestartCmd,
adminServiceStopCmd,
},
}
// mainAdmin is the handle for "mc admin service" command.
func mainAdminService(ctx *cli.Context) error {
cli.ShowCommandHelp(ctx, ctx.Args().First())
return nil
// Sub-commands like "status", "restart" have their own main.
}
+150
View File
@@ -0,0 +1,150 @@
/*
* 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"
"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"
)
var adminTopLocksCmd = cli.Command{
Name: "locks",
Usage: "Get a list of the 10 oldest locks on a MinIO cluster.",
Before: initBeforeRunningCmd,
Action: mainAdminTopLocks,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} TARGET
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Get a list of the 10 oldest locks on a MinIO cluster.
{{.Prompt}} {{.HelpName}} myminio/
`,
}
// lockMessage struct to list lock information.
type lockMessage struct {
Status string `json:"status"`
Lock madmin.LockEntry `json:"locks"`
}
func getTimeDiff(timeStamp time.Time) (string, string) {
now := time.Now().UTC()
diff := now.Sub(timeStamp)
hours := int(diff.Hours())
minutes := int(diff.Minutes()) % 60
seconds := int(diff.Seconds()) % 60
if hours == 0 {
if minutes == 0 {
return "Lock", fmt.Sprint(seconds, " seconds")
}
return "Lock", fmt.Sprint(minutes, " minutes")
}
return "StaleLock", fmt.Sprint(hours, " hours")
}
// String colorized oldest locks message.
func (u lockMessage) String() string {
timeFieldMaxLen := 20
resourceFieldMaxLen := -1
typeFieldMaxLen := 6
ownerFieldMaxLen := 20
lockState, timeDiff := getTimeDiff(u.Lock.Timestamp)
return console.Colorize(lockState, newPrettyTable(" ",
Field{"Time", timeFieldMaxLen},
Field{"Type", typeFieldMaxLen},
Field{"Owner", ownerFieldMaxLen},
Field{"Resource", resourceFieldMaxLen},
).buildRow(timeDiff, u.Lock.Type, u.Lock.Owner, u.Lock.Resource))
}
// JSON jsonified top oldest locks message.
func (u lockMessage) JSON() string {
u.Status = "success"
statusJSONBytes, e := json.MarshalIndent(u, "", " ")
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
return string(statusJSONBytes)
}
// checkAdminTopLocksSyntax - validate all the passed arguments
func checkAdminTopLocksSyntax(ctx *cli.Context) {
if len(ctx.Args()) == 0 || len(ctx.Args()) > 1 {
cli.ShowCommandHelpAndExit(ctx, "locks", 1) // last argument is exit code
}
}
func mainAdminTopLocks(ctx *cli.Context) error {
checkAdminTopLocksSyntax(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.")
// Call top locks API
entries, e := client.TopLocks(globalContext)
fatalIf(probe.NewError(e), "Cannot get server locks list.")
console.SetColor("StaleLock", color.New(color.FgRed, color.Bold))
console.SetColor("Lock", color.New(color.FgBlue, color.Bold))
console.SetColor("Headers", color.New(color.FgGreen, color.Bold))
// Print
printLocks(entries)
return nil
}
func printHeaders() {
timeFieldMaxLen := 20
resourceFieldMaxLen := -1
typeFieldMaxLen := 6
ownerFieldMaxLen := 20
console.Println(console.Colorize("Headers", newPrettyTable(" ",
Field{"Time", timeFieldMaxLen},
Field{"Type", typeFieldMaxLen},
Field{"Owner", ownerFieldMaxLen},
Field{"Resource", resourceFieldMaxLen},
).buildRow("Time", "Type", "Owner", "Resource")))
}
// Prints oldest locks.
func printLocks(locks madmin.LockEntries) {
if !globalJSON {
printHeaders()
}
for _, entry := range locks {
printMsg(lockMessage{Lock: entry})
}
}
+37
View File
@@ -0,0 +1,37 @@
/*
* 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 adminTopCmd = cli.Command{
Name: "top",
Usage: "provide top like statistics for MinIO",
Action: mainAdminTop,
Flags: globalFlags,
Subcommands: []cli.Command{
adminTopLocksCmd,
},
HideHelpCommand: true,
}
// mainAdminTop is the handle for "mc admin top" command.
func mainAdminTop(ctx *cli.Context) error {
cli.ShowCommandHelp(ctx, ctx.Args().First())
return nil
// Sub-commands like "locks" have their own main.
}
+353
View File
@@ -0,0 +1,353 @@
/*
* 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 (
"bytes"
"context"
"fmt"
"hash/fnv"
"net/http"
"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/probe"
"github.com/minio/minio/pkg/console"
"github.com/minio/minio/pkg/madmin"
)
var adminTraceFlags = []cli.Flag{
cli.BoolFlag{
Name: "verbose, v",
Usage: "print verbose trace",
},
cli.BoolFlag{
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",
Action: mainAdminTrace,
Before: initBeforeRunningCmd,
Flags: append(adminTraceFlags, globalFlags...),
HideHelpCommand: true,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} [FLAGS] TARGET
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
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.000"
var (
colors = []color.Attribute{color.FgCyan, color.FgWhite, color.FgYellow, color.FgGreen}
)
func checkAdminTraceSyntax(ctx *cli.Context) {
if len(ctx.Args()) != 1 {
cli.ShowCommandHelpAndExit(ctx, "trace", 1) // last argument is exit code
}
}
// mainAdminTrace - the entry function of trace command
func mainAdminTrace(ctx *cli.Context) error {
// Check for command syntax
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))
console.SetColor("FuncName", color.New(color.Bold, color.FgGreen))
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("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
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 trace activity.
traceCh := client.ServiceTrace(ctxt, all, errfltr)
for traceInfo := range traceCh {
if traceInfo.Err != nil {
fatalIf(probe.NewError(traceInfo.Err), "Cannot listen to http trace")
}
if verbose {
printMsg(traceMessage{traceInfo})
continue
}
printMsg(shortTrace(traceInfo))
}
return nil
}
// Short trace record
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"`
}
type traceMessage struct {
madmin.ServiceTraceInfo
}
type requestInfo struct {
Time time.Time `json:"time"`
Method string `json:"method"`
Path string `json:"path,omitempty"`
RawQuery string `json:"rawQuery,omitempty"`
Headers map[string]string `json:"headers,omitempty"`
Body string `json:"body,omitempty"`
}
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"`
}
type callStats struct {
Rx int `json:"rx"`
Tx int `json:"tx"`
Duration time.Duration `json:"duration"`
Ttfb time.Duration `json:"timeToFirstByte"`
}
type trace struct {
NodeName string `json:"host"`
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.ServiceTraceInfo) shortTraceMsg {
s := shortTraceMsg{}
t := ti.Trace
s.Time = t.ReqInfo.Time
if host, ok := t.ReqInfo.Headers["Host"]; ok {
s.Host = strings.Join(host, "")
}
s.Path = t.ReqInfo.Path
s.Query = t.ReqInfo.RawQuery
s.FuncName = t.FuncName
s.StatusCode = t.RespInfo.StatusCode
s.StatusMsg = http.StatusText(t.RespInfo.StatusCode)
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 {
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 {
var hostStr string
var b = &strings.Builder{}
if s.Host != "" {
hostStr = colorizedNodeName(s.Host)
}
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.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()
}
// colorize node name
func colorizedNodeName(nodeName string) string {
nodeHash := fnv.New32a()
nodeHash.Write([]byte(nodeName))
nHashSum := nodeHash.Sum32()
idx := uint32(nHashSum) % uint32(len(colors))
return console.Colorize(fmt.Sprintf("Node%d", colors[idx]), nodeName)
}
func (t traceMessage) JSON() string {
rqHdrs := make(map[string]string)
rspHdrs := make(map[string]string)
rq := t.Trace.ReqInfo
rs := t.Trace.RespInfo
for k, v := range rq.Headers {
rqHdrs[k] = strings.Join(v, " ")
}
for k, v := range rs.Headers {
rspHdrs[k] = strings.Join(v, " ")
}
trc := trace{
NodeName: t.Trace.NodeName,
FuncName: t.Trace.FuncName,
RequestInfo: requestInfo{
Time: rq.Time,
Method: rq.Method,
Path: rq.Path,
RawQuery: rq.RawQuery,
Body: string(rq.Body),
Headers: rqHdrs,
},
ResponseInfo: responseInfo{
Time: rs.Time,
Body: string(rs.Body),
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)
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")
}
func (t traceMessage) String() string {
var nodeNameStr string
var b = &strings.Builder{}
trc := t.Trace
if trc.NodeName != "" {
nodeNameStr = fmt.Sprintf("%s ", colorizedNodeName(trc.NodeName))
}
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%s", nodeNameStr, console.Colorize("Method", fmt.Sprintf("%s %s", ri.Method, ri.Path)))
if ri.RawQuery != "" {
fmt.Fprintf(b, "?%s", ri.RawQuery)
}
fmt.Fprint(b, "\n")
host, ok := ri.Headers["Host"]
if ok {
delete(ri.Headers, "Host")
}
hostStr := strings.Join(host, "")
fmt.Fprintf(b, "%s%s", nodeNameStr, console.Colorize("Host", fmt.Sprintf("Host: %s\n", hostStr)))
for k, v := range ri.Headers {
fmt.Fprintf(b, "%s%s", nodeNameStr, console.Colorize("ReqHeaderKey",
fmt.Sprintf("%s: ", k))+console.Colorize("HeaderValue", fmt.Sprintf("%s\n", strings.Join(v, ""))))
}
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", "[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, ""))))
}
fmt.Fprintf(b, "%s%s\n", nodeNameStr, console.Colorize("Body", string(rs.Body)))
fmt.Fprint(b, nodeNameStr)
return b.String()
}
+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
}
+193
View File
@@ -0,0 +1,193 @@
/*
* MinIO Client (C) 2018 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 (
"bufio"
"fmt"
"os"
"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"
"golang.org/x/crypto/ssh/terminal"
)
var adminUserAddCmd = cli.Command{
Name: "add",
Usage: "add a new user",
Action: mainAdminUserAdd,
Before: initBeforeRunningCmd,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} TARGET ACCESSKEY SECRETKEY
ACCESSKEY:
Also called as username.
SECRETKEY:
Also called as password.
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
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) {
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"` // 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 {
switch u.op {
case "list":
userFieldMaxLen := 9
accessFieldMaxLen := 20
policyFieldMaxLen := 20
// Create a new pretty table with cols configuration
return newPrettyTable(" ",
Field{"UserStatus", userFieldMaxLen},
Field{"AccessKey", accessFieldMaxLen},
Field{"PolicyName", policyFieldMaxLen},
).buildRow(u.UserStatus, u.AccessKey, u.PolicyName)
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":
return console.Colorize("UserMessage", "Disabled user `"+u.AccessKey+"` successfully.")
case "enable":
return console.Colorize("UserMessage", "Enabled user `"+u.AccessKey+"` successfully.")
case "add":
return console.Colorize("UserMessage", "Added user `"+u.AccessKey+"` successfully.")
}
return ""
}
func (u userMessage) JSON() string {
u.Status = "success"
jsonMessageBytes, e := json.MarshalIndent(u, "", " ")
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
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)
console.SetColor("UserMessage", color.New(color.FgGreen))
// Get the alias parameter from cli
args := ctx.Args()
aliasedURL := args.Get(0)
accessKey, secretKey := fetchUserKeys(args)
// Create a new MinIO Admin Client
client, err := newAdminClient(aliasedURL)
fatalIf(err, "Unable to initialize admin connection.")
fatalIf(probe.NewError(client.AddUser(globalContext, accessKey, secretKey)).Trace(args...), "Cannot add new user")
printMsg(userMessage{
op: "add",
AccessKey: accessKey,
SecretKey: secretKey,
UserStatus: "enabled",
})
return nil
}
+78
View File
@@ -0,0 +1,78 @@
/*
* MinIO Client (C) 2018 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 adminUserDisableCmd = cli.Command{
Name: "disable",
Usage: "disable user",
Action: mainAdminUserDisable,
Before: initBeforeRunningCmd,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} TARGET USERNAME
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Disable a user 'foobar' on MinIO server.
{{.Prompt}} {{.HelpName}} myminio foobar
`,
}
// checkAdminUserDisableSyntax - validate all the passed arguments
func checkAdminUserDisableSyntax(ctx *cli.Context) {
if len(ctx.Args()) != 2 {
cli.ShowCommandHelpAndExit(ctx, "disable", 1) // last argument is exit code
}
}
// mainAdminUserDisable is the handle for "mc admin user disable" command.
func mainAdminUserDisable(ctx *cli.Context) error {
checkAdminUserDisableSyntax(ctx)
console.SetColor("UserMessage", 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.")
e := client.SetUserStatus(globalContext, args.Get(1), madmin.AccountDisabled)
fatalIf(probe.NewError(e).Trace(args...), "Cannot disable user")
printMsg(userMessage{
op: "disable",
AccessKey: args.Get(1),
})
return nil
}
+78
View File
@@ -0,0 +1,78 @@
/*
* MinIO Client (C) 2018 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 adminUserEnableCmd = cli.Command{
Name: "enable",
Usage: "enable user",
Action: mainAdminUserEnable,
Before: initBeforeRunningCmd,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} TARGET USERNAME
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Enable a disabled user 'foobar' on MinIO server.
{{.Prompt}} {{.HelpName}} myminio foobar
`,
}
// checkAdminUserEnableSyntax - validate all the passed arguments
func checkAdminUserEnableSyntax(ctx *cli.Context) {
if len(ctx.Args()) != 2 {
cli.ShowCommandHelpAndExit(ctx, "enable", 1) // last argument is exit code
}
}
// mainAdminUserEnable is the handle for "mc admin user enable" command.
func mainAdminUserEnable(ctx *cli.Context) error {
checkAdminUserEnableSyntax(ctx)
console.SetColor("UserMessage", 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.")
e := client.SetUserStatus(globalContext, args.Get(1), madmin.AccountEnabled)
fatalIf(probe.NewError(e).Trace(args...), "Cannot enable user")
printMsg(userMessage{
op: "enable",
AccessKey: args.Get(1),
})
return nil
}
+80
View File
@@ -0,0 +1,80 @@
/*
* MinIO Client (C) 2018 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 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
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Display the info of a user "foobar".
{{.Prompt}} {{.HelpName}} myminio foobar
`,
}
// 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
}
}
// 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))
// 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.")
user, e := client.GetUserInfo(globalContext, args.Get(1))
fatalIf(probe.NewError(e).Trace(args...), "Cannot get user info")
printMsg(userMessage{
op: "info",
AccessKey: args.Get(1),
PolicyName: user.PolicyName,
UserStatus: string(user.Status),
MemberOf: user.MemberOf,
})
return nil
}
+84
View File
@@ -0,0 +1,84 @@
/*
* MinIO Client (C) 2018 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 adminUserListCmd = cli.Command{
Name: "list",
Usage: "list all users",
Action: mainAdminUserList,
Before: initBeforeRunningCmd,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} TARGET
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. List all users on MinIO server.
{{.Prompt}} {{.HelpName}} myminio
`,
}
// checkAdminUserListSyntax - validate all the passed arguments
func checkAdminUserListSyntax(ctx *cli.Context) {
if len(ctx.Args()) != 1 {
cli.ShowCommandHelpAndExit(ctx, "list", 1) // last argument is exit code
}
}
// mainAdminUserList is the handle for "mc admin user list" command.
func mainAdminUserList(ctx *cli.Context) error {
checkAdminUserListSyntax(ctx)
// Additional command speific theme customization.
console.SetColor("UserMessage", color.New(color.FgGreen))
console.SetColor("AccessKey", color.New(color.FgBlue))
console.SetColor("PolicyName", color.New(color.FgYellow))
console.SetColor("UserStatus", color.New(color.FgCyan))
// 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.")
users, e := client.ListUsers(globalContext)
fatalIf(probe.NewError(e).Trace(args...), "Cannot list user")
for k, v := range users {
printMsg(userMessage{
op: "list",
AccessKey: k,
PolicyName: v.PolicyName,
UserStatus: string(v.Status),
})
}
return nil
}
+77
View File
@@ -0,0 +1,77 @@
/*
* MinIO Client (C) 2018 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 adminUserRemoveCmd = cli.Command{
Name: "remove",
Usage: "remove user",
Action: mainAdminUserRemove,
Before: initBeforeRunningCmd,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} TARGET USERNAME
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Remove a user 'foobar' on MinIO server.
{{.Prompt}} {{.HelpName}} myminio foobar
`,
}
// checkAdminUserRemoveSyntax - validate all the passed arguments
func checkAdminUserRemoveSyntax(ctx *cli.Context) {
if len(ctx.Args()) != 2 {
cli.ShowCommandHelpAndExit(ctx, "remove", 1) // last argument is exit code
}
}
// mainAdminUserRemove is the handle for "mc admin user remove" command.
func mainAdminUserRemove(ctx *cli.Context) error {
checkAdminUserRemoveSyntax(ctx)
console.SetColor("UserMessage", 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.")
e := client.RemoveUser(globalContext, args.Get(1))
fatalIf(probe.NewError(e).Trace(args...), "Cannot remove %s", args.Get(1))
printMsg(userMessage{
op: "remove",
AccessKey: args.Get(1),
})
return nil
}
+42
View File
@@ -0,0 +1,42 @@
/*
* MinIO Client (C) 2018 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 adminUserCmd = cli.Command{
Name: "user",
Usage: "manage users",
Action: mainAdminUser,
Flags: globalFlags,
Subcommands: []cli.Command{
adminUserAddCmd,
adminUserDisableCmd,
adminUserEnableCmd,
adminUserRemoveCmd,
adminUserListCmd,
adminUserInfoCmd,
},
HideHelpCommand: true,
}
// mainAdminUser is the handle for "mc admin config" command.
func mainAdminUser(ctx *cli.Context) error {
cli.ShowCommandHelp(ctx, ctx.Args().First())
return nil
// Sub-commands like "get", "set" have their own main.
}
+367
View File
@@ -0,0 +1,367 @@
/*
* 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 (
"os"
"path/filepath"
"sort"
"strings"
"github.com/minio/cli"
"github.com/posener/complete"
)
// fsComplete knows how to complete file/dir names by the given path
type fsComplete struct{}
// 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)
func completeS3Path(s3Path string) (prediction []string) {
// Convert alias/bucket/incompl to alias/bucket/ to list its contents
parentDirPath := filepath.Dir(s3Path) + "/"
clnt, err := newClient(parentDirPath)
if err != nil {
return nil
}
// Calculate alias from the path
alias := splitStr(s3Path, "/", 3)[0]
// List dirPath content and only pick elements that corresponds
// to the path that we want to complete
for content := range clnt.List(globalContext, false, false, false, DirFirst) {
cmplS3Path := alias + getKey(content)
if content.Type.IsDir() {
if !strings.HasSuffix(cmplS3Path, "/") {
cmplS3Path += "/"
}
}
if strings.HasPrefix(cmplS3Path, s3Path) {
prediction = append(prediction, cmplS3Path)
}
}
// If completion found only one directory, recursively scan it.
if len(prediction) == 1 && strings.HasSuffix(prediction[0], "/") {
prediction = append(prediction, completeS3Path(prediction[0])...)
}
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
}
func (s3 s3Complete) Predict(a complete.Args) (prediction []string) {
defer func() {
sort.Strings(prediction)
}()
loadMcConfig = loadMcConfigFactory()
conf, err := loadMcConfig()
if err != nil {
return nil
}
arg := a.Last
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+"/")
}
}
if len(prediction) == 1 && strings.HasSuffix(prediction[0], "/") {
prediction = append(prediction, completeS3Path(prediction[0])...)
}
} else {
// Complete S3 path until the specified path deep level
if s3.deepLevel > 0 {
if strings.Count(arg, "/") >= s3.deepLevel {
return []string{arg}
}
}
// Predict S3 path
prediction = completeS3Path(arg)
}
return
}
// aliasComplete only completes aliases
type aliasComplete struct{}
func (al aliasComplete) Predict(a complete.Args) (prediction []string) {
defer func() {
sort.Strings(prediction)
}()
loadMcConfig = loadMcConfigFactory()
conf, err := loadMcConfig()
if err != nil {
return nil
}
arg := a.Last
for alias := range conf.Hosts {
if strings.HasPrefix(alias, arg) {
prediction = append(prediction, alias+"/")
}
}
return
}
var adminConfigCompleter = adminConfigComplete{}
var s3Completer = s3Complete{}
var aliasCompleter = aliasComplete{}
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{
// 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,
"/tag/list": s3Completer,
"/tag/remove": s3Completer,
"/tag/set": s3Completer,
"/share/download": s3Completer,
"/share/list": 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,
"/config/host/remove": aliasCompleter,
"/update": nil,
"/version": nil,
}
// flagsToCompleteFlags transforms a cli.Flag to complete.Flags
// understood by posener/complete library.
func flagsToCompleteFlags(flags []cli.Flag) complete.Flags {
var complFlags = make(complete.Flags)
for _, f := range flags {
for _, s := range strings.Split(f.GetName(), ",") {
var flagName string
s = strings.TrimSpace(s)
if len(s) == 1 {
flagName = "-" + s
} else {
flagName = "--" + s
}
complFlags[flagName] = complete.PredictNothing
}
}
return complFlags
}
// This function recursively transforms cli.Command to complete.Command
// understood by posener/complete library.
func cmdToCompleteCmd(cmd cli.Command, parentPath string) complete.Command {
var complCmd complete.Command
complCmd.Sub = make(complete.Commands)
for _, subCmd := range cmd.Subcommands {
complCmd.Sub[subCmd.Name] = cmdToCompleteCmd(subCmd, parentPath+"/"+cmd.Name)
}
complCmd.Flags = flagsToCompleteFlags(cmd.Flags)
complCmd.Args = completeCmds[parentPath+"/"+cmd.Name]
return complCmd
}
// Main function to answer to bash completion calls
func mainComplete() error {
// Recursively register all commands and subcommands
// along with global and local flags
var complCmds = make(complete.Commands)
for _, cmd := range appCmds {
complCmds[cmd.Name] = cmdToCompleteCmd(cmd, "")
}
complFlags := flagsToCompleteFlags(globalFlags)
mcComplete := complete.Command{
Sub: complCmds,
GlobalFlags: complFlags,
}
// Answer to bash completion call
complete.New(filepath.Base(os.Args[0]), mcComplete).Run()
return nil
}
+10 -10
View File
@@ -1,5 +1,5 @@
/*
* Minio Client (C) 2014, 2015 Minio, Inc.
* MinIO Client (C) 2014, 2015 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -14,15 +14,15 @@
* limitations under the License.
*/
package main
package cmd
var (
// mcVersion - version time.RFC3339.
mcVersion = "UNOFFICIAL.GOGET"
// mcReleaseTag - release tag in TAG.%Y-%m-%dT%H-%M-%SZ.
mcReleaseTag = "UNOFFICIAL.GOGET"
// mcCommitID - latest commit id.
mcCommitID = "UNOFFICIAL.GOGET"
// mcShortCommitID - first 12 characters from mcCommitID.
mcShortCommitID = mcCommitID[:12]
// Version - version time.RFC3339.
Version = "DEVELOPMENT.GOGET"
// ReleaseTag - release tag in TAG.%Y-%m-%dT%H-%M-%SZ.
ReleaseTag = "DEVELOPMENT.GOGET"
// CommitID - latest commit id.
CommitID = "DEVELOPMENT.GOGET"
// ShortCommitID - first 12 characters from CommitID.
ShortCommitID = CommitID[:12]
)
+255
View File
@@ -0,0 +1,255 @@
/*
* MinIO Client, (C) 2015, 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 (
"bytes"
"context"
"errors"
"fmt"
"io"
"os"
"strings"
"syscall"
"unicode"
"unicode/utf8"
"github.com/minio/cli"
"github.com/minio/mc/pkg/probe"
)
var (
// This is kept dummy for future purposes
// and also to add ioFlags and globalFlags
// in CLI registration.
catFlags = []cli.Flag{}
)
// Display contents of a file.
var catCmd = cli.Command{
Name: "cat",
Usage: "display object contents",
Action: mainCat,
Before: initBeforeRunningCmd,
Flags: append(append(catFlags, ioFlags...), globalFlags...),
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} [FLAGS] SOURCE [SOURCE...]
{{if .VisibleFlags}}
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}{{end}}
ENVIRONMENT VARIABLES:
MC_ENCRYPT_KEY: list of comma delimited prefix=secret values
EXAMPLES:
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.
{{.Prompt}} {{.HelpName}} file1.txt - > file.txt
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.
{{.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
`,
}
// prettyStdout replaces some non printable characters
// with <hex> format to be better viewable by the user
type prettyStdout struct {
// Internal data to pretty-print
writer io.Writer
// Internal buffer which contains pretty printed
// form of binary (no printable) characters
buffer *bytes.Buffer
}
// newPrettyStdout returns an initialized prettyStdout struct
func newPrettyStdout(w io.Writer) *prettyStdout {
return &prettyStdout{
writer: w,
buffer: bytes.NewBuffer([]byte{}),
}
}
// Read() returns pretty printed binary characters
func (s prettyStdout) Write(input []byte) (int, error) {
inputLen := len(input)
// Convert no printable characters to '^?'
// and fill into s.buffer
for len(input) > 0 {
r, size := utf8.DecodeRune(input)
if unicode.IsPrint(r) || unicode.IsSpace(r) {
s.buffer.WriteRune(r)
} else {
s.buffer.WriteString("^?")
}
input = input[size:]
}
bufLen := s.buffer.Len()
// Copy all buffer content to the writer (stdout)
n, err := s.buffer.WriteTo(s.writer)
if err != nil {
return 0, err
}
if int(n) != bufLen {
return 0, errors.New("error when writing to stdout")
}
return inputLen, nil
}
// checkCatSyntax performs command-line input validation for cat command.
func checkCatSyntax(ctx *cli.Context) {
args := ctx.Args()
if !args.Present() {
args = []string{"-"}
}
for _, arg := range args {
if strings.HasPrefix(arg, "-") && len(arg) > 1 {
fatalIf(probe.NewError(errors.New("")), fmt.Sprintf("Unknown flag `%s` passed.", arg))
}
}
}
// catURL displays contents of a URL to stdout.
func catURL(ctx context.Context, sourceURL string, encKeyDB map[string][]prefixSSEPair) *probe.Error {
var reader io.ReadCloser
size := int64(-1)
switch sourceURL {
case "-":
reader = os.Stdin
default:
var err *probe.Error
// Try to stat the object, the purpose is to extract the
// size of S3 object so we can check if the size of the
// 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(ctx, sourceURL, false, encKeyDB)
if err == nil && client.GetURL().Type == objectStorage {
size = content.Size
}
if reader, err = getSourceStreamFromURL(ctx, sourceURL, encKeyDB); err != nil {
return err.Trace(sourceURL)
}
defer reader.Close()
}
return catOut(reader, size).Trace(sourceURL)
}
// catOut reads from reader stream and writes to stdout. Also check the length of the
// read bytes against size parameter (if not -1) and return the appropriate error
func catOut(r io.Reader, size int64) *probe.Error {
var n int64
var e error
var stdout io.Writer
// 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 isTerminal() {
stdout = newPrettyStdout(os.Stdout)
} else {
stdout = os.Stdout
}
// Read till EOF.
if n, e = io.Copy(stdout, r); e != nil {
switch e := e.(type) {
case *os.PathError:
if e.Err == syscall.EPIPE {
// stdout closed by the user. Gracefully exit.
return nil
}
return probe.NewError(e)
default:
return probe.NewError(e)
}
}
if size != -1 && n < size {
return probe.NewError(UnexpectedEOF{
TotalSize: size,
TotalWritten: n,
})
}
if size != -1 && n > size {
return probe.NewError(UnexpectedEOF{
TotalSize: size,
TotalWritten: n,
})
}
return nil
}
// mainCat is the main entry point for cat command.
func mainCat(cliCtx *cli.Context) error {
ctx, cancelCat := context.WithCancel(globalContext)
defer cancelCat()
// Parse encryption keys per command.
encKeyDB, err := getEncKeys(cliCtx)
fatalIf(err, "Unable to parse encryption keys.")
// check 'cat' cli arguments.
checkCatSyntax(cliCtx)
// Set command flags from context.
stdinMode := false
if !cliCtx.Args().Present() {
stdinMode = true
}
// handle std input data.
if stdinMode {
fatalIf(catOut(os.Stdin, -1).Trace(), "Unable to read from standard input.")
return nil
}
// if Args contain `-`, we need to preserve its order specially.
args := []string(cliCtx.Args())
if cliCtx.Args().First() == "-" {
for i, arg := range os.Args {
if arg == "cat" {
// Overwrite cliCtx.Args with os.Args.
args = os.Args[i+1:]
break
}
}
}
// Convert arguments to URLs: expand alias, fix format.
for _, url := range args {
fatalIf(catURL(ctx, url, encKeyDB).Trace(url), "Unable to read from `"+url+"`.")
}
return nil
}
+64
View File
@@ -0,0 +1,64 @@
/*
* MinIO Client (C) 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 (
"bytes"
"io"
"io/ioutil"
"testing"
)
func TestPrettyStdout(t *testing.T) {
testCases := []struct {
originText string
prettyText string
}{
{"", ""},
{"text", "text"},
// Check with new lines
{"text\r\n", "text\r\n"},
{"\ttext\n", "\ttext\n"},
// Print some unicode characters and check if it is not altered
{"добро пожаловать.", "добро пожаловать."},
// Print colored text
{"\x1b\x5b\x33\x31\x6d\x66\x61\x69\x6c", "^?[31mfail"},
// Print clear screen
{"\x1b\x63", "^?c"},
// Random data
{"\x3d\xef\xd2\xb5", "=�ҵ"},
}
for i, testCase := range testCases {
reader := bytes.NewReader([]byte(testCase.originText))
fakeStdout := bytes.NewBuffer([]byte(""))
n, err := io.Copy(newPrettyStdout(fakeStdout), reader)
if err != nil {
t.Fatalf("Test %d: %v\n", i+1, err)
}
if int(n) != len(testCase.originText) {
t.Fatalf("Test %d: copy error\n", i+1)
}
prettyText, err := ioutil.ReadAll(fakeStdout)
if err != nil {
t.Fatalf("Test %d: %v", i+1, err)
}
if string(prettyText) != testCase.prettyText {
t.Fatalf("Test %d: expected output `%s`, found output `%s`", i+1, testCase.prettyText, string(prettyText))
}
}
}
+135
View File
@@ -0,0 +1,135 @@
/*
* MinIO Client (C) 2016 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 (
"crypto/x509"
"io/ioutil"
"os"
"path/filepath"
"github.com/minio/mc/pkg/probe"
)
// getCertsDir - return the full path of certs dir
func getCertsDir() (string, *probe.Error) {
p, err := getMcConfigDir()
if err != nil {
return "", err.Trace()
}
return filepath.Join(p, globalMCCertsDir), nil
}
// isCertsDirExists - verify if certs directory exists.
func isCertsDirExists() bool {
certsDir, err := getCertsDir()
fatalIf(err.Trace(), "Unable to determine certs folder.")
if _, e := os.Stat(certsDir); e != nil {
return false
}
return true
}
// createCertsDir - create MinIO Client certs folder
func createCertsDir() *probe.Error {
p, err := getCertsDir()
if err != nil {
return err.Trace()
}
if e := os.MkdirAll(p, 0700); e != nil {
return probe.NewError(e)
}
return nil
}
// getCAsDir - return the full path of CAs dir
func getCAsDir() (string, *probe.Error) {
p, err := getCertsDir()
if err != nil {
return "", err.Trace()
}
return filepath.Join(p, globalMCCAsDir), nil
}
// mustGetCAsDir - return the full path of CAs dir or empty string when an error occurs
func mustGetCAsDir() string {
p, err := getCAsDir()
if err != nil {
return ""
}
return p
}
// isCAsDirExists - verify if CAs directory exists.
func isCAsDirExists() bool {
CAsDir, err := getCAsDir()
fatalIf(err.Trace(), "Unable to determine CAs folder.")
if _, e := os.Stat(CAsDir); e != nil {
return false
}
return true
}
// createCAsDir - create MinIO Client CAs folder
func createCAsDir() *probe.Error {
p, err := getCAsDir()
if err != nil {
return err.Trace()
}
if e := os.MkdirAll(p, 0700); e != nil {
return probe.NewError(e)
}
return nil
}
// mustGetCAFiles - get the list of the CA certificates stored in MinIO config dir
func mustGetCAFiles() (caCerts []string) {
CAsDir := mustGetCAsDir()
caFiles, _ := ioutil.ReadDir(CAsDir)
for _, cert := range caFiles {
caCerts = append(caCerts, filepath.Join(CAsDir, cert.Name()))
}
return
}
// mustGetSystemCertPool - return system CAs or empty pool in case of error (or windows)
func mustGetSystemCertPool() *x509.CertPool {
pool, err := x509.SystemCertPool()
if err != nil {
return x509.NewCertPool()
}
return pool
}
// loadRootCAs fetches CA files provided in MinIO config and adds them to globalRootCAs
// Currently under Windows, there is no way to load system + user CAs at the same time
func loadRootCAs() {
caFiles := mustGetCAFiles()
if len(caFiles) == 0 {
return
}
// Get system cert pool, and empty cert pool under Windows because it is not supported
globalRootCAs = mustGetSystemCertPool()
// Load custom root CAs for client requests
for _, caFile := range caFiles {
caCert, err := ioutil.ReadFile(caFile)
if err != nil {
fatalIf(probe.NewError(err), "Unable to load a CA file.")
}
globalRootCAs.AppendCertsFromPEM(caCert)
}
}

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