Compare commits

..
Author SHA1 Message Date
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
409 changed files with 32151 additions and 32574 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
+9 -1
View File
@@ -1,4 +1,12 @@
cover.out
mc
*~
*.test
release
experimental
coverage.txt
*.tar.bz2
parts/
prime/
stage/
mc
.run*
+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>
+38 -20
View File
@@ -1,25 +1,43 @@
sudo: false
go_import_path: github.com/minio/mc
language: go
script:
- make test GOFLAGS="-race"
# this ensures PRs based on a local branch are not built twice
# the downside is that a PR targeting a different branch is not built
# but as a workaround you can add the branch to this list
branches:
only:
- master
os:
- linux
- osx
matrix:
include:
- os: linux
dist: trusty
env:
- ARCH=x86_64
- GO111MODULE=on
go: 1.12.1
script:
- diff -au <(gofmt -d *.go) <(printf "")
- diff -au <(gofmt -d cmd) <(printf "")
- diff -au <(gofmt -d pkg) <(printf "")
- for d in $(go list ./...); do go test -v -race "$d"; done
- make coverage
- make verifiers
- os: windows
env:
- ARCH=x86_64
- GO111MODULE=on
go: 1.12.1
script:
- go build --ldflags="$(go run buildscripts/gen-ldflags.go)" -o %GOPATH%\bin\mc.exe
- for d in $(go list ./...); do go test -v -race "$d"; done
- bash buildscripts/go-coverage.sh
env:
- ARCH=x86_64
- ARCH=i686
before_script:
# Add an IPv6 config - see the corresponding Travis issue
# https://github.com/travis-ci/travis-ci/issues/8361
- if [[ "${TRAVIS_OS_NAME}" == "linux" ]]; then sudo sh -c 'echo 0 > /proc/sys/net/ipv6/conf/all/disable_ipv6'; fi
go:
- 1.5.2
- 1.5.3
script:
- diff -au <(gofmt -d *.go) <(printf "")
- diff -au <(gofmt -d pkg) <(printf "")
notifications:
slack:
secure: McinxQ4R/Yu2r/U8lVsdAIQ195Rf+3/Ku6DViWyqLHsTt5fTnVrSfbIKs8vy0t2A0bRLO6zv2xOSMWjfiimZLPMgMbMqLtTFEzUzB8RZyx2n2xgmL8q3gjXcLA3vkBreaRYCzJzX6DjvrxRfhyOg+BQHpLpACWik3FS/7VIdDCI=
after_success:
- bash <(curl -s https://codecov.io/bash)
+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 dependencies 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>
+22
View File
@@ -0,0 +1,22 @@
FROM golang:1.12-alpine
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.9
COPY --from=0 /go/bin/mc /usr/bin/mc
RUN \
apk add --no-cache ca-certificates && \
echo 'hosts: files mdns4_minimal [NOTFOUND=return] dns mdns4' >> /etc/nsswitch.conf
ENTRYPOINT ["mc"]
+11
View File
@@ -0,0 +1,11 @@
FROM alpine:3.9
MAINTAINER MinIO Inc <dev@min.io>
RUN \
apk add --no-cache ca-certificates && \
apk add --no-cache --virtual .build-deps curl && \
curl https://dl.min.io/client/mc/release/linux-amd64/mc > /usr/bin/mc && \
chmod +x /usr/bin/mc && apk del .build-deps
ENTRYPOINT ["mc"]
-86
View File
@@ -1,86 +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
```
##### Source the new environment
```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 environment
```sh
$ source ~/.bash_profile
```
##### Testing it all
```sh
$ go env
```
+56 -64
View File
@@ -1,85 +1,77 @@
PWD := $(shell pwd)
GOPATH := $(shell go env GOPATH)
LDFLAGS := $(shell go run buildscripts/gen-ldflags.go)
BUILD_LDFLAGS := '$(LDFLAGS)'
all: install
all: build
checkdeps:
@echo "Checking deps:"
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 golint 1>/dev/null || (echo "Installing golint" && go get -u golang.org/x/lint/golint)
@which staticcheck 1>/dev/null || (echo "Installing staticcheck" && wget --quiet -O ${GOPATH}/bin/staticcheck https://github.com/dominikh/go-tools/releases/download/2019.1/staticcheck_linux_amd64 && chmod +x ${GOPATH}/bin/staticcheck)
@which misspell 1>/dev/null || (echo "Installing misspell" && wget --quiet https://github.com/client9/misspell/releases/download/v0.3.4/misspell_0.3.4_linux_64bit.tar.gz && tar xf misspell_0.3.4_linux_64bit.tar.gz && mv misspell ${GOPATH}/bin/misspell && chmod +x ${GOPATH}/bin/misspell && rm -f misspell_0.3.4_linux_64bit.tar.gz)
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 staticcheck spelling
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 $@"
@GO111MODULE=on ${GOPATH}/bin/golint -set_exit_status github.com/minio/mc/cmd/...
@GO111MODULE=on ${GOPATH}/bin/golint -set_exit_status github.com/minio/mc/pkg/...
cyclo:
@echo "Running $@:"
@GO15VENDOREXPERIMENT=1 gocyclo -over 40 *.go
@GO15VENDOREXPERIMENT=1 gocyclo -over 40 pkg
staticcheck:
@echo "Running $@"
@GO111MODULE=on ${GOPATH}/bin/staticcheck github.com/minio/mc/cmd/...
@GO111MODULE=on ${GOPATH}/bin/staticcheck github.com/minio/mc/pkg/...
deadcode:
@echo "Running $@:"
@GO15VENDOREXPERIMENT=1 deadcode
spelling:
@GO111MODULE=on ${GOPATH}/bin/misspell -locale US -error `find cmd/`
@GO111MODULE=on ${GOPATH}/bin/misspell -locale US -error `find pkg/`
@GO111MODULE=on ${GOPATH}/bin/misspell -locale US -error `find docs/`
build: verifiers
@echo "Installing mc:"
# 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)
test: verifiers
@echo "Running all testing:"
@GO15VENDOREXPERIMENT=1 go test $(GOFLAGS) ./
@GO15VENDOREXPERIMENT=1 go test $(GOFLAGS) github.com/minio/mc/pkg...
coverage: build
@echo "Running all coverage for MinIO"
@(env bash $(PWD)/buildscripts/go-coverage.sh)
gomake-all: build
@GO15VENDOREXPERIMENT=1 go build --ldflags $(BUILD_LDFLAGS) -o $(GOPATH)/bin/mc
@mkdir -p $(HOME)/.mc
# Builds mc locally.
build: checks
@echo "Building mc binary to './mc'"
@GO111MODULE=on GO_FLAGS="" CGO_ENABLED=0 go build -tags kqueue --ldflags $(BUILD_LDFLAGS) -o $(PWD)/mc
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, 2015 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.
+207 -86
View File
@@ -1,106 +1,227 @@
# 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
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)
#### GNU/Linux
Download ``mc`` for:
- ``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
~~~
$ chmod +x mc
$ ./mc --help
~~~
#### OS X
Download ``mc`` from https://dl.minio.io/client/mc/release/darwin-amd64/mc
~~~
$ chmod 755 mc
$ ./mc --help
~~~
#### Microsoft Windows
Download ``mc`` for:
- ``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
~~~
C:\Users\Username\Downloads> mc.exe --help
~~~
#### Source
<blockquote>
NOTE: Source installation is intended for only developers and advanced users. ‘mc update’ continuous 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).
```sh
$ GO15VENDOREXPERIMENT=1 go get -u github.com/minio/mc
## Docker Container
### Stable
```
docker pull minio/mc
docker run minio/mc ls play
```
## Public Minio Server
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.
## 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.
### Edge
```
$ mc config host add <ALIAS> <YOUR-S3-ENDPOINT> <YOUR-ACCESS-KEY> <YOUR-SECRET-KEY> S3v4
docker pull minio/mc:edge
docker run minio/mc:edge ls play
```
Example
**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:
```
$ mc config host add mys3 https://s3.amazonaws.com BKIKJAA5BMMU2RHO6IBB V7f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12
docker run -it --entrypoint=/bin/sh minio/mc
```
NOTE: ``S3v4`` is default if not specified.
then use the [`mc config` command](#add-a-cloud-storage-service).
## Configure mc for Google Cloud Storage
## macOS
### Homebrew
Install mc packages using [Homebrew](http://brew.sh/)
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 <ALIAS> https://storage.googleapis.com <YOUR-ACCESS-KEY> <YOUR-SECRET-KEY> S3v2
brew install minio/stable/mc
mc --help
```
NOTE: Google Cloud Storage only supports Legacy Signature Version ``2``, so you have to pick - ``S3v2``
## 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 |
## Contribute to Minio Client
Please follow Minio [Contributor's Guide](./CONTRIBUTING.md)
```
wget https://dl.min.io/client/mc/release/linux-amd64/mc
chmod +x mc
./mc --help
```
### 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.
## Microsoft Windows
### Binary Download
| Platform | Architecture | URL |
| ---------- | -------- |------|
|Microsoft Windows|64-bit Intel|https://dl.min.io/client/mc/release/windows-amd64/mc.exe |
```
mc.exe --help
```
## Install from Source
Source installation is intended only for developers and advanced users. `mc update` command does not support update notifications for source based installations. Please download official releases from https://min.io/download/#minio-client.
If you do not have a working Golang environment, please follow [How to install Golang](https://docs.min.io/docs/how-to-install-golang).
```
go get -d github.com/minio/mc
cd ${GOPATH}/src/github.com/minio/mc
make
```
## 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).
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.
```
mc config host add <ALIAS> <YOUR-S3-ENDPOINT> <YOUR-ACCESS-KEY> <YOUR-SECRET-KEY> --api <API-SIGNATURE> --lookup <BUCKET-LOOKUP-TYPE>
```
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 minio http://192.168.1.51 BKIKJAA5BMMU2RHO6IBB V7f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12
```
### 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).
```
mc config host add s3 https://s3.amazonaws.com BKIKJAA5BMMU2RHO6IBB V7f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12
```
**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
```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>"
]
}
]
}
```
### 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
```
NOTE: Google Cloud Storage only supports Legacy Signature Version 2, so you have to pick - S3v2
## Test Your Setup
`mc` is pre-configured with https://play.min.io, 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://docs.min.io/docs/how-to-install-golang)。
```
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-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 S3v4
```
### 示例-Amazon S3云存储
参考[AWS Credentials指南](http://docs.aws.amazon.com/general/latest/gr/aws-security-credentials.html)获取你的AccessKeyID和SecretAccessKey。
```
mc config host add s3 https://s3.amazonaws.com BKIKJAA5BMMU2RHO6IBB V7f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12 S3v4
```
### 示例-Google云存储
参考[Google Credentials Guide](https://cloud.google.com/storage/docs/migrating?hl=en#keys)获取你的AccessKeyID和SecretAccessKey。
```
mc config host add gcs https://storage.googleapis.com BKIKJAA5BMMU2RHO6IBB V8f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12 S3v2
```
注意: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)
-205
View File
@@ -1,205 +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/burningman2011
2. Set bucket to "public" on Amazon S3 cloud storage.
$ mc {{.Name}} set public s3/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/shared-authenticated
4. Get bucket permissions.
$ mc {{.Name}} get s3/shared
5. Get bucket permissions.
$ mc {{.Name}} get gcs/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, e := json.Marshal(s)
fatalIf(probe.NewError(e), "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 := newClient(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 := newClient(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 := ctx.Args().Tail().Tail()
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 := ctx.Args().Tail()
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
}
-167
View File
@@ -1,167 +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, e := strconv.Atoi(r.Header.Get("Content-Length"))
if e != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
var buffer bytes.Buffer
if _, e = io.CopyN(&buffer, r.Body, int64(length)); e != 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)
}
}
-47
View File
@@ -1,47 +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
- go get -u github.com/alecthomas/gometalinter
- go get -u github.com/client9/misspell
# 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...
- gometalinter --disable-all --linter='misspell:misspell ./*.go:PATH:LINE:COL:MESSAGE' --enable=misspell ./...
- gocyclo -over 40 pkg
- 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 -156
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,20 +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
GIT_VERSION="1.0"
GO_VERSION="1.5.1"
GO_VERSION="1.12"
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
@@ -50,169 +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://docs.min.io/docs/how-to-install-golang"
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})"
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})"
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
}
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 "$@"
+36
View File
@@ -0,0 +1,36 @@
#!/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"
}
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
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
}
+5
View File
@@ -0,0 +1,5 @@
#!/usr/bin/env bash
set -e
GO111MODULE=on CGO_ENABLED=0 go test -v -coverprofile=coverage.txt -covermode=atomic ./...
-152
View File
@@ -1,152 +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/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.Reader
switch sourceURL {
case "-":
reader = os.Stdin
default:
// Ignore size, since os.Stat() would not return proper size all the
// time for local filesystem for example /proc files.
var err *probe.Error
if reader, err = getSourceStream(sourceURL); 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 _, e := io.Copy(os.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)
}
}
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.
for _, url := range args {
fatalIf(catURL(url).Trace(url), "Unable to read from ‘"+url+"’.")
}
}
+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,12 +14,17 @@
* limitations under the License.
*/
package main
package cmd
import (
"encoding/json"
"fmt"
"sync"
"sync/atomic"
"time"
"github.com/cheggaaa/pb"
"github.com/minio/mc/pkg/probe"
)
// accounter keeps tabs of ongoing data transfer information.
@@ -51,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))
@@ -75,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.
@@ -86,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
@@ -107,6 +133,11 @@ func (a *accounter) Set(n int64) *accounter {
return a
}
// Get gets current value atomically
func (a *accounter) Get() int64 {
return atomic.LoadInt64(&a.current)
}
// Add add to current value atomically.
func (a *accounter) Add(n int64) int64 {
return atomic.AddInt64(&a.current, n)
+102
View File
@@ -0,0 +1,102 @@
/*
* 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 (
"github.com/minio/cli"
json "github.com/minio/mc/pkg/colorjson"
"github.com/minio/mc/pkg/probe"
)
var adminConfigGetCmd = cli.Command{
Name: "get",
Usage: "get config of a MinIO server/cluster",
Before: setGlobalsFromContext,
Action: mainAdminConfigGet,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} TARGET
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Get server configuration of a MinIO server/cluster.
$ {{.HelpName}} play/
`,
}
// configGetMessage container to hold locks information.
type configGetMessage struct {
Status string `json:"status"`
Config map[string]interface{} `json:"config"`
}
// String colorized service status message.
func (u configGetMessage) String() string {
config, e := json.MarshalIndent(u.Config, "", " ")
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
return string(config)
}
// 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 len(ctx.Args()) == 0 || len(ctx.Args()) > 2 {
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, "Cannot get a configured admin connection.")
// Call get config API
c, e := client.GetConfig()
fatalIf(probe.NewError(e), "Cannot get server configuration file.")
config := map[string]interface{}{}
e = json.Unmarshal(c, &config)
fatalIf(probe.NewError(e), "Cannot unmarshal server configuration file.")
// Print
printMsg(configGetMessage{
Config: config,
})
return nil
}
+122
View File
@@ -0,0 +1,122 @@
/*
* 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 (
"fmt"
"os"
"github.com/fatih/color"
"github.com/minio/cli"
json "github.com/minio/mc/pkg/colorjson"
"github.com/minio/mc/pkg/console"
"github.com/minio/mc/pkg/probe"
)
var adminConfigSetCmd = cli.Command{
Name: "set",
Usage: "set new config file to a MinIO server/cluster.",
Before: setGlobalsFromContext,
Action: mainAdminConfigSet,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} TARGET
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Set server configuration of a MinIO server/cluster.
$ cat myconfig | {{.HelpName}} myminio/
`,
}
// configSetMessage container to hold locks information.
type configSetMessage struct {
Status string `json:"status"`
setConfigStatus bool
targetAlias string
}
// String colorized service status message.
func (u configSetMessage) String() (msg string) {
// Print the general set config status
if u.setConfigStatus {
msg += console.Colorize("SetConfigSuccess",
"Setting new MinIO configuration file has been successful.\n")
suggestion := fmt.Sprintf("mc admin service restart %s", u.targetAlias)
msg += console.Colorize("SetConfigSuccess",
fmt.Sprintf("Please restart your server with `%s`.\n", suggestion))
} else {
msg += console.Colorize("SetConfigFailure",
"Setting new MinIO configuration file has failed.\n")
}
return
}
// JSON jsonified service status Message message.
func (u configSetMessage) JSON() string {
if u.setConfigStatus {
u.Status = "success"
} else {
u.Status = "error"
}
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 len(ctx.Args()) == 0 || len(ctx.Args()) > 2 {
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))
console.SetColor("SetConfigFailure", color.New(color.FgRed, color.Bold))
// Get the alias parameter from cli
args := ctx.Args()
aliasedURL := args.Get(0)
// Create a new MinIO Admin Client
client, err := newAdminClient(aliasedURL)
fatalIf(err, "Cannot get a configured admin connection.")
// Call get config API
fatalIf(probe.NewError(client.SetConfig(os.Stdin)), "Cannot set server configuration file.")
// Print set config result
printMsg(configSetMessage{
setConfigStatus: true,
targetAlias: aliasedURL,
})
return nil
}
+39
View File
@@ -0,0 +1,39 @@
/*
* 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 "github.com/minio/cli"
var adminConfigCmd = cli.Command{
Name: "config",
Usage: "manage configuration file",
Action: mainAdminConfig,
Before: setGlobalsFromContext,
Flags: globalFlags,
Subcommands: []cli.Command{
adminConfigGetCmd,
adminConfigSetCmd,
},
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.
}
+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
}
}
+449
View File
@@ -0,0 +1,449 @@
/*
* 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"
"os"
"strings"
"syscall"
"time"
humanize "github.com/dustin/go-humanize"
"github.com/fatih/color"
json "github.com/minio/mc/pkg/colorjson"
"github.com/minio/mc/pkg/console"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio/pkg/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) {
trapCh := signalTrap(os.Interrupt, syscall.SIGTERM, syscall.SIGKILL)
trapMsg := ui.healResumeMsg(aliasedURL)
firstIter := true
for {
select {
case <-trapCh:
return res, errors.New(trapMsg)
default:
_, res, err = ui.Client.Heal(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)
}
}
}
+256
View File
@@ -0,0 +1,256 @@
/*
* 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/console"
"github.com/minio/mc/pkg/probe"
"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: setGlobalsFromContext,
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 on one or more disks. Also heal objects with silent data corruption.
EXAMPLES:
1. To format newly replaced disks in a MinIO server with alias 'myminio'
$ {{.HelpName}} myminio
2. Heal 'testbucket' in a MinIO server with alias 'myminio'
$ {{.HelpName}} myminio/testbucket/
3. Heal all objects under 'dir' prefix
$ {{.HelpName}} --recursive myminio/testbucket/dir/
4. Issue a dry-run heal operation to inspect objects health but not heal them
$ {{.HelpName}} --dry-run myminio
5. Issue a dry-run heal operation to inspect objects health under 'dir' prefix
$ {{.HelpName}} --recursive --dry-run myminio/testbucket/dir/
6. Force start a running heal sequence (meaning it will force kill the running heal sequence and start a new one)
$ {{.HelpName}} --force-start myminio/testbucket/dir/
7. Force stop a running heal sequence (meaning it will force kill the running heal sequence)
$ {{.HelpName}} --force-stop myminio/testbucket/dir/
8. Issue a dry-run heal operation to inspect objects health under 'dir' prefix
$ {{.HelpName}} --dry-run myminio/testbucket/dir/
`,
}
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 {
healPrettyMsg := console.Colorize("HealBackgroundTitle", "Background healing status:\n")
healPrettyMsg += fmt.Sprintf(" Total items scanned: %s\n",
console.Colorize("HealBackground", s.HealInfo.ScannedItemsCount))
healPrettyMsg += fmt.Sprintf(" Last background heal check: %s\n",
console.Colorize("HealBackground", timeDurationToHumanizedDuration(time.Since(s.HealInfo.LastHealActivity)).String()+" ago"))
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("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]
// 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()
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(bucket, prefix, opts, "", forceStart, forceStop)
fatalIf(probe.NewError(herr), "Failed to stop heal sequence.")
printMsg(stopHealMessage{Status: "success", Alias: aliasedURL})
return nil
}
healStart, _, herr := client.Heal(bucket, prefix, opts, "", forceStart, false)
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
}
+318
View File
@@ -0,0 +1,318 @@
/*
* MinIO Client (C) 2016-2019 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cmd
import (
"fmt"
"net/url"
"sort"
"strings"
"time"
humanize "github.com/dustin/go-humanize"
"github.com/fatih/color"
"github.com/minio/cli"
json "github.com/minio/mc/pkg/colorjson"
"github.com/minio/mc/pkg/console"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio/pkg/madmin"
)
var (
adminInfoFlags = []cli.Flag{}
)
var adminInfoCmd = cli.Command{
Name: "info",
Usage: "display MinIO server information",
Action: mainAdminInfo,
Before: setGlobalsFromContext,
Flags: append(adminInfoFlags, globalFlags...),
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} TARGET
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Get server information of the 'play' MinIO server.
$ {{.HelpName}} play/
`,
}
// backendType - indicates the type of backend storage
type backendType string
const (
fsType = backendType("FS")
erasureType = backendType("Erasure")
)
// fsBackend contains specific FS storage information
type fsBackend struct {
Type backendType `json:"backendType"`
}
// xlBackend contains specific erasure storage information
type xlBackend struct {
Type backendType `json:"backendType"`
OnlineDisks int `json:"onlineDisks"`
OfflineDisks int `json:"offlineDisks"`
// Data disks for currently configured Standard storage class.
StandardSCData int `json:"standardSCData"`
// Parity disks for currently configured Standard storage class.
StandardSCParity int `json:"standardSCParity"`
// Data disks for currently configured Reduced Redundancy storage class.
RRSCData int `json:"rrSCData"`
// Parity disks for currently configured Reduced Redundancy storage class.
RRSCParity int `json:"rrSCParity"`
// List of all disk status.
Sets [][]madmin.DriveInfo `json:"sets"`
}
// backendStatus represents the overall information of all backend storage types
type backendStatus struct {
Used uint64 `json:"used"`
Backend interface{} `json:"backend"`
}
// ServerInfo holds the whole server information that will be
// returned by ServerInfo API.
type ServerInfo struct {
StorageInfo backendStatus `json:"storage"`
ConnStats madmin.ServerConnStats `json:"network"`
Properties madmin.ServerProperties `json:"server"`
}
// infoMessage container to hold service status information.
type infoMessage struct {
Status string `json:"status"`
Service string `json:"service"`
Addr string `json:"address"`
Err string `json:"error"`
*ServerInfo
}
// String colorized service status message.
func (u infoMessage) String() (msg string) {
dot := "●"
// When service is offline
if u.Service == "off" {
msg += fmt.Sprintf("%s %s\n", console.Colorize("InfoFail", dot), console.Colorize("PrintB", u.Addr))
msg += fmt.Sprintf(" Uptime: %s\n", console.Colorize("InfoFail", "offline"))
return
}
// Print error if any and exit
if u.Err != "" {
msg += fmt.Sprintf("%s %s\n", console.Colorize("InfoFail", dot), console.Colorize("PrintB", u.Addr))
msg += fmt.Sprintf(" Uptime: %s\n", console.Colorize("InfoFail", "offline"))
e := u.Err
if strings.Trim(e, " ") == "rpc: retry error" {
e = "unreachable"
}
msg += fmt.Sprintf(" Error: %s", console.Colorize("InfoFail", e))
return
}
// Print server title
msg += fmt.Sprintf("%s %s\n", console.Colorize("Info", dot), console.Colorize("PrintB", u.Addr))
// Uptime
msg += fmt.Sprintf(" Uptime: %s\n", console.Colorize("Info",
humanize.RelTime(time.Now(), time.Now().Add(-u.ServerInfo.Properties.Uptime), "", "")))
// Version
version := u.ServerInfo.Properties.Version
if u.ServerInfo.Properties.Version == "DEVELOPMENT.GOGET" {
version = "<development>"
}
msg += fmt.Sprintf(" Version: %s\n", version)
// Region
if u.ServerInfo.Properties.Region != "" {
msg += fmt.Sprintf(" Region: %s\n", u.ServerInfo.Properties.Region)
}
// ARNs
sqsARNs := ""
for _, v := range u.ServerInfo.Properties.SQSARN {
sqsARNs += fmt.Sprintf("%s ", v)
}
if sqsARNs != "" {
msg += fmt.Sprintf(" SQS ARNs: %s\n", sqsARNs)
}
// Incoming/outgoing
msg += fmt.Sprintf(" Storage: Used %s", humanize.IBytes(u.StorageInfo.Used))
if v, ok := u.ServerInfo.StorageInfo.Backend.(xlBackend); ok {
upBackends := 0
downBackends := 0
for _, set := range v.Sets {
for _, s := range set {
if strings.Contains(s.Endpoint, u.Addr) || s.Endpoint[0] == '/' {
if s.State == "ok" {
upBackends++
} else {
downBackends++
}
}
}
}
upBackendsString := fmt.Sprintf("%d", upBackends)
if downBackends != 0 {
upBackendsString = console.Colorize("InfoFail", fmt.Sprintf("%d", upBackends))
}
msg += fmt.Sprintf("\n Drives: %s/%d %s\n", upBackendsString,
upBackends+downBackends, console.Colorize("Info", "OK"))
}
return
}
// JSON jsonified service status Message message.
func (u infoMessage) JSON() string {
u.Status = "success"
statusJSONBytes, e := json.MarshalIndent(u, "", " ")
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
return string(statusJSONBytes)
}
// checkAdminInfoSyntax - validate all the passed arguments
func checkAdminInfoSyntax(ctx *cli.Context) {
if len(ctx.Args()) == 0 || len(ctx.Args()) > 2 {
cli.ShowCommandHelpAndExit(ctx, "info", 1) // last argument is exit code
}
}
func mainAdminInfo(ctx *cli.Context) error {
// Validate service status syntax.
checkAdminInfoSyntax(ctx)
console.SetColor("Info", color.New(color.FgGreen, color.Bold))
console.SetColor("InfoDegraded", color.New(color.FgYellow, color.Bold))
console.SetColor("InfoFail", color.New(color.FgRed, color.Bold))
// Get the alias parameter from cli
args := ctx.Args()
aliasedURL := args.Get(0)
// Create a new MinIO Admin Client
client, err := newAdminClient(aliasedURL)
fatalIf(err, "Cannot get a configured admin connection.")
// Fetch info of all servers (cluster or single server)
serversInfo, e := client.ServerInfo()
// Check the availability of the server: online or offline. A server is considered
// offline if we can't get any response or we get a bad format response
var serviceOffline bool
switch e.(type) {
case *json.SyntaxError:
serviceOffline = true
case *url.Error:
serviceOffline = true
}
if serviceOffline {
printMsg(infoMessage{Addr: aliasedURL, Service: "off"})
return nil
}
// If the error is not nil and not unrecognizable, just print it and exit
fatalIf(probe.NewError(e), "Cannot get service status.")
infoMessages := []infoMessage{}
for _, serverInfo := range serversInfo {
// Print the error if exists and jump to the next server
if serverInfo.Error != "" {
infoMessages = append(infoMessages, infoMessage{
Service: "on",
Addr: serverInfo.Addr,
Err: serverInfo.Error,
})
continue
}
// Construct the backend status
storageInfo := backendStatus{
Used: serverInfo.Data.StorageInfo.Used,
}
if serverInfo.Data.StorageInfo.Backend.Type == madmin.Erasure {
storageInfo.Backend = xlBackend{
Type: erasureType,
OnlineDisks: serverInfo.Data.StorageInfo.Backend.OnlineDisks,
OfflineDisks: serverInfo.Data.StorageInfo.Backend.OfflineDisks,
StandardSCData: serverInfo.Data.StorageInfo.Backend.StandardSCData,
StandardSCParity: serverInfo.Data.StorageInfo.Backend.StandardSCParity,
RRSCData: serverInfo.Data.StorageInfo.Backend.RRSCData,
RRSCParity: serverInfo.Data.StorageInfo.Backend.RRSCParity,
Sets: serverInfo.Data.StorageInfo.Backend.Sets,
}
} else {
storageInfo.Backend = fsBackend{
Type: fsType,
}
}
infoMessages = append(infoMessages, (infoMessage{
Service: "on",
Addr: serverInfo.Addr,
Err: serverInfo.Error,
ServerInfo: &ServerInfo{
StorageInfo: storageInfo,
ConnStats: serverInfo.Data.ConnStats,
Properties: serverInfo.Data.Properties,
},
}))
}
sort.Stable(&sortInfoWrapper{infoMessages})
for _, s := range infoMessages {
printMsg(s)
}
return nil
}
type sortInfoWrapper struct {
infos []infoMessage
}
func (s *sortInfoWrapper) Len() int {
return len(s.infos)
}
func (s *sortInfoWrapper) Swap(i, j int) {
if s.infos != nil {
s.infos[i], s.infos[j] = s.infos[j], s.infos[i]
}
}
func (s *sortInfoWrapper) Less(i, j int) bool {
if s.infos != nil {
return s.infos[i].Addr < s.infos[j].Addr
}
return false
}
+51
View File
@@ -0,0 +1,51 @@
/*
* 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{}
)
var adminCmd = cli.Command{
Name: "admin",
Usage: "manage MinIO servers",
Action: mainAdmin,
HideHelpCommand: true,
Before: setGlobalsFromContext,
Flags: append(adminFlags, globalFlags...),
Subcommands: []cli.Command{
adminServiceCmd,
adminInfoCmd,
adminUserCmd,
adminPolicyCmd,
adminConfigCmd,
adminHealCmd,
adminProfileCmd,
adminTopCmd,
adminMonitorCmd,
adminTraceCmd,
},
}
// 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.
}
+252
View File
@@ -0,0 +1,252 @@
/*
* MinIO Client (C) 2019 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cmd
import (
"fmt"
"net/url"
"sort"
"strings"
humanize "github.com/dustin/go-humanize"
"github.com/fatih/color"
"github.com/minio/cli"
json "github.com/minio/mc/pkg/colorjson"
"github.com/minio/mc/pkg/console"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio/pkg/madmin"
)
var (
adminMonitorFlags = []cli.Flag{}
)
const (
monitor = "BoldGreen"
monitorDegraded = "BoldYellow"
monitorFail = "BoldRed"
)
var adminMonitorCmd = cli.Command{
Name: "monitor",
Usage: "monitor cpu and mem statistics",
Action: mainAdminMonitor,
Before: setGlobalsFromContext,
Flags: append(adminMonitorFlags, globalFlags...),
HideHelpCommand: true,
CustomHelpTemplate: `Name:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} TARGET
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Get server cpu and mem statistics of the 'play' server.
$ {{.HelpName}} play/
`,
}
// serverMonitorMessage holds service status info along with
// cpu, mem, net and disk monitoristics
type serverMonitorMessage struct {
Monitor string `json:"status"`
Service string `json:"service"`
Addr string `json:"address"`
Err string `json:"error"`
CPULoad *madmin.ServerCPULoadInfo `json:"cpu,omitempty"`
MemUsage *madmin.ServerMemUsageInfo `json:"mem,omitempty"`
}
func (s serverMonitorMessage) JSON() string {
s.Monitor = "success"
if s.Err != "" {
s.Monitor = "fail"
}
statusJSONBytes, e := json.MarshalIndent(s, "", " ")
fatalIf(probe.NewError(e), "Unable to marshal into JSON")
return string(statusJSONBytes)
}
func (s serverMonitorMessage) String() string {
msg := ""
dot := "●"
if s.Err != "" || s.Service == "off" {
msg += fmt.Sprintf("%s %s\n", console.Colorize(monitorFail, dot), s.Addr)
msg += fmt.Sprintf(" Server is %s\n", console.Colorize(monitorFail, "offline"))
msg += fmt.Sprintf(" Error : %s\n", console.Colorize(monitorFail, s.Err))
return msg
}
// Print server title
msg += fmt.Sprintf("%s %s \n", console.Colorize(monitor, dot), s.Addr)
msg += "\n"
msg += fmt.Sprintf("%s min avg max\n", console.Colorize(monitor, " CPU"))
for i := range s.CPULoad.Load {
msg += fmt.Sprintf(" current %.2f%% %.2f%% %.2f%%\n", s.CPULoad.Load[i].Min, s.CPULoad.Load[i].Avg, s.CPULoad.Load[i].Max)
if len(s.CPULoad.HistoricLoad) > i {
msg += fmt.Sprintf(" historic %.2f%% %.2f%% %.2f%%\n", s.CPULoad.HistoricLoad[i].Min, s.CPULoad.HistoricLoad[i].Avg, s.CPULoad.HistoricLoad[i].Max)
}
msg += "\n"
}
// Mem section
msg += fmt.Sprintf("%s usage\n", console.Colorize(monitor, " MEM"))
for i := range s.MemUsage.Usage {
msg += fmt.Sprintf(" current %s\n", humanize.IBytes(s.MemUsage.Usage[i].Mem))
if len(s.MemUsage.HistoricUsage) > i {
msg += fmt.Sprintf(" historic %s\n", humanize.IBytes(s.MemUsage.HistoricUsage[i].Mem))
}
msg += "\n"
}
return msg
}
func mainAdminMonitor(ctx *cli.Context) error {
checkAdminMonitorSyntax(ctx)
// set the console colors
console.SetColor(monitor, color.New(color.FgGreen, color.Bold))
console.SetColor(monitorDegraded, color.New(color.FgYellow, color.Bold))
console.SetColor(monitorFail, color.New(color.FgRed, color.Bold))
// Get the alias
args := ctx.Args()
aliasedURL := args.Get(0)
// Create a new MinIO admin client
client, err := newAdminClient(aliasedURL)
fatalIf(err, "Cannot get a configured admin connection.")
printOfflineErrorMessage := func(err error) {
errMsg := ""
if err != nil {
errMsg = err.Error()
}
printMsg(serverMonitorMessage{
Addr: aliasedURL,
Service: "off",
Err: errMsg,
})
}
processErr := func(e error) error {
switch e.(type) {
case *json.SyntaxError:
printOfflineErrorMessage(e)
return e
case *url.Error:
printOfflineErrorMessage(e)
return e
default:
// If the error is not nil and unrecognized, just print it and exit
fatalIf(probe.NewError(e), "Cannot get service status.")
}
return nil
}
// Fetch info of all CPU loads (all MinIO server instances)
cpuLoads, e := client.ServerCPULoadInfo()
if err := processErr(e); err != nil {
// exit immediately if error encountered
return nil
}
sort.Stable(&sortWrapper{cpuLoads: cpuLoads})
memUsages, e := client.ServerMemUsageInfo()
if err := processErr(e); err != nil {
// exit immediately if error encountered
return nil
}
sort.Stable(&sortWrapper{memUsages: memUsages})
for i, cpuLoad := range cpuLoads {
memUsage := memUsages[i]
if cpuLoad.Error != "" {
printMsg(serverMonitorMessage{
Service: "off",
Addr: cpuLoad.Addr,
Err: cpuLoad.Error,
})
continue
}
if memUsage.Error != "" {
printMsg(serverMonitorMessage{
Service: "off",
Addr: memUsage.Addr,
Err: memUsage.Error,
})
continue
}
printMsg(serverMonitorMessage{
Service: "on",
Addr: cpuLoad.Addr,
CPULoad: &cpuLoad,
MemUsage: &memUsage,
})
}
return nil
}
type sortWrapper struct {
cpuLoads []madmin.ServerCPULoadInfo
memUsages []madmin.ServerMemUsageInfo
}
func (s *sortWrapper) Len() int {
if s.cpuLoads != nil {
return len(s.cpuLoads)
}
return len(s.memUsages)
}
func (s *sortWrapper) Swap(i, j int) {
if s.cpuLoads != nil {
s.cpuLoads[i], s.cpuLoads[j] = s.cpuLoads[j], s.cpuLoads[i]
return
}
if s.memUsages != nil {
s.memUsages[i], s.memUsages[j] = s.memUsages[j], s.memUsages[i]
}
}
func (s *sortWrapper) Less(i, j int) bool {
if s.cpuLoads != nil {
return strings.Compare(s.cpuLoads[i].Addr, s.cpuLoads[j].Addr) < 0
}
if s.memUsages != nil {
return strings.Compare(s.memUsages[i].Addr, s.memUsages[j].Addr) < 0
}
return false
}
// checkAdminMonitorSyntax - validate all the passed arguments
func checkAdminMonitorSyntax(ctx *cli.Context) {
if len(ctx.Args()) == 0 || len(ctx.Args()) > 1 {
exit := globalErrorExitStatus
cli.ShowCommandHelpAndExit(ctx, "monitor", exit)
}
}
+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 (
"io/ioutil"
"github.com/fatih/color"
"github.com/minio/cli"
json "github.com/minio/mc/pkg/colorjson"
"github.com/minio/mc/pkg/console"
"github.com/minio/mc/pkg/probe"
)
var adminPolicyAddCmd = cli.Command{
Name: "add",
Usage: "add new policy",
Action: mainAdminPolicyAdd,
Before: setGlobalsFromContext,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} TARGET POLICYNAME POLICYFILE
POLICYNAME:
Name of the canned policy on MinIO server.
POLICYFILE:
Name of the policy file associated with the policy name.
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Add a new canned policy 'writeonly'.
$ {{.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 []byte `json:"policyJSON,omitempty"`
}
func (u userPolicyMessage) String() string {
switch u.op {
case "info":
return string(u.PolicyJSON)
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.")
}
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, "Cannot get a configured admin connection.")
fatalIf(probe.NewError(client.AddCannedPolicy(args.Get(1), string(policy))).Trace(args...), "Cannot add new policy")
printMsg(userPolicyMessage{
op: "add",
Policy: args.Get(1),
})
return nil
}
+88
View File
@@ -0,0 +1,88 @@
/*
* 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/console"
"github.com/minio/mc/pkg/probe"
)
var adminPolicyInfoCmd = cli.Command{
Name: "info",
Usage: "show info on a policy",
Action: mainAdminPolicyInfo,
Before: setGlobalsFromContext,
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.
$ {{.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, "Cannot get a configured admin connection.")
policies, e := client.ListCannedPolicies()
fatalIf(probe.NewError(e).Trace(args...), "Cannot list policy")
if len(policies[policyName]) != 0 {
printMsg(userPolicyMessage{
op: "info",
Policy: policyName,
PolicyJSON: policies[policyName],
})
} else {
fatalIf(probe.NewError(fmt.Errorf("%s is not found", policyName)), "Cannot list the 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/console"
"github.com/minio/mc/pkg/probe"
)
var adminPolicyListCmd = cli.Command{
Name: "list",
Usage: "list all policies",
Action: mainAdminPolicyList,
Before: setGlobalsFromContext,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} TARGET
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. List all policies on MinIO server.
$ {{.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, "Cannot get a configured admin connection.")
policies, e := client.ListCannedPolicies()
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/console"
"github.com/minio/mc/pkg/probe"
)
var adminPolicyRemoveCmd = cli.Command{
Name: "remove",
Usage: "remove policy",
Action: mainAdminPolicyRemove,
Before: setGlobalsFromContext,
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.
$ {{.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, "Cannot get a configured admin connection.")
fatalIf(probe.NewError(client.RemoveCannedPolicy(args.Get(1))).Trace(args...), "Cannot remove policy")
printMsg(userPolicyMessage{
op: "remove",
Policy: args.Get(1),
})
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,
Before: setGlobalsFromContext,
Flags: globalFlags,
Subcommands: []cli.Command{
adminPolicyAddCmd,
adminPolicyRemoveCmd,
adminPolicyListCmd,
adminPolicyInfoCmd,
},
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.
}
+111
View File
@@ -0,0 +1,111 @@
/*
* 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/console"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio/pkg/madmin"
)
var adminProfileStartFlags = []cli.Flag{
cli.StringFlag{
Name: "type",
Usage: "start profiler type, possible values are 'cpu', 'mem', 'block', 'mutex' and 'trace'",
Value: "mem",
},
}
var adminProfileStartCmd = cli.Command{
Name: "start",
Usage: "start recording profile data",
Action: mainAdminProfileStart,
Before: setGlobalsFromContext,
Flags: append(adminProfileStartFlags, globalFlags...),
HideHelpCommand: true,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} [FLAGS] TARGET
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Start CPU profile
$ {{.HelpName}} --type cpu myminio/
`,
}
func checkAdminProfileStartSyntax(ctx *cli.Context) {
// Check flags combinations
if len(ctx.Args()) != 1 {
cli.ShowCommandHelpAndExit(ctx, "start", 1) // last argument is exit code
}
profilerTypes := []madmin.ProfilerType{
madmin.ProfilerCPU,
madmin.ProfilerMEM,
madmin.ProfilerBlock,
madmin.ProfilerMutex,
madmin.ProfilerTrace,
}
// Check if the provided profiler type is known and supported
supportedProfiler := false
profilerType := strings.ToLower(ctx.String("type"))
for _, profiler := range profilerTypes {
if profilerType == string(profiler) {
supportedProfiler = true
break
}
}
if !supportedProfiler {
fatalIf(errDummy(), "Profiler type unrecognized. Possible values are: %v.", profilerTypes)
}
}
// 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)
profilerType := 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(madmin.ProfilerType(profilerType))
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/console"
"github.com/minio/mc/pkg/probe"
)
var adminProfileStopCmd = cli.Command{
Name: "stop",
Usage: "stop and download profile data",
Action: mainAdminProfileStop,
Before: setGlobalsFromContext,
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
$ {{.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()
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("2006-01-02T15:04:05.999999-07:00"))
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
}
@@ -1,5 +1,5 @@
/*
* Minio Cloud Storage, (C) 2015 Minio, Inc.
* 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.
@@ -14,28 +14,27 @@
* limitations under the License.
*/
package user_test
package cmd
import (
"testing"
"github.com/minio/minio/pkg/user"
. "gopkg.in/check.v1"
"github.com/minio/cli"
)
func Test(t *testing.T) { TestingT(t) }
type MySuite struct{}
var _ = Suite(&MySuite{})
func (s *MySuite) TestUser(c *C) {
_, err := user.Current()
c.Assert(err, IsNil)
var adminProfileCmd = cli.Command{
Name: "profile",
Usage: "generate profile data for debugging purposes",
Action: mainAdminProfile,
Before: setGlobalsFromContext,
Flags: globalFlags,
Subcommands: []cli.Command{
adminProfileStartCmd,
adminProfileStopCmd,
},
HideHelpCommand: true,
}
func (s *MySuite) TestHomeDir(c *C) {
_, err := user.HomeDir()
c.Assert(err, IsNil)
// mainAdminProfile is the handle for "mc admin profile" command.
func mainAdminProfile(ctx *cli.Context) error {
cli.ShowCommandHelp(ctx, ctx.Args().First())
return nil
}
+139
View File
@@ -0,0 +1,139 @@
/*
* 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/console"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio/pkg/madmin"
)
var adminServiceRestartCmd = cli.Command{
Name: "restart",
Usage: "restart MinIO server",
Action: mainAdminServiceRestart,
Before: setGlobalsFromContext,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} TARGET
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Restart MinIO server represented by its alias 'play'.
$ {{.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, "Cannot get a configured admin connection.")
// Restart the specified MinIO server
fatalIf(probe.NewError(client.ServiceSendAction(
madmin.ServiceActionValueRestart)), "Cannot restart 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.ServiceStatus()
if e != nil {
printMsg(serviceRestartMessage{Status: "failure", Err: e, ServerURL: aliasedURL})
} else {
printMsg(serviceRestartMessage{Status: "success", ServerURL: aliasedURL})
}
return nil
}
+143
View File
@@ -0,0 +1,143 @@
/*
* MinIO Client (C) 2016-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"
json "github.com/minio/mc/pkg/colorjson"
"github.com/minio/mc/pkg/console"
"github.com/minio/mc/pkg/probe"
)
var (
adminServiceStatusFlags = []cli.Flag{}
)
var adminServiceStatusCmd = cli.Command{
Name: "status",
Usage: "get the status of MinIO server",
Action: mainAdminServiceStatus,
Before: setGlobalsFromContext,
Flags: append(adminServiceStatusFlags, globalFlags...),
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} TARGET
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Check if the 'play' MinIO server is online and show its uptime.
$ {{.HelpName}} play/
`,
}
// serviceStatusMessage container to hold service status information.
type serviceStatusMessage struct {
Status string `json:"status"`
Service string `json:"service"`
Uptime time.Duration `json:"uptime"`
}
// String colorized service status message.
func (u serviceStatusMessage) String() (msg string) {
defer func() {
msg = console.Colorize("ServiceStatus", msg)
}()
// When service is offline
if u.Service == "off" {
msg = "The server is offline."
return
}
msg = fmt.Sprintf("Uptime: %s.", timeDurationToHumanizedDuration(u.Uptime))
return
}
// JSON jsonified service status Message message.
func (u serviceStatusMessage) JSON() string {
switch u.Service {
case "on":
u.Status = "success"
case "off":
u.Status = "failure"
}
statusJSONBytes, e := json.MarshalIndent(u, "", " ")
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
return string(statusJSONBytes)
}
// checkAdminServiceStatusSyntax - validate all the passed arguments
func checkAdminServiceStatusSyntax(ctx *cli.Context) {
if len(ctx.Args()) == 0 || len(ctx.Args()) > 2 {
cli.ShowCommandHelpAndExit(ctx, "status", 1) // last argument is exit code
}
}
func mainAdminServiceStatus(ctx *cli.Context) error {
// Validate serivce status syntax.
checkAdminServiceStatusSyntax(ctx)
console.SetColor("ServiceStatus", color.New(color.FgGreen, color.Bold))
// Get the alias parameter from cli
args := ctx.Args()
aliasedURL := args.Get(0)
// Create a new MinIO Admin Client
client, err := newAdminClient(aliasedURL)
fatalIf(err, "Cannot get a configured admin connection.")
// Fetch the service status of the specified MinIO server
st, e := client.ServiceStatus()
// Check the availability of the server: online or offline. A server is considered
// offline if we can't get any response or we get a bad format response
var serviceOffline bool
switch v := e.(type) {
case *json.SyntaxError:
serviceOffline = true
case *url.Error:
if v.Timeout() {
serviceOffline = true
}
}
if serviceOffline {
printMsg(serviceStatusMessage{Service: "off"})
return nil
}
// If the error is not nil and not unrecognizable, just print it and exit
fatalIf(probe.NewError(e), "Cannot get service status.")
// Print the whole response
printMsg(serviceStatusMessage{
Service: "on",
Uptime: st.Uptime,
})
return nil
}
+97
View File
@@ -0,0 +1,97 @@
/*
* 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/console"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio/pkg/madmin"
)
var adminServiceStopCmd = cli.Command{
Name: "stop",
Usage: "stop MinIO server",
Action: mainAdminServiceStop,
Before: setGlobalsFromContext,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} TARGET
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Stop MinIO server represented by its alias 'play'.
$ {{.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, "Cannot get a configured admin connection.")
// Stop the specified MinIO server
pErr := client.ServiceSendAction(madmin.ServiceActionValueStop)
fatalIf(probe.NewError(pErr), "Cannot stop server.")
// Success..
printMsg(serviceStopMessage{Status: "success", ServerURL: aliasedURL})
return nil
}
+40
View File
@@ -0,0 +1,40 @@
/*
* 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: "stop, restart or get status of MinIO server",
Action: mainAdminService,
Before: setGlobalsFromContext,
Flags: globalFlags,
HideHelpCommand: true,
Subcommands: []cli.Command{
adminServiceStatusCmd,
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/console"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio/pkg/madmin"
)
var adminTopLocksCmd = cli.Command{
Name: "locks",
Usage: "Get a list of the 10 oldest locks on a MinIO cluster.",
Before: setGlobalsFromContext,
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.
$ {{.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, "Cannot get a configured admin connection.")
// Call top locks API
entries, e := client.TopLocks()
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})
}
}
+21 -17
View File
@@ -1,5 +1,5 @@
/*
* Minio Client (C) 2015 Minio, Inc.
* MinIO Client (C) 2019 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -14,21 +14,25 @@
* 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 adminTopCmd = cli.Command{
Name: "top",
Usage: "provide top like statistics for MinIO",
Action: mainAdminTop,
Before: setGlobalsFromContext,
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.
}
+345
View File
@@ -0,0 +1,345 @@
/*
* 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"
"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/console"
"github.com/minio/mc/pkg/probe"
"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: setGlobalsFromContext,
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'
$ {{.HelpName}} play -v -a
2. Show trace only for failed requests for a Minio server with alias 'myminio'
$ {{.HelpName}} myminio -v -e
`,
}
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
}
doneCh := make(chan struct{})
defer close(doneCh)
// Start listening on all trace activity.
traceCh := client.Trace(all, errfltr, doneCh)
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.TraceInfo
}
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"`
}
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.TraceInfo) 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.StatusOK {
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)
fmt.Fprintf(b, console.Colorize("HeaderValue", fmt.Sprintf("%2s ", s.CallStats.Duration.Round(time.Microsecond))))
fmt.Fprintf(b, console.Colorize("Stat", fmt.Sprintf(" 🠉 ")))
fmt.Fprintf(b, console.Colorize("HeaderValue", humanize.IBytes(uint64(s.CallStats.Rx))))
fmt.Fprintf(b, console.Colorize("Stat", fmt.Sprintf(" 🠋 ")))
fmt.Fprintf(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 := int(nHashSum) % 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,
},
}
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", fmt.Sprintf("[RESPONSE] ")))
fmt.Fprintf(b, "[%s] ", rs.Time.Format(timeFormat))
fmt.Fprintf(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()
}
+81
View File
@@ -0,0 +1,81 @@
/*
* 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/console"
"github.com/minio/mc/pkg/probe"
)
var adminUserPolicyCmd = cli.Command{
Name: "set-policy",
Usage: "set policy for user",
Action: mainAdminUserPolicy,
Before: setGlobalsFromContext,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} TARGET USERNAME POLICYNAME
POLICYNAME:
Name of the canned policy created on MinIO server.
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Set a policy 'writeonly' to 'foobar' on MinIO server.
$ {{.HelpName}} myminio foobar writeonly
`,
}
// checkAdminUserPolicySyntax - validate all the passed arguments
func checkAdminUserPolicySyntax(ctx *cli.Context) {
if len(ctx.Args()) != 3 {
cli.ShowCommandHelpAndExit(ctx, "policy", 1) // last argument is exit code
}
}
// mainAdminUserPolicy is the handle for "mc admin user policy" command.
func mainAdminUserPolicy(ctx *cli.Context) error {
checkAdminUserPolicySyntax(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, "Cannot get a configured admin connection.")
fatalIf(probe.NewError(client.SetUserPolicy(args.Get(1), args.Get(2))).Trace(args...), "Cannot set user policy for user")
printMsg(userMessage{
op: "policy",
AccessKey: args.Get(1),
PolicyName: args.Get(2),
UserStatus: "enabled",
})
return nil
}
+131
View File
@@ -0,0 +1,131 @@
/*
* 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"
json "github.com/minio/mc/pkg/colorjson"
"github.com/minio/mc/pkg/console"
"github.com/minio/mc/pkg/probe"
)
var adminUserAddCmd = cli.Command{
Name: "add",
Usage: "add a new user",
Action: mainAdminUserAdd,
Before: setGlobalsFromContext,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} TARGET ACCESSKEY SECRETKEY POLICYNAME
POLICYNAME:
Name of the policy available on MinIO server.
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Add a new user 'foobar' to MinIO server with policy 'writeonly'.
$ set +o history
$ {{.HelpName}} myminio foobar foo12345 writeonly
$ set -o history
`,
}
// checkAdminUserAddSyntax - validate all the passed arguments
func checkAdminUserAddSyntax(ctx *cli.Context) {
if len(ctx.Args()) != 4 {
cli.ShowCommandHelpAndExit(ctx, "add", 1) // last argument is exit code
}
}
// userMessage container for content message structure
type userMessage struct {
op string
Status string `json:"status"`
AccessKey string `json:"accessKey,omitempty"`
SecretKey string `json:"secretKey,omitempty"`
PolicyName string `json:"policyName,omitempty"`
UserStatus string `json:"userStatus,omitempty"`
}
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 "policy":
return console.Colorize("UserMessage", "Set a policy `"+u.PolicyName+"` for user `"+u.AccessKey+"` successfully.")
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)
}
// 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)
// Create a new MinIO Admin Client
client, err := newAdminClient(aliasedURL)
fatalIf(err, "Cannot get a configured admin connection.")
fatalIf(probe.NewError(client.AddUser(args.Get(1), args.Get(2))).Trace(args...), "Cannot add new user")
fatalIf(probe.NewError(client.SetUserPolicy(args.Get(1), args.Get(3))).Trace(args...), "Cannot set user policy for new user")
printMsg(userMessage{
op: "add",
AccessKey: args.Get(1),
SecretKey: args.Get(2),
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/console"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio/pkg/madmin"
)
var adminUserDisableCmd = cli.Command{
Name: "disable",
Usage: "disable user",
Action: mainAdminUserDisable,
Before: setGlobalsFromContext,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} TARGET USERNAME
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Disable a user 'foobar' on MinIO server.
$ {{.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, "Cannot get a configured admin connection.")
e := client.SetUserStatus(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/console"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio/pkg/madmin"
)
var adminUserEnableCmd = cli.Command{
Name: "enable",
Usage: "enable user",
Action: mainAdminUserEnable,
Before: setGlobalsFromContext,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} TARGET USERNAME
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Enable a disabled user 'foobar' on MinIO server.
$ {{.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, "Cannot get a configured admin connection.")
e := client.SetUserStatus(args.Get(1), madmin.AccountEnabled)
fatalIf(probe.NewError(e).Trace(args...), "Cannot enable user")
printMsg(userMessage{
op: "enable",
AccessKey: args.Get(1),
})
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/console"
"github.com/minio/mc/pkg/probe"
)
var adminUserListCmd = cli.Command{
Name: "list",
Usage: "list all users",
Action: mainAdminUserList,
Before: setGlobalsFromContext,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} TARGET
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. List all users on MinIO server.
$ {{.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, "Cannot get a configured admin connection.")
users, e := client.ListUsers()
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/console"
"github.com/minio/mc/pkg/probe"
)
var adminUserRemoveCmd = cli.Command{
Name: "remove",
Usage: "remove user",
Action: mainAdminUserRemove,
Before: setGlobalsFromContext,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} TARGET USERNAME
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Remove a user 'foobar' on MinIO server.
$ {{.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, "Cannot get a configured admin connection.")
e := client.RemoveUser(args.Get(1))
fatalIf(probe.NewError(e).Trace(args...), "Cannot remove new user")
printMsg(userMessage{
op: "remove",
AccessKey: args.Get(1),
})
return nil
}
+43
View File
@@ -0,0 +1,43 @@
/*
* 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,
Before: setGlobalsFromContext,
Flags: globalFlags,
Subcommands: []cli.Command{
adminUserAddCmd,
adminUserPolicyCmd,
adminUserDisableCmd,
adminUserEnableCmd,
adminUserRemoveCmd,
adminUserListCmd,
},
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.
}
+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]
)
+247
View File
@@ -0,0 +1,247 @@
/*
* 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"
"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: setGlobalsFromContext,
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.
$ {{.HelpName}} s3/mysql-backups/kubecon-mysql-operator.mpv | mplayer -
2. Concatenate contents of file1.txt and stdin to standard output.
$ {{.HelpName}} file1.txt - > file.txt
3. Concatenate multiple files to one.
$ {{.HelpName}} part.* > complete.img
4. Save an encrypted object from Amazon S3 cloud storage to a local file.
$ {{.HelpName}} --encrypt-key 's3/mysql-backups=32byteslongsecretkeymustbegiven1' s3/mysql-backups/backups-201810.gz > /mnt/data/recent.gz
`,
}
// 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(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(sourceURL, false, encKeyDB)
if err == nil && client.GetURL().Type == objectStorage {
size = content.Size
}
if reader, err = getSourceStreamFromURL(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(ctx *cli.Context) error {
// Parse encryption keys per command.
encKeyDB, err := getEncKeys(ctx)
fatalIf(err, "Unable to parse encryption keys.")
// 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, -1).Trace(), "Unable to read from standard input.")
return nil
}
// 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.
for _, url := range args {
fatalIf(catURL(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)
}
}
+138
View File
@@ -0,0 +1,138 @@
/*
* 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 (
"crypto/tls"
"fmt"
"hash/fnv"
"net"
"net/http"
"net/url"
"sync"
"time"
"github.com/minio/mc/pkg/httptracer"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio/pkg/madmin"
)
// newAdminFactory encloses New function with client cache.
func newAdminFactory() func(config *Config) (*madmin.AdminClient, *probe.Error) {
clientCache := make(map[uint32]*madmin.AdminClient)
mutex := &sync.Mutex{}
// Return New function.
return func(config *Config) (*madmin.AdminClient, *probe.Error) {
// Creates a parsed URL.
targetURL, e := url.Parse(config.HostURL)
if e != nil {
return nil, probe.NewError(e)
}
// By default enable HTTPs.
useTLS := true
if targetURL.Scheme == "http" {
useTLS = false
}
// Save if target supports virtual host style.
hostName := targetURL.Host
// Generate a hash out of s3Conf.
confHash := fnv.New32a()
confHash.Write([]byte(hostName + config.AccessKey + config.SecretKey))
confSum := confHash.Sum32()
// Lookup previous cache by hash.
mutex.Lock()
defer mutex.Unlock()
var api *madmin.AdminClient
var found bool
if api, found = clientCache[confSum]; !found {
// Not found. Instantiate a new MinIO
var e error
api, e = madmin.New(hostName, config.AccessKey, config.SecretKey, useTLS)
if e != nil {
return nil, probe.NewError(e)
}
// Keep TLS config.
tlsConfig := &tls.Config{RootCAs: globalRootCAs}
if config.Insecure {
tlsConfig.InsecureSkipVerify = true
}
var transport http.RoundTripper = &http.Transport{
Proxy: http.ProxyFromEnvironment,
DialContext: (&net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second,
}).DialContext,
MaxIdleConns: 100,
IdleConnTimeout: 90 * time.Second,
TLSHandshakeTimeout: 10 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
TLSClientConfig: tlsConfig,
}
if config.Debug {
transport = httptracer.GetNewTraceTransport(newTraceV4(), transport)
}
// Set custom transport.
api.SetCustomTransport(transport)
// Set app info.
api.SetAppInfo(config.AppName, config.AppVersion)
// Cache the new MinIO Client with hash of config as key.
clientCache[confSum] = api
}
// Store the new api object.
return api, nil
}
}
// newAdminClient gives a new client interface
func newAdminClient(aliasedURL string) (*madmin.AdminClient, *probe.Error) {
alias, urlStrFull, hostCfg, err := expandAlias(aliasedURL)
if err != nil {
return nil, err.Trace(aliasedURL)
}
// Verify if the aliasedURL is a real URL, fail in those cases
// indicating the user to add alias.
if hostCfg == nil && urlRgx.MatchString(aliasedURL) {
return nil, errInvalidAliasedURL(aliasedURL).Trace(aliasedURL)
}
if hostCfg == nil {
return nil, probe.NewError(fmt.Errorf("The specified alias: %s not found", urlStrFull))
}
s3Config := newS3Config(urlStrFull, hostCfg)
s3Client, err := s3AdminNew(s3Config)
if err != nil {
return nil, err.Trace(alias, urlStrFull)
}
return s3Client, nil
}
// s3AdminNew returns an initialized minioAdmin structure. If debug is enabled,
// it also enables an internal trace transport.
var s3AdminNew = newAdminFactory()
+47 -43
View File
@@ -1,5 +1,5 @@
/*
* Minio Client (C) 2015 Minio, Inc.
* 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.
@@ -14,12 +14,9 @@
* limitations under the License.
*/
package client
package cmd
import (
"fmt"
"strconv"
)
import "fmt"
/// Collection of standard errors
@@ -30,16 +27,7 @@ type APINotImplemented struct {
}
func (e APINotImplemented) Error() string {
return "‘" + e.API + "’ feature " + "is not implemented for ‘" + e.APIType + "’."
}
// InvalidRange - invalid range requested
type InvalidRange struct {
Offset int64
}
func (e InvalidRange) Error() string {
return "Invalid range offset: ‘" + strconv.FormatInt(e.Offset, 10) + "’."
return "`" + e.API + "` is not supported for `" + e.APIType + "`."
}
// GenericBucketError - generic bucket operations error
@@ -51,21 +39,14 @@ type GenericBucketError struct {
type BucketDoesNotExist GenericBucketError
func (e BucketDoesNotExist) Error() string {
return "Bucket ‘" + e.Bucket + "’ does not exist."
return "Bucket `" + e.Bucket + "` does not exist."
}
// BucketExists - bucket exists.
type BucketExists GenericBucketError
func (e BucketExists) Error() string {
return "Bucket ‘" + e.Bucket + "’ exists."
}
// InvalidBucketName - bucket name invalid (http://goo.gl/wJlzDz)
type InvalidBucketName GenericBucketError
func (e InvalidBucketName) Error() string {
return "Invalid bucketname [‘" + e.Bucket + "’], please read http://goo.gl/wJlzDz."
return "Bucket `" + e.Bucket + "` exists."
}
// BucketNameEmpty - bucket name empty (http://goo.gl/wJlzDz)
@@ -75,10 +56,13 @@ func (e BucketNameEmpty) Error() string {
return "Bucket name cannot be empty."
}
// GenericObjectError - generic object operations error
type GenericObjectError struct {
// BucketInvalid - bucket name invalid.
type BucketInvalid struct {
Bucket string
Object string
}
func (e BucketInvalid) Error() string {
return "Bucket name " + e.Bucket + " not valid."
}
// ObjectAlreadyExists - typed return for MethodNotAllowed
@@ -87,21 +71,32 @@ type ObjectAlreadyExists struct {
}
func (e ObjectAlreadyExists) Error() string {
return "Object ‘" + e.Object + "’ already exists."
return "Object `" + e.Object + "` already exists."
}
// InvalidObjectName - object requested is invalid
type InvalidObjectName GenericObjectError
// ObjectAlreadyExistsAsDirectory - typed return for XMinioObjectExistsAsDirectory
type ObjectAlreadyExistsAsDirectory struct {
Object string
}
func (e InvalidObjectName) Error() string {
return "Object ‘" + e.Object + "’ at ‘" + e.Bucket + "’ is invalid."
func (e ObjectAlreadyExistsAsDirectory) Error() string {
return "Object `" + e.Object + "` already exists as directory."
}
// ObjectOnGlacier - object is of storage class glacier.
type ObjectOnGlacier struct {
Object string
}
func (e ObjectOnGlacier) Error() string {
return "Object `" + e.Object + "` is on Glacier storage."
}
// BucketNameTopLevel - generic error
type BucketNameTopLevel struct{}
func (e BucketNameTopLevel) Error() string {
return "Buckets can only be created at the top level."
return "Buckets or prefixes can only be created with `/` suffix."
}
// GenericFileError - generic file error.
@@ -113,35 +108,35 @@ type GenericFileError struct {
type PathNotFound GenericFileError
func (e PathNotFound) Error() string {
return "Requested file ‘" + e.Path + "’ not found"
return "Requested file `" + e.Path + "` not found"
}
// PathIsNotRegular (ENOTREG) - file is not a regular file.
type PathIsNotRegular GenericFileError
func (e PathIsNotRegular) Error() string {
return "Requested file ‘" + e.Path + "’ is not a regular file."
return "Requested file `" + e.Path + "` is not a regular file."
}
// PathInsufficientPermission (EPERM) - permission denied.
type PathInsufficientPermission GenericFileError
func (e PathInsufficientPermission) Error() string {
return "Insufficient permissions to access this file ‘" + e.Path + "’"
return "Insufficient permissions to access this file `" + e.Path + "`"
}
// BrokenSymlink (ENOTENT) - file has broken symlink.
type BrokenSymlink GenericFileError
func (e BrokenSymlink) Error() string {
return "Requested file ‘" + e.Path + "’ has broken symlink"
return "Requested file `" + e.Path + "` has broken symlink"
}
// TooManyLevelsSymlink (ELOOP) - file has too many levels of symlinks.
type TooManyLevelsSymlink GenericFileError
func (e TooManyLevelsSymlink) Error() string {
return "Requested file ‘" + e.Path + "’ has too many levels of symlinks"
return "Requested file `" + e.Path + "` has too many levels of symlinks"
}
// EmptyPath (EINVAL) - invalid argument.
@@ -155,7 +150,7 @@ func (e EmptyPath) Error() string {
type ObjectMissing struct{}
func (e ObjectMissing) Error() string {
return "Object key is missing, object key cannot be empty"
return "Object does not exist"
}
// UnexpectedShortWrite - write wrote less bytes than expected.
@@ -165,7 +160,7 @@ type UnexpectedShortWrite struct {
}
func (e UnexpectedShortWrite) Error() string {
msg := fmt.Sprintf("Wrote less data than requested. Expected ‘%d’ bytes, but only wrote ‘%d’ bytes.", e.InputSize, e.WriteSize)
msg := fmt.Sprintf("Wrote less data than requested. Expected `%d` bytes, but only wrote `%d` bytes.", e.InputSize, e.WriteSize)
return msg
}
@@ -176,7 +171,7 @@ type UnexpectedEOF struct {
}
func (e UnexpectedEOF) Error() string {
msg := fmt.Sprintf("Input reader closed pre-maturely. Expected ‘%d’ bytes, but only received ‘%d’ bytes.", e.TotalSize, e.TotalWritten)
msg := fmt.Sprintf("Input reader closed pre-maturely. Expected `%d` bytes, but only received `%d` bytes.", e.TotalSize, e.TotalWritten)
return msg
}
@@ -184,6 +179,15 @@ func (e UnexpectedEOF) Error() string {
type UnexpectedExcessRead UnexpectedEOF
func (e UnexpectedExcessRead) Error() string {
msg := fmt.Sprintf("Received excess data on input reader. Expected only ‘%d’ bytes, but received ‘%d’ bytes.", e.TotalSize, e.TotalWritten)
msg := fmt.Sprintf("Received excess data on input reader. Expected only `%d` bytes, but received `%d` bytes.", e.TotalSize, e.TotalWritten)
return msg
}
// SameFile - source and destination are same files.
type SameFile struct {
Source, Destination string
}
func (e SameFile) Error() string {
return fmt.Sprintf("'%s' and '%s' are the same file", e.Source, e.Destination)
}
+1049
View File
File diff suppressed because it is too large Load Diff
+87
View File
@@ -0,0 +1,87 @@
// +build darwin
/*
* MinIO Client (C) 2017 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this fs 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/pkg/xattr"
"github.com/rjeczalik/notify"
)
var (
// EventTypePut contains the notify events that will cause a put (writer)
EventTypePut = []notify.Event{notify.Create, notify.Write, notify.Rename}
// EventTypeDelete contains the notify events that will cause a delete (remove)
EventTypeDelete = []notify.Event{notify.Remove}
// EventTypeGet contains the notify events that will cause a get (read)
EventTypeGet = []notify.Event{} // On macOS, FreeBSD, Solaris this is not available.
)
// IsGetEvent checks if the event return is a get event.
func IsGetEvent(event notify.Event) bool {
return false
}
// IsPutEvent checks if the event returned is a put event
func IsPutEvent(event notify.Event) bool {
for _, ev := range EventTypePut {
if event&ev != 0 {
return true
}
}
return false
}
// IsDeleteEvent checks if the event returned is a delete event
func IsDeleteEvent(event notify.Event) bool {
return event&notify.Remove != 0
}
// getXAttr fetches the extended attribute for a particular key on
// file
func getXAttr(path, key string) (string, error) {
data, e := xattr.Get(path, key)
if e != nil {
return "", e
}
return string(data), nil
}
// getAllXattrs returns the extended attributes for a file if supported
// by the OS
func getAllXattrs(path string) (map[string]string, error) {
xMetadata := make(map[string]string)
list, e := xattr.List(path)
if e != nil {
if isNotSupported(e) {
return nil, nil
}
return nil, e
}
for _, key := range list {
xMetadata[key], e = getXAttr(path, key)
if e != nil {
if isNotSupported(e) {
return nil, nil
}
return nil, e
}
}
return xMetadata, nil
}
+87
View File
@@ -0,0 +1,87 @@
// +build freebsd
/*
* MinIO Client (C) 2017 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this fs 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/pkg/xattr"
"github.com/rjeczalik/notify"
)
var (
// EventTypePut contains the notify events that will cause a put (writer)
EventTypePut = []notify.Event{notify.Create, notify.Write, notify.Rename}
// EventTypeDelete contains the notify events that will cause a delete (remove)
EventTypeDelete = []notify.Event{notify.Remove}
// EventTypeGet contains the notify events that will cause a get (read)
EventTypeGet = []notify.Event{} // On macOS, FreeBSD, Solaris this is not available.
)
// IsGetEvent checks if the event return is a get event.
func IsGetEvent(event notify.Event) bool {
return false
}
// IsPutEvent checks if the event returned is a put event
func IsPutEvent(event notify.Event) bool {
for _, ev := range EventTypePut {
if event&ev != 0 {
return true
}
}
return false
}
// IsDeleteEvent checks if the event returned is a delete event
func IsDeleteEvent(event notify.Event) bool {
return event&notify.Remove != 0
}
// getXAttr fetches the extended attribute for a particular key on
// file
func getXAttr(path, key string) (string, error) {
data, e := xattr.Get(path, key)
if e != nil {
return "", e
}
return string(data), nil
}
// getAllXattrs returns the extended attributes for a file if supported
// by the OS
func getAllXattrs(path string) (map[string]string, error) {
xMetadata := make(map[string]string)
list, e := xattr.List(path)
if e != nil {
if isNotSupported(e) {
return nil, nil
}
return nil, e
}
for _, key := range list {
xMetadata[key], e = getXAttr(path, key)
if e != nil {
if isNotSupported(e) {
return nil, nil
}
return nil, e
}
}
return xMetadata, nil
}
+108
View File
@@ -0,0 +1,108 @@
// +build linux
/*
* MinIO Client (C) 2015, 2016, 2017 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this fs 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 (
"encoding/hex"
"strings"
"github.com/pkg/xattr"
"github.com/rjeczalik/notify"
"unicode/utf8"
)
var (
// EventTypePut contains the notify events that will cause a put (write)
EventTypePut = []notify.Event{notify.InCloseWrite | notify.InMovedTo}
// EventTypeDelete contains the notify events that will cause a delete (remove)
EventTypeDelete = []notify.Event{notify.InDelete | notify.InDeleteSelf | notify.InMovedFrom}
// EventTypeGet contains the notify events that will cause a get (read)
EventTypeGet = []notify.Event{notify.InAccess | notify.InOpen}
)
// IsGetEvent checks if the event return is a get event.
func IsGetEvent(event notify.Event) bool {
for _, ev := range EventTypeGet {
if event&ev != 0 {
return true
}
}
return false
}
// IsPutEvent checks if the event returned is a put event
func IsPutEvent(event notify.Event) bool {
for _, ev := range EventTypePut {
if event&ev != 0 {
return true
}
}
return false
}
// IsDeleteEvent checks if the event returned is a delete event
func IsDeleteEvent(event notify.Event) bool {
for _, ev := range EventTypeDelete {
if event&ev != 0 {
return true
}
}
return false
}
// getXAttr fetches the extended attribute for a particular key on
// file
func getXAttr(path, key string) (string, error) {
data, e := xattr.Get(path, key)
if e != nil {
return "", e
}
if utf8.ValidString(string(data)) {
return string(data), nil
}
return hex.EncodeToString(data), nil
}
// getAllXattrs returns the extended attributes for a file if supported
// by the OS
func getAllXattrs(path string) (map[string]string, error) {
xMetadata := make(map[string]string)
list, e := xattr.List(path)
if e != nil {
if isNotSupported(e) {
return nil, nil
}
return nil, e
}
for _, key := range list {
// filter out system specific xattr
if strings.HasPrefix(key, "system.") {
continue
}
xMetadata[key], e = getXAttr(path, key)
if e != nil {
if isNotSupported(e) {
return nil, nil
}
return nil, e
}
}
return xMetadata, nil
}
+56
View File
@@ -0,0 +1,56 @@
// +build solaris openbsd
/*
* MinIO Client (C) 2015, 2016, 2017 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this fs 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/rjeczalik/notify"
var (
// EventTypePut contains the notify events that will cause a put (writer)
EventTypePut = []notify.Event{notify.Create, notify.Write, notify.Rename}
// EventTypeDelete contains the notify events that will cause a delete (remove)
EventTypeDelete = []notify.Event{notify.Remove}
// EventTypeGet contains the notify events that will cause a get (read)
EventTypeGet = []notify.Event{} // On macOS, FreeBSD, Solaris this is not available.
)
// IsGetEvent checks if the event return is a get event.
func IsGetEvent(event notify.Event) bool {
return false
}
// IsPutEvent checks if the event returned is a put event
func IsPutEvent(event notify.Event) bool {
for _, ev := range EventTypePut {
if event&ev != 0 {
return true
}
}
return false
}
// IsDeleteEvent checks if the event returned is a delete event
func IsDeleteEvent(event notify.Event) bool {
return event&notify.Remove != 0
}
// getAtllXAttrs returns the extended attributes for a file if supported
// by the OS
func getAllXattrs(path string) (map[string]string, error) {
return nil, nil
}
@@ -1,5 +1,5 @@
/*
* Minio Client (C) 2015 Minio, Inc.
* MinIO Client (C) 2015 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this fs except in compliance with the License.
@@ -14,61 +14,58 @@
* limitations under the License.
*/
package fs_test
package cmd
import (
"bytes"
"context"
"io"
"io/ioutil"
"os"
"path/filepath"
"testing"
"runtime"
"github.com/minio/mc/pkg/client"
"github.com/minio/mc/pkg/client/fs"
. "gopkg.in/check.v1"
)
func Test(t *testing.T) { TestingT(t) }
type MySuite struct{}
var _ = Suite(&MySuite{})
// Test list files in a folder.
func (s *MySuite) TestList(c *C) {
func (s *TestSuite) TestList(c *C) {
root, e := ioutil.TempDir(os.TempDir(), "fs-")
c.Assert(e, IsNil)
defer os.RemoveAll(root)
// Create multiple files.
objectPath := filepath.Join(root, "object1")
fsClient, err := fs.New(objectPath)
fsClient, err := fsNew(objectPath)
c.Assert(err, IsNil)
data := "hello"
reader := bytes.NewReader([]byte(data))
var n int64
n, err = fsClient.Put(reader, int64(len(data)), "application/octet-stream", nil)
n, err = fsClient.Put(context.Background(), reader, int64(len(data)), map[string]string{
"Content-Type": "application/octet-stream",
}, nil, nil)
c.Assert(err, IsNil)
c.Assert(n, Equals, int64(len(data)))
objectPath = filepath.Join(root, "object2")
fsClient, err = fs.New(objectPath)
fsClient, err = fsNew(objectPath)
c.Assert(err, IsNil)
reader = bytes.NewReader([]byte(data))
n, err = fsClient.Put(reader, int64(len(data)), "application/octet-stream", nil)
n, err = fsClient.Put(context.Background(), reader, int64(len(data)), map[string]string{
"Content-Type": "application/octet-stream",
}, nil, nil)
c.Assert(err, IsNil)
c.Assert(n, Equals, int64(len(data)))
fsClient, err = fs.New(root)
fsClient, err = fsNew(root)
c.Assert(err, IsNil)
// Verify previously create files and list them.
var contents []*client.Content
for content := range fsClient.List(false, false) {
var contents []*clientContent
for content := range fsClient.List(false, false, DirNone) {
if content.Err != nil {
err = content.Err
break
@@ -81,20 +78,22 @@ func (s *MySuite) TestList(c *C) {
// Create another file.
objectPath = filepath.Join(root, "test1/newObject1")
fsClient, err = fs.New(objectPath)
fsClient, err = fsNew(objectPath)
c.Assert(err, IsNil)
reader = bytes.NewReader([]byte(data))
n, err = fsClient.Put(reader, int64(len(data)), "application/octet-stream", nil)
n, err = fsClient.Put(context.Background(), reader, int64(len(data)), map[string]string{
"Content-Type": "application/octet-stream",
}, nil, nil)
c.Assert(err, IsNil)
c.Assert(n, Equals, int64(len(data)))
fsClient, err = fs.New(root)
fsClient, err = fsNew(root)
c.Assert(err, IsNil)
contents = nil
// List non recursive to list only top level files.
for content := range fsClient.List(false, false) {
for content := range fsClient.List(false, false, DirNone) {
if content.Err != nil {
err = content.Err
break
@@ -105,12 +104,12 @@ func (s *MySuite) TestList(c *C) {
c.Assert(len(contents), Equals, 1)
c.Assert(contents[0].Type.IsDir(), Equals, true)
fsClient, err = fs.New(root)
fsClient, err = fsNew(root)
c.Assert(err, IsNil)
contents = nil
// List recursively all files and verify.
for content := range fsClient.List(true, false) {
for content := range fsClient.List(true, false, DirNone) {
if content.Err != nil {
err = content.Err
break
@@ -119,7 +118,7 @@ func (s *MySuite) TestList(c *C) {
}
c.Assert(err, IsNil)
c.Assert(len(contents), Equals, 5)
c.Assert(len(contents), Equals, 3)
var regularFiles int
var regularDirs int
@@ -134,94 +133,149 @@ func (s *MySuite) TestList(c *C) {
continue
}
}
c.Assert(regularDirs, Equals, 2)
c.Assert(regularDirs, Equals, 0)
c.Assert(regularFiles, Equals, 3)
// Create an ignored file and list to verify if its ignored.
objectPath = filepath.Join(root, "test1/.DS_Store")
fsClient, err = fsNew(objectPath)
c.Assert(err, IsNil)
reader = bytes.NewReader([]byte(data))
n, err = fsClient.Put(context.Background(), reader, int64(len(data)), map[string]string{
"Content-Type": "application/octet-stream",
}, nil, nil)
c.Assert(err, IsNil)
c.Assert(n, Equals, int64(len(data)))
fsClient, err = fsNew(root)
c.Assert(err, IsNil)
contents = nil
// List recursively all files and verify.
for content := range fsClient.List(true, false, DirNone) {
if content.Err != nil {
err = content.Err
break
}
contents = append(contents, content)
}
c.Assert(err, IsNil)
switch runtime.GOOS {
case "darwin":
c.Assert(len(contents), Equals, 3)
default:
c.Assert(len(contents), Equals, 4)
}
regularFiles = 0
// Test number of expected files.
for _, content := range contents {
if content.Type.IsRegular() {
regularFiles++
continue
}
}
switch runtime.GOOS {
case "darwin":
c.Assert(regularFiles, Equals, 3)
default:
c.Assert(regularFiles, Equals, 4)
}
}
// Test put bucket aka 'mkdir()' operation.
func (s *MySuite) TestPutBucket(c *C) {
func (s *TestSuite) TestPutBucket(c *C) {
root, e := ioutil.TempDir(os.TempDir(), "fs-")
c.Assert(e, IsNil)
defer os.RemoveAll(root)
bucketPath := filepath.Join(root, "bucket")
fsClient, err := fs.New(bucketPath)
fsClient, err := fsNew(bucketPath)
c.Assert(err, IsNil)
err = fsClient.MakeBucket("us-east-1")
err = fsClient.MakeBucket("us-east-1", true)
c.Assert(err, IsNil)
}
// Test stat bucket aka 'stat()' operation.
func (s *MySuite) TestStatBucket(c *C) {
func (s *TestSuite) TestStatBucket(c *C) {
root, e := ioutil.TempDir(os.TempDir(), "fs-")
c.Assert(e, IsNil)
defer os.RemoveAll(root)
bucketPath := filepath.Join(root, "bucket")
fsClient, err := fs.New(bucketPath)
fsClient, err := fsNew(bucketPath)
c.Assert(err, IsNil)
err = fsClient.MakeBucket("us-east-1")
err = fsClient.MakeBucket("us-east-1", true)
c.Assert(err, IsNil)
_, err = fsClient.Stat()
_, err = fsClient.Stat(false, false, nil)
c.Assert(err, IsNil)
}
// Test bucket acl fails for directories.
func (s *MySuite) TestBucketACLFails(c *C) {
func (s *TestSuite) TestBucketACLFails(c *C) {
root, e := ioutil.TempDir(os.TempDir(), "fs-")
c.Assert(e, IsNil)
defer os.RemoveAll(root)
bucketPath := filepath.Join(root, "bucket")
fsClient, err := fs.New(bucketPath)
fsClient, err := fsNew(bucketPath)
c.Assert(err, IsNil)
err = fsClient.MakeBucket("us-east-1")
err = fsClient.MakeBucket("us-east-1", true)
c.Assert(err, IsNil)
err = fsClient.SetBucketAccess("private")
c.Assert(err, Not(IsNil))
// On windows setting permissions is not supported.
if runtime.GOOS != "windows" {
err = fsClient.SetAccess("readonly", false)
c.Assert(err, IsNil)
_, err = fsClient.GetBucketAccess()
c.Assert(err, Not(IsNil))
_, _, err = fsClient.GetAccess()
c.Assert(err, IsNil)
}
}
// Test creating a file.
func (s *MySuite) TestPut(c *C) {
func (s *TestSuite) TestPut(c *C) {
root, e := ioutil.TempDir(os.TempDir(), "fs-")
c.Assert(e, IsNil)
defer os.RemoveAll(root)
objectPath := filepath.Join(root, "object")
fsClient, err := fs.New(objectPath)
fsClient, err := fsNew(objectPath)
c.Assert(err, IsNil)
data := "hello"
reader := bytes.NewReader([]byte(data))
var n int64
n, err = fsClient.Put(reader, int64(len(data)), "application/octet-stream", nil)
n, err = fsClient.Put(context.Background(), reader, int64(len(data)), map[string]string{
"Content-Type": "application/octet-stream",
}, nil, nil)
c.Assert(err, IsNil)
c.Assert(n, Equals, int64(len(data)))
}
// Test read a file.
func (s *MySuite) TestGet(c *C) {
func (s *TestSuite) TestGet(c *C) {
root, e := ioutil.TempDir(os.TempDir(), "fs-")
c.Assert(e, IsNil)
defer os.RemoveAll(root)
objectPath := filepath.Join(root, "object")
fsClient, err := fs.New(objectPath)
fsClient, err := fsNew(objectPath)
c.Assert(err, IsNil)
data := "hello"
var reader io.Reader
reader = bytes.NewReader([]byte(data))
n, err := fsClient.Put(reader, int64(len(data)), "application/octet-stream", nil)
n, err := fsClient.Put(context.Background(), reader, int64(len(data)), map[string]string{
"Content-Type": "application/octet-stream",
}, nil, nil)
c.Assert(err, IsNil)
c.Assert(n, Equals, int64(len(data)))
reader, err = fsClient.Get()
reader, err = fsClient.Get(nil)
c.Assert(err, IsNil)
var results bytes.Buffer
_, e = io.Copy(&results, reader)
@@ -231,23 +285,25 @@ func (s *MySuite) TestGet(c *C) {
}
// Test get range in a file.
func (s *MySuite) TestGetRange(c *C) {
func (s *TestSuite) TestGetRange(c *C) {
root, e := ioutil.TempDir(os.TempDir(), "fs-")
c.Assert(e, IsNil)
defer os.RemoveAll(root)
objectPath := filepath.Join(root, "object")
fsClient, err := fs.New(objectPath)
fsClient, err := fsNew(objectPath)
c.Assert(err, IsNil)
data := "hello world"
var reader io.Reader
reader = bytes.NewReader([]byte(data))
n, err := fsClient.Put(reader, int64(len(data)), "application/octet-stream", nil)
n, err := fsClient.Put(context.Background(), reader, int64(len(data)), map[string]string{
"Content-Type": "application/octet-stream",
}, nil, nil)
c.Assert(err, IsNil)
c.Assert(n, Equals, int64(len(data)))
reader, err = fsClient.Get()
reader, err = fsClient.Get(nil)
c.Assert(err, IsNil)
var results bytes.Buffer
buf := make([]byte, 5)
@@ -260,23 +316,50 @@ func (s *MySuite) TestGetRange(c *C) {
}
// Test stat file.
func (s *MySuite) TestStatObject(c *C) {
func (s *TestSuite) TestStatObject(c *C) {
root, e := ioutil.TempDir(os.TempDir(), "fs-")
c.Assert(e, IsNil)
defer os.RemoveAll(root)
objectPath := filepath.Join(root, "object")
fsClient, err := fs.New(objectPath)
fsClient, err := fsNew(objectPath)
c.Assert(err, IsNil)
data := "hello"
dataLen := len(data)
reader := bytes.NewReader([]byte(data))
n, err := fsClient.Put(reader, int64(dataLen), "application/octet-stream", nil)
n, err := fsClient.Put(context.Background(), reader, int64(dataLen), map[string]string{
"Content-Type": "application/octet-stream",
}, nil, nil)
c.Assert(err, IsNil)
c.Assert(n, Equals, int64(len(data)))
content, err := fsClient.Stat()
content, err := fsClient.Stat(false, false, nil)
c.Assert(err, IsNil)
c.Assert(content.Size, Equals, int64(dataLen))
}
// Test copy.
func (s *TestSuite) TestCopy(c *C) {
root, e := ioutil.TempDir(os.TempDir(), "fs-")
c.Assert(e, IsNil)
defer os.RemoveAll(root)
sourcePath := filepath.Join(root, "source")
targetPath := filepath.Join(root, "target")
fsClientTarget, err := fsNew(targetPath)
c.Assert(err, IsNil)
fsClientSource, err := fsNew(sourcePath)
c.Assert(err, IsNil)
data := "hello world"
var reader io.Reader
reader = bytes.NewReader([]byte(data))
n, err := fsClientSource.Put(context.Background(), reader, int64(len(data)), map[string]string{
"Content-Type": "application/octet-stream",
}, nil, nil)
c.Assert(err, IsNil)
c.Assert(n, Equals, int64(len(data)))
err = fsClientTarget.Copy(sourcePath, int64(len(data)), nil, nil, nil, nil)
c.Assert(err, IsNil)
}
+56
View File
@@ -0,0 +1,56 @@
// +build windows
/*
* MinIO Client (C) 2017 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this fs 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/rjeczalik/notify"
var (
// EventTypePut contains the notify events that will cause a put (writer)
EventTypePut = []notify.Event{notify.Create, notify.Write, notify.Rename}
// EventTypeDelete contains the notify events that will cause a delete (remove)
EventTypeDelete = []notify.Event{notify.Remove}
// EventTypeGet contains the notify events that will cause a get (read)
EventTypeGet = []notify.Event{notify.FileNotifyChangeLastAccess}
)
// IsGetEvent checks if the event return is a get event.
func IsGetEvent(event notify.Event) bool {
return event&notify.FileNotifyChangeLastAccess != 0
}
// IsPutEvent checks if the event returned is a put event
func IsPutEvent(event notify.Event) bool {
for _, ev := range EventTypePut {
if event&ev != 0 {
return true
}
}
return false
}
// IsDeleteEvent checks if the event returned is a delete event
func IsDeleteEvent(event notify.Event) bool {
return event&notify.Remove != 0
}
// getAllXattrs returns the extended attributes for a file if supported
// by the OS
func getAllXattrs(path string) (map[string]string, error) {
return nil, nil
}
@@ -1,5 +1,5 @@
/*
* Minio Client (C) 2015 Minio, Inc.
* 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.
@@ -14,7 +14,7 @@
* limitations under the License.
*/
package s3
package cmd
import (
"net/http"
@@ -25,16 +25,16 @@ import (
"github.com/minio/mc/pkg/httptracer"
)
// TraceV2 - tracing structure
type TraceV2 struct{}
// traceV2 - tracing structure for signature version '2'.
type traceV2 struct{}
// NewTraceV2 - initialize Trace structure
func NewTraceV2() httptracer.HTTPTracer {
return TraceV2{}
// newTraceV2 - initialize Trace structure
func newTraceV2() httptracer.HTTPTracer {
return traceV2{}
}
// Request - Trace HTTP Request
func (t TraceV2) Request(req *http.Request) (err error) {
func (t traceV2) Request(req *http.Request) (err error) {
origAuth := req.Header.Get("Authorization")
if strings.TrimSpace(origAuth) != "" {
@@ -57,19 +57,23 @@ func (t TraceV2) Request(req *http.Request) (err error) {
}
// Response - Trace HTTP Response
func (t TraceV2) Response(res *http.Response) (err error) {
var resTrace []byte
func (t traceV2) Response(resp *http.Response) (err error) {
var respTrace []byte
// For errors we make sure to dump response body as well.
if res.StatusCode != http.StatusOK &&
res.StatusCode != http.StatusPartialContent &&
res.StatusCode != http.StatusNoContent {
resTrace, err = httputil.DumpResponse(res, true)
if resp.StatusCode != http.StatusOK &&
resp.StatusCode != http.StatusPartialContent &&
resp.StatusCode != http.StatusNoContent {
respTrace, err = httputil.DumpResponse(resp, true)
} else {
// Only display header
resTrace, err = httputil.DumpResponse(res, false)
respTrace, err = httputil.DumpResponse(resp, false)
}
if err == nil {
console.Debug(string(resTrace))
console.Debug(string(respTrace))
}
if globalInsecure && resp.TLS != nil {
dumpTLSCertificates(resp.TLS)
}
return err
}
@@ -1,5 +1,5 @@
/*
* Minio Client (C) 2015 Minio, Inc.
* 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.
@@ -14,7 +14,7 @@
* limitations under the License.
*/
package s3
package cmd
import (
"net/http"
@@ -26,18 +26,26 @@ import (
"github.com/minio/mc/pkg/httptracer"
)
// TraceV4 - tracing structure
type TraceV4 struct{}
// traceV4 - tracing structure for signature version '4'.
type traceV4 struct{}
// NewTraceV4 - initialize Trace structure
func NewTraceV4() httptracer.HTTPTracer {
return TraceV4{}
// newTraceV4 - initialize Trace structure
func newTraceV4() httptracer.HTTPTracer {
return traceV4{}
}
// Request - Trace HTTP Request
func (t TraceV4) Request(req *http.Request) (err error) {
func (t traceV4) Request(req *http.Request) (err error) {
origAuth := req.Header.Get("Authorization")
printTrace := func() error {
reqTrace, rerr := httputil.DumpRequestOut(req, false) // Only display header
if rerr == nil {
console.Debug(string(reqTrace))
}
return rerr
}
if strings.TrimSpace(origAuth) != "" {
// Authorization (S3 v4 signature) Format:
// Authorization: AWS4-HMAC-SHA256 Credential=AKIAJNACEGBGMXBHLEZA/20150524/us-east-1/s3/aws4_request, SignedHeaders=host;x-amz-content-sha256;x-amz-date, Signature=bbfaa693c626021bcb5f911cd898a1a30206c1fad6bad1e0eb89e282173bd24c
@@ -53,32 +61,34 @@ func (t TraceV4) Request(req *http.Request) (err error) {
// Set a temporary redacted auth
req.Header.Set("Authorization", newAuth)
var reqTrace []byte
reqTrace, err = httputil.DumpRequestOut(req, false) // Only display header
if err == nil {
console.Debug(string(reqTrace))
}
err = printTrace()
// Undo
req.Header.Set("Authorization", origAuth)
} else {
err = printTrace()
}
return err
}
// Response - Trace HTTP Response
func (t TraceV4) Response(res *http.Response) (err error) {
var resTrace []byte
func (t traceV4) Response(resp *http.Response) (err error) {
var respTrace []byte
// For errors we make sure to dump response body as well.
if res.StatusCode != http.StatusOK &&
res.StatusCode != http.StatusPartialContent &&
res.StatusCode != http.StatusNoContent {
resTrace, err = httputil.DumpResponse(res, true)
if resp.StatusCode != http.StatusOK &&
resp.StatusCode != http.StatusPartialContent &&
resp.StatusCode != http.StatusNoContent {
respTrace, err = httputil.DumpResponse(resp, true)
} else {
// Only display header
resTrace, err = httputil.DumpResponse(res, false)
respTrace, err = httputil.DumpResponse(resp, false)
}
if err == nil {
console.Debug(string(resTrace))
console.Debug(string(respTrace))
}
if globalInsecure && resp.TLS != nil {
dumpTLSCertificates(resp.TLS)
}
return err
}
+1954
View File
File diff suppressed because it is too large Load Diff
@@ -1,5 +1,5 @@
/*
* Minio Client (C) 2015 Minio, Inc.
* 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.
@@ -14,20 +14,18 @@
* limitations under the License.
*/
package s3
package cmd
// bucketHandler is an http.Handler that verifies bucket responses and validates incoming requests
import (
"bytes"
"context"
"io"
"net/http"
"net/http/httptest"
"strconv"
"testing"
"time"
"github.com/minio/mc/pkg/client"
minio "github.com/minio/minio-go/v6"
. "gopkg.in/check.v1"
)
@@ -60,13 +58,6 @@ func (h bucketHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
case r.Method == "PUT":
switch {
case r.URL.Path == h.resource:
// Handler for incoming SetBucketACL request.
_, ok := r.URL.Query()["acl"]
if ok {
if r.Header.Get("x-amz-acl") != "public-read-write" {
w.WriteHeader(http.StatusNotImplemented)
}
}
w.WriteHeader(http.StatusOK)
default:
w.WriteHeader(http.StatusBadRequest)
@@ -101,10 +92,6 @@ func (h objectHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusInternalServerError)
return
}
if !bytes.Equal(h.data, buffer.Bytes()) {
w.WriteHeader(http.StatusInternalServerError)
return
}
w.Header().Set("ETag", "9af2f8218b150c351ad802c6f3d66abe")
w.WriteHeader(http.StatusOK)
case r.Method == "HEAD":
@@ -114,7 +101,7 @@ func (h objectHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
return
}
w.Header().Set("Content-Length", strconv.Itoa(len(h.data)))
w.Header().Set("Last-Modified", time.Now().UTC().Format(http.TimeFormat))
w.Header().Set("Last-Modified", UTCNow().Format(http.TimeFormat))
w.Header().Set("ETag", "9af2f8218b150c351ad802c6f3d66abe")
w.WriteHeader(http.StatusOK)
case r.Method == "POST":
@@ -161,71 +148,62 @@ func (h objectHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
return
}
w.Header().Set("Content-Length", strconv.Itoa(len(h.data)))
w.Header().Set("Last-Modified", time.Now().UTC().Format(http.TimeFormat))
w.Header().Set("Last-Modified", UTCNow().Format(http.TimeFormat))
w.Header().Set("ETag", "9af2f8218b150c351ad802c6f3d66abe")
w.WriteHeader(http.StatusOK)
io.Copy(w, bytes.NewReader(h.data))
}
}
func Test(t *testing.T) { TestingT(t) }
type MySuite struct{}
var _ = Suite(&MySuite{})
// Test bucket operations.
func (s *MySuite) TestBucketOperations(c *C) {
func (s *TestSuite) TestBucketOperations(c *C) {
bucket := bucketHandler(bucketHandler{
resource: "/bucket/",
})
server := httptest.NewServer(bucket)
defer server.Close()
conf := new(client.Config)
conf := new(Config)
conf.HostURL = server.URL + bucket.resource
conf.AccessKey = "WLGDGYAQYIGI833EV05A"
conf.SecretKey = "BYvgJM101sHngl2uzjXS/OBF/aMxAN06JrJ3qJlF"
conf.Signature = "S3v4"
s3c, err := New(conf)
s3c, err := s3New(conf)
c.Assert(err, IsNil)
err = s3c.MakeBucket("us-east-1")
c.Assert(err, IsNil)
err = s3c.SetBucketAccess("public-read-write")
err = s3c.MakeBucket("us-east-1", true)
c.Assert(err, IsNil)
conf.HostURL = server.URL + string(s3c.GetURL().Separator)
s3c, err = New(conf)
s3c, err = s3New(conf)
c.Assert(err, IsNil)
for content := range s3c.List(false, false) {
for content := range s3c.List(false, false, DirNone) {
c.Assert(content.Err, IsNil)
c.Assert(content.Type.IsDir(), Equals, true)
}
conf.HostURL = server.URL + "/bucket"
s3c, err = New(conf)
s3c, err = s3New(conf)
c.Assert(err, IsNil)
for content := range s3c.List(false, false) {
for content := range s3c.List(false, false, DirNone) {
c.Assert(content.Err, IsNil)
c.Assert(content.Type.IsDir(), Equals, true)
}
conf.HostURL = server.URL + "/bucket/"
s3c, err = New(conf)
s3c, err = s3New(conf)
c.Assert(err, IsNil)
for content := range s3c.List(false, false) {
for content := range s3c.List(false, false, DirNone) {
c.Assert(content.Err, IsNil)
c.Assert(content.Type.IsRegular(), Equals, true)
}
}
// Test all object operations.
func (s *MySuite) TestObjectOperations(c *C) {
func (s *TestSuite) TestObjectOperations(c *C) {
object := objectHandler(objectHandler{
resource: "/bucket/object",
data: []byte("Hello, World"),
@@ -233,26 +211,24 @@ func (s *MySuite) TestObjectOperations(c *C) {
server := httptest.NewServer(object)
defer server.Close()
conf := new(client.Config)
conf := new(Config)
conf.HostURL = server.URL + object.resource
conf.AccessKey = "WLGDGYAQYIGI833EV05A"
conf.SecretKey = "BYvgJM101sHngl2uzjXS/OBF/aMxAN06JrJ3qJlF"
conf.Signature = "S3v4"
s3c, err := New(conf)
s3c, err := s3New(conf)
c.Assert(err, IsNil)
var reader io.Reader
reader = bytes.NewReader(object.data)
n, err := s3c.Put(reader, int64(len(object.data)), "application/octet-stream", nil)
n, err := s3c.Put(context.Background(), reader, int64(len(object.data)), map[string]string{
"Content-Type": "application/octet-stream",
}, nil, nil)
c.Assert(err, IsNil)
c.Assert(n, Equals, int64(len(object.data)))
content, err := s3c.Stat()
reader, err = s3c.Get(nil)
c.Assert(err, IsNil)
c.Assert(content.Size, Equals, int64(len(object.data)))
c.Assert(content.Type.IsRegular(), Equals, true)
reader, err = s3c.Get()
var buffer bytes.Buffer
{
_, err := io.Copy(&buffer, reader)
@@ -260,3 +236,28 @@ func (s *MySuite) TestObjectOperations(c *C) {
c.Assert(buffer.Bytes(), DeepEquals, object.data)
}
}
var testSelectCompressionTypeCases = []struct {
opts SelectObjectOpts
object string
compressionType minio.SelectCompressionType
}{
{SelectObjectOpts{CompressionType: minio.SelectCompressionNONE}, "a.gzip", minio.SelectCompressionNONE},
{SelectObjectOpts{CompressionType: minio.SelectCompressionBZIP}, "a.gz", minio.SelectCompressionBZIP},
{SelectObjectOpts{}, "t.parquet", minio.SelectCompressionNONE},
{SelectObjectOpts{}, "x.csv.gz", minio.SelectCompressionGZIP},
{SelectObjectOpts{}, "x.json.bz2", minio.SelectCompressionBZIP},
{SelectObjectOpts{}, "b.gz", minio.SelectCompressionGZIP},
{SelectObjectOpts{}, "k.bz2", minio.SelectCompressionBZIP},
{SelectObjectOpts{}, "a.csv", minio.SelectCompressionNONE},
{SelectObjectOpts{}, "a.json", minio.SelectCompressionNONE},
}
// TestSelectCompressionType - tests compression type returned
// by method
func (s *TestSuite) TestSelectCompressionType(c *C) {
for _, test := range testSelectCompressionTypeCases {
cType := selectCompressionType(test.opts, test.object)
c.Assert(cType, DeepEquals, test.compressionType)
}
}
+94 -23
View File
@@ -1,5 +1,5 @@
/*
* Minio Client (C) 2015 Minio, Inc.
* 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.
@@ -14,7 +14,7 @@
* limitations under the License.
*/
package client
package cmd
import (
"bytes"
@@ -22,11 +22,14 @@ import (
"regexp"
"runtime"
"strings"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio/pkg/mimedb"
)
// URL client url structure
type URL struct {
Type URLType
// url client url structure
type clientURL struct {
Type clientURLType
Scheme string
Host string
Path string
@@ -34,13 +37,13 @@ type URL struct {
Separator rune
}
// URLType - enum of different url types
type URLType int
// clientURLType - enum of different url types
type clientURLType int
// enum types
const (
Object = iota // Minio and S3 compatible cloud storage
Filesystem // POSIX compatible file systems
objectStorage = iota // MinIO and S3 compatible cloud storage
fileSystem // POSIX compatible file systems
)
// Maybe rawurl is of the form scheme:path. (Scheme must be [a-zA-Z][a-zA-Z0-9+-.]*)
@@ -87,10 +90,9 @@ func getHost(authority string) (host string) {
return authority
}
// NewURL returns an abstracted URL for filesystems and object storage.
func NewURL(urlStr string) *URL {
// newClientURL returns an abstracted URL for filesystems and object storage.
func newClientURL(urlStr string) *clientURL {
scheme, rest := getScheme(urlStr)
rest, _ = splitSpecial(rest, "?", true)
if strings.HasPrefix(rest, "//") {
// if rest has '//' prefix, skip them
var authority string
@@ -100,9 +102,9 @@ func NewURL(urlStr string) *URL {
}
host := getHost(authority)
if host != "" && (scheme == "http" || scheme == "https") {
return &URL{
return &clientURL{
Scheme: scheme,
Type: Object,
Type: objectStorage,
Host: host,
Path: rest,
SchemeSeparator: "://",
@@ -110,15 +112,15 @@ func NewURL(urlStr string) *URL {
}
}
}
return &URL{
Type: Filesystem,
return &clientURL{
Type: fileSystem,
Path: rest,
Separator: filepath.Separator,
}
}
// JoinURLs join two input urls and returns a url
func JoinURLs(url1, url2 *URL) *URL {
// joinURLs join two input urls and returns a url
func joinURLs(url1, url2 *clientURL) *clientURL {
var url1Path, url2Path string
url1Path = filepath.ToSlash(url1.Path)
url2Path = filepath.ToSlash(url2.Path)
@@ -131,14 +133,14 @@ func JoinURLs(url1, url2 *URL) *URL {
}
// String convert URL into its canonical form.
func (u URL) String() string {
func (u clientURL) String() string {
var buf bytes.Buffer
// if fileystem no translation needed, return as is.
if u.Type == Filesystem {
// if fileSystem no translation needed, return as is.
if u.Type == fileSystem {
return u.Path
}
// if Object convert from any non standard paths to a supported URL path style.
if u.Type == Object {
// if objectStorage convert from any non standard paths to a supported URL path style.
if u.Type == objectStorage {
buf.WriteString(u.Scheme)
buf.WriteByte(':')
buf.WriteString("//")
@@ -160,3 +162,72 @@ func (u URL) String() string {
}
return buf.String()
}
// urlJoinPath Join a path to existing URL.
func urlJoinPath(url1, url2 string) string {
u1 := newClientURL(url1)
u2 := newClientURL(url2)
return joinURLs(u1, u2).String()
}
// url2Stat returns stat info for URL.
func url2Stat(urlStr string, isFetchMeta bool, encKeyDB map[string][]prefixSSEPair) (client Client, content *clientContent, err *probe.Error) {
client, err = newClient(urlStr)
if err != nil {
return nil, nil, err.Trace(urlStr)
}
alias, _ := url2Alias(urlStr)
sse := getSSE(urlStr, encKeyDB[alias])
content, err = client.Stat(false, isFetchMeta, sse)
if err != nil {
return nil, nil, err.Trace(urlStr)
}
return client, content, nil
}
// url2Alias separates alias and path from the URL. Aliased URL is of
// the form alias/path/to/blah.
func url2Alias(aliasedURL string) (alias, path string) {
// Save aliased url.
urlStr := aliasedURL
// Convert '/' on windows to filepath.Separator.
urlStr = filepath.FromSlash(urlStr)
if runtime.GOOS == "windows" {
// Remove '/' prefix before alias if any to support '\\home' alias
// style under Windows
urlStr = strings.TrimPrefix(urlStr, string(filepath.Separator))
}
// Remove everything after alias (i.e. after '/').
urlParts := strings.SplitN(urlStr, string(filepath.Separator), 2)
if len(urlParts) == 2 {
// Convert windows style path separator to Unix style.
return urlParts[0], urlParts[1]
}
return urlParts[0], ""
}
// isURLPrefixExists - check if object key prefix exists.
func isURLPrefixExists(urlPrefix string, incomplete bool) bool {
clnt, err := newClient(urlPrefix)
if err != nil {
return false
}
isRecursive := false
isIncomplete := incomplete
for entry := range clnt.List(isRecursive, isIncomplete, DirNone) {
return entry.Err == nil
}
return false
}
// guessURLContentType - guess content-type of the URL.
// on failure just return 'application/octet-stream'.
func guessURLContentType(urlStr string) string {
url := newClientURL(urlStr)
contentType := mimedb.TypeByExtension(filepath.Ext(url.Path))
return contentType
}
+17 -3
View File
@@ -1,5 +1,5 @@
/*
* Minio Client (C) 2015 Minio, Inc.
* 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.
@@ -14,10 +14,24 @@
* limitations under the License.
*/
package main
package cmd
import . "gopkg.in/check.v1"
// TestURL - tests url parsing and fields.
func (s *TestSuite) TestURL(c *C) {
urlStr := "foo?.go"
url := newClientURL(urlStr)
c.Assert(url.Path, Equals, "foo?.go")
urlStr = "https://s3.amazonaws.com/mybucket/foo?.go"
url = newClientURL(urlStr)
c.Assert(url.Scheme, Equals, "https")
c.Assert(url.Host, Equals, "s3.amazonaws.com")
c.Assert(url.Path, Equals, "/mybucket/foo?.go")
}
// TestURLJoinPath - tests joining two different urls.
func (s *TestSuite) TestURLJoinPath(c *C) {
// Join two URLs
url1 := "http://s3.mycompany.io/dev"
@@ -31,7 +45,7 @@ func (s *TestSuite) TestURLJoinPath(c *C) {
url = urlJoinPath(url1, url2)
c.Assert(url, Equals, "http://s3.mycompany.io/dev/mybucket/bin/zgrep")
// Check if it strips URL2's tailing ‘/’
// Check if it strips URL2's tailing `/`
url1 = "http://s3.mycompany.io/dev"
url2 = "mybucket/bin/"
url = urlJoinPath(url1, url2)
+116
View File
@@ -0,0 +1,116 @@
/*
* 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 (
"context"
"io"
"os"
"time"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio-go/v6"
"github.com/minio/minio-go/v6/pkg/encrypt"
)
// DirOpt - list directory option.
type DirOpt int8
const (
// DirNone - do not include directories in the list.
DirNone DirOpt = iota
// DirFirst - include directories before objects in the list.
DirFirst
// DirLast - include directories after objects in the list.
DirLast
)
// Default number of multipart workers for a Put operation.
const defaultMultipartThreadsNum = 4
// Client - client interface
type Client interface {
// Common operations
Stat(isIncomplete, isFetchMeta bool, sse encrypt.ServerSide) (content *clientContent, err *probe.Error)
List(isRecursive, isIncomplete bool, showDir DirOpt) <-chan *clientContent
// Bucket operations
MakeBucket(region string, ignoreExisting bool) *probe.Error
// Access policy operations.
GetAccess() (access string, policyJSON string, error *probe.Error)
GetAccessRules() (policyRules map[string]string, error *probe.Error)
SetAccess(access string, isJSON bool) *probe.Error
// I/O operations
Copy(source string, size int64, progress io.Reader, srcSSE, tgtSSE encrypt.ServerSide, metadata map[string]string) *probe.Error
// Runs select expression on object storage on specific files.
Select(expression string, sse encrypt.ServerSide, opts SelectObjectOpts) (io.ReadCloser, *probe.Error)
// I/O operations with metadata.
Get(sse encrypt.ServerSide) (reader io.ReadCloser, err *probe.Error)
Put(ctx context.Context, reader io.Reader, size int64, metadata map[string]string, progress io.Reader, sse encrypt.ServerSide) (n int64, err *probe.Error)
// I/O operations with expiration
ShareDownload(expires time.Duration) (string, *probe.Error)
ShareUpload(bool, time.Duration, string) (string, map[string]string, *probe.Error)
// Watch events
Watch(params watchParams) (*watchObject, *probe.Error)
// Delete operations
Remove(isIncomplete, isRemoveBucket bool, contentCh <-chan *clientContent) (errorCh <-chan *probe.Error)
// GetURL returns back internal url
GetURL() clientURL
}
// Content container for content metadata
type clientContent struct {
URL clientURL
Time time.Time
Size int64
Type os.FileMode
Metadata map[string]string
UserMetadata map[string]string
ETag string
Expires time.Time
EncryptionHeaders map[string]string
Err *probe.Error
}
// Config - see http://docs.amazonwebservices.com/AmazonS3/latest/dev/index.html?RESTAuthentication.html
type Config struct {
AccessKey string
SecretKey string
Signature string
HostURL string
AppName string
AppVersion string
AppComments []string
Debug bool
Insecure bool
Lookup minio.BucketLookupType
}
// SelectObjectOpts - opts entered for select API
type SelectObjectOpts struct {
InputSerOpts map[string]map[string]string
OutputSerOpts map[string]map[string]string
CompressionType minio.SelectCompressionType
}
+338
View File
@@ -0,0 +1,338 @@
/*
* 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 (
"context"
"io"
"os"
"path/filepath"
"regexp"
"strings"
"golang.org/x/net/http/httpguts"
"gopkg.in/h2non/filetype.v1"
"github.com/minio/cli"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio-go/v6/pkg/encrypt"
)
// parse and return encryption key pairs per alias.
func getEncKeys(ctx *cli.Context) (map[string][]prefixSSEPair, *probe.Error) {
sseServer := os.Getenv("MC_ENCRYPT")
if prefix := ctx.String("encrypt"); prefix != "" {
sseServer = prefix
}
sseKeys := os.Getenv("MC_ENCRYPT_KEY")
if keyPrefix := ctx.String("encrypt-key"); keyPrefix != "" {
if sseServer != "" && strings.Contains(keyPrefix, sseServer) {
return nil, errConflictSSE(sseServer, keyPrefix).Trace(ctx.Args()...)
}
sseKeys = keyPrefix
}
encKeyDB, err := parseAndValidateEncryptionKeys(sseKeys, sseServer)
if err != nil {
return nil, err.Trace(sseKeys)
}
return encKeyDB, nil
}
// Check if the passed URL represents a folder. It may or may not exist yet.
// If it exists, we can easily check if it is a folder, if it doesn't exist,
// we can guess if the url is a folder from how it looks.
func isAliasURLDir(aliasURL string, keys map[string][]prefixSSEPair) bool {
// If the target url exists, check if it is a directory
// and return immediately.
_, targetContent, err := url2Stat(aliasURL, false, keys)
if err == nil {
return targetContent.Type.IsDir()
}
_, expandedURL, _ := mustExpandAlias(aliasURL)
// Check if targetURL is an FS or S3 aliased url
if expandedURL == aliasURL {
// This is an FS url, check if the url has a separator at the end
return strings.HasSuffix(aliasURL, string(filepath.Separator))
}
// This is an S3 url, then:
// *) If alias format is specified, return false
// *) If alias/bucket is specified, return true
// *) If alias/bucket/prefix, check if prefix has
// has a trailing slash.
pathURL := filepath.ToSlash(aliasURL)
fields := strings.Split(pathURL, "/")
switch len(fields) {
// Nothing or alias format
case 0, 1:
return false
// alias/bucket format
case 2:
return true
} // default case..
// alias/bucket/prefix format
return strings.HasSuffix(pathURL, "/")
}
// getSourceStreamMetadataFromURL gets a reader from URL.
func getSourceStreamMetadataFromURL(urlStr string, encKeyDB map[string][]prefixSSEPair) (reader io.ReadCloser,
metadata map[string]string, err *probe.Error) {
alias, urlStrFull, _, err := expandAlias(urlStr)
if err != nil {
return nil, nil, err.Trace(urlStr)
}
sseKey := getSSE(urlStr, encKeyDB[alias])
return getSourceStream(alias, urlStrFull, true, sseKey)
}
// getSourceStreamFromURL gets a reader from URL.
func getSourceStreamFromURL(urlStr string, encKeyDB map[string][]prefixSSEPair) (reader io.ReadCloser, err *probe.Error) {
alias, urlStrFull, _, err := expandAlias(urlStr)
if err != nil {
return nil, err.Trace(urlStr)
}
sse := getSSE(urlStr, encKeyDB[alias])
reader, _, err = getSourceStream(alias, urlStrFull, false, sse)
return reader, err
}
// getSourceStream gets a reader from URL.
func getSourceStream(alias string, urlStr string, fetchStat bool, sse encrypt.ServerSide) (reader io.ReadCloser, metadata map[string]string, err *probe.Error) {
sourceClnt, err := newClientFromAlias(alias, urlStr)
if err != nil {
return nil, nil, err.Trace(alias, urlStr)
}
reader, err = sourceClnt.Get(sse)
if err != nil {
return nil, nil, err.Trace(alias, urlStr)
}
metadata = make(map[string]string)
if fetchStat {
st, err := sourceClnt.Stat(false, true, sse)
if err != nil {
return nil, nil, err.Trace(alias, urlStr)
}
for k, v := range st.Metadata {
if httpguts.ValidHeaderFieldName(k) &&
httpguts.ValidHeaderFieldValue(v) {
metadata[k] = v
}
}
// If our reader is a seeker try to detect content-type further.
if s, ok := reader.(io.ReadSeeker); ok {
// All unrecognized files have `application/octet-stream`
// So we continue our detection process.
if ctype := metadata["Content-Type"]; ctype == "application/octet-stream" {
// Read a chunk to decide between utf-8 text and binary
var buf [512]byte
n, _ := io.ReadFull(reader, buf[:])
if n > 0 {
kind, e := filetype.Match(buf[:n])
if e != nil {
return nil, nil, probe.NewError(e)
}
// rewind to output whole file
if _, e := s.Seek(0, io.SeekStart); e != nil {
return nil, nil, probe.NewError(e)
}
ctype = kind.MIME.Value
if ctype == "" {
ctype = "application/octet-stream"
}
metadata["Content-Type"] = ctype
}
}
}
}
return reader, metadata, nil
}
// putTargetStream writes to URL from Reader.
func putTargetStream(ctx context.Context, alias string, urlStr string, reader io.Reader, size int64, metadata map[string]string, progress io.Reader, sse encrypt.ServerSide) (int64, *probe.Error) {
targetClnt, err := newClientFromAlias(alias, urlStr)
if err != nil {
return 0, err.Trace(alias, urlStr)
}
n, err := targetClnt.Put(ctx, reader, size, metadata, progress, sse)
if err != nil {
return n, err.Trace(alias, urlStr)
}
return n, nil
}
// putTargetStreamWithURL writes to URL from reader. If length=-1, read until EOF.
func putTargetStreamWithURL(urlStr string, reader io.Reader, size int64, sse encrypt.ServerSide) (int64, *probe.Error) {
alias, urlStrFull, _, err := expandAlias(urlStr)
if err != nil {
return 0, err.Trace(alias, urlStr)
}
contentType := guessURLContentType(urlStr)
metadata := map[string]string{
"Content-Type": contentType,
}
return putTargetStream(context.Background(), alias, urlStrFull, reader, size, metadata, nil, sse)
}
// copySourceToTargetURL copies to targetURL from source.
func copySourceToTargetURL(alias string, urlStr string, source string, size int64, progress io.Reader, srcSSE, tgtSSE encrypt.ServerSide, metadata map[string]string) *probe.Error {
targetClnt, err := newClientFromAlias(alias, urlStr)
if err != nil {
return err.Trace(alias, urlStr)
}
err = targetClnt.Copy(source, size, progress, srcSSE, tgtSSE, metadata)
if err != nil {
return err.Trace(alias, urlStr)
}
return nil
}
// createUserMetadata - returns a map of user defined function
// by combining the usermetadata of object and values passed by attr keyword
func createUserMetadata(sourceAlias, sourceURLStr string, srcSSE encrypt.ServerSide, urls URLs) (map[string]string, *probe.Error) {
metadata := make(map[string]string)
sourceClnt, err := newClientFromAlias(sourceAlias, sourceURLStr)
if err != nil {
return nil, err.Trace(sourceAlias, sourceURLStr)
}
st, err := sourceClnt.Stat(false, true, srcSSE)
if err != nil {
return nil, err.Trace(sourceAlias, sourceURLStr)
}
for k, v := range st.Metadata {
if httpguts.ValidHeaderFieldName(k) && strings.HasPrefix(k, "X-Amz-Meta-") &&
httpguts.ValidHeaderFieldValue(v) {
metadata[k] = v
}
}
for k, v := range urls.TargetContent.UserMetadata {
metadata[k] = v
}
return metadata, nil
}
// uploadSourceToTargetURL - uploads to targetURL from source.
// optionally optimizes copy for object sizes <= 5GiB by using
// server side copy operation.
func uploadSourceToTargetURL(ctx context.Context, urls URLs, progress io.Reader, encKeyDB map[string][]prefixSSEPair) URLs {
sourceAlias := urls.SourceAlias
sourceURL := urls.SourceContent.URL
targetAlias := urls.TargetAlias
targetURL := urls.TargetContent.URL
length := urls.SourceContent.Size
sourcePath := filepath.ToSlash(filepath.Join(sourceAlias, urls.SourceContent.URL.Path))
targetPath := filepath.ToSlash(filepath.Join(targetAlias, urls.TargetContent.URL.Path))
srcSSE := getSSE(sourcePath, encKeyDB[sourceAlias])
tgtSSE := getSSE(targetPath, encKeyDB[targetAlias])
// Optimize for server side copy if the host is same.
if sourceAlias == targetAlias {
metadata, err := createUserMetadata(sourceAlias, sourceURL.String(), srcSSE, urls)
if err != nil {
return urls.WithError(err.Trace(sourceURL.String()))
}
sourcePath := filepath.ToSlash(sourceURL.Path)
err = copySourceToTargetURL(targetAlias, targetURL.String(), sourcePath, length, progress, srcSSE, tgtSSE, metadata)
if err != nil {
return urls.WithError(err.Trace(sourceURL.String()))
}
} else {
// Proceed with regular stream copy.
reader, metadata, err := getSourceStream(sourceAlias, sourceURL.String(), true, srcSSE)
if err != nil {
return urls.WithError(err.Trace(sourceURL.String()))
}
defer reader.Close()
// Get metadata from target content as well
if urls.TargetContent.Metadata != nil {
for k, v := range urls.TargetContent.Metadata {
metadata[k] = v
}
}
// Get userMetadata from target content as well
if urls.TargetContent.UserMetadata != nil {
for k, v := range urls.TargetContent.UserMetadata {
metadata[k] = v
}
}
if srcSSE != nil {
delete(metadata, "X-Amz-Server-Side-Encryption-Customer-Algorithm")
delete(metadata, "X-Amz-Server-Side-Encryption-Customer-Key-Md5")
}
_, err = putTargetStream(ctx, targetAlias, targetURL.String(), reader, length, metadata, progress, tgtSSE)
if err != nil {
return urls.WithError(err.Trace(targetURL.String()))
}
}
return urls.WithError(nil)
}
// newClientFromAlias gives a new client interface for matching
// alias entry in the mc config file. If no matching host config entry
// is found, fs client is returned.
func newClientFromAlias(alias, urlStr string) (Client, *probe.Error) {
alias, _, hostCfg, err := expandAlias(alias)
if err != nil {
return nil, err.Trace(alias, urlStr)
}
if hostCfg == nil {
// No matching host config. So we treat it like a
// filesystem.
fsClient, fsErr := fsNew(urlStr)
if fsErr != nil {
return nil, fsErr.Trace(alias, urlStr)
}
return fsClient, nil
}
s3Config := newS3Config(urlStr, hostCfg)
s3Client, err := s3New(s3Config)
if err != nil {
return nil, err.Trace(alias, urlStr)
}
return s3Client, nil
}
// urlRgx - verify if aliased url is real URL.
var urlRgx = regexp.MustCompile("^https?://")
// newClient gives a new client interface
func newClient(aliasedURL string) (Client, *probe.Error) {
alias, urlStrFull, hostCfg, err := expandAlias(aliasedURL)
if err != nil {
return nil, err.Trace(aliasedURL)
}
// Verify if the aliasedURL is a real URL, fail in those cases
// indicating the user to add alias.
if hostCfg == nil && urlRgx.MatchString(aliasedURL) {
return nil, errInvalidAliasedURL(aliasedURL).Trace(aliasedURL)
}
return newClientFromAlias(alias, urlStrFull)
}
+261
View File
@@ -0,0 +1,261 @@
/*
* 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{}
func (fs fsComplete) Predict(a complete.Args) (prediction []string) {
return complete.PredictFiles("*").Predict(a)
}
// 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(false, false, DirFirst) {
completeS3Path := alias + getKey(content)
if content.Type.IsDir() {
if !strings.HasSuffix(completeS3Path, "/") {
completeS3Path += "/"
}
}
if strings.HasPrefix(completeS3Path, s3Path) {
prediction = append(prediction, completeS3Path)
}
}
// If completion found only one directory, recursively scan it.
if len(prediction) == 1 && strings.HasSuffix(prediction[0], "/") {
prediction = append(prediction, completeS3Path(prediction[0])...)
}
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 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{
"/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),
"/mb": aliasCompleter,
"/sql": s3Completer,
"/admin/info": aliasCompleter,
"/admin/heal": s3Completer,
"/admin/credential": aliasCompleter,
"/admin/config/get": aliasCompleter,
"/admin/config/set": aliasCompleter,
"/admin/service/status": aliasCompleter,
"/admin/service/restart": aliasCompleter,
"/admin/service/stop": aliasCompleter,
"/admin/trace": aliasCompleter,
"/admin/profile/start": aliasCompleter,
"/admin/profile/stop": aliasCompleter,
"/admin/policy/add": aliasCompleter,
"/admin/policy/list": aliasCompleter,
"/admin/policy/remove": aliasCompleter,
"/admin/user/add": aliasCompleter,
"/admin/user/policy:": aliasCompleter,
"/admin/user/disable": aliasCompleter,
"/admin/user/enable": aliasCompleter,
"/admin/user/list": aliasCompleter,
"/admin/user/remove": aliasCompleter,
"/event/add": aliasCompleter,
"/event/list": aliasCompleter,
"/event/remove": aliasCompleter,
"/session/clear": nil,
"/session/list": nil,
"/session/resume": nil,
"/share/download": nil,
"/share/list": nil,
"/share/upload": nil,
"/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
}
+31 -31
View File
@@ -1,5 +1,5 @@
/*
* Minio Client (C) 2015 Minio, Inc.
* 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.
@@ -14,15 +14,15 @@
* limitations under the License.
*/
package main
package cmd
import (
"fmt"
"strings"
"github.com/minio/mc/pkg/client"
"github.com/minio/mc/pkg/console"
"github.com/minio/minio-xl/pkg/quick"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio/pkg/quick"
)
func fixConfig() {
@@ -60,7 +60,7 @@ func newBrokenConfigV3() *brokenConfigV3 {
return conf
}
// Fix config version ‘3’. Some v3 config files are written without
// Fix config version `3`. Some v3 config files are written without
// proper hostConfig JSON tags. They may also contain unused ACL and
// Access fields. Rewrite the hostConfig with proper fields using JSON
// tags and drop the unused (ACL, Access) fields.
@@ -69,8 +69,8 @@ func fixConfigV3() {
return
}
brokenCfgV3 := newBrokenConfigV3()
brokenMcCfgV3, err := quick.Load(mustGetMcConfigPath(), brokenCfgV3)
fatalIf(err.Trace(), "Unable to load config.")
brokenMcCfgV3, e := quick.LoadConfig(mustGetMcConfigPath(), nil, brokenCfgV3)
fatalIf(probe.NewError(e), "Unable to load config.")
if brokenMcCfgV3.Version() != "3" {
return
@@ -101,13 +101,13 @@ func fixConfigV3() {
// We blindly drop ACL and Access fields from the broken config v3.
if isMutated {
mcNewConfigV3, err := quick.New(cfgV3)
fatalIf(err.Trace(), "Unable to initialize quick config for config version ‘3’.")
mcNewConfigV3, e := quick.NewConfig(cfgV3, nil)
fatalIf(probe.NewError(e), "Unable to initialize quick config for config version `3`.")
err = mcNewConfigV3.Save(mustGetMcConfigPath())
fatalIf(err.Trace(), "Unable to save config version ‘3’.")
e = mcNewConfigV3.Save(mustGetMcConfigPath())
fatalIf(probe.NewError(e), "Unable to save config version `3`.")
console.Infof("Successfully fixed %s broken config for version ‘3’.\n", mustGetMcConfigPath())
console.Infof("Successfully fixed %s broken config for version `3`.\n", mustGetMcConfigPath())
}
}
@@ -117,8 +117,8 @@ func fixConfigV6ForHosts() {
return
}
brokenMcCfgV6, err := quick.Load(mustGetMcConfigPath(), newConfigV6())
fatalIf(err.Trace(), "Unable to load config.")
brokenMcCfgV6, e := quick.LoadConfig(mustGetMcConfigPath(), nil, newConfigV6())
fatalIf(probe.NewError(e), "Unable to load config.")
if brokenMcCfgV6.Version() != "6" {
return
@@ -132,7 +132,7 @@ func fixConfigV6ForHosts() {
newCfgV6.Aliases[k] = v
}
url := new(client.URL)
url := &clientURL{}
// Copy hosts.
for host, hostCfgV6 := range brokenMcCfgV6.Data().(*configV6).Hosts {
// Already fixed - Copy and move on.
@@ -144,7 +144,7 @@ func fixConfigV6ForHosts() {
// If host entry does not contain "http(s)", introduce a new entry and delete the old one.
if host == "s3.amazonaws.com" || host == "storage.googleapis.com" ||
host == "localhost:9000" || host == "127.0.0.1:9000" ||
host == "play.minio.io:9000" || host == "dl.minio.io:9000" {
host == "play.min.io:9000" || host == "dl.min.io:9000" {
console.Infoln("Found broken host entries, replacing " + host + " with https://" + host + ".")
url.Host = host
url.Scheme = "https"
@@ -157,11 +157,11 @@ func fixConfigV6ForHosts() {
if isMutated {
// Save the new config back to the disk.
mcCfgV6, err := quick.New(newCfgV6)
fatalIf(err.Trace(), "Unable to initialize quick config for config version ‘v6’.")
mcCfgV6, e := quick.NewConfig(newCfgV6, nil)
fatalIf(probe.NewError(e), "Unable to initialize quick config for config version `v6`.")
err = mcCfgV6.Save(mustGetMcConfigPath())
fatalIf(err.Trace(), "Unable to save config version ‘v6’.")
e = mcCfgV6.Save(mustGetMcConfigPath())
fatalIf(probe.NewError(e), "Unable to save config version `v6`.")
}
}
@@ -170,11 +170,11 @@ func fixConfigV6() {
if !isMcConfigExists() {
return
}
config, err := quick.New(newConfigV6())
fatalIf(err.Trace(), "Unable to initialize config.")
config, e := quick.NewConfig(newConfigV6(), nil)
fatalIf(probe.NewError(e), "Unable to initialize config.")
err = config.Load(mustGetMcConfigPath())
fatalIf(err.Trace(mustGetMcConfigPath()), "Unable to load config.")
e = config.Load(mustGetMcConfigPath())
fatalIf(probe.NewError(e).Trace(mustGetMcConfigPath()), "Unable to load config.")
if config.Data().(*configV6).Version != "6" {
return
@@ -188,8 +188,8 @@ func fixConfigV6() {
newConfig.Aliases = config.Data().(*configV6).Aliases
for host, hostCfg := range config.Data().(*configV6).Hosts {
if strings.Contains(host, "*") {
fatalIf(err.Trace(),
fmt.Sprintf("Glob style ‘*’ pattern matching is no longer supported. Please fix ‘%s’ entry manually.", host))
fatalIf(errInvalidArgument(),
fmt.Sprintf("Glob style `*` pattern matching is no longer supported. Please fix `%s` entry manually.", host))
}
if strings.Contains(host, "*s3*") || strings.Contains(host, "*.s3*") {
console.Infoln("Found glob url, replacing " + host + " with s3.amazonaws.com")
@@ -232,11 +232,11 @@ func fixConfigV6() {
}
if isMutated {
newConf, err := quick.New(newConfig)
fatalIf(err.Trace(), "Unable to initialize newly fixed config.")
newConf, e := quick.NewConfig(newConfig, nil)
fatalIf(probe.NewError(e), "Unable to initialize newly fixed config.")
err = newConf.Save(mustGetMcConfigPath())
fatalIf(err.Trace(mustGetMcConfigPath()), "Unable to save newly fixed config path.")
console.Infof("Successfully fixed %s broken config for version ‘6’.\n", mustGetMcConfigPath())
e = newConf.Save(mustGetMcConfigPath())
fatalIf(probe.NewError(e).Trace(mustGetMcConfigPath()), "Unable to save newly fixed config path.")
console.Infof("Successfully fixed %s broken config for version `6`.\n", mustGetMcConfigPath())
}
}
+239
View File
@@ -0,0 +1,239 @@
/*
* 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 (
"math/rand"
"time"
"github.com/fatih/color"
"github.com/minio/cli"
"github.com/minio/mc/pkg/console"
"github.com/minio/mc/pkg/probe"
)
var hostAddFlags = []cli.Flag{
cli.StringFlag{
Name: "lookup",
Value: "auto",
Usage: "bucket lookup supported by the server. Valid options are '[dns,path,auto]'",
},
cli.StringFlag{
Name: "api",
Usage: "API signature. Valid options are '[S3v4, S3v2]'",
},
}
var configHostAddCmd = cli.Command{
Name: "add",
ShortName: "a",
Usage: "add a new host to configuration file",
Action: mainConfigHostAdd,
Before: setGlobalsFromContext,
Flags: append(hostAddFlags, globalFlags...),
HideHelpCommand: true,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} ALIAS URL ACCESSKEY SECRETKEY
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Add MinIO service under "myminio" alias. For security reasons turn off bash history momentarily.
$ set +o history
$ {{.HelpName}} myminio http://localhost:9000 minio minio123
$ set -o history
2. Add MinIO service under "myminio" alias, to use dns style bucket lookup. For security reasons
turn off bash history momentarily.
$ set +o history
$ {{.HelpName}} myminio http://localhost:9000 minio minio123 --api "s3v4" --lookup "dns"
$ set -o history
3. Add Amazon S3 storage service under "mys3" alias. For security reasons turn off bash history momentarily.
$ set +o history
$ {{.HelpName}} mys3 https://s3.amazonaws.com \
BKIKJAA5BMMU2RHO6IBB V8f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12
$ set -o history
`,
}
// checkConfigHostAddSyntax - verifies input arguments to 'config host add'.
func checkConfigHostAddSyntax(ctx *cli.Context) {
args := ctx.Args()
argsNr := len(args)
if argsNr < 4 || argsNr > 5 {
fatalIf(errInvalidArgument().Trace(ctx.Args().Tail()...),
"Incorrect number of arguments for host add command.")
}
alias := args.Get(0)
url := args.Get(1)
accessKey := args.Get(2)
secretKey := args.Get(3)
api := ctx.String("api")
bucketLookup := ctx.String("lookup")
if !isValidAlias(alias) {
fatalIf(errInvalidAlias(alias), "Invalid alias.")
}
if !isValidHostURL(url) {
fatalIf(errInvalidURL(url), "Invalid URL.")
}
if !isValidAccessKey(accessKey) {
fatalIf(errInvalidArgument().Trace(accessKey),
"Invalid access key `"+accessKey+"`.")
}
if !isValidSecretKey(secretKey) {
fatalIf(errInvalidArgument().Trace(secretKey),
"Invalid secret key `"+secretKey+"`.")
}
if api != "" && !isValidAPI(api) { // Empty value set to default "S3v4".
fatalIf(errInvalidArgument().Trace(api),
"Unrecognized API signature. Valid options are `[S3v4, S3v2]`.")
}
if !isValidLookup(bucketLookup) {
fatalIf(errInvalidArgument().Trace(bucketLookup),
"Unrecognized bucket lookup. Valid options are `[dns,auto, path]`.")
}
}
// addHost - add a host config.
func addHost(alias string, hostCfgV9 hostConfigV9) {
mcCfgV9, err := loadMcConfig()
fatalIf(err.Trace(globalMCConfigVersion), "Unable to load config `"+mustGetMcConfigPath()+"`.")
// Add new host.
mcCfgV9.Hosts[alias] = hostCfgV9
err = saveMcConfig(mcCfgV9)
fatalIf(err.Trace(alias), "Unable to update hosts in config version `"+mustGetMcConfigPath()+"`.")
printMsg(hostMessage{
op: "add",
Alias: alias,
URL: hostCfgV9.URL,
AccessKey: hostCfgV9.AccessKey,
SecretKey: hostCfgV9.SecretKey,
API: hostCfgV9.API,
Lookup: hostCfgV9.Lookup,
})
}
// probeS3Signature - auto probe S3 server signature: issue a Stat call
// using v4 signature then v2 in case of failure.
func probeS3Signature(accessKey, secretKey, url string) (string, *probe.Error) {
probeBucketName := randString(60, rand.NewSource(time.Now().UnixNano()), "probe-bucket-sign-")
// Test s3 connection for API auto probe
s3Config := &Config{
// S3 connection parameters
Insecure: globalInsecure,
AccessKey: accessKey,
SecretKey: secretKey,
Signature: "s3v4",
HostURL: urlJoinPath(url, probeBucketName),
}
s3Client, err := s3New(s3Config)
if err != nil {
return "", err
}
if _, err = s3Client.Stat(false, false, nil); err != nil {
switch err.ToGoError().(type) {
case BucketDoesNotExist:
// Bucket doesn't exist, means signature probing worked V4.
default:
// Attempt with signature v2, since v4 seem to have failed.
s3Config.Signature = "s3v2"
s3Client, err = s3New(s3Config)
if err != nil {
return "", err
}
if _, err = s3Client.Stat(false, false, nil); err != nil {
switch err.ToGoError().(type) {
case BucketDoesNotExist:
// Bucket doesn't exist, means signature probing worked with V2.
default:
return "", err
}
}
}
}
return s3Config.Signature, nil
}
// buildS3Config constructs an S3 Config and does
// signature auto-probe when needed.
func buildS3Config(url, accessKey, secretKey, api, lookup string) (*Config, *probe.Error) {
s3Config := newS3Config(url, &hostConfigV9{
AccessKey: accessKey,
SecretKey: secretKey,
URL: url,
Lookup: lookup,
})
// If api is provided we do not auto probe signature, this is
// required in situations when signature type is provided by the user.
if api != "" {
s3Config.Signature = api
return s3Config, nil
}
// Probe S3 signature version
api, err := probeS3Signature(accessKey, secretKey, url)
if err != nil {
return nil, err.Trace(url, accessKey, secretKey, api, lookup)
}
s3Config.Signature = api
// Success.
return s3Config, nil
}
func mainConfigHostAdd(ctx *cli.Context) error {
checkConfigHostAddSyntax(ctx)
console.SetColor("HostMessage", color.New(color.FgGreen))
var (
args = ctx.Args()
url = trimTrailingSeparator(args.Get(1))
accessKey = args.Get(2)
secretKey = args.Get(3)
api = ctx.String("api")
lookup = ctx.String("lookup")
)
s3Config, err := buildS3Config(url, accessKey, secretKey, api, lookup)
fatalIf(err.Trace(ctx.Args()...), "Unable to initialize new config from the provided credentials.")
addHost(ctx.Args().Get(0), hostConfigV9{
URL: s3Config.HostURL,
AccessKey: s3Config.AccessKey,
SecretKey: s3Config.SecretKey,
API: s3Config.Signature,
Lookup: lookup,
}) // Add a host with specified credentials.
return nil
}
+158
View File
@@ -0,0 +1,158 @@
/*
* 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 (
"fmt"
"sort"
"github.com/fatih/color"
"github.com/minio/cli"
"github.com/minio/mc/pkg/console"
)
var configHostListCmd = cli.Command{
Name: "list",
ShortName: "ls",
Usage: "list hosts in configuration file",
Action: mainConfigHostList,
Before: setGlobalsFromContext,
Flags: globalFlags,
HideHelpCommand: true,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} [ALIAS]
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. List all hosts.
$ {{.HelpName}}
2. List a specific host.
$ {{.HelpName}} s3
`,
}
// Input argument validator..
func checkConfigHostListSyntax(ctx *cli.Context) {
args := ctx.Args()
if len(ctx.Args()) > 1 {
fatalIf(errInvalidArgument().Trace(args...),
"Incorrect number of arguments to list hosts.")
}
if args.Get(0) != "" {
if !isValidAlias(args.Get(0)) {
fatalIf(errDummy().Trace(args.Get(0)),
"Invalid alias `"+args.Get(0)+"`.")
}
}
}
func mainConfigHostList(ctx *cli.Context) error {
checkConfigHostListSyntax(ctx)
// Additional command speific theme customization.
console.SetColor("Alias", color.New(color.FgCyan, color.Bold))
console.SetColor("URL", color.New(color.FgYellow))
console.SetColor("AccessKey", color.New(color.FgCyan))
console.SetColor("SecretKey", color.New(color.FgCyan))
console.SetColor("API", color.New(color.FgBlue))
console.SetColor("Lookup", color.New(color.FgCyan))
args := ctx.Args()
listHosts(args.Get(0)) // List all configured hosts.
return nil
}
// Prints all the hosts.
func printHosts(hosts ...hostMessage) {
var maxAlias = 0
for _, host := range hosts {
if len(host.Alias) > maxAlias {
maxAlias = len(host.Alias)
}
}
for _, host := range hosts {
if !globalJSON {
// Format properly for alignment based on alias length only in non json mode.
host.Alias = fmt.Sprintf("%-*.*s", maxAlias, maxAlias, host.Alias)
}
if host.AccessKey == "" || host.SecretKey == "" {
host.AccessKey = ""
host.SecretKey = ""
host.API = ""
}
printMsg(host)
}
}
// byAlias is a collection satisfying sort.Interface
type byAlias []hostMessage
func (d byAlias) Len() int { return len(d) }
func (d byAlias) Swap(i, j int) { d[i], d[j] = d[j], d[i] }
func (d byAlias) Less(i, j int) bool { return d[i].Alias < d[j].Alias }
// listHosts - list all host URLs or a requested host.
func listHosts(alias string) {
conf, err := loadMcConfig()
fatalIf(err.Trace(globalMCConfigVersion), "Unable to load config version `"+globalMCConfigVersion+"`.")
// If specific alias is requested, look for it and print.
if alias != "" {
if v, ok := conf.Hosts[alias]; ok {
printHosts(hostMessage{
op: "list",
prettyPrint: false,
Alias: alias,
URL: v.URL,
AccessKey: v.AccessKey,
SecretKey: v.SecretKey,
API: v.API,
Lookup: v.Lookup,
})
return
}
fatalIf(errInvalidAliasedURL(alias), "No such alias `"+alias+"` found.")
}
var hosts []hostMessage
for k, v := range conf.Hosts {
hosts = append(hosts, hostMessage{
op: "list",
prettyPrint: true,
Alias: k,
URL: v.URL,
AccessKey: v.AccessKey,
SecretKey: v.SecretKey,
API: v.API,
Lookup: v.Lookup,
})
}
// Sort hosts by alias names lexically.
sort.Sort(byAlias(hosts))
// Display all the hosts.
printHosts(hosts...)
}
+88
View File
@@ -0,0 +1,88 @@
/*
* 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 (
"github.com/fatih/color"
"github.com/minio/cli"
"github.com/minio/mc/pkg/console"
)
var configHostRemoveCmd = cli.Command{
Name: "remove",
ShortName: "rm",
Usage: "remove a host from configuration file",
Action: mainConfigHostRemove,
Before: setGlobalsFromContext,
Flags: globalFlags,
HideHelpCommand: true,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} ALIAS
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Remove "goodisk" from config.
$ {{.HelpName}} goodisk
`,
}
// checkConfigHostRemoveSyntax - verifies input arguments to 'config host remove'.
func checkConfigHostRemoveSyntax(ctx *cli.Context) {
args := ctx.Args()
if len(ctx.Args()) != 1 {
fatalIf(errInvalidArgument().Trace(args...),
"Incorrect number of arguments for remove host command.")
}
if !isValidAlias(args.Get(0)) {
fatalIf(errDummy().Trace(args.Get(0)),
"Invalid alias `"+args.Get(0)+"`.")
}
}
// mainConfigHost is the handle for "mc config host rm" command.
func mainConfigHostRemove(ctx *cli.Context) error {
checkConfigHostRemoveSyntax(ctx)
console.SetColor("HostMessage", color.New(color.FgGreen))
args := ctx.Args()
alias := args.Get(0)
removeHost(alias) // Remove a host.
return nil
}
// removeHost - removes a host.
func removeHost(alias string) {
conf, err := loadMcConfig()
fatalIf(err.Trace(globalMCConfigVersion), "Unable to load config version `"+globalMCConfigVersion+"`.")
// Remove host.
delete(conf.Hosts, alias)
err = saveMcConfig(conf)
fatalIf(err.Trace(alias), "Unable to save deleted hosts in config version `"+globalMCConfigVersion+"`.")
printMsg(hostMessage{op: "remove", Alias: alias})
}
+92
View File
@@ -0,0 +1,92 @@
/*
* 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 (
"github.com/minio/cli"
json "github.com/minio/mc/pkg/colorjson"
"github.com/minio/mc/pkg/console"
"github.com/minio/mc/pkg/probe"
)
var configHostCmd = cli.Command{
Name: "host",
Usage: "add, remove and list hosts in configuration file",
Action: mainConfigHost,
Before: setGlobalsFromContext,
Flags: globalFlags,
Subcommands: []cli.Command{
configHostAddCmd,
configHostRemoveCmd,
configHostListCmd,
},
HideHelpCommand: true,
}
// mainConfigHost is the handle for "mc config host" command.
func mainConfigHost(ctx *cli.Context) error {
cli.ShowCommandHelp(ctx, ctx.Args().First())
return nil
// Sub-commands like "remove", "list" have their own main.
}
// hostMessage container for content message structure
type hostMessage struct {
op string
prettyPrint bool
Status string `json:"status"`
Alias string `json:"alias"`
URL string `json:"URL"`
AccessKey string `json:"accessKey,omitempty"`
SecretKey string `json:"secretKey,omitempty"`
API string `json:"api,omitempty"`
Lookup string `json:"lookup,omitempty"`
}
// Print the config information of one alias, when prettyPrint flag
// is activated, fields contents are cut and '...' will be added to
// show a pretty table of all aliases configurations
func (h hostMessage) String() string {
switch h.op {
case "list":
// Create a new pretty table with cols configuration
t := newPrettyRecord(2,
Row{"Alias", "Alias"},
Row{"URL", "URL"},
Row{"AccessKey", "AccessKey"},
Row{"SecretKey", "SecretKey"},
Row{"API", "API"},
Row{"Lookup", "Lookup"},
)
return t.buildRecord(h.Alias, h.URL, h.AccessKey, h.SecretKey, h.API, h.Lookup)
case "remove":
return console.Colorize("HostMessage", "Removed `"+h.Alias+"` successfully.")
case "add":
return console.Colorize("HostMessage", "Added `"+h.Alias+"` successfully.")
default:
return ""
}
}
// JSON jsonified host message
func (h hostMessage) JSON() string {
h.Status = "success"
jsonMessageBytes, e := json.MarshalIndent(h, "", " ")
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
return string(jsonMessageBytes)
}
+13 -37
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,11 +14,11 @@
* limitations under the License.
*/
package main
package cmd
import "github.com/minio/cli"
// Configure minio client
// Configure MinIO Client
//
// ----
// NOTE: that the configure command only writes values to the config file.
@@ -30,48 +30,24 @@ import "github.com/minio/cli"
//
var (
configFlags = []cli.Flag{
cli.BoolFlag{
Name: "help, h",
Usage: "Help of config.",
},
}
configFlags = []cli.Flag{}
)
var configCmd = cli.Command{
Name: "config",
Usage: "Manage configuration file.",
Action: mainConfig,
Flags: append(configFlags, globalFlags...),
Name: "config",
Usage: "configure MinIO client",
Action: mainConfig,
Before: setGlobalsFromContext,
HideHelpCommand: true,
Flags: append(configFlags, globalFlags...),
Subcommands: []cli.Command{
configHostCmd,
},
CustomHelpTemplate: `NAME:
{{.Name}} - {{.Usage}}
USAGE:
{{.Name}} [FLAGS] COMMAND
FLAGS:
{{range .Flags}}{{.}}
{{end}}
COMMANDS:
{{range .Commands}}{{join .Names ", "}}{{ "\t" }}{{.Usage}}
{{end}}
`,
}
// mainConfig is the handle for "mc config" command. provides sub-commands which write configuration data in json format to config file.
func mainConfig(ctx *cli.Context) {
// Set global flags from context.
setGlobalsFromContext(ctx)
if ctx.Args().First() != "" { // command help.
cli.ShowCommandHelp(ctx, ctx.Args().First())
} else {
// command with Subcommands is an App.
cli.ShowAppHelp(ctx)
}
func mainConfig(ctx *cli.Context) error {
cli.ShowCommandHelp(ctx, ctx.Args().First())
return nil
// Sub-commands like "host" and "alias" have their own main.
}
+162 -58
View File
@@ -1,5 +1,5 @@
/*
* Minio Client (C) 2015 Minio, Inc.
* 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.
@@ -14,14 +14,15 @@
* limitations under the License.
*/
package main
package cmd
import (
"fmt"
"strings"
"github.com/minio/mc/pkg/console"
"github.com/minio/minio-xl/pkg/quick"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio/pkg/quick"
)
// migrate config files from the any older version to the latest.
@@ -40,6 +41,10 @@ func migrateConfig() {
migrateConfigV5ToV6()
// Migrate config V6 to V7
migrateConfigV6ToV7()
// Migrate config V7 to V8
migrateConfigV7ToV8()
// Migrate config V8 to V9
migrateConfigV8ToV9()
}
// Migrate from config version 1.0 to 1.0.1. Populate example entries and save it back.
@@ -47,8 +52,8 @@ func migrateConfigV1ToV101() {
if !isMcConfigExists() {
return
}
mcCfgV1, err := quick.Load(mustGetMcConfigPath(), newConfigV1())
fatalIf(err.Trace(), "Unable to load config version ‘1’.")
mcCfgV1, e := quick.LoadConfig(mustGetMcConfigPath(), nil, newConfigV1())
fatalIf(probe.NewError(e), "Unable to load config version `1`.")
// If loaded config version does not match 1.0.0, we do nothing.
if mcCfgV1.Version() != "1.0.0" {
@@ -91,21 +96,21 @@ func migrateConfigV1ToV101() {
}
// Save the new config back to the disk.
mcCfgV101, err := quick.New(cfgV101)
fatalIf(err.Trace(), "Unable to initialize quick config for config version ‘1.0.1’.")
err = mcCfgV101.Save(mustGetMcConfigPath())
fatalIf(err.Trace(), "Unable to save config version ‘1.0.1’.")
mcCfgV101, e := quick.NewConfig(cfgV101, nil)
fatalIf(probe.NewError(e), "Unable to initialize quick config for config version `1.0.1`.")
e = mcCfgV101.Save(mustGetMcConfigPath())
fatalIf(probe.NewError(e), "Unable to save config version `1.0.1`.")
console.Infof("Successfully migrated %s from version ‘1.0.0’ to version ‘1.0.1’.\n", mustGetMcConfigPath())
console.Infof("Successfully migrated %s from version `1.0.0` to version `1.0.1`.\n", mustGetMcConfigPath())
}
// Migrate from config ‘1.0.1’ to ‘2’. Drop semantic versioning and move to integer versioning. No other changes.
// Migrate from config `1.0.1` to `2`. Drop semantic versioning and move to integer versioning. No other changes.
func migrateConfigV101ToV2() {
if !isMcConfigExists() {
return
}
mcCfgV101, err := quick.Load(mustGetMcConfigPath(), newConfigV101())
fatalIf(err.Trace(), "Unable to load config version ‘1.0.1’.")
mcCfgV101, e := quick.LoadConfig(mustGetMcConfigPath(), nil, newConfigV101())
fatalIf(probe.NewError(e), "Unable to load config version `1.0.1`.")
// update to newer version
if mcCfgV101.Version() != "1.0.1" {
@@ -127,24 +132,24 @@ func migrateConfigV101ToV2() {
}
}
mcCfgV2, err := quick.New(cfgV2)
fatalIf(err.Trace(), "Unable to initialize quick config for config version ‘2’.")
mcCfgV2, e := quick.NewConfig(cfgV2, nil)
fatalIf(probe.NewError(e), "Unable to initialize quick config for config version `2`.")
err = mcCfgV2.Save(mustGetMcConfigPath())
fatalIf(err.Trace(), "Unable to save config version ‘2’.")
e = mcCfgV2.Save(mustGetMcConfigPath())
fatalIf(probe.NewError(e), "Unable to save config version `2`.")
console.Infof("Successfully migrated %s from version ‘1.0.1’ to version ‘2’.\n", mustGetMcConfigPath())
console.Infof("Successfully migrated %s from version `1.0.1` to version `2`.\n", mustGetMcConfigPath())
}
// Migrate from config ‘2’ to ‘3’. Use ‘-’ separated names for
// Migrate from config `2` to `3`. Use `-` separated names for
// hostConfig using struct json tags.
func migrateConfigV2ToV3() {
if !isMcConfigExists() {
return
}
mcCfgV2, err := quick.Load(mustGetMcConfigPath(), newConfigV2())
fatalIf(err.Trace(), "Unable to load mc config V2.")
mcCfgV2, e := quick.LoadConfig(mustGetMcConfigPath(), nil, newConfigV2())
fatalIf(probe.NewError(e), "Unable to load mc config V2.")
// update to newer version
if mcCfgV2.Version() != "2" {
@@ -167,23 +172,23 @@ func migrateConfigV2ToV3() {
}
}
mcNewCfgV3, err := quick.New(cfgV3)
fatalIf(err.Trace(), "Unable to initialize quick config for config version ‘3’.")
mcNewCfgV3, e := quick.NewConfig(cfgV3, nil)
fatalIf(probe.NewError(e), "Unable to initialize quick config for config version `3`.")
err = mcNewCfgV3.Save(mustGetMcConfigPath())
fatalIf(err.Trace(), "Unable to save config version ‘3’.")
e = mcNewCfgV3.Save(mustGetMcConfigPath())
fatalIf(probe.NewError(e), "Unable to save config version `3`.")
console.Infof("Successfully migrated %s from version ‘2’ to version ‘3’.\n", mustGetMcConfigPath())
console.Infof("Successfully migrated %s from version `2` to version `3`.\n", mustGetMcConfigPath())
}
// Migrate from config version ‘3’ to ‘4’. Introduce API Signature
// Migrate from config version `3` to `4`. Introduce API Signature
// field in host config. Also Use JavaScript notation for field names.
func migrateConfigV3ToV4() {
if !isMcConfigExists() {
return
}
mcCfgV3, err := quick.Load(mustGetMcConfigPath(), newConfigV3())
fatalIf(err.Trace(), "Unable to load mc config V2.")
mcCfgV3, e := quick.LoadConfig(mustGetMcConfigPath(), nil, newConfigV3())
fatalIf(probe.NewError(e), "Unable to load mc config V2.")
// update to newer version
if mcCfgV3.Version() != "3" {
@@ -206,23 +211,23 @@ func migrateConfigV3ToV4() {
}
}
mcNewCfgV4, err := quick.New(cfgV4)
fatalIf(err.Trace(), "Unable to initialize quick config for config version ‘4’.")
mcNewCfgV4, e := quick.NewConfig(cfgV4, nil)
fatalIf(probe.NewError(e), "Unable to initialize quick config for config version `4`.")
err = mcNewCfgV4.Save(mustGetMcConfigPath())
fatalIf(err.Trace(), "Unable to save config version ‘4’.")
e = mcNewCfgV4.Save(mustGetMcConfigPath())
fatalIf(probe.NewError(e), "Unable to save config version `4`.")
console.Infof("Successfully migrated %s from version ‘3’ to version ‘4’.\n", mustGetMcConfigPath())
console.Infof("Successfully migrated %s from version `3` to version `4`.\n", mustGetMcConfigPath())
}
// Migrate config version ‘4’ to ‘5’. Rename hostConfigV4.Signature -> hostConfigV5.API.
// Migrate config version `4` to `5`. Rename hostConfigV4.Signature -> hostConfigV5.API.
func migrateConfigV4ToV5() {
if !isMcConfigExists() {
return
}
mcCfgV4, err := quick.Load(mustGetMcConfigPath(), newConfigV4())
fatalIf(err.Trace(), "Unable to load mc config V4.")
mcCfgV4, e := quick.LoadConfig(mustGetMcConfigPath(), nil, newConfigV4())
fatalIf(probe.NewError(e), "Unable to load mc config V4.")
// update to newer version
if mcCfgV4.Version() != "4" {
@@ -241,23 +246,23 @@ func migrateConfigV4ToV5() {
}
}
mcNewCfgV5, err := quick.New(cfgV5)
fatalIf(err.Trace(), "Unable to initialize quick config for config version ‘5’.")
mcNewCfgV5, e := quick.NewConfig(cfgV5, nil)
fatalIf(probe.NewError(e), "Unable to initialize quick config for config version `5`.")
err = mcNewCfgV5.Save(mustGetMcConfigPath())
fatalIf(err.Trace(), "Unable to save config version ‘5’.")
e = mcNewCfgV5.Save(mustGetMcConfigPath())
fatalIf(probe.NewError(e), "Unable to save config version `5`.")
console.Infof("Successfully migrated %s from version ‘4’ to version ‘5’.\n", mustGetMcConfigPath())
console.Infof("Successfully migrated %s from version `4` to version `5`.\n", mustGetMcConfigPath())
}
// Migrate config version ‘5’ to ‘6’. Add google cloud storage servers
// Migrate config version `5` to `6`. Add google cloud storage servers
// to host config. Also remove "." from s3 aws glob rule.
func migrateConfigV5ToV6() {
if !isMcConfigExists() {
return
}
mcCfgV5, err := quick.Load(mustGetMcConfigPath(), newConfigV5())
fatalIf(err.Trace(), "Unable to load mc config V5.")
mcCfgV5, e := quick.LoadConfig(mustGetMcConfigPath(), nil, newConfigV5())
fatalIf(probe.NewError(e), "Unable to load mc config V5.")
// update to newer version
if mcCfgV5.Version() != "5" {
@@ -307,24 +312,24 @@ func migrateConfigV5ToV6() {
}
}
mcNewCfgV6, err := quick.New(cfgV6)
fatalIf(err.Trace(), "Unable to initialize quick config for config version ‘6’.")
mcNewCfgV6, e := quick.NewConfig(cfgV6, nil)
fatalIf(probe.NewError(e), "Unable to initialize quick config for config version `6`.")
err = mcNewCfgV6.Save(mustGetMcConfigPath())
fatalIf(err.Trace(), "Unable to save config version ‘6’.")
e = mcNewCfgV6.Save(mustGetMcConfigPath())
fatalIf(probe.NewError(e), "Unable to save config version `6`.")
console.Infof("Successfully migrated %s from version ‘5’ to version ‘6’.\n", mustGetMcConfigPath())
console.Infof("Successfully migrated %s from version `5` to version `6`.\n", mustGetMcConfigPath())
}
// Migrate config version ‘6’ to ‘7'. Remove alias map and introduce
// Migrate config version `6` to `7'. Remove alias map and introduce
// named Host config. Also no more glob match for host config entries.
func migrateConfigV6ToV7() {
if !isMcConfigExists() {
return
}
mcCfgV6, err := quick.Load(mustGetMcConfigPath(), newConfigV6())
fatalIf(err.Trace(), "Unable to load mc config V6.")
mcCfgV6, e := quick.LoadConfig(mustGetMcConfigPath(), nil, newConfigV6())
fatalIf(probe.NewError(e), "Unable to load mc config V6.")
if mcCfgV6.Version() != "6" {
return
@@ -332,8 +337,24 @@ func migrateConfigV6ToV7() {
cfgV7 := newConfigV7()
aliasIndex := 0
// old Aliases.
oldAliases := mcCfgV6.Data().(*configV6).Aliases
// We dropped alias support in v7. We only need to migrate host configs.
for host, hostCfgV6 := range mcCfgV6.Data().(*configV6).Hosts {
// Look through old aliases, if found any matching save those entries.
for aliasName, aliasedHost := range oldAliases {
if aliasedHost == host {
cfgV7.Hosts[aliasName] = hostConfigV7{
URL: host,
AccessKey: hostCfgV6.AccessKeyID,
SecretKey: hostCfgV6.SecretAccessKey,
API: hostCfgV6.API,
}
continue
}
}
if hostCfgV6.AccessKeyID == "YOUR-ACCESS-KEY-ID-HERE" ||
hostCfgV6.SecretAccessKey == "YOUR-SECRET-ACCESS-KEY-HERE" ||
hostCfgV6.AccessKeyID == "" ||
@@ -370,11 +391,94 @@ func migrateConfigV6ToV7() {
}
// Load default settings.
cfgV7.loadDefaults()
mcNewCfgV7, err := quick.New(cfgV7)
fatalIf(err.Trace(), "Unable to initialize quick config for config version ‘7’.")
mcNewCfgV7, e := quick.NewConfig(cfgV7, nil)
fatalIf(probe.NewError(e), "Unable to initialize quick config for config version `7`.")
err = mcNewCfgV7.Save(mustGetMcConfigPath())
fatalIf(err.Trace(), "Unable to save config version ‘7’.")
e = mcNewCfgV7.Save(mustGetMcConfigPath())
fatalIf(probe.NewError(e), "Unable to save config version `7`.")
console.Infof("Successfully migrated %s from version ‘6’ to version ‘7’.\n", mustGetMcConfigPath())
console.Infof("Successfully migrated %s from version `6` to version `7`.\n", mustGetMcConfigPath())
}
// Migrate config version `7` to `8'. Remove hosts
// 'play.min.io:9002' and 'dl.min.io:9000'.
func migrateConfigV7ToV8() {
if !isMcConfigExists() {
return
}
mcCfgV7, e := quick.LoadConfig(mustGetMcConfigPath(), nil, newConfigV7())
fatalIf(probe.NewError(e), "Unable to load mc config V7.")
if mcCfgV7.Version() != "7" {
return
}
cfgV8 := newConfigV8()
// We dropped alias support in v7. We only need to migrate host configs.
for host, hostCfgV7 := range mcCfgV7.Data().(*configV7).Hosts {
// Ignore 'player', 'play' and 'dl' aliases.
if host == "player" || host == "dl" || host == "play" {
continue
}
hostCfgV8 := hostConfigV8{}
hostCfgV8.URL = hostCfgV7.URL
hostCfgV8.AccessKey = hostCfgV7.AccessKey
hostCfgV8.SecretKey = hostCfgV7.SecretKey
hostCfgV8.API = hostCfgV7.API
cfgV8.Hosts[host] = hostCfgV8
}
// Load default settings.
cfgV8.loadDefaults()
mcNewCfgV8, e := quick.NewConfig(cfgV8, nil)
fatalIf(probe.NewError(e), "Unable to initialize quick config for config version `8`.")
e = mcNewCfgV8.Save(mustGetMcConfigPath())
fatalIf(probe.NewError(e), "Unable to save config version `8`.")
console.Infof("Successfully migrated %s from version `7` to version `8`.\n", mustGetMcConfigPath())
}
// Migrate config version `8` to `9'. Add optional field virtual
func migrateConfigV8ToV9() {
if !isMcConfigExists() {
return
}
mcCfgV8, e := quick.LoadConfig(mustGetMcConfigPath(), nil, newConfigV8())
fatalIf(probe.NewError(e), "Unable to load mc config V8.")
if mcCfgV8.Version() != "8" {
return
}
cfgV9 := newConfigV9()
isEmpty := true
// We dropped alias support in v8. We only need to migrate host configs.
for host, hostCfgV8 := range mcCfgV8.Data().(*configV8).Hosts {
// Ignore 'player', 'play' and 'dl' aliases.
if host == "player" || host == "dl" || host == "play" {
continue
}
isEmpty = false
hostCfgV9 := hostConfigV9{}
hostCfgV9.URL = hostCfgV8.URL
hostCfgV9.AccessKey = hostCfgV8.AccessKey
hostCfgV9.SecretKey = hostCfgV8.SecretKey
hostCfgV9.API = hostCfgV8.API
hostCfgV9.Lookup = "auto"
cfgV9.Hosts[host] = hostCfgV9
}
if isEmpty {
// Load default settings.
cfgV9.loadDefaults()
}
mcNewCfgV9, e := quick.NewConfig(cfgV9, nil)
fatalIf(probe.NewError(e), "Unable to initialize quick config for config version `9`.")
e = mcNewCfgV9.Save(mustGetMcConfigPath())
fatalIf(probe.NewError(e), "Unable to save config version `9`.")
console.Infof("Successfully migrated %s from version `8` to version `9`.\n", mustGetMcConfigPath())
}
+147 -3
View File
@@ -1,5 +1,5 @@
/*
* Minio Client (C) 2015 Minio, Inc.
* 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.
@@ -14,7 +14,7 @@
* limitations under the License.
*/
package main
package cmd
/////////////////// Config V1 ///////////////////
type hostConfigV1 struct {
@@ -160,5 +160,149 @@ func newConfigV6() *configV6 {
return conf
}
/////////////////// Config V7 ///////////////////
/////////////////// Config V6 ///////////////////
// hostConfig configuration of a host - version '7'.
type hostConfigV7 struct {
URL string `json:"url"`
AccessKey string `json:"accessKey"`
SecretKey string `json:"secretKey"`
API string `json:"api"`
}
// configV7 config version.
type configV7 struct {
Version string `json:"version"`
Hosts map[string]hostConfigV7 `json:"hosts"`
}
// newConfigV7 - new config version '7'.
func newConfigV7() *configV7 {
cfg := new(configV7)
cfg.Version = "7"
cfg.Hosts = make(map[string]hostConfigV7)
return cfg
}
func (c *configV7) loadDefaults() {
// MinIO server running locally.
c.setHost("local", hostConfigV7{
URL: "http://localhost:9000",
AccessKey: "",
SecretKey: "",
API: "S3v4",
})
// Amazon S3 cloud storage service.
c.setHost("s3", hostConfigV7{
URL: "https://s3.amazonaws.com",
AccessKey: defaultAccessKey,
SecretKey: defaultSecretKey,
API: "S3v4",
})
// Google cloud storage service.
c.setHost("gcs", hostConfigV7{
URL: "https://storage.googleapis.com",
AccessKey: defaultAccessKey,
SecretKey: defaultSecretKey,
API: "S3v2",
})
// MinIO anonymous server for demo.
c.setHost("play", hostConfigV7{
URL: "https://play.min.io",
AccessKey: "",
SecretKey: "",
API: "S3v4",
})
// MinIO demo server with public secret and access keys.
c.setHost("player", hostConfigV7{
URL: "https://play.min.io:9002",
AccessKey: "Q3AM3UQ867SPQQA43P2F",
SecretKey: "zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG",
API: "S3v4",
})
// MinIO public download service.
c.setHost("dl", hostConfigV7{
URL: "https://dl.min.io:9000",
AccessKey: "",
SecretKey: "",
API: "S3v4",
})
}
// SetHost sets host config if not empty.
func (c *configV7) setHost(alias string, cfg hostConfigV7) {
if _, ok := c.Hosts[alias]; !ok {
c.Hosts[alias] = cfg
}
}
/////////////////// Config V8 ///////////////////
// configV8 config version.
// hostConfig configuration of a host.
type hostConfigV8 struct {
URL string `json:"url"`
AccessKey string `json:"accessKey"`
SecretKey string `json:"secretKey"`
API string `json:"api"`
}
type configV8 struct {
Version string `json:"version"`
Hosts map[string]hostConfigV8 `json:"hosts"`
}
// newConfigV8 - new config version.
func newConfigV8() *configV8 {
cfg := new(configV8)
cfg.Version = globalMCConfigVersion
cfg.Hosts = make(map[string]hostConfigV8)
return cfg
}
// SetHost sets host config if not empty.
func (c *configV8) setHost(alias string, cfg hostConfigV8) {
if _, ok := c.Hosts[alias]; !ok {
c.Hosts[alias] = cfg
}
}
// load default values for missing entries.
func (c *configV8) loadDefaults() {
// MinIO server running locally.
c.setHost("local", hostConfigV8{
URL: "http://localhost:9000",
AccessKey: "",
SecretKey: "",
API: "S3v4",
})
// Amazon S3 cloud storage service.
c.setHost("s3", hostConfigV8{
URL: "https://s3.amazonaws.com",
AccessKey: defaultAccessKey,
SecretKey: defaultSecretKey,
API: "S3v4",
})
// Google cloud storage service.
c.setHost("gcs", hostConfigV8{
URL: "https://storage.googleapis.com",
AccessKey: defaultAccessKey,
SecretKey: defaultSecretKey,
API: "S3v2",
})
// MinIO anonymous server for demo.
c.setHost("play", hostConfigV8{
URL: "https://play.min.io",
AccessKey: "Q3AM3UQ867SPQQA43P2F",
SecretKey: "zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG",
API: "S3v4",
})
}
/////////////////// Config V9 ///////////////////
// RESERVED FOR FUTURE
+81
View File
@@ -0,0 +1,81 @@
/*
* MinIO Client (C) 2015, 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 "strings"
var validAPIs = []string{"S3v4", "S3v2"}
const (
accessKeyMinLen = 3
secretKeyMinLen = 8
)
// isValidAccessKey - validate access key for right length.
func isValidAccessKey(accessKey string) bool {
if accessKey == "" {
return true
}
return len(accessKey) >= accessKeyMinLen
}
// isValidSecretKey - validate secret key for right length.
func isValidSecretKey(secretKey string) bool {
if secretKey == "" {
return true
}
return len(secretKey) >= secretKeyMinLen
}
// trimTrailingSeparator - Remove trailing separator.
func trimTrailingSeparator(hostURL string) string {
separator := string(newClientURL(hostURL).Separator)
return strings.TrimSuffix(hostURL, separator)
}
// isValidHostURL - validate input host url.
func isValidHostURL(hostURL string) (ok bool) {
if strings.TrimSpace(hostURL) != "" {
url := newClientURL(hostURL)
if url.Scheme == "https" || url.Scheme == "http" {
if url.Path == "/" {
ok = true
}
}
}
return ok
}
// isValidAPI - Validates if API signature string of supported type.
func isValidAPI(api string) (ok bool) {
switch strings.ToLower(api) {
case "s3v2", "s3v4":
ok = true
}
return ok
}
// isValidLookup - validates if bucket lookup is of valid type
func isValidLookup(lookup string) (ok bool) {
l := strings.ToLower(strings.TrimSpace(lookup))
for _, v := range []string{"dns", "path", "auto"} {
if l == v {
return true
}
}
return false
}
+78
View File
@@ -0,0 +1,78 @@
/*
* 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 "testing"
// Tests valid host URL functionality.
func TestValidHostURL(t *testing.T) {
testCases := []struct {
hostURL string
isHost bool
}{
{
hostURL: "https://localhost:9000",
isHost: true,
},
{
hostURL: "/",
isHost: false,
},
}
for _, testCase := range testCases {
isHost := isValidHostURL(testCase.hostURL)
if testCase.isHost != isHost {
t.Fatalf("Expected %t, got %t", testCase.isHost, isHost)
}
}
}
func TestIsValidAPI(t *testing.T) {
equalAssert(isValidAPI("s3V2"), true, t)
equalAssert(isValidAPI("S3v2"), true, t)
equalAssert(isValidAPI("s3"), false, t)
}
func equalAssert(ok1, ok2 bool, t *testing.T) {
if ok1 != ok2 {
t.Errorf("Expected %t, got %t", ok2, ok1)
}
}
// Tests valid and invalid secret keys.
func TestValidSecretKeys(t *testing.T) {
equalAssert(isValidSecretKey("aaa"), false, t)
equalAssert(isValidSecretKey(""), true, t)
equalAssert(isValidSecretKey("password"), true, t)
equalAssert(isValidSecretKey("password%%"), true, t)
equalAssert(isValidSecretKey("BYvgJM101sHngl2uzjXS/OBF/aMxAN06JrJ3qJlF"), true, t)
}
// Tests valid and invalid access keys.
func TestValidAccessKeys(t *testing.T) {
equalAssert(isValidAccessKey("aa"), false, t)
equalAssert(isValidAccessKey(""), true, t)
equalAssert(isValidAccessKey("adm"), true, t)
equalAssert(isValidAccessKey("admin"), true, t)
equalAssert(isValidAccessKey("$$%%%%%3333"), true, t)
equalAssert(isValidAccessKey("c67W2-r4MAyAYScRl"), true, t)
equalAssert(isValidAccessKey("EXOb76bfeb1234562iu679f11588"), true, t)
equalAssert(isValidAccessKey("BYvgJM101sHngl2uzjXS/OBF/aMxAN06JrJ3qJlF"), true, t)
}
+59 -56
View File
@@ -1,5 +1,5 @@
/*
* Minio Client (C) 2015 Minio, Inc.
* 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.
@@ -14,13 +14,13 @@
* limitations under the License.
*/
package main
package cmd
import (
"sync"
"github.com/minio/minio-xl/pkg/probe"
"github.com/minio/minio-xl/pkg/quick"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio/pkg/quick"
)
const (
@@ -30,128 +30,131 @@ const (
var (
// set once during first load.
cacheCfgV7 *configV7
cacheCfgV9 *configV9
// All access to mc config file should be synchronized.
cfgMutex = &sync.RWMutex{}
)
// hostConfig configuration of a host.
type hostConfigV7 struct {
type hostConfigV9 struct {
URL string `json:"url"`
AccessKey string `json:"accessKey"`
SecretKey string `json:"secretKey"`
API string `json:"api"`
Lookup string `json:"lookup"`
}
// configV7 config version.
type configV7 struct {
// configV8 config version.
type configV9 struct {
Version string `json:"version"`
Hosts map[string]hostConfigV7 `json:"hosts"`
Hosts map[string]hostConfigV9 `json:"hosts"`
}
// newConfigV7 - new config version.
func newConfigV7() *configV7 {
cfg := new(configV7)
// newConfigV9 - new config version.
func newConfigV9() *configV9 {
cfg := new(configV9)
cfg.Version = globalMCConfigVersion
cfg.Hosts = make(map[string]hostConfigV7)
cfg.Hosts = make(map[string]hostConfigV9)
return cfg
}
// SetHost sets host config if not empty.
func (c *configV7) setHost(alias string, cfg hostConfigV7) {
func (c *configV9) setHost(alias string, cfg hostConfigV9) {
if _, ok := c.Hosts[alias]; !ok {
c.Hosts[alias] = cfg
}
}
// load default values for missing entries.
func (c *configV7) loadDefaults() {
// Minio server running locally.
c.setHost("local", hostConfigV7{
func (c *configV9) loadDefaults() {
// MinIO server running locally.
c.setHost("local", hostConfigV9{
URL: "http://localhost:9000",
AccessKey: "",
SecretKey: "",
API: "S3v4",
Lookup: "auto",
})
// Amazon S3 cloud storage service.
c.setHost("s3", hostConfigV7{
c.setHost("s3", hostConfigV9{
URL: "https://s3.amazonaws.com",
AccessKey: defaultAccessKey,
SecretKey: defaultSecretKey,
API: "S3v4",
Lookup: "dns",
})
// Google cloud storage service.
c.setHost("gcs", hostConfigV7{
c.setHost("gcs", hostConfigV9{
URL: "https://storage.googleapis.com",
AccessKey: defaultAccessKey,
SecretKey: defaultSecretKey,
API: "S3v2",
Lookup: "dns",
})
// Minio anonymous server for demo.
c.setHost("play", hostConfigV7{
URL: "https://play.minio.io:9000",
AccessKey: "",
SecretKey: "",
API: "S3v4",
})
// Minio demo server with public secret and access keys.
c.setHost("player", hostConfigV7{
URL: "https://play.minio.io:9002",
// MinIO anonymous server for demo.
c.setHost("play", hostConfigV9{
URL: "https://play.min.io",
AccessKey: "Q3AM3UQ867SPQQA43P2F",
SecretKey: "zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG",
API: "S3v4",
})
// Minio public download service.
c.setHost("dl", hostConfigV7{
URL: "https://dl.minio.io:9000",
AccessKey: "",
SecretKey: "",
API: "S3v4",
Lookup: "auto",
})
}
// loadConfigV7 - loads a new config.
func loadConfigV7() (*configV7, *probe.Error) {
// loadConfigV9 - loads a new config.
func loadConfigV9() (*configV9, *probe.Error) {
cfgMutex.RLock()
defer cfgMutex.RUnlock()
// Cached in private global variable.
if cacheCfgV7 != nil {
return cacheCfgV7, nil
// If already cached, return the cached value.
if cacheCfgV9 != nil {
return cacheCfgV9, nil
}
if !isMcConfigExists() {
return nil, errInvalidArgument().Trace()
}
mcCfgV7, err := quick.Load(mustGetMcConfigPath(), newConfigV7())
fatalIf(err.Trace(), "Unable to load mc config file ‘"+mustGetMcConfigPath()+"’.")
// Initialize a new config loader.
qc, e := quick.NewConfig(newConfigV9(), nil)
if e != nil {
return nil, probe.NewError(e)
}
cfgV7 := mcCfgV7.Data().(*configV7)
// Load config at configPath, fails if config is not
// accessible, malformed or version missing.
if e = qc.Load(mustGetMcConfigPath()); e != nil {
return nil, probe.NewError(e)
}
// cache it.
cacheCfgV7 = cfgV7
cfgV9 := qc.Data().(*configV9)
return cfgV7, nil
// Cache config.
cacheCfgV9 = cfgV9
// Success.
return cfgV9, nil
}
// saveConfigV7 - saves an updated config.
func saveConfigV7(cfgV7 *configV7) *probe.Error {
// saveConfigV8 - saves an updated config.
func saveConfigV9(cfgV9 *configV9) *probe.Error {
cfgMutex.Lock()
defer cfgMutex.Unlock()
qs, err := quick.New(cfgV7)
if err != nil {
return err.Trace()
qs, e := quick.NewConfig(cfgV9, nil)
if e != nil {
return probe.NewError(e)
}
// update the cache.
cacheCfgV7 = cfgV7
cacheCfgV9 = cfgV9
return qs.Save(mustGetMcConfigPath()).Trace(mustGetMcConfigPath())
e = qs.Save(mustGetMcConfigPath())
if e != nil {
return probe.NewError(e).Trace(mustGetMcConfigPath())
}
return nil
}
+65
View File
@@ -0,0 +1,65 @@
/*
* 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 (
"fmt"
"strings"
)
// Check if version of the config is valid
func validateConfigVersion(config *configV9) (bool, string) {
if config.Version != globalMCConfigVersion {
return false, fmt.Sprintf("Config version '%s' does not match mc config version '%s', please update your binary.\n",
config.Version, globalMCConfigVersion)
}
return true, ""
}
// Verifies the config file of the MinIO Client
func validateConfigFile(config *configV9) (bool, []string) {
ok, err := validateConfigVersion(config)
var validationSuccessful = true
var errors []string
if !ok {
validationSuccessful = false
errors = append(errors, err)
}
hosts := config.Hosts
for _, hostConfig := range hosts {
hostConfigHealthOk, hostErrors := validateConfigHost(hostConfig)
if !hostConfigHealthOk {
validationSuccessful = false
errors = append(errors, hostErrors...)
}
}
return validationSuccessful, errors
}
func validateConfigHost(host hostConfigV9) (bool, []string) {
var validationSuccessful = true
var hostErrors []string
if !isValidAPI(strings.ToLower(host.API)) {
validationSuccessful = false
hostErrors = append(hostErrors, errInvalidAPISignature(host.API, host.URL).ToGoError().Error())
}
if !isValidHostURL(host.URL) {
validationSuccessful = false
hostErrors = append(hostErrors, errInvalidURL(host.URL).ToGoError().Error())
}
return validationSuccessful, hostErrors
}
+316
View File
@@ -0,0 +1,316 @@
/*
* 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 (
"fmt"
"net/url"
"os"
"path/filepath"
"regexp"
"runtime"
"github.com/minio/mc/pkg/probe"
"github.com/mitchellh/go-homedir"
)
// mcCustomConfigDir contains the whole path to config dir. Only access via get/set functions.
var mcCustomConfigDir string
// setMcConfigDir - set a custom MinIO Client config folder.
func setMcConfigDir(configDir string) {
mcCustomConfigDir = configDir
}
// getMcConfigDir - construct MinIO Client config folder.
func getMcConfigDir() (string, *probe.Error) {
if mcCustomConfigDir != "" {
return mcCustomConfigDir, nil
}
homeDir, e := homedir.Dir()
if e != nil {
return "", probe.NewError(e)
}
var configDir string
// For windows the path is slightly different
if runtime.GOOS == "windows" {
configDir = filepath.Join(homeDir, globalMCConfigWindowsDir)
} else {
configDir = filepath.Join(homeDir, globalMCConfigDir)
}
return configDir, nil
}
// mustGetMcConfigDir - construct MinIO Client config folder or fail
func mustGetMcConfigDir() (configDir string) {
configDir, err := getMcConfigDir()
fatalIf(err.Trace(), "Unable to get mcConfigDir.")
return configDir
}
// createMcConfigDir - create MinIO Client config folder
func createMcConfigDir() *probe.Error {
p, err := getMcConfigDir()
if err != nil {
return err.Trace()
}
if e := os.MkdirAll(p, 0700); e != nil {
return probe.NewError(e)
}
return nil
}
// getMcConfigPath - construct MinIO Client configuration path
func getMcConfigPath() (string, *probe.Error) {
if mcCustomConfigDir != "" {
return filepath.Join(mcCustomConfigDir, globalMCConfigFile), nil
}
dir, err := getMcConfigDir()
if err != nil {
return "", err.Trace()
}
return filepath.Join(dir, globalMCConfigFile), nil
}
// mustGetMcConfigPath - similar to getMcConfigPath, ignores errors
func mustGetMcConfigPath() string {
path, err := getMcConfigPath()
fatalIf(err.Trace(), "Unable to get mcConfigPath.")
return path
}
// newMcConfig - initializes a new version '9' config.
func newMcConfig() *configV9 {
cfg := newConfigV9()
cfg.loadDefaults()
return cfg
}
// loadMcConfigCached - returns loadMcConfig with a closure for config cache.
func loadMcConfigFactory() func() (*configV9, *probe.Error) {
// Load once and cache in a closure.
cfgCache, err := loadConfigV9()
// loadMcConfig - reads configuration file and returns config.
return func() (*configV9, *probe.Error) {
return cfgCache, err
}
}
// loadMcConfig - returns configuration, initialized later.
var loadMcConfig func() (*configV9, *probe.Error)
// saveMcConfig - saves configuration file and returns error if any.
func saveMcConfig(config *configV9) *probe.Error {
if config == nil {
return errInvalidArgument().Trace()
}
err := createMcConfigDir()
if err != nil {
return err.Trace(mustGetMcConfigDir())
}
// Save the config.
if err := saveConfigV9(config); err != nil {
return err.Trace(mustGetMcConfigPath())
}
// Refresh the config cache.
loadMcConfig = loadMcConfigFactory()
return nil
}
// isMcConfigExists returns err if config doesn't exist.
func isMcConfigExists() bool {
configFile, err := getMcConfigPath()
if err != nil {
return false
}
if _, e := os.Stat(configFile); e != nil {
return false
}
return true
}
// isValidAlias - Check if alias valid.
func isValidAlias(alias string) bool {
return regexp.MustCompile("^[a-zA-Z][a-zA-Z0-9-_]+$").MatchString(alias)
}
// getHostConfig retrieves host specific configuration such as access keys, signature type.
func getHostConfig(alias string) (*hostConfigV9, *probe.Error) {
mcCfg, err := loadMcConfig()
if err != nil {
return nil, err.Trace(alias)
}
// if host is exact return quickly.
if _, ok := mcCfg.Hosts[alias]; ok {
hostCfg := mcCfg.Hosts[alias]
return &hostCfg, nil
}
// return error if cannot be matched.
return nil, errNoMatchingHost(alias).Trace(alias)
}
// mustGetHostConfig retrieves host specific configuration such as access keys, signature type.
func mustGetHostConfig(alias string) *hostConfigV9 {
hostCfg, _ := getHostConfig(alias)
// If alias is not found,
// look for it in the environment variable.
if hostCfg == nil {
if envConfig, ok := os.LookupEnv(mcEnvHostPrefix + alias); ok {
hostCfg, _ = expandAliasFromEnv(envConfig)
}
}
if hostCfg == nil {
if envConfig, ok := os.LookupEnv(mcEnvHostsDeprecatedPrefix + alias); ok {
errorIf(errInvalidArgument().Trace(mcEnvHostsDeprecatedPrefix+alias), "`MC_HOSTS_<alias>` environment variable is deprecated. Please use `MC_HOST_<alias>` instead for the same functionality.")
hostCfg, _ = expandAliasFromEnv(envConfig)
}
}
return hostCfg
}
// parse url usually obtained from env.
func parseEnvURL(envURL string) (*url.URL, string, string, *probe.Error) {
u, e := url.Parse(envURL)
if e != nil {
return nil, "", "", probe.NewError(e).Trace(envURL)
}
var accessKey, secretKey string
// Check if username:password is provided in URL, with no
// access keys or secret we proceed and perform anonymous
// requests.
if u.User != nil {
accessKey = u.User.Username()
secretKey, _ = u.User.Password()
}
// Look for if URL has invalid values and return error.
if !((u.Scheme == "http" || u.Scheme == "https") &&
(u.Path == "/" || u.Path == "") && u.Opaque == "" &&
!u.ForceQuery && u.RawQuery == "" && u.Fragment == "") {
return nil, "", "", errInvalidArgument().Trace(u.String())
}
// Now that we have validated the URL to be in expected style.
u.User = nil
return u, accessKey, secretKey, nil
}
// parse url usually obtained from env.
func parseEnvURLStr(envURL string) (*url.URL, string, string, *probe.Error) {
var envURLStr string
u, accessKey, secretKey, err := parseEnvURL(envURL)
if err != nil {
// url parsing can fail when accessKey/secretKey contains non url encoded values
// such as #. Strip accessKey/secretKey from envURL and parse again.
re := regexp.MustCompile("^(https?://)(.*?):(.*?)@(.*?)$")
res := re.FindAllStringSubmatch(envURL, -1)
// regex will return full match, scheme, accessKey, secretKey and endpoint:port as
// captured groups.
if res == nil || len(res[0]) != 5 {
return nil, "", "", err
}
for k, v := range res[0] {
if k == 2 {
accessKey = v
}
if k == 3 {
secretKey = v
}
if k == 1 || k == 4 {
envURLStr = fmt.Sprintf("%s%s", envURLStr, v)
}
}
u, _, _, err = parseEnvURL(envURLStr)
if err != nil {
return nil, "", "", err
}
}
// Check if username:password is provided in URL, with no
// access keys or secret we proceed and perform anonymous
// requests.
if u.User != nil {
accessKey = u.User.Username()
secretKey, _ = u.User.Password()
}
return u, accessKey, secretKey, nil
}
const (
mcEnvHostPrefix = "MC_HOST_"
mcEnvHostsDeprecatedPrefix = "MC_HOSTS_"
)
func expandAliasFromEnv(envURL string) (*hostConfigV9, *probe.Error) {
u, accessKey, secretKey, err := parseEnvURLStr(envURL)
if err != nil {
return nil, err.Trace(envURL)
}
return &hostConfigV9{
URL: u.String(),
API: "S3v4",
AccessKey: accessKey,
SecretKey: secretKey,
}, nil
}
// expandAlias expands aliased URL if any match is found, returns as is otherwise.
func expandAlias(aliasedURL string) (alias string, urlStr string, hostCfg *hostConfigV9, err *probe.Error) {
// Extract alias from the URL.
alias, path := url2Alias(aliasedURL)
var envConfig string
var ok bool
if envConfig, ok = os.LookupEnv(mcEnvHostPrefix + alias); !ok {
envConfig, ok = os.LookupEnv(mcEnvHostsDeprecatedPrefix + alias)
if ok {
errorIf(errInvalidArgument().Trace(mcEnvHostsDeprecatedPrefix+alias), "`MC_HOSTS_<alias>` environment variable is deprecated. Please use `MC_HOST_<alias>` instead for the same functionality.")
}
}
if ok {
hostCfg, err = expandAliasFromEnv(envConfig)
if err != nil {
return "", "", nil, err.Trace(aliasedURL)
}
return alias, urlJoinPath(hostCfg.URL, path), hostCfg, nil
}
// Find the matching alias entry and expand the URL.
if hostCfg = mustGetHostConfig(alias); hostCfg != nil {
return alias, urlJoinPath(hostCfg.URL, path), hostCfg, nil
}
return "", aliasedURL, nil, nil // No matching entry found. Return original URL as is.
}
// mustExpandAlias expands aliased URL if any match is found, returns as is otherwise.
func mustExpandAlias(aliasedURL string) (alias string, urlStr string, hostCfg *hostConfigV9) {
alias, urlStr, hostCfg, _ = expandAlias(aliasedURL)
return alias, urlStr, hostCfg
}
+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 "testing"
// Tests valid host URL functionality.
func TestParseEnvURLStr(t *testing.T) {
testCases := []struct {
hostURL string
accessKey string
secretKey string
hostname string
port string
}{
{
hostURL: "https://minio:minio1#23@localhost:9000",
accessKey: "minio",
secretKey: "minio1#23",
hostname: "localhost",
port: "9000",
},
{
hostURL: "https://minio:minio123@localhost:9000",
accessKey: "minio",
secretKey: "minio123",
hostname: "localhost",
port: "9000",
},
{
hostURL: "https://localhost:9000",
accessKey: "",
secretKey: "",
hostname: "localhost",
port: "9000",
},
}
for i, testCase := range testCases {
url, ak, sk, err := parseEnvURLStr(testCase.hostURL)
if testCase.accessKey != ak {
t.Fatalf("Test %d: Expected %s, got %s", i+1, testCase.accessKey, ak)
}
if testCase.secretKey != sk {
t.Fatalf("Test %d: Expected %s, got %s", i+1, testCase.secretKey, sk)
}
if testCase.hostname != url.Hostname() {
t.Fatalf("Test %d: Expected %s, got %s", i+1, testCase.hostname, url.Hostname())
}
if testCase.port != url.Port() {
t.Fatalf("Test %d: Expected %s, got %s", i+1, testCase.port, url.Port())
}
if err != nil {
t.Fatalf("Test %d: Expected test to pass. Failed with err %s", i+1, err)
}
}
}
func TestParseEnvURLStrInvalid(t *testing.T) {
_, _, _, err := parseEnvURLStr("")
if err == nil {
t.Fatalf("Expected failure")
}
}
+516
View File
@@ -0,0 +1,516 @@
/*
* MinIO Client (C) 2014-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 (
"bufio"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"strings"
"syscall"
"github.com/fatih/color"
"github.com/minio/cli"
"github.com/minio/mc/pkg/console"
"github.com/minio/mc/pkg/probe"
)
// cp command flags.
var (
cpFlags = []cli.Flag{
cli.BoolFlag{
Name: "recursive, r",
Usage: "copy recursively",
},
cli.StringFlag{
Name: "older-than",
Usage: "copy objects older than L days, M hours and N minutes",
},
cli.StringFlag{
Name: "newer-than",
Usage: "copy objects newer than L days, M hours and N minutes",
},
cli.StringFlag{
Name: "storage-class, sc",
Usage: "set storage class for new object(s) on target",
},
cli.StringFlag{
Name: "encrypt",
Usage: "encrypt/decrypt objects (using server-side encryption with server managed keys)",
},
cli.StringFlag{
Name: "attr",
Usage: "add custom metadata for the object",
},
}
)
// ErrInvalidMetadata reflects invalid metadata format
var ErrInvalidMetadata = errors.New("specified metadata should be of form key1=value1,key2=value2,... and so on")
// Copy command.
var cpCmd = cli.Command{
Name: "cp",
Usage: "copy objects",
Action: mainCopy,
Before: setGlobalsFromContext,
Flags: append(append(cpFlags, ioFlags...), globalFlags...),
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} [FLAGS] SOURCE [SOURCE...] TARGET
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
ENVIRONMENT VARIABLES:
MC_ENCRYPT: list of comma delimited prefixes
MC_ENCRYPT_KEY: list of comma delimited prefix=secret values
EXAMPLES:
01. Copy a list of objects from local file system to Amazon S3 cloud storage.
$ {{.HelpName}} Music/*.ogg s3/jukebox/
02. Copy a folder recursively from MinIO cloud storage to Amazon S3 cloud storage.
$ {{.HelpName}} --recursive play/mybucket/burningman2011/ s3/mybucket/
03. Copy multiple local folders recursively to MinIO cloud storage.
$ {{.HelpName}} --recursive backup/2014/ backup/2015/ play/archive/
04. Copy a bucket recursively from aliased Amazon S3 cloud storage to local filesystem on Windows.
$ {{.HelpName}} --recursive s3\documents\2014\ C:\Backups\2014
05. Copy files older than 7 days and 10 hours from MinIO cloud storage to Amazon S3 cloud storage.
$ {{.HelpName}} --older-than 7d10h play/mybucket/burningman2011/ s3/mybucket/
06. Copy files newer than 7 days and 10 hours from MinIO cloud storage to a local path.
$ {{.HelpName}} --newer-than 7d10h play/mybucket/burningman2011/ ~/latest/
07. Copy an object with name containing unicode characters to Amazon S3 cloud storage.
$ {{.HelpName}} 本語 s3/andoria/
08. Copy a local folder with space separated characters to Amazon S3 cloud storage.
$ {{.HelpName}} --recursive 'workdir/documents/May 2014/' s3/miniocloud
09. Copy a folder with encrypted objects recursively from Amazon S3 to MinIO cloud storage.
$ {{.HelpName}} --recursive --encrypt-key "s3/documents/=32byteslongsecretkeymustbegiven1,myminio/documents/=32byteslongsecretkeymustbegiven2" s3/documents/ myminio/documents/
10. Copy a list of objects from local file system to MinIO cloud storage with specified metadata.
$ {{.HelpName}} --attr key1=value1,key2=value2 Music/*.mp4 play/mybucket/
11. Copy a folder recursively from MinIO cloud storage to Amazon S3 cloud storage with specified metadata.
$ {{.HelpName}} --attr key1=value1,key2=value2 --recursive play/mybucket/burningman2011/ s3/mybucket/
12. Copy a text file to an object storage and assign REDUCED_REDUNDANCY storage-class to the uploaded object.
$ {{.HelpName}} --storage-class REDUCED_REDUNDANCY myobject.txt play/mybucket
`,
}
// copyMessage container for file copy messages
type copyMessage struct {
Status string `json:"status"`
Source string `json:"source"`
Target string `json:"target"`
Size int64 `json:"size"`
TotalCount int64 `json:"totalCount"`
TotalSize int64 `json:"totalSize"`
}
// String colorized copy message
func (c copyMessage) String() string {
return console.Colorize("Copy", fmt.Sprintf("`%s` -> `%s`", c.Source, c.Target))
}
// JSON jsonified copy message
func (c copyMessage) JSON() string {
c.Status = "success"
copyMessageBytes, e := json.MarshalIndent(c, "", " ")
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
return string(copyMessageBytes)
}
// Progress - an interface which describes current amount
// of data written.
type Progress interface {
Get() int64
}
// ProgressReader can be used to update the progress of
// an on-going transfer progress.
type ProgressReader interface {
io.Reader
Progress
}
// doCopy - Copy a singe file from source to destination
func doCopy(ctx context.Context, cpURLs URLs, pg ProgressReader, encKeyDB map[string][]prefixSSEPair) URLs {
if cpURLs.Error != nil {
cpURLs.Error = cpURLs.Error.Trace()
return cpURLs
}
sourceAlias := cpURLs.SourceAlias
sourceURL := cpURLs.SourceContent.URL
targetAlias := cpURLs.TargetAlias
targetURL := cpURLs.TargetContent.URL
length := cpURLs.SourceContent.Size
if progressReader, ok := pg.(*progressBar); ok {
progressReader.SetCaption(cpURLs.SourceContent.URL.String() + ": ")
} else {
sourcePath := filepath.ToSlash(filepath.Join(sourceAlias, sourceURL.Path))
targetPath := filepath.ToSlash(filepath.Join(targetAlias, targetURL.Path))
printMsg(copyMessage{
Source: sourcePath,
Target: targetPath,
Size: length,
TotalCount: cpURLs.TotalCount,
TotalSize: cpURLs.TotalSize,
})
}
return uploadSourceToTargetURL(ctx, cpURLs, pg, encKeyDB)
}
// doCopyFake - Perform a fake copy to update the progress bar appropriately.
func doCopyFake(cpURLs URLs, pg Progress) URLs {
if progressReader, ok := pg.(*progressBar); ok {
progressReader.ProgressBar.Add64(cpURLs.SourceContent.Size)
}
return cpURLs
}
// doPrepareCopyURLs scans the source URL and prepares a list of objects for copying.
func doPrepareCopyURLs(session *sessionV8, trapCh <-chan bool, cancelCopy context.CancelFunc) {
// Separate source and target. 'cp' can take only one target,
// but any number of sources.
sourceURLs := session.Header.CommandArgs[:len(session.Header.CommandArgs)-1]
targetURL := session.Header.CommandArgs[len(session.Header.CommandArgs)-1] // Last one is target
var totalBytes int64
var totalObjects int64
// Access recursive flag inside the session header.
isRecursive := session.Header.CommandBoolFlags["recursive"]
olderThan := session.Header.CommandStringFlags["older-than"]
newerThan := session.Header.CommandStringFlags["newer-than"]
encryptKeys := session.Header.CommandStringFlags["encrypt-key"]
encrypt := session.Header.CommandStringFlags["encrypt"]
encKeyDB, err := parseAndValidateEncryptionKeys(encryptKeys, encrypt)
fatalIf(err, "Unable to parse encryption keys.")
// Create a session data file to store the processed URLs.
dataFP := session.NewDataWriter()
var scanBar scanBarFunc
if !globalQuiet && !globalJSON { // set up progress bar
scanBar = scanBarFactory()
}
URLsCh := prepareCopyURLs(sourceURLs, targetURL, isRecursive, encKeyDB)
done := false
for !done {
select {
case cpURLs, ok := <-URLsCh:
if !ok { // Done with URL preparation
done = true
break
}
if cpURLs.Error != nil {
// Print in new line and adjust to top so that we don't print over the ongoing scan bar
if !globalQuiet && !globalJSON {
console.Eraseline()
}
if strings.Contains(cpURLs.Error.ToGoError().Error(), " is a folder.") {
errorIf(cpURLs.Error.Trace(), "Folder cannot be copied. Please use `...` suffix.")
} else {
errorIf(cpURLs.Error.Trace(), "Unable to prepare URL for copying.")
}
break
}
jsonData, e := json.Marshal(cpURLs)
if e != nil {
session.Delete()
fatalIf(probe.NewError(e), "Unable to prepare URL for copying. Error in JSON marshaling.")
}
// Skip objects older than --older-than parameter if specified
if olderThan != "" && isOlder(cpURLs.SourceContent.Time, olderThan) {
continue
}
// Skip objects newer than --newer-than parameter if specified
if newerThan != "" && isNewer(cpURLs.SourceContent.Time, newerThan) {
continue
}
fmt.Fprintln(dataFP, string(jsonData))
if !globalQuiet && !globalJSON {
scanBar(cpURLs.SourceContent.URL.String())
}
totalBytes += cpURLs.SourceContent.Size
totalObjects++
case <-trapCh:
cancelCopy()
// Print in new line and adjust to top so that we don't print over the ongoing scan bar
if !globalQuiet && !globalJSON {
console.Eraseline()
}
session.Delete() // If we are interrupted during the URL scanning, we drop the session.
os.Exit(0)
}
}
session.Header.TotalBytes = totalBytes
session.Header.TotalObjects = totalObjects
session.Save()
}
func doCopySession(session *sessionV8, encKeyDB map[string][]prefixSSEPair) error {
trapCh := signalTrap(os.Interrupt, syscall.SIGTERM, syscall.SIGKILL)
ctx, cancelCopy := context.WithCancel(context.Background())
defer cancelCopy()
if !session.HasData() {
doPrepareCopyURLs(session, trapCh, cancelCopy)
}
// Prepare URL scanner from session data file.
urlScanner := bufio.NewScanner(session.NewDataReader())
// isCopied returns true if an object has been already copied
// or not. This is useful when we resume from a session.
isCopied := isLastFactory(session.Header.LastCopied)
// Store a progress bar or an accounter
var pg ProgressReader
// Enable progress bar reader only during default mode.
if !globalQuiet && !globalJSON { // set up progress bar
pg = newProgressBar(session.Header.TotalBytes)
} else {
pg = newAccounter(session.Header.TotalBytes)
}
var quitCh = make(chan struct{})
var statusCh = make(chan URLs)
parallel, queueCh := newParallelManager(statusCh)
go func() {
gracefulStop := func() {
close(queueCh)
parallel.wait()
close(statusCh)
}
for {
select {
case <-quitCh:
gracefulStop()
return
default:
if !urlScanner.Scan() {
// No more entries, quit immediately
gracefulStop()
return
}
if e := urlScanner.Err(); e != nil {
// Error while reading. quit immediately
gracefulStop()
return
}
var cpURLs URLs
// Unmarshal copyURLs from each line. This expects each line to be
// an entire JSON object.
if e := json.Unmarshal([]byte(urlScanner.Text()), &cpURLs); e != nil {
errorIf(probe.NewError(e), "Unable to unmarshal %s", urlScanner.Text())
continue
}
// Save total count.
cpURLs.TotalCount = session.Header.TotalObjects
// Save totalSize.
cpURLs.TotalSize = session.Header.TotalBytes
// Check and handle storage class if passed in command line args
if _, ok := session.Header.CommandStringFlags["storage-class"]; ok {
if cpURLs.TargetContent.Metadata == nil {
cpURLs.TargetContent.Metadata = make(map[string]string)
}
cpURLs.TargetContent.Metadata["X-Amz-Storage-Class"] = session.Header.CommandStringFlags["storage-class"]
}
// metaMap, metaSet := session.Header.UserMetaData
// Check and handle metadata if passed in command line args
if len(session.Header.UserMetaData) != 0 {
if cpURLs.TargetContent.UserMetadata == nil {
cpURLs.TargetContent.UserMetadata = make(map[string]string)
}
for metaDataKey, metaDataVal := range session.Header.UserMetaData {
cpURLs.TargetContent.UserMetadata[metaDataKey] = metaDataVal
}
}
// Verify if previously copied, notify progress bar.
if isCopied(cpURLs.SourceContent.URL.String()) {
queueCh <- func() URLs {
return doCopyFake(cpURLs, pg)
}
} else {
queueCh <- func() URLs {
return doCopy(ctx, cpURLs, pg, encKeyDB)
}
}
}
}
}()
var retErr error
loop:
for {
select {
case <-trapCh:
quitCh <- struct{}{}
cancelCopy()
// Receive interrupt notification.
if !globalQuiet && !globalJSON {
console.Eraseline()
}
session.CloseAndDie()
case cpURLs, ok := <-statusCh:
// Status channel is closed, we should return.
if !ok {
break loop
}
if cpURLs.Error == nil {
session.Header.LastCopied = cpURLs.SourceContent.URL.String()
session.Save()
} else {
// Set exit status for any copy error
retErr = exitStatus(globalErrorExitStatus)
// Print in new line and adjust to top so that we
// don't print over the ongoing progress bar.
if !globalQuiet && !globalJSON {
console.Eraseline()
}
errorIf(cpURLs.Error.Trace(cpURLs.SourceContent.URL.String()),
fmt.Sprintf("Failed to copy `%s`.", cpURLs.SourceContent.URL.String()))
if isErrIgnored(cpURLs.Error) {
continue loop
}
// For critical errors we should exit. Session
// can be resumed after the user figures out
// the problem.
session.CloseAndDie()
}
}
}
if progressReader, ok := pg.(*progressBar); ok {
if progressReader.ProgressBar.Get() > 0 {
progressReader.ProgressBar.Finish()
}
} else {
if accntReader, ok := pg.(*accounter); ok {
printMsg(accntReader.Stat())
}
}
return retErr
}
// validate the passed metadataString and populate the map
func getMetaDataEntry(metadataString string) (map[string]string, *probe.Error) {
metaDataMap := make(map[string]string)
for _, metaData := range strings.Split(metadataString, ",") {
metaDataEntry := strings.Split(metaData, "=")
if len(metaDataEntry) == 2 {
metaDataMap[metaDataEntry[0]] = metaDataEntry[1]
} else {
return nil, probe.NewError(ErrInvalidMetadata)
}
}
return metaDataMap, nil
}
// mainCopy is the entry point for cp command.
func mainCopy(ctx *cli.Context) error {
// Parse encryption keys per command.
encKeyDB, err := getEncKeys(ctx)
fatalIf(err, "Unable to parse encryption keys.")
// Parse metadata.
userMetaMap := make(map[string]string)
if ctx.String("attr") != "" {
userMetaMap, err = getMetaDataEntry(ctx.String("attr"))
fatalIf(err, "Unable to parse attribute %v", ctx.String("attr"))
}
// check 'copy' cli arguments.
checkCopySyntax(ctx, encKeyDB)
// Additional command speific theme customization.
console.SetColor("Copy", color.New(color.FgGreen, color.Bold))
recursive := ctx.Bool("recursive")
olderThan := ctx.String("older-than")
newerThan := ctx.String("newer-than")
storageClass := ctx.String("storage-class")
sseKeys := os.Getenv("MC_ENCRYPT_KEY")
if key := ctx.String("encrypt-key"); key != "" {
sseKeys = key
}
sse := ctx.String("encrypt")
session := newSessionV8()
session.Header.CommandType = "cp"
session.Header.CommandBoolFlags["recursive"] = recursive
session.Header.CommandStringFlags["older-than"] = olderThan
session.Header.CommandStringFlags["newer-than"] = newerThan
session.Header.CommandStringFlags["storage-class"] = storageClass
session.Header.CommandStringFlags["encrypt-key"] = sseKeys
session.Header.CommandStringFlags["encrypt"] = sse
session.Header.UserMetaData = userMetaMap
var e error
if session.Header.RootPath, e = os.Getwd(); e != nil {
session.Delete()
fatalIf(probe.NewError(e), "Unable to get current working folder.")
}
// extract URLs.
session.Header.CommandArgs = ctx.Args()
e = doCopySession(session, encKeyDB)
session.Delete()
return e
}
+61
View File
@@ -0,0 +1,61 @@
/*
* 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 (
"reflect"
"testing"
)
func TestParseMetaData(t *testing.T) {
metaDataCases := []struct {
input string
output map[string]string
err error
status bool
}{
// success scenerio
{"key1=value1,key2=value2", map[string]string{"key1": "value1", "key2": "value2"}, nil, true},
// using different delimitter, other than ',' between multiple meta data
{"key1=value1;key2=value2", nil, ErrInvalidMetadata, false},
// using different delimitter, other than '=' between key value
{"key1:value1,key2:value2", nil, ErrInvalidMetadata, false},
// using no delimitter
{"key1:value1:key2:value2", nil, ErrInvalidMetadata, false},
}
for idx, testCase := range metaDataCases {
metaDatamap, errMeta := getMetaDataEntry(testCase.input)
if testCase.status == true {
if errMeta != nil {
t.Fatalf("Test %d: generated error not matching, expected = `%s`, found = `%s`", idx+1, testCase.err, errMeta)
}
if !reflect.DeepEqual(metaDatamap, testCase.output) {
t.Fatalf("Test %d: generated Map not matching, expected = `%s`, found = `%s`", idx+1, testCase.input, metaDatamap)
}
}
if testCase.status == false {
if !reflect.DeepEqual(metaDatamap, testCase.output) {
t.Fatalf("Test %d: generated Map not matching, expected = `%s`, found = `%s`", idx+1, testCase.input, metaDatamap)
}
if errMeta.Cause.Error() != testCase.err.Error() {
t.Fatalf("Test %d: generated error not matching, expected = `%s`, found = `%s`", idx+1, testCase.err, errMeta)
}
}
}
}
+164
View File
@@ -0,0 +1,164 @@
/*
* 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 (
"fmt"
"github.com/minio/cli"
"github.com/minio/mc/pkg/console"
)
func checkCopySyntax(ctx *cli.Context, encKeyDB map[string][]prefixSSEPair) {
if len(ctx.Args()) < 2 {
cli.ShowCommandHelpAndExit(ctx, "cp", 1) // last argument is exit code.
}
// extract URLs.
URLs := ctx.Args()
if len(URLs) < 2 {
fatalIf(errDummy().Trace(ctx.Args()...), fmt.Sprintf("Unable to parse source and target arguments."))
}
srcURLs := URLs[:len(URLs)-1]
tgtURL := URLs[len(URLs)-1]
isRecursive := ctx.Bool("recursive")
// Verify if source(s) exists.
for _, srcURL := range srcURLs {
_, _, err := url2Stat(srcURL, false, encKeyDB)
if err != nil {
console.Fatalf("Unable to validate source %s\n", srcURL)
}
}
// Check if bucket name is passed for URL type arguments.
url := newClientURL(tgtURL)
if url.Host != "" {
if url.Path == string(url.Separator) {
fatalIf(errInvalidArgument().Trace(), fmt.Sprintf("Target `%s` does not contain bucket name.", tgtURL))
}
}
// Guess CopyURLsType based on source and target URLs.
copyURLsType, err := guessCopyURLType(srcURLs, tgtURL, isRecursive, encKeyDB)
if err != nil {
fatalIf(errInvalidArgument().Trace(), "Unable to guess the type of copy operation.")
}
switch copyURLsType {
case copyURLsTypeA: // File -> File.
checkCopySyntaxTypeA(srcURLs, tgtURL, encKeyDB)
case copyURLsTypeB: // File -> Folder.
checkCopySyntaxTypeB(srcURLs, tgtURL, encKeyDB)
case copyURLsTypeC: // Folder... -> Folder.
checkCopySyntaxTypeC(srcURLs, tgtURL, isRecursive, encKeyDB)
case copyURLsTypeD: // File1...FileN -> Folder.
checkCopySyntaxTypeD(srcURLs, tgtURL, encKeyDB)
default:
fatalIf(errInvalidArgument().Trace(), "Unable to guess the type of copy operation.")
}
}
// checkCopySyntaxTypeA verifies if the source and target are valid file arguments.
func checkCopySyntaxTypeA(srcURLs []string, tgtURL string, keys map[string][]prefixSSEPair) {
// Check source.
if len(srcURLs) != 1 {
fatalIf(errInvalidArgument().Trace(), "Invalid number of source arguments.")
}
srcURL := srcURLs[0]
_, srcContent, err := url2Stat(srcURL, false, keys)
fatalIf(err.Trace(srcURL), "Unable to stat source `"+srcURL+"`.")
if !srcContent.Type.IsRegular() {
fatalIf(errInvalidArgument().Trace(), "Source `"+srcURL+"` is not a file.")
}
}
// checkCopySyntaxTypeB verifies if the source is a valid file and target is a valid folder.
func checkCopySyntaxTypeB(srcURLs []string, tgtURL string, keys map[string][]prefixSSEPair) {
// Check source.
if len(srcURLs) != 1 {
fatalIf(errInvalidArgument().Trace(), "Invalid number of source arguments.")
}
srcURL := srcURLs[0]
_, srcContent, err := url2Stat(srcURL, false, keys)
fatalIf(err.Trace(srcURL), "Unable to stat source `"+srcURL+"`.")
if !srcContent.Type.IsRegular() {
fatalIf(errInvalidArgument().Trace(srcURL), "Source `"+srcURL+"` is not a file.")
}
// Check target.
if _, tgtContent, err := url2Stat(tgtURL, false, keys); err == nil {
if !tgtContent.Type.IsDir() {
fatalIf(errInvalidArgument().Trace(tgtURL), "Target `"+tgtURL+"` is not a folder.")
}
}
}
// checkCopySyntaxTypeC verifies if the source is a valid recursive dir and target is a valid folder.
func checkCopySyntaxTypeC(srcURLs []string, tgtURL string, isRecursive bool, keys map[string][]prefixSSEPair) {
// Check source.
if len(srcURLs) != 1 {
fatalIf(errInvalidArgument().Trace(), "Invalid number of source arguments.")
}
// Check target.
if _, tgtContent, err := url2Stat(tgtURL, false, keys); err == nil {
if !tgtContent.Type.IsDir() {
fatalIf(errInvalidArgument().Trace(tgtURL), "Target `"+tgtURL+"` is not a folder.")
}
}
for _, srcURL := range srcURLs {
c, srcContent, err := url2Stat(srcURL, false, keys)
// incomplete uploads are not necessary for copy operation, no need to verify for them.
isIncomplete := false
if err != nil {
if !isURLPrefixExists(srcURL, isIncomplete) {
fatalIf(err.Trace(srcURL), "Unable to stat source `"+srcURL+"`.")
}
// No more check here, continue to the next source url
continue
}
if srcContent.Type.IsDir() {
// Require --recursive flag if we are copying a directory
if !isRecursive {
fatalIf(errInvalidArgument().Trace(srcURL), "To copy a folder requires --recursive flag.")
}
// Check if we are going to copy a directory into itself
if isURLContains(srcURL, tgtURL, string(c.GetURL().Separator)) {
fatalIf(errInvalidArgument().Trace(), "Copying a folder into itself is not allowed.")
}
}
}
}
// checkCopySyntaxTypeD verifies if the source is a valid list of files and target is a valid folder.
func checkCopySyntaxTypeD(srcURLs []string, tgtURL string, keys map[string][]prefixSSEPair) {
// Source can be anything: file, dir, dir...
// Check target if it is a dir
if _, tgtContent, err := url2Stat(tgtURL, false, keys); err == nil {
if !tgtContent.Type.IsDir() {
fatalIf(errInvalidArgument().Trace(tgtURL), "Target `"+tgtURL+"` is not a folder.")
}
}
}
+62 -73
View File
@@ -1,5 +1,5 @@
/*
* Minio Client (C) 2015 Minio, Inc.
* 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.
@@ -14,24 +14,15 @@
* limitations under the License.
*/
package main
package cmd
import (
"path/filepath"
"strings"
"github.com/minio/mc/pkg/client"
"github.com/minio/minio-xl/pkg/probe"
"github.com/minio/mc/pkg/probe"
)
type copyURLs struct {
SourceAlias string
SourceContent *client.Content
TargetAlias string
TargetContent *client.Content
Error *probe.Error `json:"-"`
}
type copyURLsType uint8
// NOTE: All the parse rules should reduced to A: Copy(Source, Target).
@@ -57,12 +48,12 @@ const (
copyURLsTypeD
)
// guessCopyURLType guesses the type of URL. This approach all allows prepareURL
// guessCopyURLType guesses the type of clientURL. This approach all allows prepareURL
// functions to accurately report failure causes.
func guessCopyURLType(sourceURLs []string, targetURL string, isRecursive bool) (copyURLsType, *probe.Error) {
func guessCopyURLType(sourceURLs []string, targetURL string, isRecursive bool, keys map[string][]prefixSSEPair) (copyURLsType, *probe.Error) {
if len(sourceURLs) == 1 { // 1 Source, 1 Target
sourceURL := sourceURLs[0]
_, sourceContent, err := url2Stat(sourceURL)
_, sourceContent, err := url2Stat(sourceURL, false, keys)
if err != nil {
return copyURLsTypeInvalid, err
}
@@ -74,7 +65,7 @@ func guessCopyURLType(sourceURLs []string, targetURL string, isRecursive bool) (
}
// If target is a folder, it is Type B.
if isTargetURLDir(targetURL) {
if isAliasURLDir(targetURL, keys) {
return copyURLsTypeB, nil
}
// else Type A.
@@ -82,7 +73,7 @@ func guessCopyURLType(sourceURLs []string, targetURL string, isRecursive bool) (
}
// Multiple source args and target is a folder. It is Type D.
if isTargetURLDir(targetURL) {
if isAliasURLDir(targetURL, keys) {
return copyURLsTypeD, nil
}
@@ -90,97 +81,94 @@ func guessCopyURLType(sourceURLs []string, targetURL string, isRecursive bool) (
}
// SINGLE SOURCE - Type A: copy(f, f) -> copy(f, f)
// prepareCopyURLsTypeA - prepares target and source URLs for copying.
func prepareCopyURLsTypeA(sourceURL string, targetURL string) copyURLs {
// Extract alias before fiddling with the URL.
// prepareCopyURLsTypeA - prepares target and source clientURLs for copying.
func prepareCopyURLsTypeA(sourceURL string, targetURL string, encKeyDB map[string][]prefixSSEPair) URLs {
// Extract alias before fiddling with the clientURL.
sourceAlias, _, _ := mustExpandAlias(sourceURL)
// Find alias and expanded URL.
// Find alias and expanded clientURL.
targetAlias, targetURL, _ := mustExpandAlias(targetURL)
_, sourceContent, err := url2Stat(sourceURL)
_, sourceContent, err := url2Stat(sourceURL, false, encKeyDB)
if err != nil {
// Source does not exist or insufficient privileges.
return copyURLs{Error: err.Trace(sourceURL)}
return URLs{Error: err.Trace(sourceURL)}
}
if !sourceContent.Type.IsRegular() {
// Source is not a regular file
return copyURLs{Error: errInvalidSource(sourceURL).Trace(sourceURL)}
}
if sourceContent.URL.String() == targetURL {
// source and target can not be same
return copyURLs{Error: errSourceTargetSame(sourceURL).Trace(sourceURL)}
return URLs{Error: errInvalidSource(sourceURL).Trace(sourceURL)}
}
// All OK.. We can proceed. Type A
return makeCopyContentTypeA(sourceAlias, sourceContent, targetAlias, targetURL)
return makeCopyContentTypeA(sourceAlias, sourceContent, targetAlias, targetURL, encKeyDB)
}
// prepareCopyContentTypeA - makes CopyURLs content for copying.
func makeCopyContentTypeA(sourceAlias string, sourceContent *client.Content, targetAlias string, targetURL string) copyURLs {
return copyURLs{
func makeCopyContentTypeA(sourceAlias string, sourceContent *clientContent, targetAlias string, targetURL string, encKeyDB map[string][]prefixSSEPair) URLs {
targetContent := clientContent{URL: *newClientURL(targetURL)}
return URLs{
SourceAlias: sourceAlias,
SourceContent: sourceContent,
TargetAlias: targetAlias,
TargetContent: &client.Content{URL: *client.NewURL(targetURL)},
TargetContent: &targetContent,
}
}
// SINGLE SOURCE - Type B: copy(f, d) -> copy(f, d/f) -> A
// prepareCopyURLsTypeB - prepares target and source URLs for copying.
func prepareCopyURLsTypeB(sourceURL string, targetURL string) copyURLs {
// Extract alias before fiddling with the URL.
// prepareCopyURLsTypeB - prepares target and source clientURLs for copying.
func prepareCopyURLsTypeB(sourceURL string, targetURL string, encKeyDB map[string][]prefixSSEPair) URLs {
// Extract alias before fiddling with the clientURL.
sourceAlias, _, _ := mustExpandAlias(sourceURL)
// Find alias and expanded URL.
// Find alias and expanded clientURL.
targetAlias, targetURL, _ := mustExpandAlias(targetURL)
_, sourceContent, err := url2Stat(sourceURL)
_, sourceContent, err := url2Stat(sourceURL, false, encKeyDB)
if err != nil {
// Source does not exist or insufficient privileges.
return copyURLs{Error: err.Trace(sourceURL)}
return URLs{Error: err.Trace(sourceURL)}
}
if !sourceContent.Type.IsRegular() {
if sourceContent.Type.IsDir() {
return copyURLs{Error: errSourceIsDir(sourceURL).Trace(sourceURL)}
return URLs{Error: errSourceIsDir(sourceURL).Trace(sourceURL)}
}
// Source is not a regular file.
return copyURLs{Error: errInvalidSource(sourceURL).Trace(sourceURL)}
return URLs{Error: errInvalidSource(sourceURL).Trace(sourceURL)}
}
// All OK.. We can proceed. Type B: source is a file, target is a folder and exists.
return makeCopyContentTypeB(sourceAlias, sourceContent, targetAlias, targetURL)
return makeCopyContentTypeB(sourceAlias, sourceContent, targetAlias, targetURL, encKeyDB)
}
// makeCopyContentTypeB - CopyURLs content for copying.
func makeCopyContentTypeB(sourceAlias string, sourceContent *client.Content, targetAlias string, targetURL string) copyURLs {
func makeCopyContentTypeB(sourceAlias string, sourceContent *clientContent, targetAlias string, targetURL string, encKeyDB map[string][]prefixSSEPair) URLs {
// All OK.. We can proceed. Type B: source is a file, target is a folder and exists.
targetURLParse := client.NewURL(targetURL)
targetURLParse := newClientURL(targetURL)
targetURLParse.Path = filepath.ToSlash(filepath.Join(targetURLParse.Path, filepath.Base(sourceContent.URL.Path)))
return makeCopyContentTypeA(sourceAlias, sourceContent, targetAlias, targetURLParse.String())
return makeCopyContentTypeA(sourceAlias, sourceContent, targetAlias, targetURLParse.String(), encKeyDB)
}
// SINGLE SOURCE - Type C: copy(d1..., d2) -> []copy(d1/f, d1/d2/f) -> []A
// prepareCopyRecursiveURLTypeC - prepares target and source URLs for copying.
func prepareCopyURLsTypeC(sourceURL, targetURL string, isRecursive bool) <-chan copyURLs {
// Extract alias before fiddling with the URL.
// prepareCopyRecursiveURLTypeC - prepares target and source clientURLs for copying.
func prepareCopyURLsTypeC(sourceURL, targetURL string, isRecursive bool, encKeyDB map[string][]prefixSSEPair) <-chan URLs {
// Extract alias before fiddling with the clientURL.
sourceAlias, _, _ := mustExpandAlias(sourceURL)
// Find alias and expanded URL.
// Find alias and expanded clientURL.
targetAlias, targetURL, _ := mustExpandAlias(targetURL)
copyURLsCh := make(chan copyURLs)
go func(sourceURL, targetURL string, copyURLsCh chan copyURLs) {
copyURLsCh := make(chan URLs)
go func(sourceURL, targetURL string, copyURLsCh chan URLs) {
defer close(copyURLsCh)
sourceClient, err := newClient(sourceURL)
if err != nil {
// Source initialization failed.
copyURLsCh <- copyURLs{Error: err.Trace(sourceURL)}
copyURLsCh <- URLs{Error: err.Trace(sourceURL)}
return
}
for sourceContent := range sourceClient.List(isRecursive, false) {
isIncomplete := false
for sourceContent := range sourceClient.List(isRecursive, isIncomplete, DirNone) {
if sourceContent.Err != nil {
// Listing failed.
copyURLsCh <- copyURLs{Error: sourceContent.Err.Trace(sourceClient.GetURL().String())}
copyURLsCh <- URLs{Error: sourceContent.Err.Trace(sourceClient.GetURL().String())}
continue
}
@@ -190,14 +178,14 @@ func prepareCopyURLsTypeC(sourceURL, targetURL string, isRecursive bool) <-chan
}
// All OK.. We can proceed. Type B: source is a file, target is a folder and exists.
copyURLsCh <- makeCopyContentTypeC(sourceAlias, sourceClient.GetURL(), sourceContent, targetAlias, targetURL)
copyURLsCh <- makeCopyContentTypeC(sourceAlias, sourceClient.GetURL(), sourceContent, targetAlias, targetURL, encKeyDB)
}
}(sourceURL, targetURL, copyURLsCh)
return copyURLsCh
}
// makeCopyContentTypeC - CopyURLs content for copying.
func makeCopyContentTypeC(sourceAlias string, sourceURL client.URL, sourceContent *client.Content, targetAlias string, targetURL string) copyURLs {
func makeCopyContentTypeC(sourceAlias string, sourceURL clientURL, sourceContent *clientContent, targetAlias string, targetURL string, encKeyDB map[string][]prefixSSEPair) URLs {
newSourceURL := sourceContent.URL
pathSeparatorIndex := strings.LastIndex(sourceURL.Path, string(sourceURL.Separator))
newSourceSuffix := filepath.ToSlash(newSourceURL.Path)
@@ -206,17 +194,17 @@ func makeCopyContentTypeC(sourceAlias string, sourceURL client.URL, sourceConten
newSourceSuffix = strings.TrimPrefix(newSourceSuffix, sourcePrefix)
}
newTargetURL := urlJoinPath(targetURL, newSourceSuffix)
return makeCopyContentTypeA(sourceAlias, sourceContent, targetAlias, newTargetURL)
return makeCopyContentTypeA(sourceAlias, sourceContent, targetAlias, newTargetURL, encKeyDB)
}
// MULTI-SOURCE - Type D: copy([](f|d...), d) -> []B
// prepareCopyURLsTypeE - prepares target and source URLs for copying.
func prepareCopyURLsTypeD(sourceURLs []string, targetURL string, isRecursive bool) <-chan copyURLs {
copyURLsCh := make(chan copyURLs)
go func(sourceURLs []string, targetURL string, copyURLsCh chan copyURLs) {
// prepareCopyURLsTypeE - prepares target and source clientURLs for copying.
func prepareCopyURLsTypeD(sourceURLs []string, targetURL string, isRecursive bool, encKeyDB map[string][]prefixSSEPair) <-chan URLs {
copyURLsCh := make(chan URLs)
go func(sourceURLs []string, targetURL string, copyURLsCh chan URLs) {
defer close(copyURLsCh)
for _, sourceURL := range sourceURLs {
for cpURLs := range prepareCopyURLsTypeC(sourceURL, targetURL, isRecursive) {
for cpURLs := range prepareCopyURLsTypeC(sourceURL, targetURL, isRecursive, encKeyDB) {
copyURLsCh <- cpURLs
}
}
@@ -224,30 +212,31 @@ func prepareCopyURLsTypeD(sourceURLs []string, targetURL string, isRecursive boo
return copyURLsCh
}
// prepareCopyURLs - prepares target and source URLs for copying.
func prepareCopyURLs(sourceURLs []string, targetURL string, isRecursive bool) <-chan copyURLs {
copyURLsCh := make(chan copyURLs)
go func(sourceURLs []string, targetURL string, copyURLsCh chan copyURLs) {
// prepareCopyURLs - prepares target and source clientURLs for copying.
func prepareCopyURLs(sourceURLs []string, targetURL string, isRecursive bool, encKeyDB map[string][]prefixSSEPair) <-chan URLs {
copyURLsCh := make(chan URLs)
go func(sourceURLs []string, targetURL string, copyURLsCh chan URLs, encKeyDB map[string][]prefixSSEPair) {
defer close(copyURLsCh)
cpType, err := guessCopyURLType(sourceURLs, targetURL, isRecursive)
cpType, err := guessCopyURLType(sourceURLs, targetURL, isRecursive, encKeyDB)
fatalIf(err.Trace(), "Unable to guess the type of copy operation.")
switch cpType {
case copyURLsTypeA:
copyURLsCh <- prepareCopyURLsTypeA(sourceURLs[0], targetURL)
copyURLsCh <- prepareCopyURLsTypeA(sourceURLs[0], targetURL, encKeyDB)
case copyURLsTypeB:
copyURLsCh <- prepareCopyURLsTypeB(sourceURLs[0], targetURL)
copyURLsCh <- prepareCopyURLsTypeB(sourceURLs[0], targetURL, encKeyDB)
case copyURLsTypeC:
for cURLs := range prepareCopyURLsTypeC(sourceURLs[0], targetURL, isRecursive) {
for cURLs := range prepareCopyURLsTypeC(sourceURLs[0], targetURL, isRecursive, encKeyDB) {
copyURLsCh <- cURLs
}
case copyURLsTypeD:
for cURLs := range prepareCopyURLsTypeD(sourceURLs, targetURL, isRecursive) {
for cURLs := range prepareCopyURLsTypeD(sourceURLs, targetURL, isRecursive, encKeyDB) {
copyURLsCh <- cURLs
}
default:
copyURLsCh <- copyURLs{Error: errInvalidArgument().Trace(sourceURLs...)}
copyURLsCh <- URLs{Error: errInvalidArgument().Trace(sourceURLs...)}
}
}(sourceURLs, targetURL, copyURLsCh)
}(sourceURLs, targetURL, copyURLsCh, encKeyDB)
return copyURLsCh
}
+211
View File
@@ -0,0 +1,211 @@
/*
* MinIO Client (C) 2015-2019 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* 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/console"
"github.com/minio/mc/pkg/probe"
)
// diff specific flags.
var (
diffFlags = []cli.Flag{}
)
// Compute differences in object name, size, and date between two buckets.
var diffCmd = cli.Command{
Name: "diff",
Usage: "list differences in object name, size, and date between two buckets",
Action: mainDiff,
Before: setGlobalsFromContext,
Flags: append(diffFlags, globalFlags...),
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} [FLAGS] FIRST SECOND
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
DESCRIPTION:
Diff only calculates differences in object name, size and time. It *DOES NOT* compare objects' contents.
LEGEND:
< - object is only in source.
> - object is only in destination.
! - newer object is in source.
EXAMPLES:
1. Compare a local folder with a folder on Amazon S3 cloud storage.
$ {{.HelpName}} ~/Photos s3/mybucket/Photos
2. Compare two folders on a local filesystem.
$ {{.HelpName}} ~/Photos /Media/Backup/Photos
`,
}
// diffMessage json container for diff messages
type diffMessage struct {
Status string `json:"status"`
FirstURL string `json:"first"`
SecondURL string `json:"second"`
Diff differType `json:"diff"`
Error *probe.Error `json:"error,omitempty"`
firstContent *clientContent
secondContent *clientContent
}
// String colorized diff message
func (d diffMessage) String() string {
msg := ""
switch d.Diff {
case differInFirst:
msg = console.Colorize("DiffOnlyInFirst", "< "+d.FirstURL)
case differInSecond:
msg = console.Colorize("DiffOnlyInSecond", "> "+d.SecondURL)
case differInType:
msg = console.Colorize("DiffType", "! "+d.SecondURL)
case differInSize:
msg = console.Colorize("DiffSize", "! "+d.SecondURL)
case differInTime:
msg = console.Colorize("DiffTime", "! "+d.SecondURL)
default:
fatalIf(errDummy().Trace(d.FirstURL, d.SecondURL),
"Unhandled difference between `"+d.FirstURL+"` and `"+d.SecondURL+"`.")
}
return msg
}
// JSON jsonified diff message
func (d diffMessage) JSON() string {
d.Status = "success"
diffJSONBytes, e := json.MarshalIndent(d, "", " ")
fatalIf(probe.NewError(e),
"Unable to marshal diff message `"+d.FirstURL+"`, `"+d.SecondURL+"` and `"+string(d.Diff)+"`.")
return string(diffJSONBytes)
}
func checkDiffSyntax(ctx *cli.Context, encKeyDB map[string][]prefixSSEPair) {
if len(ctx.Args()) != 2 {
cli.ShowCommandHelpAndExit(ctx, "diff", 1) // last argument is exit code
}
for _, arg := range ctx.Args() {
if strings.TrimSpace(arg) == "" {
fatalIf(errInvalidArgument().Trace(ctx.Args()...), "Unable to validate empty argument.")
}
}
URLs := ctx.Args()
firstURL := URLs[0]
secondURL := URLs[1]
// Diff only works between two directories, verify them below.
// Verify if firstURL is accessible.
_, firstContent, err := url2Stat(firstURL, false, encKeyDB)
if err != nil {
fatalIf(err.Trace(firstURL), fmt.Sprintf("Unable to stat '%s'.", firstURL))
}
// Verify if its a directory.
if !firstContent.Type.IsDir() {
fatalIf(errInvalidArgument().Trace(firstURL), fmt.Sprintf("`%s` is not a folder.", firstURL))
}
// Verify if secondURL is accessible.
_, secondContent, err := url2Stat(secondURL, false, encKeyDB)
if err != nil {
fatalIf(err.Trace(secondURL), fmt.Sprintf("Unable to stat '%s'.", secondURL))
}
// Verify if its a directory.
if !secondContent.Type.IsDir() {
fatalIf(errInvalidArgument().Trace(secondURL), fmt.Sprintf("`%s` is not a folder.", secondURL))
}
}
// doDiffMain runs the diff.
func doDiffMain(firstURL, secondURL string) error {
// Source and targets are always directories
sourceSeparator := string(newClientURL(firstURL).Separator)
if !strings.HasSuffix(firstURL, sourceSeparator) {
firstURL = firstURL + sourceSeparator
}
targetSeparator := string(newClientURL(secondURL).Separator)
if !strings.HasSuffix(secondURL, targetSeparator) {
secondURL = secondURL + targetSeparator
}
// Expand aliased urls.
firstAlias, firstURL, _ := mustExpandAlias(firstURL)
secondAlias, secondURL, _ := mustExpandAlias(secondURL)
firstClient, err := newClientFromAlias(firstAlias, firstURL)
if err != nil {
fatalIf(err.Trace(firstAlias, firstURL, secondAlias, secondURL),
fmt.Sprintf("Failed to diff '%s' and '%s'", firstURL, secondURL))
}
secondClient, err := newClientFromAlias(secondAlias, secondURL)
if err != nil {
fatalIf(err.Trace(firstAlias, firstURL, secondAlias, secondURL),
fmt.Sprintf("Failed to diff '%s' and '%s'", firstURL, secondURL))
}
// Diff first and second urls.
for diffMsg := range objectDifference(firstClient, secondClient, firstURL, secondURL) {
if diffMsg.Error != nil {
errorIf(diffMsg.Error, "Unable to calculate objects difference.")
// Ignore error and proceed to next object.
continue
}
printMsg(diffMsg)
}
return nil
}
// mainDiff main for 'diff'.
func mainDiff(ctx *cli.Context) error {
// Parse encryption keys per command.
encKeyDB, err := getEncKeys(ctx)
fatalIf(err, "Unable to parse encryption keys.")
// check 'diff' cli arguments.
checkDiffSyntax(ctx, encKeyDB)
// Additional command specific theme customization.
console.SetColor("DiffMessage", color.New(color.FgGreen, color.Bold))
console.SetColor("DiffOnlyInFirst", color.New(color.FgRed))
console.SetColor("DiffOnlyInSecond", color.New(color.FgGreen))
console.SetColor("DiffType", color.New(color.FgMagenta))
console.SetColor("DiffSize", color.New(color.FgYellow, color.Bold))
console.SetColor("DiffTime", color.New(color.FgYellow, color.Bold))
URLs := ctx.Args()
firstURL := URLs.Get(0)
secondURL := URLs.Get(1)
return doDiffMain(firstURL, secondURL)
}
+226
View File
@@ -0,0 +1,226 @@
/*
* 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 (
"strings"
"unicode/utf8"
// golang does not support flat keys for path matching, find does
"golang.org/x/text/unicode/norm"
)
// differType difference in type.
type differType int
const (
differInNone differType = iota // does not differ
differInSize // differs in size
differInTime // differs in time
differInType // differs in type, exfile/directory
differInFirst // only in source (FIRST)
differInSecond // only in target (SECOND)
)
func (d differType) String() string {
switch d {
case differInNone:
return ""
case differInSize:
return "size"
case differInTime:
return "time"
case differInType:
return "type"
case differInFirst:
return "only-in-first"
case differInSecond:
return "only-in-second"
}
return "unknown"
}
func objectDifference(sourceClnt, targetClnt Client, sourceURL, targetURL string) (diffCh chan diffMessage) {
return difference(sourceClnt, targetClnt, sourceURL, targetURL, true, false, DirNone)
}
func dirDifference(sourceClnt, targetClnt Client, sourceURL, targetURL string) (diffCh chan diffMessage) {
return difference(sourceClnt, targetClnt, sourceURL, targetURL, false, true, DirFirst)
}
// objectDifference function finds the difference between all objects
// recursively in sorted order from source and target.
func difference(sourceClnt, targetClnt Client, sourceURL, targetURL string, isRecursive, returnSimilar bool, dirOpt DirOpt) (diffCh chan diffMessage) {
var (
srcEOF, tgtEOF bool
srcOk, tgtOk bool
srcCtnt, tgtCtnt *clientContent
srcSuffix, tgtSuffix string
)
// Set default values for listing.
isIncomplete := false // we will not compare any incomplete objects.
srcCh := sourceClnt.List(isRecursive, isIncomplete, dirOpt)
tgtCh := targetClnt.List(isRecursive, isIncomplete, dirOpt)
diffCh = make(chan diffMessage, 1000)
go func() {
srcCtnt, srcOk = <-srcCh
tgtCtnt, tgtOk = <-tgtCh
defer close(diffCh)
for {
srcEOF = !srcOk
tgtEOF = !tgtOk
// No objects from source AND target: Finish
if srcEOF && tgtEOF {
break
}
if !srcEOF && srcCtnt.Err != nil {
diffCh <- diffMessage{Error: srcCtnt.Err.Trace(sourceURL, targetURL)}
return
}
if !tgtEOF && tgtCtnt.Err != nil {
diffCh <- diffMessage{Error: tgtCtnt.Err.Trace(sourceURL, targetURL)}
return
}
// If source doesn't have objects anymore, comparison becomes obvious
if srcEOF {
diffCh <- diffMessage{
SecondURL: tgtCtnt.URL.String(),
Diff: differInSecond,
secondContent: tgtCtnt,
}
tgtCtnt, tgtOk = <-tgtCh
continue
}
// The same for target
if tgtEOF {
diffCh <- diffMessage{
FirstURL: srcCtnt.URL.String(),
Diff: differInFirst,
firstContent: srcCtnt,
}
srcCtnt, srcOk = <-srcCh
continue
}
srcSuffix = strings.TrimPrefix(srcCtnt.URL.String(), sourceURL)
tgtSuffix = strings.TrimPrefix(tgtCtnt.URL.String(), targetURL)
current := urlJoinPath(targetURL, srcSuffix)
expected := urlJoinPath(targetURL, tgtSuffix)
if !utf8.ValidString(srcSuffix) {
// Error. Keys must be valid UTF-8.
diffCh <- diffMessage{Error: errInvalidSource(current).Trace()}
srcCtnt, srcOk = <-srcCh
continue
}
if !utf8.ValidString(tgtSuffix) {
// Error. Keys must be valid UTF-8.
diffCh <- diffMessage{Error: errInvalidTarget(expected).Trace()}
tgtCtnt, tgtOk = <-tgtCh
continue
}
// Normalize to avoid situations where multiple byte representations are possible.
// e.g. 'ä' can be represented as precomposed U+00E4 (UTF-8 0xc3a4) or decomposed
// U+0061 U+0308 (UTF-8 0x61cc88).
normalizedCurrent := norm.NFC.String(current)
normalizedExpected := norm.NFC.String(expected)
if normalizedExpected > normalizedCurrent {
diffCh <- diffMessage{
FirstURL: srcCtnt.URL.String(),
Diff: differInFirst,
firstContent: srcCtnt,
}
srcCtnt, srcOk = <-srcCh
continue
}
if normalizedExpected == normalizedCurrent {
srcType, tgtType := srcCtnt.Type, tgtCtnt.Type
srcSize, tgtSize := srcCtnt.Size, tgtCtnt.Size
srcTime, tgtTime := srcCtnt.Time, tgtCtnt.Time
if srcType.IsRegular() && !tgtType.IsRegular() ||
!srcType.IsRegular() && tgtType.IsRegular() {
// Type differs. Source is never a directory.
diffCh <- diffMessage{
FirstURL: srcCtnt.URL.String(),
SecondURL: tgtCtnt.URL.String(),
Diff: differInType,
firstContent: srcCtnt,
secondContent: tgtCtnt,
}
continue
}
if (srcType.IsRegular() && tgtType.IsRegular()) && srcSize != tgtSize {
// Regular files differing in size.
diffCh <- diffMessage{
FirstURL: srcCtnt.URL.String(),
SecondURL: tgtCtnt.URL.String(),
Diff: differInSize,
firstContent: srcCtnt,
secondContent: tgtCtnt,
}
} else if srcTime.After(tgtTime) {
// Regular files differing in timestamp.
diffCh <- diffMessage{
FirstURL: srcCtnt.URL.String(),
SecondURL: tgtCtnt.URL.String(),
Diff: differInTime,
firstContent: srcCtnt,
secondContent: tgtCtnt,
}
}
// No differ
if returnSimilar {
diffCh <- diffMessage{
FirstURL: srcCtnt.URL.String(),
SecondURL: tgtCtnt.URL.String(),
Diff: differInNone,
firstContent: srcCtnt,
secondContent: tgtCtnt,
}
}
srcCtnt, srcOk = <-srcCh
tgtCtnt, tgtOk = <-tgtCh
continue
}
// Differ in second
diffCh <- diffMessage{
SecondURL: tgtCtnt.URL.String(),
Diff: differInSecond,
secondContent: tgtCtnt,
}
tgtCtnt, tgtOk = <-tgtCh
continue
}
}()
return diffCh
}

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