Compare commits

...
Author SHA1 Message Date
Poorna 015134b2b7 Add mc replicate diff cmd to show unreplicated objects (#4127) 2022-07-23 19:25:13 -07:00
Anis Elleuch 657b6315fc support perf to execute all speed tests (#4158)
This commit will make `mc support perf <alias>` to execute all
performance tests, networking, drive and object speed tests.

perf will only have --duration and --verbose flags.

The user can still test with 'drive', 'object', and 'net' but they will
be hidden for now along with their flags.
2022-07-23 18:58:57 -07:00
Harshavardhana 95e6947f9c remove sysinfo from --json mode without --debug (#4159) 2022-07-23 18:57:57 -07:00
Taran Pelkey 537ad9468a Add support for NewerNoncurrentVersions (#4153) 2022-07-22 15:29:30 -07:00
Anis Elleuch 1c1ee7a5a4 info: Show pools summary of a erasure cluster (#4162)
Also fix the assumption that each node has one pool, so print all pools
indexes that belong to a particular node
2022-07-21 07:30:50 -07:00
Klaus Post cb7f9b6db2 Add mc cat --tail and --offset (#4149)
Allow range requests for cat operations, either specifying tail or an absolute offset.

If tail is longer then fail, the entire file is listed.
2022-07-18 21:22:10 -07:00
Shireesh Anjal 603857371c Add license update command (#4155) 2022-07-18 18:54:45 -07:00
Klaus Post 48e9183957 Move mc admin top scanner -> mc admin scanner info (#4151)
Also, add `mc admin scanner trace` which gives a simplified trace 
with only relevant options.
2022-07-15 02:20:55 -07:00
Harshavardhana 288e8e3678 update madmin-go to v1.4.5 (#4154) 2022-07-13 22:22:35 -07:00
Shireesh Anjal 7b20dc2958 Move support register to license register (#4150)
Also, introduce a new command `license info` to print information 
from the license (when the license is available)
2022-07-13 18:25:30 -07:00
Ashish Kumar Sinha add7b7b881 add mc ping command (#4074) 2022-07-11 09:16:12 -07:00
Minio Trusted afa79f2bd7 update minio-go to v7.0.31
for local files there is a significant
memory reduction by moving back the
multipart upload implementation to use
unbuffered implementation.
2022-07-10 22:32:40 -07:00
Krishnan Parthasarathi 11771955b3 fix: tier-add help (#4148) 2022-07-08 08:47:12 -07:00
Shireesh Anjal 81c4a5ad6e Add --api-key flag to mc support register (#4144) 2022-07-06 07:54:36 -07:00
Aditya Manthramurthy 811d7e5edb Add commands to manage external IDPs (#4131)
This adds the set, info, ls and rm commands
2022-07-05 18:19:13 -07:00
Klaus Post 01b87ecc02 Upgrade madmin (#4145)
Upgrade madmin to fix trace regression.
2022-07-05 11:08:30 -07:00
Harshavardhana 58860ccb15 reset timer after the function body is finished (#4143)
reset timer after the function body is finished

this is needed to make sure to wait "expected" amount
of time, otherwise the timer has already fired (negating
the wait of your function body)
2022-07-02 08:45:00 -07:00
Klaus Post 82a6c4f20f Add admin top scanner & trace --call=scanner (#4130)
mc: Add admin top scanner & trace --call=scanner

Examples:
```
λ mc admin top scanner myminio
Scanner Activity: ●∙∙
+-------------------------------------------------------------------------------------------------------+
| Last full scan time:   0d0h5m; Estimated 7358.44/month                                                |
| Current cycle:         129439; Started: 2022-06-22 18:01:50.5775259 +0200 CEST                        |
| Active disks:          1                                                                              |
| -------------------------------------- Last Minute Statistics --------------------------------------- |
| Objects Scanned:       101 objects; Avg: 3.775ms; Rate: 145440/day                                    |
| Versions Scanned:      10001 versions; Avg: 31.998µs; Rate: 14401440/day                              |
| Versions Heal Checked: 200 versions; Avg: 1.394ms; Rate: 288000/day                                   |
| Read Metadata:         101 objects; Avg: 0ms                                                          |
| ILM checks:            10001 versions; Avg: 408ns                                                     |
| Check Replication:     10001 versions; Avg: 3.646µs                                                   |
| Verify Deleted:        0 folders; Avg: 0ms                                                            |
| Yield:                 59.083s total; Avg: 584.978ms/obj                                              |
| ------------------------------------- Currently Scanning Paths -------------------------------------- |
| 127.0.0.1:9002/d:/data/distxl-plain/s2/d1/warp-benchmark-bucket/qwrShN3c/405.M(nsCrNI(PZhkAqA.rnd     |
+-------------------------------------------------------------------------------------------------------+
```

```
λ mc admin trace --call=scanner myminio
2022-06-22T18:04:12.705 [SCANNER] scanner.ScanFolder 127.0.0.1:9002 d:\data\distxl-plain\s2\d4 warp-benchmark-bucket/ajJkH6Ic/2425.mLeCC9gkg)7aQxfJ.rnd 15.2171467s
2022-06-22T18:04:28.022 [SCANNER] scanner.ScanObject 127.0.0.1:9002 d:\data\distxl-plain\s2\d4 ajJkH6Ic/304.SAWTkh9)WJrnZF7l.rnd/xl.meta 1.0691ms
2022-06-22T18:04:27.922 [SCANNER] scanner.ScanFolder 127.0.0.1:9002 d:\data\distxl-plain\s2\d4 warp-benchmark-bucket/ajJkH6Ic/304.SAWTkh9)WJrnZF7l.rnd 209.3969ms
2022-06-22T18:04:28.232 [SCANNER] scanner.ScanObject 127.0.0.1:9002 d:\data\distxl-plain\s2\d4 ajJkH6Ic/405.(kO1pyUPMdhsaXev.rnd/xl.meta 1.0531ms
2022-06-22T18:04:28.131 [SCANNER] scanner.ScanFolder 127.0.0.1:9002 d:\data\distxl-plain\s2\d4 warp-benchmark-bucket/ajJkH6Ic/405.(kO1pyUPMdhsaXev.rnd 207.7757ms
2022-06-22T18:04:28.440 [SCANNER] scanner.ScanObject 127.0.0.1:9002 d:\data\distxl-plain\s2\d4 ajJkH6Ic/506.E726EiB(GNLfSLro.rnd/xl.meta 1.0317ms
...
```
2022-07-01 16:04:04 -07:00
Praveen raj Mani c29c4a38a6 Implement mc ready to check if the cluster is ready or not (#4101)
Also adds option to check if the cluster has enough read quorum and if
the cluster is taken down for any maintenance.

Uses madmin.AnonymousClient for invoking the requests
2022-07-01 12:02:25 -07:00
Shireesh Anjal 5afc2bdfad Add support status command (#4140)
Will print following information:

- Is the cluster registered
- Is pushing logs to SUBNET enabled
- Is pushing callhome info to SUBNET enabled
2022-07-01 11:20:35 -07:00
Harshavardhana bf1145af1e update minio-go/v7 to v7.0.30 (#4136) 2022-06-28 05:09:02 -07:00
Eng Zer Jun 264d21c65a refactor: replace strings.Replace with strings.ReplaceAll (#4135)
strings.ReplaceAll(s, old, new) is a wrapper function for
strings.Replace(s, old, new, -1). But strings.ReplaceAll is more
readable and removes the hardcoded -1.

Signed-off-by: Eng Zer Jun <engzerjun@gmail.com>
2022-06-27 03:59:09 -07:00
Minio Trusted 5212e42ded update to RedHat UBI 8.6 2022-06-26 12:44:40 -07:00
Ashish Kumar Sinha 40ee1a4ed6 change admin console to support logs show (#4132) 2022-06-26 11:51:48 -07:00
Poorna b1d8ca83f2 admin: add admin cluster iam import/export cmd (#4102) 2022-06-26 11:36:48 -07:00
Shireesh Anjal 78f844a357 Save license at the time of registration (#4123)
Currently we only extract the `api_key` from SUBNET's registration api
response and store it in the minio subnet config. The response contains
license also, and it can be useful in getting information about the
subscription. So this PR enhances the register command to extract and
store the license also.
2022-06-26 11:35:31 -07:00
Harshavardhana 17f5b7b11c add further license banners in default 'help' output (#4129) 2022-06-22 09:41:02 -07:00
Aditya Manthramurthy 2754c91048 Switch to last commit time based release (#4128) 2022-06-17 11:16:51 -07:00
Anis Elleuch 0e44ad30db Update version printing to include more information (#4125)
Show licence, copyright header and platform in addition to mc version.
2022-06-16 13:17:03 -07:00
Harshavardhana fc1d65b6e8 filter out hidden flags from error printing (#4122) 2022-06-16 09:45:16 -07:00
Anis Elleuch b0e8574969 Healing finish estimation time relies on disk usage space (#4124)
Do not rely on the disk scanner's total object numbers.

Also, remove healing MRF from the calculation for simplicity.
2022-06-16 09:43:53 -07:00
Harshavardhana a9a7b7a225 fix: help output formatting for cluster bucket export/import 2022-06-15 13:34:24 -07:00
Harshavardhana ce9e444740 add unfreeze command to 'unfreeze' S3 API calls (#4121) 2022-06-15 13:29:14 -07:00
Shireesh Anjal 80ae287b02 Add commands to enable/disable callhome and logs (#4107)
- Remove the get/set options under `callhome`
- Move logs settings to a separate command (`mc support logs`)
- Provide toggle options (`enable, disable, status`) for both the
commands

In case of logs (`mc support logs enable|disable|status`),

`enable` configures minio to push logs to SUBNET in real-time by
configuring the webhook `logger_webhook:subnet`
`disable` disables the webhook
`status` displays whether it is enabled or disabled

In the case of call home (`mc support callhome enable|disable|status`),

`enable` configures minio to automatically push callhome info to SUBNET
every 24hrs by setting the config `callhome enable=on`
`disable` disables callhome by setting `enable=off`
`status` displays whether it is enabled or disabled
2022-06-15 09:14:52 -07:00
Harshavardhana 127d84854d improve UI for driveperf inspired from object perf test (#4118) 2022-06-14 23:09:58 -07:00
Poorna a59de0d37e add import/export bucket metadata command (#4087) 2022-06-14 10:55:58 -07:00
Harshavardhana d2960d67ce extend Go's time.ParseDuration to support days, weeks and years (#4116) 2022-06-13 04:18:38 -07:00
Harshavardhana 36d5749991 improve UI for netperf inspired from object perf test (#4117)
Refer for the behavior https://asciinema.org/a/501270
2022-06-13 04:17:28 -07:00
Harshavardhana fc64e84829 fix: 'mc admin top api' IOPs, RX/TX remove them (#4115)
The current implementation didn't cater to concurrency
factor i.e X calls happening in parallel so the
resulting values for IOPs, RX, and TX were all skewed,
change this to print totals instead.

We need to bring moving average behavior to know
the overall IOPs, RX, TX per second here.

Will bring this change subsequently, keep it simple
for now.
2022-06-10 17:37:20 -07:00
Shireesh Anjal 7a6a43046c Improve success message in support register cmd (#4108)
Change the success message on cluster registration to `{alias}
registered successfully`.

When the `mc support register` command is run for an already registered
cluster, show the message `{alias} updated successfully` to indicate
that updated information about the cluster was sent to SUBNET.
2022-06-10 15:12:40 -07:00
Harshavardhana 50669cafa6 ignore remove errors for WORM protected objects (#4111)
this error is similar to insufficient permission
on local folders, we can proceed to remove whatever
objects we can.
2022-06-10 15:12:16 -07:00
Aditya Manthramurthy d42880acb1 Bump up linter version (#4114)
- Add Go 1.18 to CI
- Appears to be needed for Go 1.18
2022-06-10 15:12:05 -07:00
Harshavardhana 250c0e4e59 update help for 'mc admin top api' 2022-06-10 11:09:54 -07:00
Harshavardhana e19fcb8daf feat: Add 'mc admin top api' for realtime view (#4112)
This is just a beginning but this can be enhanced further
to have different views of S3 calls, internal calls, and
disk/storage calls.
2022-06-10 11:02:26 -07:00
Anis Elleuch abfc6709b0 heal: Fix single disk healing ETA reporting (#4113)
ETA disk during healing was not accurate especially when the number of
files is low. The reason is that the estimation is based on time.Now()
though heal info in the server side is only updated each minute.

Use heal info last update field instead of time.Now().
2022-06-10 07:17:00 -07:00
Shireesh Anjal e9d27aef5c fix: callhome get error when subnet hook not set (#4089)
When there is no SUBNET webhook configured in the cluster (which is the
default state), the `mc support callhome get` command fails as it tries
to fetch the `logger_webhook:subnet` setting which doesn't exist.

Fixed by ignoring the specific error that says the sub-system target
doesn't exist, and printing `logs=off` in such cases.
2022-06-03 10:24:25 -07:00
Poorna 591858cd1a Fix replicate status detail summary (#4104)
refactor display to report consistent status by ARN

Fixes issue: #4105
2022-06-02 20:11:09 -07:00
Harshavardhana 6e2ed46cb4 add hidden force-delete option (#4097) 2022-05-30 12:51:43 -07:00
Harshavardhana 30fd595df6 cleanup print message for 'support profile' (#4099)
use single logging style, we do not use
`go` logger in `mc` avoid it.
2022-05-30 06:24:31 -07:00
Harshavardhana 8f7accb135 update go deps for yaml.v3 and minio-go 2022-05-29 17:56:24 -07:00
Claudio B 1cff14a109 regression: update golang.org/x/crypto (#4096) 2022-05-26 20:07:32 -07:00
Shireesh Anjal 03e876aeaa Hide mc support callhome command (#4091)
As the functionality is not fully ready yet.
2022-05-23 09:58:29 -07:00
Anis Elleuch 6c0d5e4b65 alias: Enable self signed TLS prompt in darwin platforms (#4094)
Not trusted TLS error message has another string representation in
Darwin platform. Since there is no another way to test for this specific
error with Golang API, we will need to support this alternate error message.
2022-05-23 06:36:11 -07:00
Harshavardhana 83d81ea590 fix: SubKeyId may not be same AuthorityKeyId for self-signed CA (#4093)
In situations when cert is its own CA the SubKeyId is not
same as AuthorityKeyId

Refer
https://cs.opensource.google/go/go/+/refs/tags/go1.18.2:src/crypto/x509/x509.go;l=1525

This PR handles this by validating the SubKeyId with correct value
that is expected, extends the current TOFU style.
2022-05-23 05:13:20 -07:00
Shireesh Anjal 907555c849 Deprecate --name flag from support diag (#4092)
Earlier the `support diag` command used to work even when the cluster
was not registered with SUBNET. In such cases, it used to pass the value
of `--name` flag as the cluster name to be set on SUBNET.

Now it errors out if the cluster is not registered. i.e. It expects the
cluster to be already registered with SUBNET, which means it already has
a name. Hence the `--name` flag is meaningless.

Removing the code that used this flag, and marking it as hidden and
deprecated.
2022-05-19 10:35:19 -07:00
Harshavardhana 1b1a5940ab add JSON flag support for decom status (#4086) 2022-05-16 16:09:53 -07:00
Ashish Kumar Sinha aa60a8db1e modify support profile command (#4061) 2022-05-12 06:43:21 -07:00
Anis Elleuch 8ca59cdebf trace: Show milliseconds in trace output (#4083)
Trace output without --verbose was always missing milliseconds precision
due to a typo in the code. This commit fixes the issue.
2022-05-11 10:17:36 -07:00
Krishnan Parthasarathi b5a0640899 Prefix version suspension (#4064) 2022-05-08 18:15:17 -07:00
Pablo Hinojosa b5937c68bc doc: Fix broken link (#4072) 2022-05-08 17:19:27 -07:00
Harshavardhana 0d9d42166a avoid cascading deletes for active-active setups (#4079)
This PR in-turn ends up supporting cascading deletes
for `mc mirror` setups when you have

```
mc mirror --watch alias1 alias2
mc mirror --watch alias2 alias3
```

IT still avoids cyclical deletes such as

```
mc mirror --watch alias1 alias2
mc mirror --watch alias2 alias1
```
2022-05-06 16:14:21 -07:00
Poorna 844139d52d Fix example for mc admin replicate edit (#4080) 2022-05-06 11:42:07 -07:00
Ashish Kumar Sinha d62c1e2418 Add admin prometheus metrics (#4049) 2022-05-05 23:38:16 -07:00
Shireesh Anjal 4e8402e46f Use latest version of madmin-go (1.3.13) (#4075)
Contains a new structure for Kubernetes information that will be
returned in the health report (mc support diag)
2022-05-05 04:21:35 -07:00
Krishnan Parthasarathi f126341342 Add support for minio warm tier (#4009) 2022-05-04 16:45:46 -07:00
DanielMcKracken 5619a78ead update golang.org/x/crypto (#4068) 2022-04-29 07:42:08 -07:00
Harshavardhana 04161f5e19 fix: support autocompletion for command aliases (#4070) 2022-04-28 13:55:44 -07:00
ksonj c586b4c06e Document setting multiple policies (#4065)
*
2022-04-28 12:50:32 -07:00
Anis Elleuch 19952de324 Fix client-s3 Stat() for prefix with parallel lower prefixes (#4069)
client-s3.Stat() does not properly detect a prefix when there is another
lower one,

e.g: Stat() of 'dir/' fails when there is 'dir-name/' in the same parent
prefix.
2022-04-28 12:50:01 -07:00
Klooven 7c229abb05 fix: README.md rename config to alias (#4062) 2022-04-26 17:27:16 -07:00
Prakash Senthil Vel 276e1db70d Error message when update failing due to permissions (#4057) 2022-04-26 04:30:21 -07:00
Anis Elleuch 162609d6d0 info: Add the count of total versions details (#4060)
admin info command will show the total number of versions of a
deployment, if available.
2022-04-25 22:05:56 -07:00
Harshavardhana 32dfeaaf6b update minio/pkg to v1.1.22 2022-04-25 19:45:34 -07:00
Ashish Kumar Sinha cc4ff3a0cc Remove cpuio as default in profiling (#4056) 2022-04-19 08:54:41 -07:00
Nick Doornekamp 0530f5a471 Update documentation for --older/newer-than flags (#4039) 2022-04-16 08:10:14 -07:00
Harshavardhana e964a37a3f update minio/pkg deps 2022-04-15 19:51:00 -07:00
Anis Elleuch 606cdd3453 Load proxy config when probing for server TLS certificate (#4052)
mc alias set recently started to probe the TLS certificate for
the remote server, however it should load the proxy environment
configuration if any.
2022-04-15 16:49:57 -07:00
Anis Elleuch 1187be0ad2 mirror: Do not create remote bucket with --dry-run (#4054)
In a site wide mirroring, non existing buckets in the destination site
are still created if --dry-run is passed. This commit will avoid this.

This commit also prints a mirror message of the newly created buckets
in a site wide mirroring.
2022-04-15 16:49:28 -07:00
Anis Elleuch 6a61b286b1 mirror: Stop minio-go bucket listen when watch is cancelled (#4053)
When mirror in --watch mode is restarted, the previous minio-go
ListenNotification/ListenBucketNotification call is not properly
canceled. This commit creates a new context for that listen call and
cancels it when client-s3 Watch() is asked to be stopped.
2022-04-15 16:49:13 -07:00
Harshavardhana 792c6c1475 update minio-go/v7, minio/pkg deps 2022-04-15 00:38:49 -07:00
Ashish Kumar Sinha 1a504e6e64 Replace fake with dry-run (#4050) 2022-04-14 06:49:57 -07:00
Gabriel Dolberg 8e6b9c8a49 fix usage message wording (#4048) 2022-04-13 13:27:25 -07:00
Ashish Kumar Sinha 8df32e87d6 Add mutex, threads and cpuio as default in profiling (#4046) 2022-04-12 00:08:34 -07:00
jinapurapu 45c6f376c4 Error handling for remove alias request if alias not found (#4017) 2022-04-11 13:26:40 -07:00
Harshavardhana 2a5195f2d2 update to latest madmin-go v1.3.11 2022-04-08 16:20:13 -07:00
Anis Elleuch 3f0953f9f4 Do not rely on contentCh to print removal messages (#4041)
Removal is an asynchrounous operation. We should not use structures that
we send to the removal goroutine and use them in removal messages.
2022-04-07 11:52:55 -07:00
Shireesh Anjal dbc09a8bf0 Get speedtest results as part of support diag (#4034)
Also remove the `--full` flag and run the new perf tests (that run quite
fast) always (if the minio version supports it).

In case of older versions of minio that have the older versions of the
performance tests, mc will not request for those tests to be run, and
subsequently will not look for their results in the response.
2022-04-07 08:12:51 -07:00
Daniel Valdivia 42bb4df233 Simplify mc ilm ls (#4042)
Signed-off-by: Daniel Valdivia <hola@danielvaldivia.com>
2022-04-05 12:56:01 -07:00
Anis ElleuchandAnis Elleuch d9feb87286 Compute bucket/object correctly for some endpoints (#4040)
Removing an old code that calculates incorrectly the bucket and object
from the client-s3.targetURL. The old code assumed that
client-s3.targetURL can have this style
http://bucket.endpoint/prefix/object but this is not true.

client-s3.targetURL will always have this endpoint style
https://endpoint/bucket/object whenever vhost is enabled or not for a
given alias.

Co-authored-by: Anis Elleuch <anis@min.io>
2022-04-04 18:47:08 -07:00
Anis ElleuchandAnis Elleuch 661afae983 mirror: Do not exit upon errors when --watch is passed (#4032)
Currently, when mirror is not able to copy an object (e.g. corrupted)
and watch is specified, mirror will restart mirroring again to stop
again at the same problematic object.

Co-authored-by: Anis Elleuch <anis@min.io>
2022-04-02 16:16:34 -07:00
Anis ElleuchandAnis Elleuch 033969a0bf rm: Fix sending an object/version to removal with --no-current flag (#4038)
Do no miss sending object/version to contentCh when there is deletion
result available.

This commit fixes issues seen when some objects/versions are not deleted
when --no-current is passed.

Co-authored-by: Anis Elleuch <anis@min.io>
2022-04-02 16:14:23 -07:00
PoornaandPoorna Krishnamoorthy 5a3ad93ab9 `mc rm --non-current should remove top level deletemarker (#4037)
Earlier commit #8eae2e3bbfafe952ecb33904c0d9073871a32169 reverted
this behavior, bringing it back

Co-authored-by: Poorna Krishnamoorthy <poorna@minio.io>
2022-04-01 16:39:16 -07:00
PoornaandPoorna Krishnamoorthy dc2a851b54 Make sure to print mc rm dry run message (#4033)
Co-authored-by: Poorna Krishnamoorthy <poorna@minio.io>
2022-04-01 01:19:02 -07:00
PoornaandPoorna Krishnamoorthy 8eae2e3bbf Fix mc rm --non-current to use --older-than filter if specified (#4030)
This PR also changes the interpretation of --non-current flag to delete
all non current versions that qualify irrespective of whether top level
version is a delete marker.

Co-authored-by: Poorna Krishnamoorthy <poorna@minio.io>
2022-03-30 16:21:42 -07:00
Shireesh Anjal 4d7b58bac5 Fix message in admin subnet health (#4019) 2022-03-30 12:03:50 -07:00
Gabriel Dolberg 9c34f6c94b Typo: Fix error messages on service account operations (#4026) 2022-03-30 11:55:55 -07:00
Poorna d6ffdbc8fb admin trace: convert trace type to string in json fmt (#4029) 2022-03-25 01:52:53 -07:00
Harshavardhana 84a7b83eda use globalRootCAs always do not initialize new certPools
automatic prompt for certs broke system trusted tls endpoints
since it ignored the currently loaded certs as trusted.

if they are available and we can establish TLS we should
proceed instead of failing and asking users to always use
`--insecure`
2022-03-17 12:56:43 -07:00
Anis Elleuch de063f9252 Fix alias add when --insecure is passed in a non tty (#4025)
--insecure does not have an effect when running mc in a non-terminal. This
commit fixes the behavior by ignoring the prompt from trusting self
signed certificate when --insecure is passed as well.
2022-03-17 10:35:24 -07:00
Harshavardhana b01f48836a replicate add should enable all replication types by default (#4021)
fixes #4020
2022-03-16 13:06:05 -07:00
Andreas Auernhammer 3252573ed2 alias: fetch peer certificate when adding an alias (#4010)
This commit adds an extension to the `alias set`
command. When adding an alias fails due to a TLS
trust error - i.e. remote peer certificate verification
fails - `mc` fetches the remote peer certificate,
computes the public key fingerprint and asks the user
to confirm the fingerprint.

When the user confirms the fingerprint, the certificate
is added to the `CAs` directory.

This allows users to use a TOFU authentication with
self-signed certificates - similar to SSH.

Signed-off-by: Andreas Auernhammer <hi@aead.dev>
2022-03-16 10:00:25 -07:00
Anis Elleuch 0f31ce23b9 mv: Fix regression when checking lock in target bucket (#4015)
A recent commit changed the behavior of client-s3.GetObjectLockConfig()
without properly checking the behavior of the callers introducing a bug
during mv command where the target is an S3 server.

Add some tests for the mc mv command as well.
2022-03-11 15:10:02 -08:00
Anis Elleuch 869c875967 svcacct: Show successful message after deletion (#4016)
Fix some typo that prevented the command to print a success message
when a service account is deleted.
2022-03-11 15:09:46 -08:00
Poorna bd00af5a71 Allow remote target endpoint to point to different host (#4012) 2022-03-08 17:42:16 -08:00
Krishna Srinivas def1988b92 Implement "mc support perf net" for network throughput test (#3998) 2022-03-08 11:30:42 -08:00
Harshavardhana f13defa545 update some wording and docs under tier commands (#4007) 2022-03-01 17:12:26 -08:00
Shireesh Anjal a7a9b65237 Remove --schedule flag from support diag command (#4003)
Going forward, periodic upload of diagnostics is not expected to be
performed using the `support diag` command.
2022-03-01 10:53:59 -08:00
Anis Elleuch 88b984a6e2 more validation for retention commands (#4004) 2022-03-01 10:53:43 -08:00
Krishnan Parthasarathi 9aa7712c43 Add support for tier-rm/tier-verify (#3996) 2022-03-01 10:53:09 -08:00
Klaus Post 0d5acd8820 Fix arm FreeBSD build (#4006)
Fixes #4005

Tested with `GOOS=freebsd GOARCH=arm go build .`.
2022-03-01 10:23:05 -08:00
supriyo-biswas 9de0045882 Quote special characters in share curl command (#4000)
* Quote special characters in share curl command
* Add testcases and other unsafe chars
2022-02-28 12:25:19 -08:00
Anis Elleuch cce6451b63 watch: Clean up watch when restarting mirror after an error (#3993)
Add cleanup for watch code when it exits and mirroring is restarted.
2022-02-25 20:15:21 -08:00
Harshavardhana a1d6c3d4af remove trimming of top level path 2022-02-25 18:10:25 -08:00
Klaus Post 5488be0c8b Add cpuio profile type (#3988) 2022-02-25 10:46:22 -08:00
jinapurapu 9cf722a3aa Updated help text to clarify alias (#4001) 2022-02-24 16:04:29 -08:00
Anis Elleuch 096fbbf24a mirror: Proper cleanup after exit (#3994) 2022-02-24 14:24:22 -08:00
Harshavardhana af342c3780 update wording of svacct command line 2022-02-24 13:31:00 -08:00
Harshavardhana d7846dab9e update CREDITs file for new deps 2022-02-24 12:59:29 -08:00
Harshavardhana b44a7642ed update go mod tidy -compat=1.17 2022-02-24 12:58:21 -08:00
Krishnan Parthasarathi 2cae86c783 tier-info: Add bar charts for 24hr dailys tier-stats (#3928) 2022-02-24 12:51:21 -08:00
Harshavardhana 620455a22c update minio-go/v7 to v7.0.23 2022-02-22 18:50:59 -08:00
Harshavardhana dec8d91dbc fix: rename 'perf drives' to 'perf drive' (#3991) 2022-02-22 10:13:07 -08:00
Shireesh Anjal f4f5932d3f Add mc support callhome get command (#3986)
* Add `mc support callhome get` command

Will print all the callhome settings (currently just `logs=on|off`)

* Rename retrieveCallhomeSetting to printCallhomeSetting

As it doesn't need to return anything, and only prints the setting.
2022-02-21 15:47:31 -08:00
Anis Elleuch 3902b3b03f Refactor profiling and add goroutines (#3992)
Running mc like this,

`MC_PROFILER=mem,goroutine mc ...` will start profiling and save
profiling data when mc quits with Control-C.
2022-02-21 14:50:51 -08:00
Harshavardhana c7a8815414 fix: rm should reject --non-current with --recursive (#3987) 2022-02-18 02:59:34 -08:00
Shireesh Anjal 99bdf20c64 Remove cli flag subnet-proxy (#3989)
System now supports setting the subnet proxy as a config, so the command
line flag is not required anymore.
2022-02-17 11:05:53 -08:00
Harshavardhana 3b15bec803 update minio-go to v7.0.22 2022-02-16 10:40:26 -08:00
Harshavardhana c5e56141bd fix: admin info output for multiple pools (#3985)
fixes #3984
fixes #3976
2022-02-16 10:35:24 -08:00
Shireesh Anjal 220f7c217a Fix cluster registration failing when proxy not set (#3983) 2022-02-15 04:03:39 -08:00
Klaus Post 2f42260f98 Add remote zip support to mc ls/cp/cat (#3977)
--zip flag is hidden for now
2022-02-15 03:09:39 -08:00
Harshavardhana a11a264933 extend 'mc support inspect --export=json' to export JSON directly (#3981)
this is essentially the same code at
https://github.com/minio/minio/tree/master/docs/debugging/xl-meta

--export option provides exporting 'xl.meta' information as 'JSON'
or export the inlined-data 'JSON' that represents 'version-id' and
the corresponding size of the inlined data.

This essentially now provides full visibility of the inspected data
that is captured, extracts and converts into some parseable
JSON.
2022-02-15 01:52:18 -08:00
Shireesh Anjal c7537a171f Improve descriptions of support commands (#3982) 2022-02-14 02:48:56 -08:00
Shireesh Anjal 65efe40a82 Use subnet proxy from minio config if available (#3969)
minio now supports storing the proxy to be used for connecting to subnet
in the `subnet proxy` config. So mc can use it if available when
communicating with subnet during cluster registration or diagnostics
upload.
2022-02-13 22:13:27 -08:00
Shireesh Anjal f65871e305 Move admin speedtest to support perf (#3966)
related to drives and objects sub-commands
2022-02-13 22:13:06 -08:00
Shireesh Anjal ab2bce93ea Move admin profile to support profile (#3972)
As part of reorganization of support related commands
2022-02-13 16:08:52 -08:00
Shireesh Anjal 7b93343803 Move admin inspect to support inspect (#3971) 2022-02-13 15:38:06 -08:00
Poorna c579c0b403 Add subcommands to mc replicate resync (#3964)
This PR adds `start` and `status` subcommands for
managing replication resync
2022-02-13 15:36:24 -08:00
Harshavardhana c595efe440 fix: some inconsistencies in 'mc support' command 2022-02-13 15:21:46 -08:00
Harshavardhana cb1daf1567 simplify wording for mc replicate edit and default sane values (#3980) 2022-02-11 17:07:53 -08:00
Harshavardhana 2be75594d0 simplify wording for mc replicate add and default sane values (#3978) 2022-02-11 16:36:37 -08:00
Harshavardhana ed42cdc3a8 fix: alias import comment formatting (#3979) 2022-02-11 13:27:48 -08:00
jinapurapu 8e3b5ebc46 Add alias import command (#3958) 2022-02-11 10:15:02 -08:00
Shireesh Anjal 5d50c9beb9 Error out from support diag if cluster not registered (#3970)
If user tries to run `mc support diag` for a cluster that is not yet
registered, error out asking the user to register the cluster first.
2022-02-11 09:28:15 -08:00
Poorna 9b6f6cdbb4 Add admin replicate remove command to allow removal of sites (#3919) 2022-02-10 18:50:11 -08:00
Sidhartha Mani 006c48c51c add admin speedtest drive command (#3939) 2022-02-10 17:53:39 -08:00
Klaus Post e71b1c80b4 Skip Shell check on Windows (#3973)
Fixes `mc: <ERROR> Failed to enable autocompletion. Cannot 
determine shell-type and SHELL environment variable found: exit status 1.` 
on Windows.
2022-02-10 17:52:02 -08:00
jinapurapu 548dc0fd99 Added help message if no arguments passed to mc alias set command (#3963) 2022-02-09 03:14:03 -08:00
Harshavardhana 3a7a724753 error out when bucket not found with proper exitcode (#3959)
fixes #3953
2022-02-08 12:23:17 -08:00
Shireesh Anjal 5960c628f3 Move admin-subnet commands to support (#3949) 2022-02-08 10:05:36 -08:00
Harshavardhana dabc6c598e set bucketName always in RemoveResult response (#3957) 2022-02-04 12:21:02 -08:00
Harshavardhana cb7674133a make sure backendType is looked up properly 2022-02-04 12:14:06 -08:00
Harshavardhana 98bc432b53 add pool id as part of 'mc admin info' output (#3954) 2022-02-04 12:05:16 -08:00
Christian Muehlhaeuser e048c85d71 fix: don't query terminal on startup (#3956)
This change bumps the lipgloss and termenv dependencies, which prevents
the terminal from being OSC-queried on startup. Additionally, OSC
queries will never be run if the process isn't in control of the
terminal, for example when started in the background / detached.

Fixes #3955.
2022-02-03 20:46:44 -08:00
Harshavardhana f5cd21bcf0 update container images for ubi-8.5 2022-02-03 09:40:49 -08:00
Klaus Post 8ad226ca83 du: Add object counts (#3950) 2022-02-03 09:39:15 -08:00
Harshavardhana fd6d470242 update container image to ubi-8.5 (#3948) 2022-02-02 10:15:49 -08:00
Poorna a7147d221d Change mc admin replicate status ui to have additional filters (#3936) 2022-02-01 15:51:09 -08:00
Shireesh Anjal af7c550f26 Add command to configure callhome options (#3940) 2022-02-01 15:50:39 -08:00
Harshavardhana f5596de2fe ignore expiration and expires from JSON output (#3947) 2022-02-01 15:50:09 -08:00
Christian Muehlhaeuser 8a0d1134bb fix: don't block if terminal does not respond to OSC query (#3946)
This aborts OSC queries after a timeout, and prevents mc from getting
stuck when encountering unresponsive or non-compliant terminals, like
CircleCI's.

Fixes #3938.
2022-02-01 10:01:06 -08:00
apendragon 3f23cdd921 honor --bypass flag for 'mc retention' command (#3945)
Fixes #3944
2022-01-29 09:20:38 -08:00
Harshavardhana 829153f47c update go.sum - go mod tidy 2022-01-28 16:23:20 -08:00
Poorna ccbc1ff725 Add mc admin replicate edit command (#3908) 2022-01-28 16:22:14 -08:00
Harshavardhana 3e28003f82 fix: admin speedtest verbose output \n (#3943) 2022-01-28 16:21:37 -08:00
Aditya Manthramurthy 6d12396b47 Add option to mc admin policy info to save policy JSON to file (#3914) 2022-01-28 16:21:28 -08:00
Villena Guillaume 9914c8187e Allow storageclass to be specified on mc ls (#3915) 2022-01-28 14:42:21 -08:00
Harshavardhana 43524f7978 remove quota FIFO support (#3942) 2022-01-28 14:41:44 -08:00
Harshavardhana f06a4b20a3 add missing 'mc admin inspect' examples (#3934) 2022-01-28 14:41:35 -08:00
Anis Elleuch 0c58d62a1f Fix mirror with relative fs path (#3929)
mc diff <alias>/<bucket>/ ./dir/ is not calculated correctly because the
difference code relies on the format of the argument, for example,
whether it is dir/ or ./dir/ or ../my/dir/.

This commit will calculate the absolute path of the passed argument if
it is a filesystem path and uses it through the code.
2022-01-28 10:19:21 -08:00
Christian Muehlhaeuser 068e19a7e4 fix: do not query terminal when running in a CI context (#3941)
This prevents mc from querying the terminal via OSC when running in a
CI context, like CircleCI. As the CI never responds to the query we
get stuck in a read we can not cancel.

Fixes #3938.
2022-01-28 08:57:53 -08:00
Harshavardhana 16249f3587 add amount of time 'service restart' took (#3935) 2022-01-24 14:18:11 -08:00
d-tork 7656636373 docs: add example instructions for IBM cloud storage (#3932) 2022-01-24 08:37:25 -08:00
Anis Elleuch fd70dd59c6 heal: Add verbose flag to heal command (#3927)
For deployments which has many disks, it is annoying to list all disks
by default. Add --verbose flag to only show the status of all disks.
2022-01-21 08:51:18 -08:00
Anis Elleuch 2f9bcdf344 typo: Error out if the policy is already set in policy update cmd (#3931)
Fix a typo when checking if a policy is already set to a user or a
group.
2022-01-21 08:46:49 -08:00
Harshavardhana dd01c71445 use actual UTF-8 characters instead of \u for readability 2022-01-16 16:57:51 -08:00
Harshavardhana ac39184c35 make UI changes to speedtest bring a more cleaner spinner (#3921)
- Removes flickering of spinner
- Moves to a more maintained library bubbles spinner
- Adds better visual formatting for table output
2022-01-16 12:21:55 -08:00
Poorna d2b7c3c3ac update admin replicate info output format (#3920) 2022-01-14 18:53:23 -08:00
Harshavardhana 91278da28d 'decom status' progress and UI improvements 2022-01-12 21:52:33 -08:00
Harshavardhana 0ddf3e2691 implement pool decomission commands (#3769) 2022-01-10 22:35:35 -08:00
Harshavardhana 1264168162 sufficiently colorize svacct command outputs (#3917)
also print help when no args passed, instead of asking
for `--help`

fixes #3803
2022-01-10 08:55:23 -08:00
Poorna aed4d3062f Add admin replicate status command (#3887) 2022-01-06 13:50:28 -08:00
Harshavardhana 61db086b10 run gofumpt as part of golang-ci 2022-01-06 13:21:58 -08:00
Harshavardhana a59f9e4d30 add gofumpt support, automated cleanup (#3911) 2022-01-06 10:55:40 -08:00
Harshavardhana 8b3935e24d error out if --non-current is used without --versions (#3910) 2022-01-06 02:05:21 -08:00
Harshavardhana 0373840f42 turn-off auto-tuning only when --concurrent is specified (#3909) 2022-01-05 15:36:59 -08:00
Harshavardhana 8132c286e4 rm: fix printing when deleting content 2022-01-05 00:28:46 -08:00
Klaus Post eef80d47cd find: Fix --exec parsing (#3907)
Find would replace placeholders before splitting input, meaning files with spaces would be executed as separate args.

Split before replacing args, and use shell-style parsing.

Technically, this requires quotes in input to be escaped, so to specify `--exec='echo {""}'` you must escape them like this: `--exec='echo {\"\"}'`. Quoted inputs aren't documented, but it is a change.

Errors would not be displayed, like `./mc find play/test123/ --exec='unknown {}'` would just exit. Instead it now prints `exec: "unknown": executable file not found in $PATH`.

Fixes #3906
2022-01-03 23:56:55 -08:00
Harshavardhana 37e0f8ba27 update all dependencies for mc 2021-12-31 14:58:08 -08:00
Harshavardhana 05c3ae8716 fix: admin heal info output for multiple pools (#3905)
locally setup multiple pools was showing incorrect
values where secondary pool was ignored, also fix
possible estimate correction if needed.
2021-12-28 22:50:11 -08:00
Harshavardhana f06a0987a3 rm: print proper paths instead of just objectnames for S3 endpoints 2021-12-28 18:37:48 -08:00
Anis Elleuch 3391f39521 mirror: Sort bucket names with slash for site wide scenarios (#3894)
mc diff/mirror command fails to compare source & target when doing
an S3 site-wide listing.

The reason is that client-s3.List(), when doing a site-wide listing,
lists buckets first and list objects inside each bucket with the order
returned by S3 ListBuckets API.

However this can produce a non properly sorted listing output,
e.g.:

```
$ mc ls -r myminio/
[2021-12-14 15:58:27 CET] 227KiB bucketname/object1
[2021-12-14 15:58:24 CET] 227KiB bucketname-0/object2
```

Though it should be
```
$ mc ls -r myminio/
[2021-12-14 15:58:24 CET] 227KiB bucketname-0/object2
[2021-12-14 15:58:27 CET] 227KiB bucketname/object1
```

because '/' has a higher ASCII value than '-'

This commit fixes the behavior by always sorting bucket names with
a fake trailing slash when doing a site-wide recursive listing.
2021-12-28 17:49:45 -08:00
Harshavardhana e08ded6d28 display when delete markers are created (#3904) 2021-12-28 17:48:54 -08:00
Harshavardhana 3144cb97ed remove retry in difference() comparator (#3903)
it is potentially harmful when retrying
a lot of buckets where in this might
trigger a retry - continous Listing()

however this retry is not needed as the
callers restart as needed when --watch
or --active-active are used.
2021-12-27 09:16:15 -08:00
Klaus Post 12012eafad du: Fix double counting of objects (#3901)
`mc du play` would count objects twice since it was doing a recursive listing AND travering into folders.

Compare total to `mc du play --depth=2` and `mc du play --recursive`.
2021-12-22 08:21:52 -08:00
Dean Kleissas 385bc1b23a Set default value for --event flag of omitted (#3752) 2021-12-21 02:16:36 -08:00
Ravind Kumar 0b2f0c9b48 Fix mc ilm restore --help (#3897) 2021-12-20 14:23:47 -08:00
Krishnan Parthasarathi 409ccc7c07 Update go.mod to include NewerNoncurrentVersions support (#3898)
With this `mc ilm import` accepts NewerNoncurrentVersions tag.
2021-12-20 14:23:35 -08:00
Anis Elleuch 7bd5c343f7 heal: Show healed objects count even if healing start time is unknown (#3896)
mc summary should still show some information when some disks report
healing in progress but without started time.
2021-12-16 08:36:38 -08:00
Anis Elleuch 68a9e3f52e ux: Fix admin heal display with multiple zones (#3893)
mc admin heal was showing additional unnecessary entries 
of nodes with empty disks listing when that node does not 
belong to the current pool number. A node only belongs to 
one pool, so remove the extra entries.
2021-12-14 09:43:38 -08:00
Aditya Manthramurthy 7031efb55a Update admin policy/user commands with new policy info API (#3877)
will support older minio versions as well
2021-12-11 09:04:32 -08:00
Harshavardhana 2d516d350a Allow specifying many aliases in MC_CONFIG_ENV_FILE (#3885)
Allows for getting ENV secrets remotely, or from
secure vault secrets.
2021-12-11 08:29:11 -08:00
Harshavardhana 2a84f0f1f9 disable IPv6 locally for all interfaces before docker build 2021-12-09 17:51:31 -08:00
Harshavardhana 9bdd7660f6 remove support for go1.16 2021-12-09 12:16:18 -08:00
Shireesh Anjal b6c50a92a1 Use subnet api key instead of license (#3876)
The earlier approach of using a license token for communicating with
SUBNET is being replaced with a simpler mechanism of API keys. Unlike
the license which is a JWT token, these API keys will be simple UUID
tokens, and don't have any embedded information in them. SUBNET would
generate the API key on cluster registration, and return in the API
response. mc then stores it in the `subnet api_key` config of minio,
to be used for subsequent communication with SUBNET.

In case the api_key is not available in the config, but the cluster's
license is available, it will be used as auth in the subnet API call,
and api_key will be set after the call succeeds. This will help in
smooth migration from older versions of MinIO.
2021-12-09 09:40:27 -08:00
Krishnan Parthasarathi 23a05f5a17 Update ilm-add examples (#3884)
Hide date options like expiry-date and transition-date to 
avoid unintended consequences explained here -
  
https://docs.aws.amazon.com/AmazonS3/latest/userguide/intro-lifecycle-rules.html#intro-lifecycle-rules-actions
  
> If you specify an S3 Lifecycle action with a date that is in the past, 
> all qualified objects become immediately eligible for that Lifecycle action.
2021-12-07 15:06:06 -08:00
Anis Elleuch bd7a49f500 tags: Show how to assign two tags to an object (#3881)
mc cp --tags is able to assign more than one tag to an object, 
enhance the example to show that.
2021-12-06 09:39:13 -08:00
Harshavardhana 8a207df2ab avoid double formatting svacct policy (#3878) 2021-12-02 08:48:13 -08:00
Krishnan Parthasarathi cb73b76c81 Add tier-info command for tier-specific stats (#3827) 2021-11-29 09:10:00 -08:00
Anis Elleuch e84871950a speedtest: Ask the user to increase duration with empty result. (#3875)
Sometimes, with slow machines, speedtest will not able to accomplish
any PUT/GET operations though no errors is met. In that case, this
commit will show an adequate error message asking the user to increase
the --duration flag.
2021-11-29 09:05:33 -08:00
Anis Elleuch a064265d0c svcacct: Validate policy document and error out if needed (#3873) 2021-11-27 14:47:48 -08:00
Harshavardhana 4793c40bf6 remove HTML tags from README.md 2021-11-22 00:42:08 -08:00
Harshavardhana 18a579da0b Set theme jekyll-theme-minimal 2021-11-22 00:37:50 -08:00
Shireesh Anjal df75eed32e Use latest version of madmin-go (#3866)
It contains a new field `TLSInfoAvailable` which will get added under
the `tls` node in health report, helping `health-analyzer` perform the
TLS related checks more reliably.
2021-11-18 14:30:26 -08:00
Harshavardhana 26e7e49cd7 honor cgroup memory limits in parallel-manager (#3871) 2021-11-18 14:30:02 -08:00
Shireesh Anjal d0c62eb584 Fix health upload to subnet failing (#3870)
The writer needs to be closed before creating the request. Otherwise the
call to subnet api fails with error like:

HTTP/1.x transport connection broken: http: ContentLength=6235 with Body length 6303.
2021-11-16 08:37:08 -08:00
Harshavardhana 3a4e469334 feat: detect starting from windows explorer (#3869)
Windows users often click on the binary without
knowing `mc` is a command-line tool and should be
run from a terminal. Throw a message to guide them
on what to do.
2021-11-16 00:21:48 -08:00
Harshavardhana ae66e893c7 with --force flag no need for exit code (#3868)
fixes #3673
2021-11-15 10:00:12 -08:00
ebozduman 7fd441ec6c Removes Windows path adjustment for prefixes (#3614) 2021-11-14 21:21:00 -08:00
Krishnan Parthasarathi 6460d2facf Update go.mod to include support for MaxNoncurrentVersions (#3863) 2021-11-12 16:18:15 -08:00
Harshavardhana b2ff347c69 cleanup 'admin health' command (#3862)
- reach subnet, upon failure provide `--airgap` command line
  to allow them to upload report manually.

- use a proper httpClient when reaching out to subnet
  with a 10sec timeout, and also support custom proxies
  with self signed certs.

- also fix some error messages and cleanup help with correct
  wording and grammar.
2021-11-12 09:34:29 -08:00
Shireesh Anjal b882f3e484 Better message on reset of dynamic config (#3861)
When a dynamic config is reset, the minio api response has `true` as
value of the header `x-minio-config-applied`. In such cases, mc should
not show the message asking the user to restart `minio`.
2021-11-11 06:49:13 -08:00
Shireesh Anjal 1461b652d9 Introduce admin health command (#3847)
It will be a hidden command and will behave 
exactly same as `mc admin subnet health`

Also, remove the deprecated command `admin subnet obd`
2021-11-09 16:36:02 -08:00
Poorna K a776222b33 Uppercase tier name in admin tier add cmd (#3849) 2021-11-09 16:35:32 -08:00
Harshavardhana e7c79413d7 fallback to bucket retention info for only bucket names (#3860) 2021-11-08 09:49:56 -08:00
Harshavardhana 9b5d0ba1ef update Dockerfile files 2021-11-05 03:29:49 -07:00
Harshavardhana 9f6b500142 update go.sum 2021-11-04 23:51:20 -07:00
Krishna Srinivas 9e8fea96ca Show live updates for speedtest (#3855) 2021-11-04 23:50:28 -07:00
Robert LütznerandRobert Lützner 6e1d044f91 admin-trace: Add missing asterisk to --path example in usage (#3857)
Limiting tracing to a specific path requires an asterisk at the end. I
don't know if this is a regression or the example was always wrong. I
only ever figured this out by trial and error.

This fixes #3856.

Co-authored-by: Robert Lützner <robert.luetzner@iternity.com>
2021-11-03 09:34:32 -07:00
Shireesh Anjal c0cfc9c507 Fix usage validation in mc admin service restart (#3859)
The command needs exactly one argument, but was allowing two and
ignoring the second if passed. Fixed the validation.

Signed-off-by: Shireesh Anjal <shireesh@minio.io>
2021-11-03 09:33:01 -07:00
Shireesh Anjal 905502e311 Fix subnet health crash on passing invalid flag (#3858)
The custom `String()` function written for the `HealthDataTypeFlag` was
resulting in a crash as it did not contain `\t` character on which the
usage gets split when printing the error message.

Fixed by reusing the `FlagStringer` from cli package, which is used by StringFlag.String() as well.
2021-11-03 09:32:36 -07:00
Poorna KandPoorna Krishnamoorthy 14303ec6cf fix --disable-proxy flag in admin bucket remote add command (#3851)
Co-authored-by: Poorna Krishnamoorthy <poorna@minio.io>
2021-10-29 12:05:56 -07:00
Harshavardhana 7866f97ef5 Revert "Remove unused Transport option. (#3818)"
This reverts commit bc69976481.

This option is used by console
2021-10-26 19:49:40 -07:00
Harshavardhana 6339784743 update gjson to avoid CVE-2021-42836 2021-10-25 20:56:15 -07:00
Shireesh Anjal b9bfcb50a3 Fix subnet login during registration not working (#3841)
Subnet doesn't return `ContentLength` in it's api response, and hence
using it as the limit with `LimitReader` doesn't work. Fixed by using a
sufficiently large (1 MiB) limit.
2021-10-20 21:15:00 -07:00
Shireesh Anjal b493f01699 Update go.mod to use latest version of madmin-go (#3839)
So that the TLS config related data gets added in the health report.
2021-10-20 10:26:36 -07:00
Shireesh Anjal e45d648ce9 Rename --offline flag to --airgap (#3837)
Retain `--offline` as hidden for backward compatibility (won't show up
in help)
2021-10-18 09:49:52 -07:00
Aditya Manthramurthy 3177a62819 Add functional tests to test sanity of users in internal IDP (#3838) 2021-10-18 08:41:14 -07:00
Harshavardhana ae271e7645 add new linters and fix unnecessary type conversions (#3835) 2021-10-14 15:33:31 -07:00
Klaus Post 0eef0174a7 inspect: Save data unencrypted by default (#3832)
By default decrypt the data. Add `--encrypt`.
2021-10-12 11:49:49 -07:00
Daniel Jakots b880f09931 fix: build on 32-bit systems (#3732) 2021-10-12 02:08:54 -07:00
Ori Hoch 6047ef858a fixes minio/mc#3830 servers without lock returns locking disabled (#3831) 2021-10-11 14:26:23 -07:00
Shireesh Anjal e4d4bf6641 Add register sub-command to mc admin subnet (#3808)
By default, it will run in `online` mode and try to register the cluster
on subnet. If the subnet license is not available in minio/mc config, it
will

- ask the user for login credentials
- use the credentials for authentication and call the registration api
- get the license from response of the api and store it in config
- use the stored license for any subsequent calls

In case the user belongs to multiple organizations in subnet, they will
be prompted to choose the appropriate organization from the list.

If the client machine is in an airgapped environment, user can choose to
use the `--offline` flag when running the command. In this case, it will

- generate and print the registration token
- ask the user to paste it in the subnet registration screen
- accept the license generated by subnet and store it in config

As part of this work, the `health` sub-command is also enhanced to:
- run in `online` mode by default, which tries to upload the health
report to subnet. Here the user will be prompted for subnet credentials
(if license not available in config) _before_ generating the health
report as it is a long running process.
- support a new flag `--offline` which can be used when subnet is not
reachable. When used, the health report will be generated in a local
json.gz file, which can then be uploaded on subnet.

The examples in help text of both the sub-commands are enhanced to list
multiple use cases.

When saving license to config, first preference is given to minio
config. If the minio server supports the `subnet license` key, the
license will be stored here. In case it is an older version of minio
that doesn't support this key, then the license will be stored in mc
host config.
2021-10-07 11:20:28 -07:00
Aditya Manthramurthy 198bca9cdf Add new admin replicate subcommand (#3810)
This change adds support for enabling site replication
2021-10-06 16:57:01 -07:00
Krishnan Parthasarathi 054cfa0103 ilm-edit: Accept zero days for transition (#3824) 2021-10-06 13:34:41 -07:00
Anis Elleuch 6b329ce01f rb: Fix side wide removal of an alias (#3796)
* rb: Fix side wide removal of an alias

rb --force --dangerous should remove all buckets under an alias. This
PR fixes a recent regression.
2021-10-06 09:56:57 -07:00
Harshavardhana 44a597a9f9 allow removal of replica/ilm event-types (#3823) 2021-10-06 09:24:12 -07:00
Shireesh Anjal 55c6a1fccc fix: incorrect spinner for network perf test (#3813)
In case of non-distributed setup, the server doesn't return network perf
data. Because of this, the network spinner doesn't finish, and is closed
explicitly outside the loop, resulting two lines (one incomplete, one
complete) for it.

Fixed by explicitly checking the number of servers when checking for
completion of the network spinner.
2021-10-05 17:00:41 -07:00
Anis Elleuch 026cfa16c5 admin info: Show 'OK' in yellow when offline networks/disks (#3814)
In mc admin info output, it is better to show 'OK' status in yellow and
not in green when there is a failed disk or a failed network link so it
is easier for users to detect something wrong.
2021-10-05 17:00:27 -07:00
Krishnan Parthasarathi 924df70b33 Add support for immediate tiering (#3816) 2021-10-04 12:19:48 -07:00
Shireesh Anjal 6c41669342 health: perform only lightweight tests by default (#3820)
Perform only lightweight tests by default, and include the long running
tests only if specified through a `--full` flag in the `admin subnet
health` command.
2021-10-04 09:03:19 -07:00
Anis Elleuch 1aa0f47736 ilm: Correctly show tags in tabular info when this non AND tag (#3819)
Tag can be set directly under Filter tag and not always under
Filter.And in the lifecycle document. In that case, the tag won't be
properly showed in the tabular info of the ILM listing. This PR fixes
it.
2021-10-01 11:59:15 -07:00
Klaus Post bc69976481 Remove unused Transport option. (#3818) 2021-10-01 11:41:34 -07:00
Harshavardhana 88544fee85 update all dependencies in go.mod (#3812) 2021-09-29 22:05:43 -07:00
Klaus Post 7e6f46fba6 Bump CI Go versions (#3811)
* Bump CI Go versions
* Fix changed fmt.
* Only check vet on one version.
* Bump minimum go version in go.mod
* Add Darwin test.

Replaces #3807
2021-09-28 09:19:52 -07:00
Anis Elleuch 1bcd5df300 Add ilm restore command (#3790) 2021-09-24 09:32:39 -07:00
Krishnan Parthasarathi 368b4106d7 Disallow updating azure tier account-name (#3805) 2021-09-23 10:57:39 -07:00
Anis Elleuch 445414dc0c svcacct: Colorize svcacct output (#3806) 2021-09-23 10:01:37 -07:00
Harshavardhana 2d01434415 update madmin-go and minio-go dependency 2021-09-22 15:08:05 -07:00
Anis Elleuch fa0aa1e45f heal: More verbose information (#3795)
heal info now shows the list of all MinIO nodes and the status of disks,
OK, unformatted, healing with an estimation of the time of healing
completion. It also shows the tolerance of nodes/disks, meaning how many
nodes or disks we can turn off before losing read operation in the
cluster.
2021-09-22 14:39:59 -07:00
ebozduman 5a8f677304 Windows support for copying local files to object storage (#3666) 2021-09-22 14:38:56 -07:00
Anis Elleuch 4e4c912b37 Order mc admin info output by endpoint (#3804)
To make easy for users to navigate through the list of servers.
2021-09-21 09:08:28 -07:00
Ashish Kumar Sinhaandsinhaashish a8bf2a463b Add global flags to edit tier command (#3802)
Co-authored-by: sinhaashish <ashish@minio.com>
2021-09-17 07:09:00 -07:00
Krishna Srinivas e576844f0f Erase the spinner on speedtest completion (#3800) 2021-09-16 17:25:17 -07:00
Krishna Srinivas d7bc62efa6 Show spinner during speedtest (#3799) 2021-09-16 15:39:12 -07:00
Poorna Krishnamoorthy 77a4c9f9e5 update minio-go dependency (#3797) 2021-09-16 15:30:10 -07:00
Harshavardhana 1f997000a3 trace: multiple values for headers are ',' separated (#3798) 2021-09-16 08:55:08 -07:00
Ashish Kumar Sinha 1f2429c336 validation for namespace removal (#3783) 2021-09-15 11:34:41 -07:00
Poorna Krishnamoorthy 6bf64d9704 Add multisite replication support in mc replicate cmd (#3766)
Also adding a flag to `mc replicate reset` to allow 
granular replication reset by target
2021-09-15 10:32:28 -07:00
Krishna Srinivas 24456eb990 Support speedtest autotuning on the server side (#3777) 2021-09-14 23:29:49 -07:00
Shireesh Anjal 56b22c37fc fix: subnet health spinners not working properly (#3788)
The "admin info" step was moved from being the first step to the last
step in minio at some point, but the sequence of spinners in mc was not
updated with this change. Because of this, the first spinner itself used
to get stuck for the whole duration of report generation.

Fixed by correcting the sequence of spinners to make them in sync with
the processing in minio.

Signed-off-by: Shireesh Anjal <shireesh@minio.io>
2021-09-08 08:01:55 -07:00
Kaan Kabalak 4e56329bae Replace 'none' in 'mc anonymous get/set' with 'private' (#3792)
This commit replaces the 'none' policy with 'private' for the
'mc anonymous get/set' command without breaking 
backward compatibility
2021-09-07 19:10:13 -07:00
Harshavardhana e7d3f4637a update CREDITS, add quay.io/minio/mc:latest 2021-09-02 11:24:57 -07:00
Klaus Post f661334f3d doc: Update diff table (#3778) 2021-09-01 16:47:57 -07:00
Anis Elleuch 7f37854b02 parallel-manager: Reduce parallelism when there is not enough memory (#3629)
Some users with low memory and good connection uploading some big files
can see memory crash, since mc will increase upload parallelism over
time when the bandwidth and the server is able to carry the load.

This PR will check the free OS memory before starting mirror/cp and will
estimate current memory usage based on uploaded objects sizes, it will
stop parallelism until the memory gets some room.
2021-09-01 09:07:26 -07:00
Shireesh Anjal ef90b8b3dd Add sys services and config spinner in subnet health (#3772)
Signed-off-by: Shireesh Anjal <shireesh@minio.io>
2021-08-31 11:17:58 -07:00
Artem Yarmoliuk 855333e4ab Update x/sys to support go 1.17 (#3779)
See: https://github.com/golang/go/issues/45702
2021-08-25 10:56:52 -07:00
Anis Elleuch 0667914d16 rb: --force flag forces bucket removal after BucketNotEmpty err (#3780)
Some users struggle to remove a bucket when they don't use recommended
setups, such as NFS disks.

This command will force bucket removal in server side, using
x-minio-force-delete during DELETE bucket call.
2021-08-23 07:10:41 -07:00
Harshavardhana c19d58bb88 add 'mc update' progress bar support (#3782) 2021-08-21 21:01:31 -07:00
Anis ElleuchandAnis Elleuch a88acb58d4 fix: Avoid crash when asking for no existing transition/expiry info (#3771)
mc ilm ls has --expiry and --transition to show for only expiry or
transition information, but if one of them doesn't exist, mc crashes.
The PR fixes this.

Co-authored-by: Anis Elleuch <anis@min.io>
2021-08-17 14:11:09 -07:00
Harshavardhana 43b03a8532 support 'mc rm --non-current' to delete non-current objects (#3768) 2021-08-10 18:29:22 -07:00
Klaus Post b3ce21fb72 Add mc admin inspect (#3754)
Add function to download data from server with admin privileges.

For https://github.com/minio/minio/pull/12635
2021-08-06 06:42:23 -07:00
Shireesh Anjal 539a6b5654 Add sys errors spinner in subnet health output (#3760)
The subnet health report generation now includes collection of system
errors. So add a spinner for this step too in the screen output of the
command.

Signed-off-by: Shireesh Anjal <shireesh@minio.io>
2021-08-05 22:30:19 -07:00
Krishna Srinivas bc5835e680 feat: admin speedtest implementation (#3759) 2021-07-29 18:18:58 -07:00
Harshavardhana 4af8b2d20b do not prematurely default multipart to 16MiB 2021-07-27 08:42:07 -07:00
Harshavardhana addaf66de8 fix: do not prematurely error out during Heal() (#3762) 2021-07-26 08:01:59 -07:00
Harshavardhana c3ab68ed1e allow configuring multipart size for testing (#3761)
add MC_UPLOAD_MULTIPART_SIZE, MC_UPLOAD_MULTIPART_THREADS
to test in situations when default values are not enough
for showing proper bandwidth usage.
2021-07-23 09:21:59 -07:00
Harshavardhana 7dafdaf88e rename policy to anonymous command (#3755)
although keep `policy` command hidden
for backward compatibility.
2021-07-19 08:49:28 -07:00
Harshavardhana c319567430 do not print config values in base64 (#3757)
fixes #3696
2021-07-19 08:29:20 -07:00
Anis Elleuch bfafb96632 heal: Refactor info output (#3730)
mc admin heal <alias> will show simplifed output which aggregates MRF &
new disks healing.

e.g.:

```
$ mc admin heal myminio/
Objects Healed: 7/27 (25.9%), 31 MB/110 MB (0%)
Heal rate: 3 obj/s, 10 MB/s
Estimated Completion: 11 seconds

```
2021-07-16 09:51:00 -07:00
Emir İşman 05ec684549 deps: update jwt-go dependency (#3756) 2021-07-10 13:37:58 -07:00
Harshavardhana 5e95eea60c fix: openbsd/amd64 cross compilation 2021-07-04 00:46:58 -07:00
Shireesh Anjal db1b1bd811 fix: health report incompatibility with old minio (#3751)
When the subnet health command from current mc is used with the MinIO
versions before the latest health data structure changes (v2) were
introduced, the generated report doesn't contain the cluster information
(minio -> info).

This is because these old versions of minio don't return this
information in the output of the `healthinfo` api.

Fixed this by explicitly pulling the server info separately when we
detect that the health schema version is not v2.
2021-07-01 10:04:08 -07:00
Klaus Post a1ba511f16 trace: Display times in local timezone (#3750)
Make sure times are converted to local time zone.
2021-06-29 08:48:12 -07:00
Harshavardhana cebf331854 update minio/pkg to v1.0.8 2021-06-25 17:21:08 -07:00
Poorna Krishnamoorthy 2c52cdf27c Add flag to mc replicate for existing object replication (#3698)
This allows triggering a resyncing of previously
replicated objects when existing object replication is
enabled. It is useful in scenarios where replication target
is entirely lost and content needs to be replicated again.
2021-06-12 18:02:25 -07:00
Harshavardhana 776643ff2a fix: remove legacy path for prometheus (#3743)
additionally add `--public` flag for unauthenticated
prometheus config.
2021-06-12 09:47:30 -07:00
Anis Elleuch b70da9cbcb mirror: Add S3 latency metric (#3679)
Add a new metric called: `mc_mirror_replication_duration`, which shows
the histogram of replication time of different categories of object
sizes
2021-06-11 21:21:15 -07:00
Harshavardhana 9242dbdf69 add support for quay.io mirror 2021-06-11 16:51:03 -07:00
Klaus Post 7c0ab1b2d5 Add single line json output (#3739) 2021-06-11 14:40:16 -07:00
Harshavardhana 27d0ea67cb remove legacy errors from docs
fixes #12474
2021-06-09 10:24:38 -07:00
Poorna Krishnamoorthy c8d9eee2b4 Add options to enable|disable proxy,sync for remote target (#3701)
Also allow URL endpoint, bandwidth limit, healthcheck-duration
and path to be updated for an ARN.
2021-06-07 18:11:38 -07:00
Poorna Krishnamoorthy 6a2b118473 tier: support using aws role for s3 (#3736)
Signed-off-by: Poorna Krishnamoorthy <poorna@minio.io>
2021-06-07 13:44:30 -07:00
Anis ElleuchandKlaus Post a06096f8ee du: Use recursive listing when no detailed report is asked (#3737)
mc du will always count the size of all objects under a specified
path, du -r will show the disk usage in a more detailed fashion, but if
not specified, let's do a recursive LIST call instead of calling du()
multiple times.

Co-authored-by: Klaus Post <klauspost@gmail.com>
2021-06-03 08:19:04 -07:00
Harshavardhana 87092404e0 fix: 'mc admin tier' CLI fix typos (#3734) 2021-06-01 15:00:06 -07:00
Harshavardhana 4b7e85d7e9 reduce memstats information in 'admin info' 2021-06-01 11:25:23 -07:00
Bala FA fbbae711bd Add new health data structure support. (#3687)
`mc admin subnet health` command supports new health data structure
and versioning of health API.

Signed-off-by: Bala.FA <bala.gluster@gmail.com>
2021-05-30 20:02:40 -07:00
Harshavardhana 5b972bb7b0 update latest colorjson v1.0.1 2021-05-30 19:45:00 -07:00
Harshavardhana 91efd0c066 migrate mc to minio/pkg (#3731)
remove all dependency for minio/minio
2021-05-29 09:30:33 -07:00
Anis ElleuchandAnis Elleuch 9740a09584 restart: Avoid bad empty line (#3729)
Print '...' instead, for a distributed cluster, other characters will
follow to indicate the status of the restart command.

Co-authored-by: Anis Elleuch <anis@min.io>
2021-05-27 19:46:30 -07:00
Harshavardhana 8d65ee7130 fix: enhance support for special access/secretkeys in remote targets (#3725)
it latest release and master `mc admin bucket remote add` cannot
parse accesskeys/secretkeys with special characters such as `@`,
this is due to an incorrect implementation.

use the technique used in parsing MC_HOST_alias here to allow
for more complex use-cases.
2021-05-18 22:29:47 -07:00
Poorna Krishnamoorthy 6e251456d2 Add flag for replica sync to mc replicate command (#3722)
Signed-off-by: Poorna Krishnamoorthy <poorna@minio.io>
2021-05-17 14:11:51 -07:00
Shireesh Anjal 9714e1cf49 Use new URL for upload to subnet (#3720)
Old path: /api/auth/health_reports
New path: /api/health/upload

Signed-off-by: Shireesh Anjal <shireesh@minio.io>
2021-05-15 22:20:22 -07:00
Harshavardhana 60d3646baf attr is optional for mc pipe
fixes #3718
2021-05-12 09:27:36 -07:00
Harshavardhana 7d142be711 support parsing special tags after releaseTag 2021-05-11 19:51:36 -07:00
Krishnan Parthasarathi deb714784c Add mc admin tier subcommands (#3566)
Signed-off-by: Krishnan Parthasarathi <kp@minio.io>
2021-05-11 19:42:49 -07:00
Klaus Post 757b9d6872 pipe: Add custom attributes and tags (#3706)
Support adding custom attributes and tags.

Examples included.
2021-05-11 19:35:58 -07:00
Harshavardhana 954f0a5fd1 add fips build support for mc 2021-05-11 18:25:46 -07:00
Harshavardhana ac08bf41a7 fix: gofmt on some files 2021-05-11 17:46:41 -07:00
Harshavardhana 077fff35dd update CREDITS file with latest deps 2021-05-11 17:45:49 -07:00
Harshavardhana 1402987ccb change license to AGPLv3 2021-05-11 17:45:08 -07:00
Anis Elleuch 0c11cf9f28 Update minio-go for a fix in ILM (#3716)
Signed-off-by: Anis Elleuch <anis@min.io>
2021-05-11 14:11:15 -07:00
Shireesh Anjal e207f3bfa4 Fix incorrect error related to "name" flag (#3714) 2021-05-10 19:48:14 -07:00
Harshavardhana 073c9c6308 remove fetchUserKeys _contrib 2021-05-10 10:13:23 -07:00
Harshavardhana 8cf4031ef5 add some self contained functions to contrib
remove chinese doc translations, move docs to CC-BY 4.0 license
2021-05-10 09:38:59 -07:00
Harshavardhana dfbedf9f3a update madmin-go to v1.0.2 2021-05-06 16:34:09 -07:00
Harshavardhana 6c3ac00e18 update madmin to github.com/minio/madmin-go (#3710) 2021-05-06 13:33:17 -07:00
Shireesh Anjal 8c4a2698d9 Add --schedule and --name flags to subnet health (#3685)
* Add --schedule flag to subnet health command

If passed along with --license, the health diagnostics will be executed
and uploaded to Subnet at given schedule (in days).

Also, delete the generated file after succesful upload to subnet.

* Add --name flag to subnet health command

If passed along with the --license flag, this will be passed as the name
of the cluster in the subnet upload request. Subnet uses this only for
the 1st upload of the given cluster.

If not passed, the alias of the cluster will be passed as default value
for the cluster name.
2021-05-06 10:31:33 -07:00
Anis ElleuchandAnis Elleuch a62d2b4659 svcacct: Print password when generating a new service account (#3709)
Sometimes passwords are auto-generated, print them so the user can
easily copy it somewhere.

Signed-off-by: Anis Elleuch <anis@min.io>

Co-authored-by: Anis Elleuch <anis@min.io>
2021-05-05 17:22:38 -07:00
Poorna Krishnamoorthy c4890d949b trace: display time in UTC format (#3708) 2021-05-03 11:52:16 -07:00
Bala FA af1676e6ec admin.subnet.health: add-flag-to-support-subnet-proxy (#3692)
Signed-off-by: Bala.FA <bala.gluster@gmail.com>
2021-04-26 09:45:50 -07:00
Anis Elleuch 4eae7ec7ed Add support of service account commands (#3650)
Signed-off-by: Anis Elleuch <anis@min.io>
2021-04-22 10:17:34 -07:00
Harshavardhana 36c17891d6 update build to use go1.16 2021-04-22 10:07:50 -07:00
Harshavardhana 37f5eff195 fix: use madmin constants 2021-04-21 16:52:21 -07:00
Poorna Krishnamoorthy 20e5905de0 Add mc replicate status command (#3684) 2021-04-21 14:05:17 -07:00
Anis Elleuch a17153cf9e admin: Implement a better restart command UX (#3618)
mc admin restart service clearly indicates to the user that restarting
the process is started and also shows progress using:

 `.` in red to indicate the cluster is still offline
 `!` in yellow to indicate the cluster is up but still initializing
2021-04-21 14:05:06 -07:00
Anis Elleuch c00c7e3a35 admin: Add policy subcommand to user (#3648)
mc admin user policy will download all 
policies JSON linked to a user and 
merge them into one.
2021-04-19 07:35:52 -07:00
Harshavardhana d8393a365e fix: mirror monitoring cli to be --monitoring-address (#3695)
fixes #3693
fixes #3694
2021-04-18 09:11:45 -07:00
Anis Elleuch 78e3c94f5a trace: Make evaluation filters more user friendly (#3642)
Currently trace filters are like OR operations, but I think in debugging
we want AND instead.

Currently, --status-code 503 --path 'bucket/path'  will show 503 requests or
requests with 'bucket/path', this PR will require having both conditions
in the requests in order to be shown in the trace.
2021-04-16 08:56:26 -07:00
ebozduman ef59238007 Adds error exit codes for SIGINT, SIGTERM and SIGKILL (#3662) 2021-04-15 16:58:49 -07:00
Poorna Krishnamoorthy b537ee408b report bandwidth limit in --json mode (#3688)
for `mc admin bucket remote ls`

This PR also removes label for a remote target
2021-04-15 16:58:13 -07:00
Anis Elleuch 4380288249 trace: Add support of older admin tarce API (#3683) 2021-04-07 12:25:53 -07:00
Shireesh Anjal 1ac898c382 Fix net perf spinner not finishing in subnet health (#3676)
In case of single server setups, the network performance data is empty.
Because of this, the condition that indicates that the network test step
is over never evaluates to true and hence the spinner doesn't finish
(doesn't show the tickmark indicating the step has completed).

While this is a nigligible issue in normal execution of the subnet
health command, it has a weird side effect when the `--license` flag is
passed. In such cases, the network test spinner finishes _after_ the
message about succesful generation of the report is printed.

Ensuring that all the spinners are stopped explicitly after the api call
returns resolves this issue.
2021-04-07 12:14:25 -07:00
Anis Elleuch a093f822e2 Avoid automatic copy of storage class (#3681) 2021-04-06 10:24:34 -07:00
Klaus Post 9f9f7ec542 trace: Add goroutines by default (#3664)
Goroutines are very often useful. Include them by default.
2021-04-06 09:23:01 -07:00
Harshavardhana e513a4f68f improve bandwidth monitor UI (#3680)
make the reporting UI more succint as below

```
┌──────────────────┬──────────────────────────┬───────────────────┐
│ Bucket           │ Configured Max Bandwidth │ Current Bandwidth │
├──────────────────┼──────────────────────────┼───────────────────┤
│ testbucket       │ N/A                      │ 4.4 kb/sec        │
└──────────────────┴──────────────────────────┴───────────────────┘
```
2021-04-05 16:07:00 -07:00
Harshavardhana 6074aa43ff add nodeName and path properly for os/storage calls (#3670) 2021-03-28 08:07:34 -07:00
Anis Elleuch 9914d28527 trace: Add support of Storage & OS tracing (#3663) 2021-03-27 05:38:57 -07:00
Poorna Krishnamoorthy 0ee9471197 trace: fix missing client info for ipv6 (#3661)
fixes: https://github.com/minio/minio/issues/11833
2021-03-24 03:50:02 -07:00
Anis Elleuch c3cae160b3 mirror: Add total_s3uploaded_bytes metric (#3646)
The new metric will track the total bytes of copied objects in the
target during mirroring.
2021-03-22 13:27:01 -07:00
Shireesh Anjal 1f71fdc03a Add option to upload health report to Subnet (#3641)
Add an optional text flag `license` to the `subnet health`
command. If this flag is passed, upload the generated health report to
Subnet by passing the license key as auth.
2021-03-22 09:26:09 -07:00
Harshavardhana 49e85e9109 reduce default part size upto 16MiB (#3654) 2021-03-19 09:10:36 -07:00
Anis Elleuch bac257a6e0 dep: Update minio/minio dependency for disk metrics (#3649)
After updating minio/minio dependency, mc admin info --json shows the
latency and the number of calls of each API in the POSIX layer.
2021-03-17 23:28:01 -07:00
Anis Elleuch e10c82f9ad cp: Add --tags to tag uploaded objects (#3644)
Applying tagging to objects copied in an S3 object using --tags flag.
2021-03-16 08:46:28 -07:00
ebozduman 501b791408 Fixes conflicting Failure&Successful msgs in 'mc rb' output (#3616) 2021-03-10 23:13:55 -08:00
Anis Elleuch ccb35f1672 mv: Fix panic and simply the code a little bit (#3640)
Also, mv did not consider --fake flag, fix it as well.
2021-03-10 23:12:04 -08:00
Ritesh H Shukla faa895dd75 Track remote replication bandwidth consumption (#3609) 2021-03-10 17:30:36 -08:00
Harshavardhana dde89f7604 add release build-arg for multiarch builds 2021-03-10 00:10:53 -08:00
Anis ElleuchandAnis Elleuch 28d8677578 mirror: Add monitoring endpoint for mirroring operations (#3636)
* mirror: Add monitoring endpoint for mirroring operations

The following are the added metrics:

mc_mirror_failed_s3ops 3
mc_mirror_time_last_activity 9
mc_mirror_total_restarts 3
mc_mirror_total_s3ops 199920

Also, --watch automatically restarted if an error is detected

Co-authored-by: Anis Elleuch <anis@min.io>
2021-03-09 09:38:35 +05:30
Anis Elleuch 1d9873c512 admin policy: Add unset & update command (#3638)
`unset` will remove policies from a user or a group
`update` will add new policies to a user or a group
2021-03-06 13:14:49 -08:00
Harshavardhana a8c6f751a7 update to latest minio master with healing struct changes 2021-03-04 17:09:55 -08:00
Harshavardhana 13cf091af6 update to latest minio master 2021-03-02 18:00:29 -08:00
Jackson Borchardt cb577322fd fix typo (#3631) 2021-03-02 09:53:28 -08:00
Shireesh Anjal f9d36f9b52 Update minio dependency to latest master branch (#3628) 2021-03-01 08:22:50 -08:00
Harshavardhana 56ea65a78e update go CREDITS 2021-03-01 00:21:17 -08:00
Harshavardhana 8bbd07802e update 'madmin' deps to latest master 2021-03-01 00:17:22 -08:00
Anis Elleuch e3b84c39df ilm: Fix edit ILM versioning parameters (#3626)
After the introduction of versioning parameter in mc ilm document, we
didn't test mc ilm edit. This PR fixes this behavior and add more
lifecycle validation for versioning parameters
2021-02-27 09:08:28 -08:00
ebozduman cb909f5ce5 Stops 'mc cp --attr' preserve file attributes without '--preserve' (#3625) 2021-02-25 09:32:44 -08:00
Anis Elleuch 18da584d5a session: Fix resuming cp/mv session (#3580)
Session files contained a colored json which leaded a problem with
unparsing it, use jsoniter instead of the colorjson when marshal
unmarshal session data.
2021-02-19 10:51:48 -08:00
Shireesh Anjal b3c692d6eb Ignore parallel net perf data when its empty (#3607)
When parallel net perf tests are not performed, for example in FS mode,
the server response contains an empty node for the net pef data with
value of `addr` as empty string (`""`).

This data should be ignored when mapping the server response to the
health report format. Otherwise we end up with a health report with an
empty server node under `hardware` section.
2021-02-16 19:35:39 -08:00
Anis Elleuch 0053d58648 rm: Better messages when buckets are empty (#3606) 2021-02-16 13:53:04 -08:00
Harshavardhana 97482653ac update go mod for latest changes in pkg/iam 2021-02-16 12:05:04 -08:00
Harshavardhana 7672841f8c update go mod for latest changes in pkg/iam 2021-02-13 00:45:25 -08:00
Anis Elleuch d759f195f2 trace: Add source IP in verbose mode (#3612)
Add the source IP information in the REQUEST trace line when the verbose
mode is enabled.
2021-02-12 21:32:08 -08:00
Anis Elleuch 006cb0c0cf mirror: Fix behavior under Windows when source url is S3 (#3611)
Removed one block of code which seems to be useless and no comment with
it. This was causing issue doing mirroring under Windows.
2021-02-12 21:31:34 -08:00
Aditya Manthramurthy 4eb6f999a6 fix: crash on invalid input to policy set (#3610) 2021-02-12 11:22:02 -08:00
Aditya Manthramurthy 7c0fb6a99e Fix user/group argument parsing (#3602) 2021-02-09 14:25:11 -08:00
Ritesh H Shukla f782b462c6 Do not print v2 prometheus metrics for older releases (#3600) 2021-02-09 10:34:39 -08:00
Shireesh Anjal 4942cffc2c Update minio dependency to latest master branch (#3601) 2021-02-09 09:50:40 -08:00
Poorna Krishnamoorthy c44387cb32 Add --sync flag to admin bucket remote add command (#3549) 2021-02-05 15:21:31 -08:00
Anis Elleuch e93ec078dc ilm: Fix adding ExpiredObjectDeleteMarker alone (#3596)
It is not possible to add rule with only ExpiredObjectDeleteMarker
activated. This commit fixes the issue.
2021-02-04 21:13:53 -08:00
Anis Elleuch 650a4b8d66 cp: Fix crash with recursive copy with non existant resource (#3592)
Fixing a recent regression introduced when copying a non
existent bucket or prefix when --recursive flag is passed.
2021-02-02 08:37:30 -08:00
Harshavardhana ade302d969 fix: suggestion format with 'mc admin config set' 2021-01-27 18:27:58 -08:00
Ritesh H Shukla 169aa24ae0 Update the URL for metrics (#3584) 2021-01-25 17:32:58 -08:00
Harshavardhana 24ebcf13cf fix: make listing consistent with top level delete marker (#3587)
```
~ mc ls s3/tbucket13/x.txt
[2021-01-25 13:24:09 PST]   525B z.txt
```

```
~ mc ls s3/tbucket132/x.txt
[2021-01-25 13:31:41 PST]   525B x.txt/z.txt
```
2021-01-25 14:39:16 -08:00
Anis Elleuch 130f4393bb cp: Copy recursive paths having the passed prefix (#3563) 2021-01-24 00:06:40 -08:00
Anis Elleuch 7e19044d98 ilm: Import aborts when lifecycle config does not have a rule (#3576)
Currently, there is a success message misleading the user, while what is
really happened is that minio-go SetLifecycle removes any existing
lifecycle configuration in the bucket.
2021-01-23 23:05:15 -08:00
Harshavardhana 1fd739cc50 update admin docs with expected 'admin info' output 2021-01-22 12:13:46 -08:00
Stuart Thomson 93d579a936 doc: Add section to README for use in GitLab CI (#3577) 2021-01-21 20:50:17 -08:00
Frederick ZhangandErsan 8760185bc3 Remove IsInstalled() call before auto-completion installation (#3548)
At the moment posener/complete [1] doesn't allow specifying shell for
IsInstalled(), which might lead to confusing error messages, since it
just returns true if it's able to find completion definition in *any*
shell configurations even if it's not what the user currently uses.

Hence we should remove this check and call Install() directly, and user
can get more details in this case.

[1] https://github.com/posener/complete

* Improve auto-completion installation handling as per @ebozduman
* Improve messages when user's using an unsupported shell
* Refactors mc auto-complete logic

Co-authored-by: Ersan <ersan.bozduman@gmail.com>
2021-01-21 20:48:22 -08:00
Harshavardhana f73987fc34 fix: invalid user-agent release tag for mc (#3575)
fixes #3529
2021-01-20 09:51:52 -08:00
Harshavardhana 1c3e6516f0 allow trace filters on handler names (#3568)
also convert the filter options to slice flags, for example
if you wish to trace only for status code 404 and 503 then
you would specify the following command

```
mc admin trace --status-code 404 --status-code 503 myminio/
```

Refactor and make implementation more readable.
2021-01-19 02:20:34 -08:00
Maxime Bochon 419a6935db fix: extra spaces prevent italic formatting in doc (#3459) 2021-01-18 15:40:03 -08:00
Anis Elleuch f1f3003e5e Update minio-go to fix lcp bug (#3572) 2021-01-14 03:26:28 -08:00
Anis Elleuch 5fcb069e8a Add missing lifecycle versioning config parameters (#3565)
Add the following flags to mc ilm command:

  --expired-object-delete-marker
  --noncurrentversion-expiration-days
  --noncurrentversion-transition-days
  --noncurrentversion-transition-storage-class
2021-01-12 23:47:39 -08:00
Anis Elleuch c1fe60f7ad admin info: Show yellow dot when the cluster is not fully initialized (#3555) 2021-01-05 09:13:08 -08:00
Anis Elleuch e7df97d1e0 trace: Add more filters options (#3556)
Filter options are necessary if the server receives a lot of requests,
especially when the verbose mode is passed.
2021-01-04 21:00:48 -08:00
Harshavardhana 95ee8f0714 list with maxKeys=1 for url2Stat() calls (#3557) 2021-01-03 11:34:53 -08:00
Harshavardhana c041d86f03 fix: add hidden flag to return count number of locks (#3552) 2020-12-30 14:58:00 -08:00
Anis Elleuch e13737383f mirror: FS should ignore some non supported S3 events (#3554)
Bucket creation & removal are events only supported by MinIO server and
they are not meaningful for FS. Just ignore them at FS level and avoid
reporting an error.
2020-12-30 07:02:10 -08:00
Damien Degois c00afbc516 Fix code block issue in remote section (#3531) 2020-12-24 15:53:57 -08:00
Poorna Krishnamoorthy 766b69802c Remove transition targets (#3547)
Remove transition targets from `mc admin bucket remote` command 
and references to transition s.c label in `mc ilm add` command and docs.

This is being deprecated in favor of an improved approach
to transition in the works.
2020-12-24 14:09:26 -08:00
Anis Elleuch 864e4589ac doc: Update missing versioning documentation (#3417) 2020-12-22 09:23:04 -08:00
Harshavardhana 41c804b179 fix: update to minio/pkg/console changes (#3545) 2020-12-20 10:10:29 -08:00
Anis Elleuch fca6cb2815 cp: Add unit test for copying directories (#3540)
Add unit tests to copy a directory in S3 with and without a trailing
slash.
2020-12-18 09:19:36 -08:00
Anis ElleuchandAnis Elleuch d0e1456be3 client-s3: Stat() should return data for passed directories (#3539)
Co-authored-by: Anis Elleuch <anis@min.io>
2020-12-18 02:42:34 -08:00
SaintMalik 2b99236a22 Fix broken url in docs (#3537)
## Summary

Easy navigation and easy reading for others
2020-12-17 08:53:22 -08:00
Harshavardhana 5023905a3a use minio/pkg/certs instead of custom implementation (#3536)
also depends on https://github.com/minio/minio/pull/11123
for k8s automatic trust for MinIO deployments under operator
2020-12-16 19:41:15 -08:00
Poorna Krishnamoorthy 5ed74df9ed Add mc admin bucket remote edit to edit credentials (#3480) 2020-12-16 15:51:29 -08:00
Anis Elleuch 4e8e67fb04 mirror: Add support of site-wide mirroring (#3467) 2020-12-14 14:10:09 -08:00
Harshavardhana 1967d38dd4 remove arm32 binary 2020-12-12 17:29:33 -08:00
Chengyou LiuandHarshavardhana 74fc02e5eb Add --summarize for ls (#3517)
Co-authored-by: Harshavardhana <harsha@minio.io>
2020-12-09 15:26:29 -08:00
Harshavardhana 52fc5e8c15 fix extra space character in docker files 2020-12-07 16:17:40 -08:00
Nitish Tiwari 7ef637884c Move to Red Hat UBI (#3514)
Also use multi-arch Dockerfile instead of separate
files for each arch.
2020-12-07 16:09:05 -08:00
Harshavardhana 24101f18aa update minio/minio deps to honor dynamic config settings (#3526) 2020-12-07 16:02:56 -08:00
Harshavardhana b6969bc501 add support for watching for replication/ilm events (#3525) 2020-12-07 12:23:11 -08:00
Harshavardhana 4dc0a44ebf docs: update 'mc admin config' doc (#3522) 2020-12-03 23:56:18 -08:00
Harshavardhana c691cc5488 update dependencies to minio master (#3518) 2020-12-03 13:43:12 -08:00
Anis Elleuch d4fbfb5975 Show better looking help when a wrong flag is passed (#3461) 2020-12-02 22:19:26 -08:00
Harshavardhana 00873e4b93 update dependencies (#3515) 2020-12-01 18:44:48 -08:00
Harshavardhana b1f5e78980 fix indentation/help across commands (#3512) 2020-12-01 16:34:43 -08:00
Ritesh H Shukla bd7442fbc6 Add under what condition overwrite flag will copy data from source to target (#3513) 2020-12-01 12:26:01 -08:00
Lenin Alevski c7989d06bc Support for setting custom Transport in S3Client configuration (#3510) 2020-11-30 20:52:08 -08:00
Harshavardhana 681cbb06de use directly S3 event types instead of re-defining them (#3511) 2020-11-30 09:10:34 -08:00
Shireesh Anjal 3dffa04f66 Implement new format of the health report (#3492) 2020-11-26 05:41:14 -08:00
Poorna Krishnamoorthy 060b0762fb Remove trailing slash for mc admin bucket remote ls (#3506)
if any, after alias/bucket
2020-11-25 13:12:43 -08:00
Poorna Krishnamoorthy df5f03a109 Fix cutoff header in mc admin bucket remote ls (#3502) 2020-11-25 12:05:37 -08:00
Harshavardhana 465e6cf63c fix: indent help properly (#3504) 2020-11-25 12:05:05 -08:00
Anis Elleuch 25fd302af6 More flags check in replicate add command (#3503) 2020-11-25 10:20:43 -08:00
Poorna Krishnamoorthy bf2f7f0292 do not append default port to target in bucket remote cmd(#3501) 2020-11-24 17:12:37 -08:00
Poorna Krishnamoorthy 138587816a Rename ilm set as ilm edit (#3420) 2020-11-23 13:46:44 -08:00
Cesar N d4f9ea859d Change GetOptions' fields to public (#3498)
This allows minio/console to take advantage of the current
S3Client Get function for downloading objects with version
2020-11-19 13:43:35 -08:00
Harshavardhana adafa0024f fix: allow mirror to perform 'dir/ -> alias/' (#3493)
fixes a regression introduced in #3488
2020-11-16 15:52:34 -08:00
Anis Elleuch 9ac1bf4a29 fix: copy bucket policy/lock config only with new buckets and with -a (#3488)
mc did not require -a to trigger mirroring of bucket policy & locking
configurations, this commit enforces this requirement. Besides, the config
mirroring will only happen if the mirror command is creating new buckets in
the target server.
2020-11-16 11:36:50 -08:00
Anis Elleuch f3dd24f578 Implement barrier in parallel manager (#3469)
Mirroring watch supports parallel manager to run actions of the received
events in parallel, but sometimes the order of the execution of those
actions matter.

For example:
- A new bucket is created
- A new file is uploaded in the new bucket

This PR will bring support of the barrier concept. A task with a barrier
will only executed after all the previous tasks finish, the
subsequent tasks will also be only executed when the barrier task is
finished.

Later, we will bring support of tasks dependency to optimize the
parallelism.
2020-11-15 13:26:38 -08:00
Harshavardhana 3792e9f906 multiple bug fixes for mirror, ls, rm (#3491)
- fixes errant top level directory creation, regression introduced in #3313
- fixes `mc ls -r` regression introduced in #3476
- fixes other bugs such as `mc mirror` would perpetually hang if the
  destination bucket doesn't exist, create and proceed instead.
- removes DirOpt style implementations for List, ListIncompleteUploads
  these are not useful anymore.
2020-11-15 13:24:00 -08:00
Harshavardhana f1c04ad4b8 fix: no reason to look for file extensions (#3490)
fixes #3489
2020-11-13 12:12:49 -08:00
Anis Elleuch e216394765 Better autocompletion msg (#3481)
This commit also removes checking for msgp generated files since snap
command is not merged yet.

msgp check will be added in snap change.
2020-11-12 16:27:05 -08:00
Anis Elleuch 6ab70467cc Always send MD5 when creating an empty directory (#3487)
Otherwise it could fail with a bucket with locking enabled.
2020-11-12 10:25:20 -08:00
Harshavardhana b2ab462551 add workers per GOMAXPROCS (#3483) 2020-11-11 09:22:39 -08:00
Poorna Krishnamoorthy 786a53672b Add flag to allow delete marker replication (#3395) 2020-11-10 19:36:48 -08:00
Harshavardhana 63ce578c46 update go mod tidy 2020-11-06 13:56:50 -08:00
Anis Elleuch 965747e45d Fix client-s3.Makebucket behavior with object in path (#3470) 2020-11-06 09:38:43 -08:00
Anis Elleuch 0289d32164 errorIf(): Convert context canceled to canceling upon request (#3463) 2020-11-06 09:37:59 -08:00
Ritesh H Shukla 40e328eac2 Add support for setting bandwidth limit (#3430) 2020-11-03 16:02:17 -08:00
Harshavardhana 470ae1ee5f allow empty buckets listed with mc ls -r (#3476) 2020-11-02 15:49:07 -08:00
Shireesh Anjal 50bfa26724 Remove logging info from health report (#3465) 2020-11-01 21:50:46 -08:00
Poorna Krishnamoorthy ab396ae957 Add a --label flag to mc admin bucket remote add command (#3443) 2020-10-29 10:58:36 -07:00
Poorna Krishnamoorthy 7838365102 fix mc stat with --versions flag to show versionID correctly (#3471)
If --versions flag is specified, instead of HEAD currently
repeated listing is being done and latest version ID reported
for all the versions instead of actual version ID.
2020-10-27 16:54:05 -07:00
Anis Elleuch 6c2325129f Simply queueing to parallel manager (#3468) 2020-10-24 14:02:35 -07:00
Anis Elleuch fa4da03a4f ls: Fix listing buckets with --versions (#3462)
mc ls --versions alias/ has an unexpected output due to missing
consideration of this use case. This commit fixes the behavior.
2020-10-22 17:35:51 -07:00
Maxime Bochon d1232dc089 fix: missing closing part of code block and italic (#3460) 2020-10-22 09:23:59 -07:00
Harshavardhana 91c9364f3c add context for mirror failures (#3464) 2020-10-21 13:42:18 -07:00
Shireesh Anjal 440f6dccbc Deprecate admin health, add admin subnet health (#3455)
The existing command `admin health` is being restructured to `admin
subnet health` as the reports generated by this command are primarily
intended to be uploaded to Subnet.

If user runs the `admin health` command, they'll be asked to run `admin
subnet health` command.
2020-10-21 09:29:58 -07:00
Anis Elleuch 6bae0eb218 More fixes for retention/legalhold docs (#3458) 2020-10-19 14:00:02 -07:00
Ravind Kumar b47b2e19a8 Update mc retention, remove mc lock links. (#3457) 2020-10-19 09:20:48 -07:00
Anis Elleuch 00f655ac41 Fix missing completion rules for new/modified cmds (#3454)
Add a unit test to check new or any command modification as well.
2020-10-18 11:35:15 -07:00
Anis Elleuch b7a3dff287 Fix 'did you mean' message (#3448) 2020-10-12 09:53:51 -07:00
Anis Elleuch 8a8611cf74 s3: Stat() to filter object name when falling back to listing (#3449)
client S3 Stat() API tries to use HEAD requests but fall back to regular
listing when there is a permission issue with HEAD or when the object is
encrypted using SSE-C.

However the code accepts any entry from the minio-go listing API
which is wrong. It needs to only accept the object name as passed
by the the upper layer.
2020-10-10 15:24:39 -07:00
Anis Elleuch bb2bfdc918 Show a better err msg when Control-C is hit (#3446)
Currently the error message is "context canceled" which is cryptic
2020-10-08 11:46:11 -07:00
Anis Elleuch 0324fdcc6e mv: Fail only if bucket locking is enabled in source urls (#3444) 2020-10-08 11:04:49 -07:00
Anis Elleuch 2b36376bbc retention: Fix status msg with info --default command (#3445)
Make the output little more prettier as well.
2020-10-08 11:04:33 -07:00
Shireesh Anjal f11c3a9733 Update minio dependency and go version (#3440)
Update the minio dependency to latest master branch, and bump the go
version number to 1.14 (same as minio)
2020-10-07 22:19:11 -07:00
Anis Elleuch 3b65e9cba6 client-s3: List sends bucket names when bucket not specified (#3439)
This commit also has some simplifications in the the listing code.
2020-10-06 11:17:58 -07:00
Harshavardhana f11ae85566 allow selection of tests in 'mc admin health' (#3434) 2020-10-02 12:02:03 -07:00
Cesar N 7f2df96e48 Change ListOptions' fields to public (#3433) 2020-10-01 09:50:56 -07:00
Anis Elleuch 4b34df590a Makefile should check for possible changes in the generated code (#3427)
We should not release mc while the code is not according to the
generated code, like when we forgot to run go generate command.
2020-10-01 08:13:52 -07:00
Anis Elleuch 177f15db2e Fix help for cp and head commands (#3418) 2020-09-30 16:06:38 -07:00
Anis Elleuch 2568f9e7bf rm: Remove a delete marker (#3422)
A code refactor made rm to invoke HEAD request instead of LIST to stat
object to remove, and this introduced a problem removing a delete-marker
since HEAD of a delete-marker returns 405 Method Not Allowed
2020-09-30 15:13:19 -07:00
Harshavardhana 217f5fcbae rename obd->health - keep the alias for now (#3429)
Also additionally fix colorjson usage
2020-09-30 13:10:29 -07:00
Poorna Krishnamoorthy 1ca2182203 Change mc stat output format for bucket info (#3318) 2020-09-30 13:07:19 -07:00
Harshavardhana 150d2494e9 update admin top locks implementation (#3424) 2020-09-29 09:18:00 -07:00
Harshavardhana db1b508d8b update minio to pkg/madmin changes 2020-09-23 13:00:06 -07:00
Harshavardhana d24de97cde pretty print KMS key status (#3412) 2020-09-23 08:32:57 -07:00
Nugine 3776dff20f fix: make assert_failure exit properly (#3415) 2020-09-22 10:41:53 -07:00
Anis Elleuch 9ff6c146b4 rm: Show deleted error msg when delete marker is found (#3407)
HEAD object returns 404 with a delete-marker header when the object is a
delete-marker in a versioning bucket. This PR will show a better error
message in that case.

Use url2Stat() and ignore 400 bad request error.
2020-09-21 11:42:31 -07:00
Harshavardhana ce0c109ae3 update json flag help to indicate the correct format (#3411)
some users may get confused without reading the docs
might end up assuming that --json is a full JSON document.
2020-09-21 00:43:41 -07:00
Andreas Auernhammer 0449df8887 admin: add new command for creating KMS master keys (#3287)
This commit adds a new admin command for creating
KMS master keys:
```
mc admin kms key create <alias> <key-name>
```
2020-09-19 22:00:46 -07:00
Anis Elleuch a5d03c51e2 ls: New output format when versioning is enabled (#3392) 2020-09-19 21:56:37 -07:00
poornas 0c1f1e29f1 vendorize pkg/madmin needed for mc admin remote fixes (#3410) 2020-09-17 16:06:07 -07:00
Harshavardhana 1dde65d9c0 fix: display objects endpoint with / properly (#3408) 2020-09-17 15:34:47 -07:00
Anis Elleuch f7b1b4a139 obd: Add log spinner (#3406) 2020-09-17 15:30:07 -07:00
Anis Elleuch fede0756d4 Implement undo command (#3394) 2020-09-16 18:59:28 -07:00
John Hixson 64fb8f0a8f FreeBSD build fixes (#3404)
commit a80eca5af8 broke mc from building
on FreeBSD. This commit seperates out the files to have individual NetBSD files.
2020-09-15 09:46:57 -07:00
Harshavardhana 93209e842c re-implement metadata handling to preserve nanosecs as well (#3402) 2020-09-12 10:20:03 -07:00
Anis Elleuch 8f2ffbfa86 cp: Fix url check not considering version-id in some cases (#3401)
cp checks the existance of the source object in Type A and Type B, but
forgets to pass version-id as well. Fix this behavior.
2020-09-08 07:08:35 -07:00
Anis Elleuch af6cff00a5 retention: Refactor and add support of versioning (#3347) 2020-09-06 10:33:15 -07:00
Anis Elleuch 7f550f9482 legalhold: Refactor & add versioning support (#3343) 2020-09-05 17:11:38 -07:00
Harshavardhana 19c49468b7 handle admin info output for offline nodes properly (#3397)
```
●  localhost:9002
   Uptime: 11 minutes
   Version: 2020-09-03T23:04:07Z
   Network: 3/4 OK
   Drives: 1/1 OK

●  localhost:9003
   Uptime: offline
   Drives: 0/1 OK

●  localhost:9005
   Uptime: 11 minutes
   Version: 2020-09-03T23:04:07Z
   Network: 3/4 OK
   Drives: 1/1 OK

●  localhost:9004
   Uptime: 11 minutes
   Version: 2020-09-03T23:04:07Z
   Network: 3/4 OK
   Drives: 1/1 OK

3 drives online, 1 drive offline
```
2020-09-04 14:33:41 -07:00
Harshavardhana f992322606 fix encrypt info UI (#3393) 2020-09-02 10:28:22 -07:00
Harshavardhana b7e4a633d8 rename all 'cannot' messages to 'unable to' (#3388) 2020-09-01 15:40:31 -07:00
Harshavardhana 5649deee40 fix ls output when latest version is delete marker (#3391) 2020-09-01 13:46:07 -07:00
poornas b55e3e2d29 Update minio-go dependency (#3390) 2020-08-31 19:11:41 -07:00
飞雪无情 05d63c9aba upgrade minio module to fix mc admin trace bug. (#3385)
fixes https://github.com/minio/minio/issues/10369
2020-08-31 18:11:45 -07:00
Harshavardhana d5b4a04592 allow specifying a custom region override for any endpoint (#3386) 2020-08-31 09:04:22 -07:00
poornas d584adda01 Add ilm set command (#3384) 2020-08-28 11:57:54 -07:00
Harshavardhana 25a043b508 continue to remove content upon any error (#3383) 2020-08-28 08:13:35 -07:00
Anis Elleuch 85cce08a85 cat: Fix a regression when copying from stdin (#3381)
`mc cat >/tmp/output` is not working properly due to mc cat versioning
changes, this commit fixes the issue to make mc cat works as expected.

It also adds a unit test for it.
2020-08-27 10:31:53 -07:00
Cédric Roger 8f1ce3c59f Update minio-client-complete-guide.md (#3382) 2020-08-27 09:30:14 -07:00
Harshavardhana 41d337e95c fix: messages for version-id and rewind (#3380) 2020-08-26 15:48:47 -07:00
Anis Elleuch e10c597425 stat: Add support of --rewind, --versions and --version-id (#3350) 2020-08-26 15:04:52 -07:00
Harshavardhana 6fc39cdf8e imply rewind correctly what it does (#3373) 2020-08-26 14:51:37 -07:00
Anis Elleuch 35632bc1af head: Add support of --version-id and --rewind (#3354) 2020-08-26 10:38:35 -07:00
Anis Elleuch a104aa1cb2 tag: Add --version-id support (#3364) 2020-08-25 21:40:09 -07:00
ebozduman 2a6bdd8164 preserve the same dir structure for backup and restore (#3313) 2020-08-25 17:16:48 -07:00
Harshavardhana c58148a421 avoid calling get bucket object lock config for same bucket (#3378) 2020-08-25 10:50:40 -07:00
Anis Elleuch b1ca6482d5 share: Support --version-id in Download command (#3365) 2020-08-21 00:08:55 -07:00
Anis Elleuch 54fab0ad8f du: Add support of --rewind and --versions (#3367) 2020-08-21 12:10:24 +05:30
Harshavardhana ebb05ce469 fix: rm --version-id option (#3372) 2020-08-19 16:55:02 -07:00
Harshavardhana ce7ffc38df fix: alignment in help for multiple commands (#3371) 2020-08-19 15:44:12 -07:00
poornas ff9731a0d2 fix functional test test_copy_object_with_sse_rewrite (#3369)
`mc rm` on sse-c encrypted object needs encrypt-key flag passed.
2020-08-19 14:22:48 -07:00
Harshavardhana b604a89a9c rename 'config host add' to 'alias set' (#3366) 2020-08-17 22:41:42 -07:00
Harshavardhana fe5e714593 migrate CI to go1.14, go1.15 (#3361) 2020-08-17 08:40:27 -07:00
Anis Elleuch cd41dbc0a2 tree: Add --rewind flag (#3359) 2020-08-14 22:11:38 -07:00
Anis Elleuch 24e58fce38 ls: --rewind without --versions shows correct version number (#3360) 2020-08-14 15:46:12 -07:00
Anis Elleuch 6f2dc37ad8 cat: Add version-id flag (#3352) 2020-08-14 14:07:03 -07:00
poornas eafc9ee7b4 Add --remote-bucket as flag in mc replicate add/set (#3349) 2020-08-14 13:59:52 -07:00
Tobias Nygren a80eca5af8 fix mc build on NetBSD (#3358) 2020-08-13 15:09:23 -07:00
Harshavardhana 091a109e5a fix: set replace metadata to preserve (#3356) 2020-08-12 19:41:44 -07:00
Harshavardhana cdb458c987 fix: do not close contentCh prematurely without versioning 2020-08-12 16:03:30 -07:00
Harshavardhana f9dc22561c fix: mc rb site-wide removal with versioning (#3355) 2020-08-12 14:19:10 -07:00
poornas 5ad2d36f5c Add ReplicationStatus to stat cmd output (#3351) 2020-08-11 14:19:17 -07:00
Anis Elleuch 6313ee7dab Add versioning support for rm cmd (#3339) 2020-08-10 15:19:06 -07:00
Anis Elleuch 73d8b35425 cp: Add support of --version-id flag (#3342) 2020-08-08 20:15:34 -07:00
Harshavardhana 4d70066990 use credits file from master 2020-08-07 23:05:18 -07:00
Anis Elleuch 7e52c104be ls: New printing format for versions (#3341) 2020-08-07 17:56:14 -07:00
kannappanr 588a8fcd17 rename versioning to version (#3345) 2020-08-07 13:32:11 -07:00
poornas 0ba1633a04 Change admin bucket remote cli args (#3340)
Add support to list all remote targets for a tenant
2020-08-07 10:52:09 -07:00
poornas 069968c8aa Change replicate command cli (#3335) 2020-08-07 08:15:27 -07:00
Anis Elleuch 0c4b649369 stat: Show lifecycle expiration date if set (#3344)
Add a new field in the stat output to show if the object has any
expiration date due to lifecycle expiration rules. The expiration date
is show in machine local time.
2020-08-06 14:19:41 -07:00
Harshavardhana bd03dfbb15 fix: docs command line typo 2020-08-03 18:26:58 -07:00
Harshavardhana 9498227542 fix: fallback listing to regular objects (#3338) 2020-08-03 17:22:33 -07:00
Harshavardhana 32c13f2977 fix: rb command regression deleting bucket (#3337) 2020-08-03 15:32:42 -07:00
Harshavardhana 6f8859262c fix go mod tidy 2020-08-03 14:01:50 -07:00
poornas cd1f28e20c Rename mc admin bucket replication command (#3328)
Rename to `mc admin bucket remote` to manage generic
bucket targets
2020-08-03 13:57:54 -07:00
Anis Elleuch b1aa159838 rb: Delete object versions as well (#3322) 2020-08-03 13:54:07 -07:00
Harshavardhana 3c0bc7ec33 update CREDITS with new deps (#3336) 2020-08-01 11:53:13 -07:00
Harshavardhana 6a98216c53 rename all bucket commands (#3334) 2020-07-31 15:18:57 -07:00
poornas 7ffa755cd9 Move version commands to top level (#3329) 2020-07-30 09:53:15 -07:00
kannappanr 0631315535 Fix mc encrypt documentation (#3330) 2020-07-29 23:12:26 -07:00
poornas 2be7f6dd13 Fix example for mc admin bucket quota (#3326) 2020-07-29 21:27:07 -07:00
poornas ceb216f8a3 Add mc encrypt command (#3312) 2020-07-29 21:26:42 -07:00
Anis Elleuch d93b7f7638 More fixes in the doc for mc alias command (#3327) 2020-07-28 15:04:27 -07:00
Anis Elleuch ec734d0f71 Add --rewind flag for cat command (#3321) 2020-07-28 13:19:56 -07:00
Anis Elleuch 90dc31f6ba Move from mc config host to alias command (#3311)
```
mc alias set
   alias remove
   alias list
```

are new commands that replace mc config host sub-commands.

mc config host will still be available but hidden for backward
compatiblity. The JSON output is also kept if the user is running mc
config host command.
2020-07-28 10:26:41 -07:00
Harshavardhana 9c09f78982 add license section about Apache2.0 2020-07-26 01:02:14 -07:00
Harshavardhana 90d22b271f move 'mc ilm' to 'mc bucket ilm' (#3320)
update relevant docs and use the same
usage message consistently
2020-07-25 11:31:42 -07:00
poornas 2750c4bfe6 Add replication commands (#3272)
`mc admin bucket replication` command
manages replication targets on MinIO server

`mc bucket replicate` allows setting replication 
configuration on the source bucket
2020-07-24 12:34:13 -07:00
poornas c61a26269f Move mc lock to mc bucket lock (#3309) 2020-07-24 01:18:55 -07:00
Anis Elleuch 65d564dd87 ilm: Add ignores bucket lifecycle not found error (#3315) 2020-07-23 11:31:13 -07:00
Anis Elleuch 442facedd1 Implement rewind flag in ls and cp commands (#3304)
--rewind will go back in time and select specific object versions that are
the latest at the specified time.

--versions will display all the versions

cp will just ignore if the latest version is a delete marker
ls will print delete markers with a (deleted) at the end
2020-07-23 11:18:38 -07:00
Anis Elleuch a2592cef84 mirror: Exit with status code 1 if source does not exist (#3314) 2020-07-22 17:48:15 -07:00
poornas 023e56e0a1 Add mc bucket version command (#3308) 2020-07-21 10:10:57 -07:00
Anis Elleuch c8a3b7bff0 ilm: Add doc to the complete mc guide (#3270) 2020-07-19 12:46:30 -07:00
Harshavardhana 12acca5abd upgrade minio-go to fix lifecycle removal issue (#3310) 2020-07-19 12:40:37 -07:00
Harshavardhana 67f2472d24 api: upgrade to minio-go v7.0.1 (#3306) 2020-07-17 08:03:04 -07:00
Dmitry Afanasiev f19a10dce2 fix attr argument parsing - support quoted keys and values (#3294) 2020-07-16 19:23:35 -07:00
Harshavardhana ea8c0db96e update minio-go/v7 APIs again (#3305) 2020-07-16 18:03:17 -07:00
Harshavardhana 0b0acc611f Revert "cli: Load global flags in initBeforeRunningCmd (#3283)" (#3302)
This reverts commit 712ff33319.
2020-07-16 11:10:35 -07:00
ebozduman 7b5d5ea990 Fixes --attr regression (#3303) 2020-07-16 08:59:38 -07:00
Anis Elleuch 56c2c1a5c5 Fix object copying after upgrading to v7 (#3298) 2020-07-15 16:53:38 -07:00
Harshavardhana f3c9e9172a honor preserve flag during Copy operation (#3299)
continuation of #3285 which wasn't complete
2020-07-15 16:39:04 -07:00
Harshavardhana 9193388568 fix go mod tidy 2020-07-14 15:50:12 -07:00
Anis Elleuch a419bb4130 Use minio-go v7 and madmin master (#3295) 2020-07-14 11:15:19 -07:00
Harshavardhana 469665f886 update the correct cross platform qemu 2020-07-10 23:02:15 -07:00
Harshavardhana 5d98d19608 for release use the dl.min.io for containers 2020-07-10 22:40:06 -07:00
kannappanr 9d762f5aa6 Fix typos in the examples (#3289) 2020-07-07 21:08:33 -07:00
P R 51a3d287bb mc ilm list cell alignment for text (#3291) 2020-07-07 20:52:01 -07:00
Harshavardhana fbb7d75c1c support proper proxy for all transports (#3290)
fixes #3225
2020-07-07 17:07:49 -07:00
Harshavardhana 53dc65c92a move to latest released minio to fix policy (#3288)
fixes #3265
2020-07-07 12:19:48 -07:00
ebozduman d811d416a5 Fixes copy with partial metadata failure (#3282) 2020-07-06 17:22:06 -07:00
Harshavardhana ba37e08f1f support goreleaser for mc (#3286) 2020-07-05 18:37:43 -07:00
ebozduman 5c713e5ecb Adds support to preserve X-Amz-Meta-Mc-Attrs when os -> fs (#3285) 2020-07-03 15:31:27 -07:00
Anis Elleuch 712ff33319 cli: Load global flags in initBeforeRunningCmd (#3283)
app.Before receives a cli.Context but without flags parsed. There is no
point calling ctx.Bool() or ctx.IsSet() at that stage.

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

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

For better UX, mc will issue another request to get the real policy
mode.
2020-07-01 09:22:22 -07:00
poornas b8570a9a0b Fix mc cp regression for recursive copy (#3278)
Fixes #3267. Revert commit dc430afe07
which attempted to preserve similar behavior across mc cp and mc
mirror, but introduces a regression for cp when wildcards are
specified.
2020-06-29 20:33:31 -07:00
Anis Elleuch 360d094828 s3: Use list object v1 in case of GCS (#3274) 2020-06-24 05:22:29 -07:00
Harshavardhana 08685bae6a make sure active/active enables watch by default (#3271)
- effectively use context everywhere
- effectively look for source-mtime in all
  variations
- `mc diff` should do metadata diff as well
2020-06-23 16:56:08 -07:00
Harshavardhana 4989d51e2c fix: overwrite is implicit with active-active (#3268)
refactor lengthy options as mirrorOptions{} for
ease of readability and usage.
2020-06-22 23:41:24 -07:00
Harshavardhana a62a539399 fix: support STS for admin commands (#3264) 2020-06-19 12:37:57 -07:00
ebozduman d5b6931a1e Apply global context for all apis (#3240) 2020-06-16 16:55:31 -07:00
poornas 397f41c71c Fix mc cp when legal-hold or retention is set (#3257)
- Send Content-MD5 header if default retention is set on the bucket
- legal-hold needs to be case insensitive
2020-06-16 12:13:35 -07:00
Harshavardhana 707f46c32b rename multi-master to active-active (#3255) 2020-06-15 18:16:31 -07:00
380 changed files with 39191 additions and 29841 deletions
-52
View File
@@ -1,52 +0,0 @@
name: "Code scanning - action"
on:
push:
pull_request:
schedule:
- cron: '0 19 * * 0'
jobs:
CodeQL-Build:
# CodeQL runs on ubuntu-latest and windows-latest
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v2
with:
# We must fetch at least the immediate parents so that if this is
# a pull request then we can checkout the head.
fetch-depth: 2
# If this run was triggered by a pull request event, then checkout
# the head of the pull request instead of the merge commit.
- run: git checkout HEAD^2
if: ${{ github.event_name == 'pull_request' }}
# Initializes the CodeQL tools for scanning.
- name: Initialize CodeQL
uses: github/codeql-action/init@v1
# Override language selection by uncommenting this and choosing your languages
# with:
# languages: go, javascript, csharp, python, cpp, java
# Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
# If this step fails, then you should remove it and run the build manually (see below)
- name: Autobuild
uses: github/codeql-action/autobuild@v1
# ℹ️ Command-line programs to run using the OS shell.
# 📚 https://git.io/JvXDl
# ✏️ If the Autobuild fails above, remove it and uncomment the following three lines
# and modify them (or add more) to build your code if your project
# uses a compiled language
#- run: |
# make bootstrap
# make release
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v1
+39 -11
View File
@@ -4,18 +4,23 @@ on:
pull_request:
branches:
- master
push:
branches:
- master
# This ensures that previous jobs for the PR are canceled when the PR is
# updated.
concurrency:
group: ${{ github.workflow }}-${{ github.head_ref }}
cancel-in-progress: true
jobs:
build:
name: Test on Go ${{ matrix.go-version }} and ${{ matrix.os }}
runs-on: ${{ matrix.os }}
env:
GO111MODULE: on
strategy:
matrix:
go-version: [1.13.x]
os: [ubuntu-latest, windows-latest]
go-version: [1.17.x, 1.18.x]
os: [ubuntu-latest, macos-latest, windows-latest]
steps:
- name: Set up Go ${{ matrix.go-version }} on ${{ matrix.os }}
uses: actions/setup-go@v1
@@ -28,20 +33,43 @@ jobs:
- name: Build on ${{ matrix.os }}
if: matrix.os == 'windows-latest'
env:
GO111MODULE: on
run: |
go build --ldflags="-s -w" -o %GOPATH%\bin\mc.exe
go test -v -race --timeout 30m ./...
- name: Build on ${{ matrix.os }}
if: matrix.os == 'macos-latest'
run: |
go build --ldflags="-s -w" -o %GOPATH%\bin\mc
go test -v -race --timeout 30m ./...
- name: Build on ${{ matrix.os }}
if: matrix.os == 'ubuntu-latest'
env:
GO111MODULE: on
ACCESS_KEY: minioadmin
SECRET_KEY: minioadmin
ENABLE_HTTPS: 1
MINIO_CI_CD: 1
SERVER_ENDPOINT: localhost:9000
run: |
wget https://dl.min.io/server/minio/release/linux-amd64/minio && chmod +x minio
mkdir -p ~/.minio/certs/ && cp testdata/localhost.crt ~/.minio/certs/public.crt && cp testdata/localhost.key ~/.minio/certs/private.key
sudo cp testdata/localhost.crt /usr/local/share/ca-certificates/ && sudo update-ca-certificates
./minio server /tmp/test-xl/{1...4}/ & sleep 10
make
diff -au <(gofmt -d *.go) <(printf "")
diff -au <(gofmt -s -d cmd) <(printf "")
diff -au <(gofmt -s -d pkg) <(printf "")
make test-race
make verify
make crosscompile
vetchecks: # Run vet checks against one version.
env:
CGO_ENABLED: 0
runs-on: ubuntu-latest
steps:
- name: Set up Go
uses: actions/setup-go@v2
with:
go-version: 1.17.x
- name: Checkout code
uses: actions/checkout@v2
- name: Test 386
run: GOOS=linux GOARCH=386 go test -short ./...
+20 -6
View File
@@ -12,17 +12,31 @@ linters:
- goimports
- misspell
- govet
- golint
- revive
- ineffassign
- gosimple
- deadcode
- structcheck
- gomodguard
- gofmt
- unused
- structcheck
- varcheck
- gofumpt
linters-settings:
gofumpt:
lang-version: "1.17"
# Choose whether or not to use the extra rules that are disabled
# by default
extra-rules: false
issues:
exclude-use-default: false
exclude:
- instead of using struct literal
- should have a package comment
- error strings should not be capitalized or end with punctuation or a newline
- instead of using struct literal
- should have a package comment
- error strings should not be capitalized or end with punctuation or a newline
service:
golangci-lint-version: 1.20.0 # use the fixed version to not introduce new linters unexpectedly
golangci-lint-version: 1.43.0 # use the fixed version to not introduce new linters unexpectedly
+167
View File
@@ -0,0 +1,167 @@
project_name: mc
release:
name_template: "Version {{.Version}}"
disable: true
github:
owner: minio
name: mc
env:
- CGO_ENABLED=0
- GO111MODULE=on
before:
hooks:
- make clean
- go generate ./...
- go mod tidy
- go mod download
builds:
-
goos:
- linux
- darwin
- windows
- freebsd
goarch:
- amd64
- arm64
- arm
- ppc64le
- s390x
goarm:
- 7
ignore:
- goos: darwin
goarch: arm64
- goos: darwin
goarch: arm
- goos: darwin
goarch: ppc64le
- goos: darwin
goarch: s390x
- goos: windows
goarch: arm64
- goos: windows
goarch: arm
- goos: windows
goarch: ppc64le
- goos: windows
goarch: s390x
- goos: freebsd
goarch: arm
- goos: freebsd
goarch: arm64
- goos: freebsd
goarch: ppc64le
- goos: freebsd
goarch: s390x
flags:
- -tags=kqueue
- -trimpath
ldflags:
- "-s -w -X github.com/minio/mc/cmd.Version={{.Version}} -X github.com/minio/mc/cmd.ReleaseTag={{.Tag}} -X github.com/minio/mc/cmd.CommitID={{.FullCommit}} -X github.com/minio/mc/cmd.ShortCommitID={{.ShortCommit}}"
archives:
-
format: binary
name_template: "{{ .Binary }}-release/{{ .Os }}-{{ .Arch }}/{{ .Binary }}.{{ .Version }}"
nfpms:
-
id: minio
package_name: mc
vendor: MinIO, Inc.
homepage: https://min.io/
maintainer: dev@min.io
description: MinIO Client (mc) provides a modern alternative to UNIX commands like ls, cat, cp, mirror, diff, find etc. It supports filesystems and Amazon S3 compatible cloud storage service (AWS Signature v2 and v4).
license: Apache 2.0
bindir: /usr/bin
formats:
- deb
- rpm
overrides:
deb:
file_name_template: "{{ .Binary }}-release/debs/{{ .ProjectName }}-{{ .Version }}_{{ .Arch }}"
replacements:
arm: armv7
files:
"NOTICE": "/usr/share/mc/NOTICE"
"CREDITS": "/usr/share/mc/CREDITS"
"LICENSE": "/usr/share/mc/LICENSE"
"README.md": "/usr/share/mc/README.md"
rpm:
file_name_template: "{{ .Binary }}-release/rpms/{{ .ProjectName }}-{{ .Version }}.{{ .Arch }}"
replacements:
amd64: x86_64
arm64: aarch64
arm: armv7
files:
"NOTICE": "/usr/share/mc/NOTICE"
"CREDITS": "/usr/share/mc/CREDITS"
"LICENSE": "/usr/share/mc/LICENSE"
"README.md": "/usr/share/mc/README.md"
checksum:
algorithm: sha256
signs:
-
signature: "${artifact}.asc"
cmd: "sh"
args:
- '-c'
- 'gpg --quiet --detach-sign -a ${artifact}'
artifacts: all
changelog:
sort: asc
filters:
exclude:
- '^Update yaml files'
dockers:
-
goos: linux
goarch: amd64
dockerfile: Dockerfile.release
image_templates:
- minio/mc:{{ .Tag }}
- minio/mc:latest
-
goos: linux
goarch: ppc64le
dockerfile: Dockerfile.ppc64le.release
image_templates:
- minio/mc:{{ .Tag }}-ppc64le
-
goos: linux
goarch: s390x
dockerfile: Dockerfile.s390x.release
image_templates:
- minio/mc:{{ .Tag }}-s390x
-
goos: linux
goarch: arm64
goarm: ''
dockerfile: Dockerfile.arm64.release
image_templates:
- minio/mc:{{ .Tag }}-arm64
-
goos: linux
goarch: arm
goarm: '7'
dockerfile: Dockerfile.arm.release
image_templates:
- minio/mc:{{ .Tag }}-arm
+2372 -13132
View File
File diff suppressed because it is too large Load Diff
+10 -5
View File
@@ -1,4 +1,4 @@
FROM golang:1.13-alpine
FROM golang:1.17-alpine as builder
LABEL maintainer="MinIO Inc <dev@min.io>"
@@ -11,12 +11,17 @@ RUN \
git clone https://github.com/minio/mc && cd mc && \
go install -v -ldflags "$(go run buildscripts/gen-ldflags.go)"
FROM alpine:3.10
FROM registry.access.redhat.com/ubi8/ubi-minimal:8.6
COPY --from=0 /go/bin/mc /usr/bin/mc
ARG TARGETARCH
COPY --from=builder /go/bin/mc /usr/bin/mc
COPY --from=builder /go/mc/CREDITS /licenses/CREDITS
COPY --from=builder /go/mc/LICENSE /licenses/LICENSE
RUN \
apk add --no-cache ca-certificates && \
echo 'hosts: files mdns4_minimal [NOTFOUND=return] dns mdns4' >> /etc/nsswitch.conf
microdnf update --nodocs && \
microdnf install ca-certificates --nodocs && \
microdnf clean all
ENTRYPOINT ["mc"]
+9 -5
View File
@@ -1,10 +1,14 @@
FROM alpine:3.10
FROM registry.access.redhat.com/ubi8/ubi-minimal:8.6
LABEL maintainer="MinIO Inc <dev@min.io>"
COPY mc /usr/bin/
COPY CREDITS /licenses/CREDITS
COPY LICENSE /licenses/LICENSE
RUN \
apk add --no-cache ca-certificates && \
echo 'hosts: files mdns4_minimal [NOTFOUND=return] dns mdns4' >> /etc/nsswitch.conf \
chmod +x /usr/bin/mc
RUN \
microdnf update --nodocs && \
microdnf install ca-certificates --nodocs && \
microdnf clean all
ENTRYPOINT ["mc"]
+14 -6
View File
@@ -1,11 +1,19 @@
FROM alpine:3.10
FROM registry.access.redhat.com/ubi8/ubi-minimal:8.6
MAINTAINER MinIO Inc <dev@min.io>
ARG TARGETARCH
ARG RELEASE
LABEL maintainer="MinIO Inc <dev@min.io>"
COPY CREDITS /licenses/CREDITS
COPY LICENSE /licenses/LICENSE
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
microdnf update --nodocs && \
microdnf install curl ca-certificates shadow-utils --nodocs && \
microdnf clean all && \
curl -s -q https://dl.minio.io/client/mc/release/linux-${TARGETARCH}/archive/mc.${RELEASE} -o /usr/bin/mc && \
chmod +x /usr/bin/mc
ENTRYPOINT ["mc"]
+628 -169
View File
@@ -1,202 +1,661 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
Preamble
1. Definitions.
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
The precise terms and conditions for copying, distribution and
modification follow.
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
TERMS AND CONDITIONS
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
0. Definitions.
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
"This License" refers to version 3 of the GNU Affero General Public License.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
A "covered work" means either the unmodified Program or a work based
on the Program.
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
1. Source Code.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
END OF TERMS AND CONDITIONS
The Corresponding Source for a work in source code form is that
same work.
APPENDIX: How to apply the Apache License to your work.
2. Basic Permissions.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
Copyright [yyyy] [name of copyright owner]
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
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
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
http://www.apache.org/licenses/LICENSE-2.0
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
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.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<https://www.gnu.org/licenses/>.
+3 -8
View File
@@ -18,12 +18,13 @@ checks:
getdeps:
@mkdir -p ${GOPATH}/bin
@which golangci-lint 1>/dev/null || (echo "Installing golangci-lint" && curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(GOPATH)/bin v1.27.0)
@echo "Installing golangci-lint" && curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(GOPATH)/bin v1.46.2
@echo "Installing stringer" && go install -v golang.org/x/tools/cmd/stringer@latest
crosscompile:
@(env bash $(PWD)/buildscripts/cross-compile.sh)
verifiers: getdeps vet fmt lint
verifiers: getdeps vet lint
docker: build
@docker build -t $(TAG) . -f Dockerfile.dev
@@ -32,14 +33,8 @@ vet:
@echo "Running $@"
@GO111MODULE=on go vet github.com/minio/mc/...
fmt:
@echo "Running $@"
@GO111MODULE=on gofmt -d cmd/
@GO111MODULE=on gofmt -d pkg/
lint:
@echo "Running $@ check"
@GO111MODULE=on ${GOPATH}/bin/golangci-lint cache clean
@GO111MODULE=on ${GOPATH}/bin/golangci-lint run --timeout=5m --config ./.golangci.yml
# Builds mc, runs the verifiers then runs the tests.
+1 -1
View File
@@ -1,4 +1,4 @@
MinIO Client (C) 2014, 2015 MinIO, Inc.
MinIO Client (C) 2014-2020 MinIO, Inc.
This product includes software developed at MinIO, Inc.
(https://min.io/).
+61 -40
View File
@@ -1,34 +1,40 @@
# 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/)
[![Slack](https://slack.min.io/slack?type=svg)](https://slack.min.io) [![Go Report Card](https://goreportcard.com/badge/minio/mc)](https://goreportcard.com/report/minio/mc) [![Docker Pulls](https://img.shields.io/docker/pulls/minio/mc.svg?maxAge=604800)](https://hub.docker.com/r/minio/mc/) [![license](https://img.shields.io/badge/license-AGPL%20V3-blue)](https://github.com/minio/mc/blob/master/LICENSE)
MinIO Client (mc) provides a modern alternative to UNIX commands like ls, cat, cp, mirror, diff, find etc. It supports filesystems and Amazon S3 compatible cloud storage service (AWS Signature v2 and v4).
```
ls list buckets and objects
mb make a bucket
rb remove a bucket
cat display object contents
head display first 'n' lines of an object
pipe stream STDIN to an object
share generate URL for temporary access to an object
cp copy objects
mirror synchronize objects to a remote site
find search for objects
sql run sql queries on objects
stat stat contents of objects
lock set and get object lock configuration
retention set object retention for objects with a given prefix
legalhold set object legal hold for objects
diff list differences in object name, size, and date between buckets
rm remove objects
event manage object notifications
watch watch for object events
policy manage anonymous access to objects
admin manage MinIO servers
session manage saved sessions for cp command
config manage mc configuration file
update check for a new software update
version print version info
alias set, remove and list aliases in configuration file
ls list buckets and objects
mb make a bucket
rb remove a bucket
cp copy objects
mirror synchronize object(s) to a remote site
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
find search for objects
sql run sql queries on objects
stat show object metadata
mv move objects
tree list buckets and objects in a tree format
du summarize disk usage recursively
retention set retention for object(s)
legalhold set legal hold for object(s)
diff list differences in object name, size, and date between two buckets
rm remove objects
encrypt manage bucket encryption config
event manage object notifications
watch listen for object notification events
undo undo PUT/DELETE operations
policy manage anonymous access to buckets and objects
tag manage tags for bucket(s) and object(s)
ilm manage bucket lifecycle
version manage bucket versioning
replicate configure server side bucket replication
admin manage MinIO servers
update update mc to latest release
```
## Docker Container
@@ -50,7 +56,22 @@ docker run minio/mc:edge ls play
docker run -it --entrypoint=/bin/sh minio/mc
```
then use the [`mc config` command](#add-a-cloud-storage-service).
then use the [`mc alias` command](#add-a-cloud-storage-service).
### GitLab CI
When using the Docker container in GitLab CI, you must [set the entrypoint to an empty string](https://docs.gitlab.com/ee/ci/docker/using_docker_images.html#override-the-entrypoint-of-an-image).
```
deploy:
image:
name: minio/mc
entrypoint: ['']
stage: deploy
before_script:
- mc alias set minio $MINIO_HOST $MINIO_ACCESS_KEY $MINIO_SECRET_KEY
script:
- mc cp <source> <destination>
```
## macOS
### Homebrew
@@ -85,10 +106,10 @@ mc.exe --help
```
## Install from Source
Source installation is only intended for developers and advanced users. If you do not have a working Golang environment, please follow [How to install Golang](https://golang.org/doc/install). Minimum version required is [go1.13](https://golang.org/dl/#stable)
Source installation is only intended for developers and advanced users. If you do not have a working Golang environment, please follow [How to install Golang](https://golang.org/doc/install). Minimum version required is [go1.17](https://golang.org/dl/#stable)
```sh
GO111MODULE=on go get github.com/minio/mc
go install github.com/minio/mc@latest
```
## Add a Cloud Storage Service
@@ -97,25 +118,25 @@ If you are planning to use `mc` only on POSIX compatible filesystems, you may sk
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>
mc alias set <ALIAS> <YOUR-S3-ENDPOINT> <YOUR-ACCESS-KEY> <YOUR-SECRET-KEY> --api <API-SIGNATURE> --path <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".
`<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.
Path is an optional argument. It is used to indicate whether dns or path style url requests are supported by the server. It accepts "on", "off" as valid values to enable/disable path style requests.. 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.
MinIO server startup banner displays URL, access and secret keys.
```
mc config host add minio http://192.168.1.51 BKIKJAA5BMMU2RHO6IBB V7f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12
mc alias set 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
mc alias set 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
@@ -149,9 +170,12 @@ mc config host add s3 https://s3.amazonaws.com BKIKJAA5BMMU2RHO6IBB V7f1CwQqAcwo
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
mc alias set gcs https://storage.googleapis.com BKIKJAA5BMMU2RHO6IBB V8f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12
```
### Example - IBM Cloud Object Storage
See [the complete guide](docs/minio-client-complete-guide.md) for IBM instructions.
## 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.
@@ -186,9 +210,6 @@ 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
@@ -221,4 +242,4 @@ cat cp event head mb pipe rm share stat
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)
Use of `mc` is governed by the GNU AGPLv3 license that can be found in the [LICENSE](https://github.com/minio/mc/blob/master/LICENSE) file.
+4 -4
View File
@@ -92,7 +92,7 @@ make
添加一个或多个S3兼容的服务,请参考下面说明。`mc`将所有的配置信息都存储在``~/.mc/config.json``文件中。
```
mc config host add <ALIAS> <YOUR-S3-ENDPOINT> <YOUR-ACCESS-KEY> <YOUR-SECRET-KEY> [--api API-SIGNATURE]
mc alias set <ALIAS> <YOUR-S3-ENDPOINT> <YOUR-ACCESS-KEY> <YOUR-SECRET-KEY> [--api API-SIGNATURE]
```
别名就是给你的云存储服务起了一个短点的外号。S3 endpoint,access key和secret key是你的云存储服务提供的。API签名是可选参数,默认情况下,它被设置为"S3v4"。
@@ -101,21 +101,21 @@ mc config host add <ALIAS> <YOUR-S3-ENDPOINT> <YOUR-ACCESS-KEY> <YOUR-SECRET-KEY
从MinIO服务获得URL、access key和secret key。
```
mc config host add minio http://192.168.1.51 BKIKJAA5BMMU2RHO6IBB V7f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12 --api s3v4
mc alias set minio http://192.168.1.51 BKIKJAA5BMMU2RHO6IBB V7f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12 --api s3v4
```
### 示例-Amazon S3云存储
参考[AWS Credentials指南](http://docs.aws.amazon.com/general/latest/gr/aws-security-credentials.html)获取你的AccessKeyID和SecretAccessKey。
```
mc config host add s3 https://s3.amazonaws.com BKIKJAA5BMMU2RHO6IBB V7f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12 --api s3v4
mc alias set s3 https://s3.amazonaws.com BKIKJAA5BMMU2RHO6IBB V7f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12 --api s3v4
```
### 示例-Google云存储
参考[Google Credentials Guide](https://cloud.google.com/storage/docs/migrating?hl=en#keys)获取你的AccessKeyID和SecretAccessKey。
```
mc config host add gcs https://storage.googleapis.com BKIKJAA5BMMU2RHO6IBB V8f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12 --api s3v2
mc alias set gcs https://storage.googleapis.com BKIKJAA5BMMU2RHO6IBB V8f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12 --api s3v2
```
注意:Google云存储只支持旧版签名版本V2,所以你需要选择S3v2。
+1
View File
@@ -0,0 +1 @@
theme: jekyll-theme-minimal
-1
View File
@@ -22,4 +22,3 @@ check_minimum_version() {
return 0
}
+18
View File
@@ -1,4 +1,22 @@
#!/bin/bash
#
# Copyright (c) 2015-2021 MinIO, Inc.
#
# This file is part of MinIO Object Storage stack
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
_init() {
# Save release LDFLAGS
+13 -10
View File
@@ -1,18 +1,21 @@
#!/usr/bin/env bash
#
# MinIO Client, (C) 2015, 2016, 2017, 2018, 2019 MinIO, Inc.
# Copyright (c) 2015-2021 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
# This file is part of MinIO Object Storage stack
#
# http://www.apache.org/licenses/LICENSE-2.0
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# 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.
# This program is distributed in the hope that it will be useful
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# shellcheck source=buildscripts/build.env
+22 -2
View File
@@ -1,14 +1,34 @@
#!/bin/bash
#
# Copyright (c) 2015-2021 MinIO, Inc.
#
# This file is part of MinIO Object Storage stack
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
set -e
# Enable tracing if set.
[ -n "$BASH_XTRACEFD" ] && set -ex
[ -n "$BASH_XTRACEFD" ] && set -x
function _init() {
## All binaries are static make sure to disable CGO.
export CGO_ENABLED=0
## List of architectures and OS to test coss compilation.
SUPPORTED_OSARCH="linux/ppc64le linux/arm64 linux/s390x darwin/amd64 freebsd/amd64 linux/arm linux/386"
SUPPORTED_OSARCH="linux/ppc64le linux/mips64 linux/arm64 linux/s390x darwin/arm64 darwin/amd64 freebsd/amd64 windows/amd64 linux/arm linux/386 netbsd/amd64 linux/mips openbsd/amd64"
}
function _build() {
+63 -23
View File
@@ -1,20 +1,22 @@
//go:build ignore
// +build ignore
/*
* 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.
* 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.
*/
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package main
@@ -27,25 +29,34 @@ import (
)
func genLDFlags(version string) string {
releaseTag, date := releaseTag(version)
copyrightYear := fmt.Sprintf("%d", date.Year())
var ldflagsStr string
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.CopyrightYear=" + copyrightYear + " "
ldflagsStr = ldflagsStr + "-X github.com/minio/mc/cmd.ReleaseTag=" + releaseTag + " "
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 {
// releaseTag prints release tag to the console for easy git tagging.
func releaseTag(version string) (string, time.Time) {
relPrefix := "DEVELOPMENT"
if prefix := os.Getenv("MC_RELEASE"); prefix != "" {
relPrefix = prefix
}
relTag := strings.Replace(version, " ", "-", -1)
relTag = strings.Replace(relTag, ":", "-", -1)
relTag = strings.Replace(relTag, ",", "", -1)
return relPrefix + "." + relTag
relTag := strings.ReplaceAll(version, " ", "-")
relTag = strings.ReplaceAll(relTag, ":", "-")
relTag = strings.ReplaceAll(relTag, ",", "")
t, err := time.Parse("2006-01-02T15-04-05Z", relTag)
if err != nil {
panic(err)
}
return relPrefix + "." + relTag, t
}
// commitID returns the abbreviated commit-id hash of the last commit.
@@ -65,6 +76,35 @@ func commitID() string {
return strings.TrimSpace(string(commit))
}
func commitTime() time.Time {
// git log --format=%cD -n1
var (
commitUnix []byte
err error
)
cmdName := "git"
cmdArgs := []string{"log", "--format=%cI", "-n1"}
if commitUnix, err = exec.Command(cmdName, cmdArgs...).Output(); err != nil {
fmt.Fprintln(os.Stderr, "Error generating git commit-time: ", err)
os.Exit(1)
}
t, err := time.Parse(time.RFC3339, strings.TrimSpace(string(commitUnix)))
if err != nil {
fmt.Fprintln(os.Stderr, "Error generating git commit-time: ", err)
os.Exit(1)
}
return t.UTC()
}
func main() {
fmt.Println(genLDFlags(time.Now().UTC().Format(time.RFC3339)))
var version string
if len(os.Args) > 1 {
version = os.Args[1]
} else {
version = commitTime().Format(time.RFC3339)
}
fmt.Println(genLDFlags(version))
}
+18 -16
View File
@@ -1,18 +1,19 @@
/*
* 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.
*/
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
@@ -21,7 +22,7 @@ import "path/filepath"
// isValidAccessPERM - is provided access perm string supported.
func (b accessPerms) isValidAccessPERM() bool {
switch b {
case accessNone, accessDownload, accessUpload, accessPublic:
case accessNone, accessDownload, accessUpload, accessPrivate, accessPublic:
return true
}
return false
@@ -39,6 +40,7 @@ const (
accessNone = accessPerms("none")
accessDownload = accessPerms("download")
accessUpload = accessPerms("upload")
accessPrivate = accessPerms("private")
accessPublic = accessPerms("public")
accessCustom = accessPerms("custom")
)
+17 -16
View File
@@ -1,18 +1,19 @@
/*
* 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.
* 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.
*/
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
@@ -23,7 +24,7 @@ import (
"time"
"github.com/cheggaaa/pb"
json "github.com/minio/mc/pkg/colorjson"
json "github.com/minio/colorjson"
"github.com/minio/mc/pkg/probe"
)
+49 -69
View File
@@ -1,18 +1,19 @@
/*
* MinIO Client (C) 2020 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
@@ -22,17 +23,13 @@ import (
humanize "github.com/dustin/go-humanize"
"github.com/fatih/color"
"github.com/minio/cli"
json "github.com/minio/mc/pkg/colorjson"
json "github.com/minio/colorjson"
"github.com/minio/madmin-go"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio/pkg/console"
"github.com/minio/minio/pkg/madmin"
"github.com/minio/pkg/console"
)
var adminQuotaFlags = []cli.Flag{
cli.StringFlag{
Name: "fifo",
Usage: "set fifo quota, allowing automatic deletion of older content",
},
cli.StringFlag{
Name: "hard",
Usage: "set a hard quota, disallowing writes after quota is reached",
@@ -74,56 +71,44 @@ func (q quotaMessage) JSON() string {
}
var adminBucketQuotaCmd = cli.Command{
Name: "quota",
Usage: "Manage bucket quota",
Action: mainAdminBucketQuota,
Before: setGlobalsFromContext,
Flags: append(adminQuotaFlags, globalFlags...),
Name: "quota",
Usage: "manage bucket quota",
Action: mainAdminBucketQuota,
OnUsageError: onUsageError,
Before: setGlobalsFromContext,
Flags: append(adminQuotaFlags, globalFlags...),
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} TARGET [--fifo QUOTA | --hard QUOTA | --clear]
{{.HelpName}} TARGET [--hard QUOTA | --clear]
QUOTA
quota accepts human-readable case-insensitive number
suffixes such as "k", "m", "g" and "t" referring to the metric units KB,
MB, GB and TB respectively. Adding an "i" to these prefixes, uses the IEC
units, so that "gi" refers to "gibibyte" or "GiB". A "b" at the end is
also accepted. Without suffixes the unit is bytes.
quota accepts human-readable case-insensitive number
suffixes such as "k", "m", "g" and "t" referring to the metric units KB,
MB, GB and TB respectively. Adding an "i" to these prefixes, uses the IEC
units, so that "gi" refers to "gibibyte" or "GiB". A "b" at the end is
also accepted. Without suffixes the unit is bytes.
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Display bucket quota configured for "mybucket" on MinIO.
{{.Prompt}} {{.HelpName}} myminio/mybucket
2. Set FIFO quota for a bucket "mybucket" on MinIO.
{{.Prompt}} {{.HelpName}} myminio/mybucket --fifo 64kB
1. Display bucket quota configured for "mybucket" on MinIO.
{{.Prompt}} {{.HelpName}} myminio/mybucket
3. Set hard quota of 1gb for a bucket "mybucket" on MinIO.
{{.Prompt}} {{.HelpName}} myminio/mybucket --hard 1gb
3. Set hard quota of 1gb for a bucket "mybucket" on MinIO.
{{.Prompt}} {{.HelpName}} myminio/mybucket --hard 1GB
4. Clear bucket quota configured for bucket "mybucket" on MinIO.
{{.Prompt}} {{.HelpName}} myminio/mybucket --clear
4. Clear bucket quota configured for bucket "mybucket" on MinIO.
{{.Prompt}} {{.HelpName}} myminio/mybucket --clear
`,
}
// checkAdminBucketQuotaSyntax - validate all the passed arguments
func checkAdminBucketQuotaSyntax(ctx *cli.Context) {
if len(ctx.Args()) == 0 || len(ctx.Args()) > 1 {
cli.ShowCommandHelpAndExit(ctx, "quota", 1) // last argument is exit code
}
if ctx.IsSet("hard") && ctx.IsSet("fifo") {
fatalIf(errInvalidArgument(), "Only one of --hard or --fifo flags can be set")
}
if (ctx.IsSet("hard") || ctx.IsSet("fifo")) && len(ctx.Args()) == 0 {
fatalIf(errInvalidArgument().Trace(ctx.Args()...), "please specify bucket and quota")
}
if ctx.IsSet("clear") && len(ctx.Args()) == 0 {
fatalIf(errInvalidArgument().Trace(ctx.Args()...), "clear flag must be passed with target alone")
cli.ShowCommandHelpAndExit(ctx, ctx.Command.Name, 1) // last argument is exit code
}
}
@@ -141,16 +126,11 @@ func mainAdminBucketQuota(ctx *cli.Context) error {
// Create a new MinIO Admin Client
client, err := newAdminClient(aliasedURL)
fatalIf(err, "Unable to initialize admin connection.")
quotaStr := ctx.String("fifo")
if ctx.IsSet("hard") {
quotaStr = ctx.String("hard")
}
_, targetURL := url2Alias(args[0])
if ctx.IsSet("fifo") || ctx.IsSet("hard") && len(args) == 1 {
qType := madmin.FIFOQuota
if ctx.IsSet("hard") {
qType = madmin.HardQuota
}
if ctx.IsSet("hard") {
qType := madmin.HardQuota
quotaStr := ctx.String("hard")
quota, e := humanize.ParseBytes(quotaStr)
fatalIf(probe.NewError(e).Trace(quotaStr), "Unable to parse quota")
if e = client.SetBucketQuota(globalContext, targetURL, &madmin.BucketQuota{Quota: quota, Type: qType}); e != nil {
@@ -163,7 +143,7 @@ func mainAdminBucketQuota(ctx *cli.Context) error {
QuotaType: string(qType),
Status: "success",
})
} else if ctx.Bool("clear") && len(args) == 1 {
} else if ctx.Bool("clear") {
if err := client.SetBucketQuota(globalContext, targetURL, &madmin.BucketQuota{}); err != nil {
fatalIf(probe.NewError(err).Trace(args...), "Unable to clear bucket quota config")
}
+309
View File
@@ -0,0 +1,309 @@
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
import (
"fmt"
"net/url"
"path"
"time"
humanize "github.com/dustin/go-humanize"
"github.com/fatih/color"
"github.com/minio/cli"
json "github.com/minio/colorjson"
"github.com/minio/madmin-go"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio-go/v7/pkg/s3utils"
"github.com/minio/pkg/console"
)
var adminBucketRemoteAddFlags = []cli.Flag{
cli.StringFlag{
Name: "path",
Value: "auto",
Usage: "bucket path lookup supported by the server. Valid options are '[on,off,auto]'",
},
cli.StringFlag{
Name: "service",
Usage: "type of service. Valid options are '[replication]'",
},
cli.StringFlag{
Name: "region",
Usage: "region of the destination bucket (optional)",
},
cli.StringFlag{
Name: "bandwidth",
Usage: "Set bandwidth limit in bits per second (K,B,G,T for metric and Ki,Bi,Gi,Ti for IEC units)",
},
cli.BoolFlag{
Name: "sync",
Usage: "enable synchronous replication for this target. Default is async",
},
cli.UintFlag{
Name: "healthcheck-seconds",
Usage: "health check duration in seconds",
Value: 60,
},
cli.BoolFlag{
Name: "disable-proxy",
Usage: "disable proxying in active-active replication. If unset, default behavior is to proxy",
},
}
var adminBucketRemoteAddCmd = cli.Command{
Name: "add",
Usage: "add a new remote target",
Action: mainAdminBucketRemoteAdd,
OnUsageError: onUsageError,
Before: setGlobalsFromContext,
Flags: append(globalFlags, adminBucketRemoteAddFlags...),
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} TARGET http(s)://ACCESSKEY:SECRETKEY@DEST_URL/DEST_BUCKET [--path | --region | --bandwidth] --service
TARGET:
Also called as alias/sourcebucketname
DEST_BUCKET:
Also called as remote target bucket.
DEST_URL:
Also called as remote endpoint.
ACCESSKEY:
Also called as username.
SECRETKEY:
Also called as password.
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Set a new remote replication target "targetbucket" in region "us-west-1" on https://minio.siteb.example.com for bucket 'sourcebucket'.
{{.Prompt}} {{.HelpName}} sitea/sourcebucket https://foobar:foo12345@minio.siteb.example.com/targetbucket \
--service "replication" --region "us-west-1"
2. Set a new remote replication target 'targetbucket' in region "us-west-1" on https://minio.siteb.example.com for
bucket 'sourcebucket' with bandwidth set to 2 gigabits per second. Enable synchronous replication to the target
and perform health check of target every 100 seconds
{{.Prompt}} {{.HelpName}} sitea/sourcebucket https://foobar:foo12345@minio.siteb.example.com/targetbucket \
--service "replication" --region "us-west-1 --bandwidth "2G" --sync
`,
}
// checkAdminBucketRemoteAddSyntax - validate all the passed arguments
func checkAdminBucketRemoteAddSyntax(ctx *cli.Context) {
argsNr := len(ctx.Args())
if argsNr < 2 {
cli.ShowCommandHelpAndExit(ctx, ctx.Command.Name, 1) // last argument is exit code
}
if argsNr > 2 {
fatalIf(errInvalidArgument().Trace(ctx.Args().Tail()...),
"Incorrect number of arguments for remote add command.")
}
}
// RemoteMessage container for content message structure
type RemoteMessage struct {
op string
Status string `json:"status"`
AccessKey string `json:"accessKey,omitempty"`
SecretKey string `json:"secretKey,omitempty"`
SourceBucket string `json:"sourceBucket"`
TargetURL string `json:"TargetURL,omitempty"`
TargetBucket string `json:"TargetBucket,omitempty"`
RemoteARN string `json:"RemoteARN,omitempty"`
Path string `json:"path,omitempty"`
Region string `json:"region,omitempty"`
ServiceType string `json:"service"`
Bandwidth int64 `json:"bandwidth"`
ReplicationSync bool `json:"replicationSync"`
Proxy bool `json:"proxy"`
HealthCheckDuration time.Duration `json:"healthcheckDuration"`
ResetID string `json:"resetID"`
ResetBefore time.Time `json:"resetBeforeDate"`
}
func (r RemoteMessage) String() string {
switch r.op {
case "ls":
message := console.Colorize("TargetURL", fmt.Sprintf("%s ", r.TargetURL))
message += console.Colorize("SourceBucket", r.SourceBucket)
message += console.Colorize("Arrow", "->")
message += console.Colorize("TargetBucket", r.TargetBucket)
message += " "
message += console.Colorize("ARN", r.RemoteARN)
syncStr := " "
if r.ReplicationSync && r.ServiceType == string(madmin.ReplicationService) {
syncStr = "sync"
}
message += " " + console.Colorize("SyncLabel", syncStr)
proxyStr := " "
if r.Proxy && r.ServiceType == string(madmin.ReplicationService) {
proxyStr = "proxy"
}
message += " "
message += console.Colorize("ProxyLabel", proxyStr)
return message
case "rm":
return console.Colorize("RemoteMessage", "Removed remote target for `"+r.SourceBucket+"` bucket successfully.")
case "add":
return console.Colorize("RemoteMessage", "Remote ARN = `"+r.RemoteARN+"`.")
case "edit":
return console.Colorize("RemoteMessage", "Remote target updated successfully for target with ARN:`"+r.RemoteARN+"`.")
}
return ""
}
// JSON returns jsonified message
func (r RemoteMessage) JSON() string {
r.Status = "success"
jsonMessageBytes, e := json.MarshalIndent(r, "", " ")
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
return string(jsonMessageBytes)
}
func extractCredentialURL(argURL string) (accessKey, secretKey string, u *url.URL) {
var parsedURL string
if hostKeyTokens.MatchString(argURL) {
fatalIf(errInvalidArgument().Trace(argURL), "temporary tokens are not allowed for remote targets")
}
if hostKeys.MatchString(argURL) {
parts := hostKeys.FindStringSubmatch(argURL)
if len(parts) != 5 {
fatalIf(errInvalidArgument().Trace(argURL), "Unsupported remote target format, please check --help")
}
accessKey = parts[2]
secretKey = parts[3]
parsedURL = fmt.Sprintf("%s%s", parts[1], parts[4])
}
var e error
if parsedURL == "" {
fatalIf(errInvalidArgument().Trace(argURL), "No valid credentials were detected")
}
u, e = url.Parse(parsedURL)
if e != nil {
fatalIf(errInvalidArgument().Trace(parsedURL), "Unsupported URL format %v", e)
}
return accessKey, secretKey, u
}
// fetchRemoteTarget - returns the dest bucket, dest endpoint, access and secret key
func fetchRemoteTarget(cli *cli.Context) (sourceBucket string, bktTarget *madmin.BucketTarget) {
args := cli.Args()
argCount := len(args)
if argCount < 2 {
fatalIf(probe.NewError(fmt.Errorf("Missing Remote target configuration")), "Unable to parse remote target")
}
_, sourceBucket = url2Alias(args[0])
p := cli.String("path")
if !isValidPath(p) {
fatalIf(errInvalidArgument().Trace(p),
"Unrecognized bucket path style. Valid options are `[on,off, auto]`.")
}
tgtURL := args[1]
accessKey, secretKey, u := extractCredentialURL(tgtURL)
var tgtBucket string
if u.Path != "" {
tgtBucket = path.Clean(u.Path[1:])
}
if e := s3utils.CheckValidBucketName(tgtBucket); e != nil {
fatalIf(probe.NewError(e).Trace(tgtURL), "Invalid target bucket specified")
}
serviceType := cli.String("service")
if !madmin.ServiceType(serviceType).IsValid() {
fatalIf(errInvalidArgument().Trace(serviceType), "Invalid service type. Valid option is `[replication]`.")
}
if cli.IsSet("sync") && serviceType != string(madmin.ReplicationService) {
fatalIf(errInvalidArgument(), "Invalid usage. --sync flag applies only to replication service")
}
bandwidthStr := cli.String("bandwidth")
bandwidth, err := getBandwidthInBytes(bandwidthStr)
if err != nil {
fatalIf(errInvalidArgument().Trace(bandwidthStr), "Invalid bandwidth number")
}
console.SetColor(cred, color.New(color.FgYellow, color.Italic))
creds := &madmin.Credentials{AccessKey: accessKey, SecretKey: secretKey}
disableproxy := cli.Bool("disable-proxy")
bktTarget = &madmin.BucketTarget{
TargetBucket: tgtBucket,
Secure: u.Scheme == "https",
Credentials: creds,
Endpoint: u.Host,
Path: p,
API: "s3v4",
Type: madmin.ServiceType(serviceType),
Region: cli.String("region"),
BandwidthLimit: int64(bandwidth),
ReplicationSync: cli.Bool("sync"),
DisableProxy: disableproxy,
HealthCheckDuration: time.Duration(cli.Uint("healthcheck-seconds")) * time.Second,
}
return sourceBucket, bktTarget
}
func getBandwidthInBytes(bandwidthStr string) (bandwidth uint64, err error) {
if bandwidthStr != "" {
bandwidth, err = humanize.ParseBytes(bandwidthStr)
if err != nil {
return
}
}
bandwidth = bandwidth / 8
return
}
// mainAdminBucketRemoteAdd is the handle for "mc admin bucket remote set" command.
func mainAdminBucketRemoteAdd(ctx *cli.Context) error {
checkAdminBucketRemoteAddSyntax(ctx)
console.SetColor("RemoteMessage", color.New(color.FgGreen))
// Get the alias parameter from cli
args := ctx.Args()
aliasedURL := args.Get(0)
// Create a new MinIO Admin Client
client, cerr := newAdminClient(aliasedURL)
fatalIf(cerr, "Unable to initialize admin connection.")
sourceBucket, bktTarget := fetchRemoteTarget(ctx)
arn, e := client.SetRemoteTarget(globalContext, sourceBucket, bktTarget)
if e != nil {
fatalIf(probe.NewError(e).Trace(args...), "Unable to configure remote target")
}
printMsg(RemoteMessage{
op: ctx.Command.Name,
TargetURL: bktTarget.URL().String(),
TargetBucket: bktTarget.TargetBucket,
AccessKey: bktTarget.Credentials.AccessKey,
SourceBucket: sourceBucket,
RemoteARN: arn,
ReplicationSync: bktTarget.ReplicationSync,
Proxy: !bktTarget.DisableProxy,
})
return nil
}
+131
View File
@@ -0,0 +1,131 @@
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
import (
"testing"
)
func TestGetBandwidthInBytes(t *testing.T) {
type args struct {
bandwidthStr string
}
f1 := 999.123457 * 1024 * 1024 / 8
f2 := 10.123456790 * 1024 * 1024 * 1024 / 8
f3 := 10000.123456790 * 1024 * 1024 * 1024 / 8
f4 := (0.001*1024*1024*1024 + 1) / 8 // round up
tests := []struct {
name string
args args
want uint64
}{
{
name: "1MegaByte",
args: args{
bandwidthStr: "1Mi",
},
want: 1024 * 1024 / 8,
},
{
name: "1MegaBit",
args: args{
bandwidthStr: "1M",
},
want: 1000000 / 8,
},
{
name: "1GigaBit",
args: args{
bandwidthStr: "1G",
},
want: 1000000000 / 8,
},
{
name: "1GigaByte",
args: args{
bandwidthStr: "1Gi",
},
want: 1024 * 1024 * 1024 / 8,
},
{
name: "FractionalMegaBits",
args: args{
bandwidthStr: "999.123456789123456789M",
},
want: 999123457 / 8,
},
{
name: "FractionalGigaBits",
args: args{
bandwidthStr: "10.123456789123456789123456G",
},
want: 10123456789 / 8,
},
{
name: "FractionalBigGigaBits",
args: args{
bandwidthStr: "10000.123456789123456789123456G",
},
want: 10000123456789 / 8,
},
{
name: "FractionalMegaBytes",
args: args{
bandwidthStr: "999.123456789123456789Mi",
},
want: uint64(f1),
},
{
name: "FractionalGigaBytes",
args: args{
bandwidthStr: "10.123456789123456789123456Gi",
},
want: uint64(f2),
},
{
name: "FractionalBigGigaBytes",
args: args{
bandwidthStr: "10000.123456789123456789123456Gi",
},
want: uint64(f3),
},
{
name: "SmallGiga",
args: args{
bandwidthStr: "0.001Gi",
},
want: uint64(f4),
},
{
name: "LargeK",
args: args{
bandwidthStr: "1024Ki",
},
want: 1024 * 1024 / 8,
},
}
t.Parallel()
for _, tt := range tests {
tt := tt
t.Run(tt.name, func(t *testing.T) {
if got, err := getBandwidthInBytes(tt.args.bandwidthStr); err != nil || got != tt.want {
t.Errorf("getBandwidthInBytes() = %v, want %v", got, tt.want)
}
})
}
}
+196
View File
@@ -0,0 +1,196 @@
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
import (
"fmt"
"sort"
"strings"
"time"
"github.com/dustin/go-humanize"
"github.com/fatih/color"
"github.com/minio/cli"
json "github.com/minio/colorjson"
"github.com/minio/madmin-go"
"github.com/minio/mc/pkg/probe"
"github.com/minio/pkg/console"
)
var adminBandwidthInfoCmdFlags = []cli.Flag{
cli.StringFlag{
Name: "unit",
Value: "b",
Usage: "[b|bi|B|Bi] Display bandwidth in bits (IEC [bi] or SI [b]) or bytes (IEC [Bi] or SI [B])",
},
}
var adminBwInfoCmd = cli.Command{
Name: "bandwidth",
Usage: "Show bandwidth info for buckets on the MinIO server in bits or bytes per second. Ki,Bi,Mi,Gi represent IEC units.",
Action: mainAdminBwInfo,
Before: setGlobalsFromContext,
OnUsageError: onUsageError,
Flags: append(globalFlags, adminBandwidthInfoCmdFlags...),
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} FLAGS TARGET
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Show the bandwidth usage for all the buckets in a MinIO server setup
{{.Prompt}} {{.HelpName}} play/
2. Show the bandwidth usage for the bucket 'source-bucket' in a MinIO server setup
{{.Prompt}} {{.HelpName}} play/source-bucket
`,
}
func printTable(report madmin.Report, bits bool, iec bool) {
bucketMaxLength := 63
bucketColLength := 6
var bucketKeys []string
for bucket := range report.Report.BucketStats {
if len(bucket) <= bucketMaxLength && len(bucket) > bucketColLength {
bucketColLength = len(bucket)
}
bucketKeys = append(bucketKeys, bucket)
}
sort.Strings(bucketKeys)
dspOrder := []col{colGreen} // Header
for i := 0; i < len(report.Report.BucketStats); i++ {
dspOrder = append(dspOrder, colGrey)
}
var printColors []*color.Color
for _, c := range dspOrder {
printColors = append(printColors, getPrintCol(c))
}
cellText := make([][]string, len(report.Report.BucketStats)+1) // 1 for the header
tbl := console.NewTable(printColors, []bool{false, false, false}, 0)
bucketTitle := fmt.Sprintf("%-16v", "Bucket")
cellText[0] = []string{
bucketTitle,
"Configured Max Bandwidth",
"Current Bandwidth",
}
tbl.HeaderRowSeparator = true
index := 1
for _, bucket := range bucketKeys {
values := report.Report.BucketStats[bucket]
if len(bucket) > bucketMaxLength {
bucket = bucket[:bucketMaxLength] + ".."
}
var mul uint64
mul = 1
if bits {
mul = 8
}
limit := humanize.Bytes(uint64(values.LimitInBytesPerSecond) * mul)
current := humanize.Bytes(uint64(values.CurrentBandwidthInBytesPerSecond) * mul)
if iec {
limit = humanize.IBytes(uint64(values.LimitInBytesPerSecond)*mul) + "/sec"
current = humanize.IBytes(uint64(values.CurrentBandwidthInBytesPerSecond)*mul) + "/sec"
}
if bits {
limit = strings.ToLower(limit) + "/sec"
current = strings.ToLower(current) + "/sec"
}
if values.LimitInBytesPerSecond == 0 {
limit = "N/A" // N/A means cluster bandwidth is not configured
}
cellText[index] = []string{
bucket,
limit,
current,
}
index++
}
if len(report.Report.BucketStats) > 0 {
err := tbl.DisplayTable(cellText)
if err != nil {
console.Error(err)
}
}
}
func checkAdminBwInfoSyntax(ctx *cli.Context) {
u := ctx.String("unit")
if u != "bi" &&
u != "b" &&
u != "Bi" &&
u != "B" &&
u != "" {
cli.ShowCommandHelpAndExit(ctx, "bandwidth", globalErrorExitStatus)
}
if len(ctx.Args()) > 1 || len(ctx.Args()) == 0 {
cli.ShowCommandHelpAndExit(ctx, "bandwidth", globalErrorExitStatus)
}
}
func mainAdminBwInfo(ctx *cli.Context) {
checkAdminBwInfoSyntax(ctx)
aliasURL, bucket := getAliasAndBucket(ctx)
client := getClient(aliasURL)
reportCh := client.GetBucketBandwidth(globalContext, bucket)
firstPrint := true
bandwidthUnitsString := ctx.String("unit")
for {
select {
case report := <-reportCh:
if len(report.Report.BucketStats) == 0 {
continue
}
if report.Err != nil {
if strings.Contains(report.Err.Error(), "EOF") {
continue
}
console.Error(report.Err)
}
printBandwidth(report, firstPrint, bandwidthUnitsString == "bi" || bandwidthUnitsString == "b",
bandwidthUnitsString == "bi" || bandwidthUnitsString == "Bi")
firstPrint = false
case <-globalContext.Done():
return
}
}
}
func printBandwidth(report madmin.Report, firstPrint bool, bits bool, iec bool) {
rewindLines := len(report.Report.BucketStats) + 4
if firstPrint {
rewindLines = 0
}
if globalJSON {
reportJSON, e := json.MarshalIndent(report, "", " ")
fatalIf(probe.NewError(e), "Unable to marshal to JSON")
console.Println(string(reportJSON))
time.Sleep(1 * time.Second)
return
}
if len(report.Report.BucketStats) > 0 {
console.RewindLines(rewindLines)
// For the next iteration, rewind lines
printTable(report, bits, iec)
}
time.Sleep(1 * time.Second)
}
+247
View File
@@ -0,0 +1,247 @@
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
import (
"path"
"strconv"
"strings"
"time"
"github.com/fatih/color"
"github.com/minio/cli"
"github.com/minio/madmin-go"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio-go/v7/pkg/s3utils"
"github.com/minio/pkg/console"
)
var adminBucketRemoteEditFlags = []cli.Flag{
cli.StringFlag{
Name: "arn",
Usage: "ARN of target",
},
cli.StringFlag{
Name: "sync",
Usage: "enable synchronous replication for this target. Valid values are enable,disable.Defaults to disable if unset",
},
cli.StringFlag{
Name: "proxy",
Usage: "enable proxying in active-active replication. Valid values are enable,disable.By default proxying is enabled.",
},
cli.StringFlag{
Name: "bandwidth",
Usage: "Set bandwidth limit in bits per second (K,B,G,T for metric and Ki,Bi,Gi,Ti for IEC units)",
},
cli.UintFlag{
Name: "healthcheck-seconds",
Usage: "health check duration in seconds",
Value: 60,
},
cli.StringFlag{
Name: "path",
Value: "auto",
Usage: "bucket path lookup supported by the server. Valid options are '[on,off,auto]'",
},
}
var adminBucketRemoteEditCmd = cli.Command{
Name: "edit",
Usage: "edit remote target",
Action: mainAdminBucketRemoteEdit,
Before: setGlobalsFromContext,
OnUsageError: onUsageError,
Flags: append(globalFlags, adminBucketRemoteEditFlags...),
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} TARGET http(s)://ACCESSKEY:SECRETKEY@DEST_URL/DEST_BUCKET --arn arn
TARGET:
Also called as alias/sourcebucketname
DEST_BUCKET:
Also called as remote target bucket.
DEST_URL:
Also called as remote endpoint.
ACCESSKEY:
Also called as username.
SECRETKEY:
Also called as password.
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Edit credentials for existing remote target with arn where a remote target has been configured between sourcebucket on sitea to targetbucket on siteb.
{{.DisableHistory}}
{{.Prompt}} {{.HelpName}} sitea/sourcebucket \
https://foobar:newpassword@minio.siteb.example.com/targetbucket \
--arn "arn:minio:replication:us-west-1:993bc6b6-accd-45e3-884f-5f3e652aed2a:dest1"
{{.EnableHistory}}
2. Edit remote target for sourceBucket on sitea with specified ARN to disable proxying and enable synchronous replication
{{.Prompt}} {{.HelpName}} sitea/sourcebucket --sync "enable" --proxy "disable"
--arn "arn:minio:replication:us-west-1:993bc6b6-accd-45e3-884f-5f3e652aed2a:dest1"
`,
}
// checkAdminBucketRemoteEditSyntax - validate all the passed arguments
func checkAdminBucketRemoteEditSyntax(ctx *cli.Context) {
argsNr := len(ctx.Args())
if argsNr > 2 || argsNr == 0 {
cli.ShowCommandHelpAndExit(ctx, ctx.Command.Name, 1) // last argument is exit code
}
if !ctx.IsSet("arn") {
fatalIf(errInvalidArgument().Trace(ctx.Args()...), "--arn flag needs to be set")
}
}
// modifyRemoteTarget - modifies the dest credentials or updates sync , disable-proxy settings
func modifyRemoteTarget(cli *cli.Context, targets []madmin.BucketTarget) (*madmin.BucketTarget, []madmin.TargetUpdateType) {
args := cli.Args()
foundIdx := -1
arn := cli.String("arn")
for i, t := range targets {
if t.Arn == arn {
foundIdx = i
break
}
}
if foundIdx < 0 {
fatalIf(errInvalidArgument().Trace(args...), "Unable to edit remote target - `"+arn+"` not found")
}
var ops []madmin.TargetUpdateType
bktTarget := targets[foundIdx].Clone()
if cli.IsSet("sync") {
syncState := strings.ToLower(cli.String("sync"))
switch syncState {
case "enable", "disable":
bktTarget.ReplicationSync = syncState == "enable"
ops = append(ops, madmin.SyncUpdateType)
default:
fatalIf(errInvalidArgument().Trace(args...), "--sync can be either [enable|disable]")
}
}
if cli.IsSet("proxy") {
proxyState := strings.ToLower(cli.String("proxy"))
switch proxyState {
case "enable", "disable":
bktTarget.DisableProxy = proxyState == "disable"
ops = append(ops, madmin.ProxyUpdateType)
default:
fatalIf(errInvalidArgument().Trace(args...), "--proxy can be either [enable|disable]")
}
}
if len(args) == 2 {
_, sourceBucket := url2Alias(args[0])
tgtURL := args[1]
accessKey, secretKey, u := extractCredentialURL(tgtURL)
var tgtBucket string
if u.Path != "" {
tgtBucket = path.Clean(u.Path[1:])
}
if e := s3utils.CheckValidBucketName(tgtBucket); e != nil {
fatalIf(probe.NewError(e).Trace(tgtURL), "Invalid target bucket specified")
}
secure := u.Scheme == "https"
host := u.Host
if u.Port() == "" {
port := 80
if secure {
port = 443
}
host = host + ":" + strconv.Itoa(port)
}
console.SetColor(cred, color.New(color.FgYellow, color.Italic))
creds := &madmin.Credentials{AccessKey: accessKey, SecretKey: secretKey}
if tgtBucket != bktTarget.TargetBucket {
fatalIf(errInvalidArgument().Trace(args...), "configured remote target bucket `"+tgtBucket+"` does not match "+bktTarget.TargetBucket+"` for this ARN `"+bktTarget.Arn+"`")
}
if sourceBucket != bktTarget.SourceBucket {
fatalIf(errInvalidArgument().Trace(args...), "configured source bucket `"+sourceBucket+"` does not match "+bktTarget.SourceBucket+"` for this ARN `"+bktTarget.Arn+"`")
}
bktTarget.TargetBucket = tgtBucket
bktTarget.Secure = secure
bktTarget.Credentials = creds
bktTarget.Endpoint = host
ops = append(ops, madmin.CredentialsUpdateType)
}
if cli.IsSet("bandwidth") {
bandwidthStr := cli.String("bandwidth")
bandwidth, err := getBandwidthInBytes(bandwidthStr)
if err != nil {
fatalIf(errInvalidArgument().Trace(bandwidthStr), "Invalid bandwidth number")
}
bktTarget.BandwidthLimit = int64(bandwidth)
ops = append(ops, madmin.BandwidthLimitUpdateType)
}
if cli.IsSet("healthcheck-seconds") {
bktTarget.HealthCheckDuration = time.Duration(cli.Uint("healthcheck-seconds")) * time.Second
ops = append(ops, madmin.HealthCheckDurationUpdateType)
}
if cli.IsSet("path") {
bktTarget.Path = cli.String("path")
ops = append(ops, madmin.PathUpdateType)
}
return &bktTarget, ops
}
// mainAdminBucketRemoteEdit is the handle for "mc admin bucket remote edit" command.
func mainAdminBucketRemoteEdit(ctx *cli.Context) error {
checkAdminBucketRemoteEditSyntax(ctx)
console.SetColor("RemoteMessage", color.New(color.FgGreen))
// Get the alias parameter from cli
args := ctx.Args()
aliasedURL := args.Get(0)
// Create a new MinIO Admin Client
client, cerr := newAdminClient(aliasedURL)
fatalIf(cerr, "Unable to initialize admin connection.")
_, sourceBucket := url2Alias(args[0])
targets, e := client.ListRemoteTargets(globalContext, sourceBucket, "")
fatalIf(probe.NewError(e).Trace(args...), "Unable to fetch remote target.")
bktTarget, ops := modifyRemoteTarget(ctx, targets)
arn, e := client.UpdateRemoteTarget(globalContext, bktTarget, ops...)
if e != nil {
fatalIf(probe.NewError(e).Trace(args...), "Unable to update remote target `"+bktTarget.Endpoint+"` from `"+bktTarget.SourceBucket+"` -> `"+bktTarget.TargetBucket+"`")
}
printMsg(RemoteMessage{
op: ctx.Command.Name,
TargetURL: bktTarget.URL().String(),
TargetBucket: bktTarget.TargetBucket,
AccessKey: bktTarget.Credentials.AccessKey,
SourceBucket: bktTarget.SourceBucket,
RemoteARN: arn,
})
return nil
}
+164
View File
@@ -0,0 +1,164 @@
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
import (
"fmt"
"path/filepath"
"github.com/fatih/color"
"github.com/minio/cli"
"github.com/minio/madmin-go"
"github.com/minio/mc/pkg/probe"
"github.com/minio/pkg/console"
)
var adminBucketRemoteListFlags = []cli.Flag{
cli.StringFlag{
Name: "service",
Usage: "type of service. valid options are '[replication]'",
},
}
var adminBucketRemoteListCmd = cli.Command{
Name: "ls",
Usage: "list remote target ARN(s)",
Action: mainAdminBucketRemoteList,
OnUsageError: onUsageError,
Before: setGlobalsFromContext,
Flags: append(globalFlags, adminBucketRemoteListFlags...),
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} TARGET
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Get remote bucket target for replication on MinIO server for bucket 'srcbucket'.
{{.Prompt}} {{.HelpName}} myminio/srcbucket --service "replication"
2. List all remote bucket target(s) on MinIO server for bucket 'srcbucket'.
{{.Prompt}} {{.HelpName}} myminio/srcbucket
3. List all remote bucket target(s) on MinIO tenant.
{{.Prompt}} {{.HelpName}} myminio
`,
}
// checkAdminBucketRemoteListSyntax - validate all the passed arguments
func checkAdminBucketRemoteListSyntax(ctx *cli.Context) {
if len(ctx.Args()) != 1 {
cli.ShowCommandHelpAndExit(ctx, ctx.Command.Name, 1) // last argument is exit code
}
}
// mainAdminBucketRemoteList is the handle for "mc admin bucket remote list" command.
func mainAdminBucketRemoteList(ctx *cli.Context) error {
checkAdminBucketRemoteListSyntax(ctx)
// Additional command specific theme customization.
console.SetColor("RemoteListMessage", color.New(color.Bold, color.FgHiGreen))
console.SetColor("RemoteListEmpty", color.New(color.FgYellow))
console.SetColor("SourceBucket", color.New(color.FgYellow))
console.SetColor("TargetBucket", color.New(color.FgYellow))
console.SetColor("TargetURL", color.New(color.FgHiWhite))
console.SetColor("ARN", color.New(color.FgCyan))
console.SetColor("Arrow", color.New(color.FgHiWhite))
console.SetColor("SyncLabel", color.New(color.FgHiYellow))
console.SetColor("ProxyLabel", color.New(color.FgHiYellow))
// Get the alias parameter from cli
args := ctx.Args()
aliasedURL := args.Get(0)
aliasedURL = filepath.Clean(aliasedURL)
_, sourceBucket := url2Alias(aliasedURL)
// Create a new MinIO Admin Client
client, err := newAdminClient(aliasedURL)
fatalIf(err, "Unable to initialize admin connection.")
targets, e := client.ListRemoteTargets(globalContext, sourceBucket, ctx.String("service"))
fatalIf(probe.NewError(e).Trace(args...), "Unable to list remote target")
printRemotes(ctx, aliasedURL, targets)
return nil
}
func printRemotes(ctx *cli.Context, urlStr string, targets []madmin.BucketTarget) {
maxURLLen := 10
maxTgtLen := 6
maxSrcLen := 6
maxArnLen := 3
if !globalJSON {
if len(targets) == 0 {
console.Print(console.Colorize("RemoteListEmpty", fmt.Sprintf("No remote targets found for `%s`. \n", urlStr)))
return
}
for _, t := range targets {
l := len(t.Endpoint)
if l > maxURLLen {
maxURLLen = l
}
if len(t.TargetBucket) > maxTgtLen {
maxTgtLen = len(t.TargetBucket)
}
if len(t.SourceBucket) > maxSrcLen {
maxSrcLen = len(t.SourceBucket)
}
if len(t.Arn) > maxArnLen {
maxArnLen = len(t.Arn)
}
}
if maxURLLen > 0 {
console.Println(console.Colorize("RemoteListMessage", fmt.Sprintf("%-*.*s %-*.*s->%-*.*s %-*.*s %s %s", maxURLLen+8, maxURLLen+8, "Remote URL", maxSrcLen, maxSrcLen, "Source", maxTgtLen, maxTgtLen, "Target", maxArnLen, maxArnLen, "ARN", "SYNC", "PROXY")))
}
}
for _, target := range targets {
targetURL := target.URL().String()
if !globalJSON {
if maxURLLen > 0 {
targetURL = fmt.Sprintf("%-*.*s", maxURLLen+8, maxURLLen+8, target.URL().String())
}
if maxTgtLen > 0 {
target.TargetBucket = fmt.Sprintf("%-*.*s", maxTgtLen, maxTgtLen, target.TargetBucket)
}
if maxSrcLen > 0 {
target.SourceBucket = fmt.Sprintf("%-*.*s", maxSrcLen, maxSrcLen, target.SourceBucket)
}
if maxArnLen > 0 {
target.Arn = fmt.Sprintf("%-*.*s", maxArnLen, maxArnLen, target.Arn)
}
}
printMsg(RemoteMessage{
op: ctx.Command.Name,
AccessKey: target.Credentials.AccessKey,
TargetBucket: target.TargetBucket,
TargetURL: targetURL,
SourceBucket: target.SourceBucket,
RemoteARN: target.Arn,
ServiceType: string(target.Type),
ReplicationSync: target.ReplicationSync,
Bandwidth: target.BandwidthLimit,
Proxy: !target.DisableProxy,
ResetID: target.ResetID,
ResetBefore: target.ResetBeforeDate,
})
}
}
+45
View File
@@ -0,0 +1,45 @@
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
import "github.com/minio/cli"
var adminBucketRemoteSubcommands = []cli.Command{
adminBucketRemoteAddCmd,
adminBucketRemoteEditCmd,
adminBucketRemoteListCmd,
adminBucketRemoteRmCmd,
adminBwInfoCmd,
}
var adminBucketRemoteCmd = cli.Command{
Name: "remote",
Usage: "configure remote target buckets",
Action: mainadminBucketRemote,
Before: setGlobalsFromContext,
Flags: globalFlags,
Subcommands: adminBucketRemoteSubcommands,
HideHelpCommand: true,
}
// mainadminBucketRemote is the handle for "mc admin bucket remote" command.
func mainadminBucketRemote(ctx *cli.Context) error {
commandNotFound(ctx, adminBucketRemoteSubcommands)
return nil
// Sub-commands like "add", "ls", "rm" have their own main.
}
+93
View File
@@ -0,0 +1,93 @@
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
import (
"github.com/fatih/color"
"github.com/minio/cli"
"github.com/minio/mc/pkg/probe"
"github.com/minio/pkg/console"
)
var adminBucketRemoteRmFlags = []cli.Flag{
cli.StringFlag{
Name: "arn",
Usage: "ARN to be removed",
},
}
var adminBucketRemoteRmCmd = cli.Command{
Name: "rm",
Usage: "remove configured remote target",
Action: mainAdminBucketRemoteRemove,
OnUsageError: onUsageError,
Before: setGlobalsFromContext,
Flags: append(globalFlags, adminBucketRemoteRmFlags...),
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} TARGET
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Remove existing remote target with arn "arn:minio:replication:us-west-1:993bc6b6-accd-45e3-884f-5f3e652aed2a:dest1"
for bucket srcbucket on MinIO server.
{{.Prompt}} {{.HelpName}} myminio/srcbucket --arn "arn:minio:replication:us-west-1:993bc6b6-accd-45e3-884f-5f3e652aed2a:dest1"
`,
}
// checkAdminBucketRemoteRemoveSyntax - validate all the passed arguments
func checkAdminBucketRemoteRemoveSyntax(ctx *cli.Context) {
if len(ctx.Args()) != 1 {
cli.ShowCommandHelpAndExit(ctx, ctx.Command.Name, 1) // last argument is exit code
}
}
// mainAdminBucketRemoteRemove is the handle for "mc admin bucket remote rm" command.
func mainAdminBucketRemoteRemove(ctx *cli.Context) error {
checkAdminBucketRemoteRemoveSyntax(ctx)
console.SetColor("RemoteMessage", color.New(color.FgGreen))
// Get the alias parameter from cli
args := ctx.Args()
aliasedURL := args.Get(0)
// Create a new MinIO Admin Client
client, cerr := newAdminClient(aliasedURL)
fatalIf(cerr.Trace(aliasedURL), "Unable to initialize admin connection.")
_, sourceBucket := url2Alias(args[0])
if sourceBucket == "" {
fatalIf(errInvalidArgument(), "Source bucket not specified in `"+args[0]+"`.")
}
arn := ctx.String("arn")
if arn == "" {
fatalIf(errInvalidArgument(), "ARN needs to be specified.")
}
fatalIf(probe.NewError(client.RemoveRemoteTarget(globalContext, sourceBucket, arn)).Trace(args...), "Unable to remove remote target")
printMsg(RemoteMessage{
op: ctx.Command.Name,
SourceBucket: sourceBucket,
RemoteARN: arn,
})
return nil
}
+29 -25
View File
@@ -1,38 +1,42 @@
/*
* MinIO Client (C) 2020 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
import "github.com/minio/cli"
var adminBucketSubcommands = []cli.Command{
adminBucketRemoteCmd,
adminBucketQuotaCmd,
}
var adminBucketCmd = cli.Command{
Name: "bucket",
Usage: "manage buckets defined in the MinIO server",
Action: mainAdminBucket,
Before: setGlobalsFromContext,
Flags: globalFlags,
Subcommands: []cli.Command{
adminBucketQuotaCmd,
},
Name: "bucket",
Usage: "manage buckets defined in the MinIO server",
Action: mainAdminBucket,
Before: setGlobalsFromContext,
Flags: globalFlags,
Subcommands: adminBucketSubcommands,
HideHelpCommand: true,
}
// mainAdminBucket is the handle for "mc admin bucket" command.
func mainAdminBucket(ctx *cli.Context) error {
cli.ShowCommandHelp(ctx, ctx.Args().First())
commandNotFound(ctx, adminBucketSubcommands)
return nil
// Sub-commands like "quota", "usage" have their own main.
// Sub-commands like "quota", "remote" have their own main.
}
+138
View File
@@ -0,0 +1,138 @@
// Copyright (c) 2022 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
import (
"context"
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
"time"
"github.com/fatih/color"
"github.com/minio/cli"
json "github.com/minio/colorjson"
"github.com/minio/mc/pkg/probe"
"github.com/minio/pkg/console"
)
var adminClusterBucketExportCmd = cli.Command{
Name: "export",
Usage: "backup bucket metadata to a zip file",
Action: mainClusterBucketExport,
OnUsageError: onUsageError,
Before: setGlobalsFromContext,
Flags: globalFlags,
HideHelpCommand: true,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} [FLAGS] TARGET/[BUCKET]
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Download all bucket metadata for a bucket into zip file.
{{.Prompt}} {{.HelpName}} myminio/bucket
2. Download metadata of all buckets in cluster into zip file.
{{.Prompt}} {{.HelpName}} myminio
`,
}
func checkBucketExportSyntax(ctx *cli.Context) {
if len(ctx.Args()) != 1 {
cli.ShowCommandHelpAndExit(ctx, "export", 1) // last argument is exit code
}
}
// mainClusterBucketExport - metadata export command
func mainClusterBucketExport(ctx *cli.Context) error {
// Check for command syntax
checkBucketExportSyntax(ctx)
// Get the alias parameter from cli
args := ctx.Args()
aliasedURL := args.Get(0)
console.SetColor("File", color.New(color.FgWhite, color.Bold))
// Create a new MinIO Admin Client
client, err := newAdminClient(aliasedURL)
if err != nil {
fatalIf(err.Trace(aliasedURL), "Unable to initialize admin client.")
return nil
}
// Compute bucket and object from the aliased URL
aliasedURL = filepath.ToSlash(aliasedURL)
aliasedURL = filepath.Clean(aliasedURL)
_, bucket := url2Alias(aliasedURL)
r, ierr := client.ExportBucketMetadata(context.Background(), bucket)
fatalIf(probe.NewError(ierr).Trace(aliasedURL), "Unable to export bucket metadata.")
if bucket == "" {
bucket = "allbuckets"
}
// Create bucket metadata zip file
tmpFile, e := ioutil.TempFile("", fmt.Sprintf("%s-metadata-", bucket))
fatalIf(probe.NewError(e), "Unable to download file data.")
ext := "zip"
// Copy zip content to target download file
_, e = io.Copy(tmpFile, r)
fatalIf(probe.NewError(e), "Unable to download bucket metadata.")
// Close everything
r.Close()
tmpFile.Close()
// We use 4 bytes of the 32 bytes to identify the file.
downloadPath := fmt.Sprintf("%s-metadata.%s", bucket, ext)
fi, e := os.Stat(downloadPath)
if e == nil && !fi.IsDir() {
e = moveFile(downloadPath, downloadPath+"."+time.Now().Format(dateTimeFormatFilename))
fatalIf(probe.NewError(e), "Unable to create a backup of "+downloadPath)
} else {
if !os.IsNotExist(e) {
fatal(probe.NewError(e), "Unable to download file data")
}
}
fatalIf(probe.NewError(moveFile(tmpFile.Name(), downloadPath)), "Unable to rename downloaded data, file exists at %s", tmpFile.Name())
if !globalJSON {
console.Infof("Bucket metadata successfully downloaded as %s\n", downloadPath)
return nil
}
v := struct {
File string `json:"file"`
Key string `json:"key,omitempty"`
}{
File: downloadPath,
}
b, e := json.Marshal(v)
fatalIf(probe.NewError(e), "Unable to serialize data")
console.Println(string(b))
return nil
}
+109
View File
@@ -0,0 +1,109 @@
// Copyright (c) 2022 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
import (
"context"
"fmt"
"io"
"os"
"path/filepath"
"github.com/klauspost/compress/zip"
"github.com/minio/cli"
"github.com/minio/mc/pkg/probe"
"github.com/minio/pkg/console"
)
var adminClusterBucketImportCmd = cli.Command{
Name: "import",
Usage: "restore bucket metadata from a zip file",
Action: mainClusterBucketImport,
OnUsageError: onUsageError,
Before: setGlobalsFromContext,
Flags: globalFlags,
HideHelpCommand: true,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} [FLAGS] TARGET/[BUCKET] /path/to/backups/bucket-metadata.zip
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Set bucket metadata for 'mybucket' from previously exported metadata zip file.
{{.Prompt}} {{.HelpName}} myminio/mybucket /backups/mybucket-metadata.zip
2. Set bucket metadata for all buckets from previously exported metadata zip file.
{{.Prompt}} {{.HelpName}} myminio /backups/cluster-bucket-metadata.zip
`,
}
func checkBucketImportSyntax(ctx *cli.Context) {
if len(ctx.Args()) != 2 {
cli.ShowCommandHelpAndExit(ctx, "import", 1) // last argument is exit code
}
}
// mainClusterBucketImport - bucket metadata import command
func mainClusterBucketImport(ctx *cli.Context) error {
// Check for command syntax
checkBucketImportSyntax(ctx)
// Get the alias parameter from cli
args := ctx.Args()
aliasedURL := args.Get(0)
var r io.Reader
var sz int64
f, e := os.Open(args.Get(1))
if e != nil {
fatalIf(probe.NewError(e).Trace(args...), "Unable to get bucket metadata")
}
if st, e := f.Stat(); e == nil {
sz = st.Size()
}
defer f.Close()
r = f
_, e = zip.NewReader(r.(io.ReaderAt), sz)
fatalIf(probe.NewError(e).Trace(args...), fmt.Sprintf("Unable to read zip file %s", args.Get(1)))
f, e = os.Open(args.Get(1))
fatalIf(probe.NewError(e).Trace(args...), "Unable to get bucket metadata")
// Create a new MinIO Admin Client
client, err := newAdminClient(aliasedURL)
if err != nil {
fatalIf(err.Trace(aliasedURL), "Unable to initialize admin client.")
return nil
}
// Compute bucket and object from the aliased URL
aliasedURL = filepath.ToSlash(aliasedURL)
aliasedURL = filepath.Clean(aliasedURL)
_, bucket := url2Alias(aliasedURL)
ierr := client.ImportBucketMetadata(context.Background(), bucket, f)
fatalIf(probe.NewError(ierr).Trace(aliasedURL), "Unable to import bucket metadata.")
if !globalJSON {
console.Infof("Bucket metadata imported to %s from %s\n", bucket, args.Get(1))
}
return nil
}
+42
View File
@@ -0,0 +1,42 @@
// Copyright (c) 2022 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
import "github.com/minio/cli"
var adminClusterBucketSubcommands = []cli.Command{
adminClusterBucketImportCmd,
adminClusterBucketExportCmd,
}
var adminClusterBucketCmd = cli.Command{
Name: "bucket",
Usage: "manage bucket metadata on MinIO cluster",
Action: mainAdminClusterBucket,
Before: setGlobalsFromContext,
Flags: globalFlags,
Subcommands: adminClusterBucketSubcommands,
HideHelpCommand: true,
}
// mainAdminClusterBucket is the handle for "mc admin cluster bucket" command.
func mainAdminClusterBucket(ctx *cli.Context) error {
commandNotFound(ctx, adminClusterBucketSubcommands)
return nil
// Sub-commands like "export", "import" have their own main.
}
+125
View File
@@ -0,0 +1,125 @@
// Copyright (c) 2022 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
import (
"context"
"fmt"
"io"
"io/ioutil"
"os"
"time"
"github.com/fatih/color"
"github.com/minio/cli"
json "github.com/minio/colorjson"
"github.com/minio/mc/pkg/probe"
"github.com/minio/pkg/console"
)
var adminClusterIAMExportCmd = cli.Command{
Name: "export",
Usage: "exports IAM info to zipped file",
Action: mainClusterIAMExport,
OnUsageError: onUsageError,
Before: setGlobalsFromContext,
Flags: globalFlags,
HideHelpCommand: true,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} [FLAGS] TARGET
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Download all IAM metadata for cluster into zip file.
{{.Prompt}} {{.HelpName}} myminio
`,
}
func checkIAMExportSyntax(ctx *cli.Context) {
if len(ctx.Args()) != 1 {
cli.ShowCommandHelpAndExit(ctx, "export", 1) // last argument is exit code
}
}
// mainClusterIAMExport - metadata export command
func mainClusterIAMExport(ctx *cli.Context) error {
// Check for command syntax
checkIAMExportSyntax(ctx)
// Get the alias parameter from cli
args := ctx.Args()
aliasedURL := args.Get(0)
console.SetColor("File", color.New(color.FgWhite, color.Bold))
// Create a new MinIO Admin Client
client, err := newAdminClient(aliasedURL)
if err != nil {
fatalIf(err.Trace(aliasedURL), "Unable to initialize admin client.")
return nil
}
r, ierr := client.ExportIAM(context.Background())
fatalIf(probe.NewError(ierr).Trace(aliasedURL), "Unable to export IAM info.")
// Create iam info zip file
tmpFile, e := ioutil.TempFile("", fmt.Sprintf("%s-iam-info", aliasedURL))
fatalIf(probe.NewError(e), "Unable to download file data.")
ext := "zip"
// Copy zip content to target download file
_, e = io.Copy(tmpFile, r)
fatalIf(probe.NewError(e), "Unable to download IAM info.")
// Close everything
r.Close()
tmpFile.Close()
downloadPath := fmt.Sprintf("%s-iam-info.%s", aliasedURL, ext)
fi, e := os.Stat(downloadPath)
if e == nil && !fi.IsDir() {
e = moveFile(downloadPath, downloadPath+"."+time.Now().Format(dateTimeFormatFilename))
fatalIf(probe.NewError(e), "Unable to create a backup of "+downloadPath)
} else {
if !os.IsNotExist(e) {
fatal(probe.NewError(e), "Unable to download file data")
}
}
fatalIf(probe.NewError(moveFile(tmpFile.Name(), downloadPath)), "Unable to rename downloaded data, file exists at %s", tmpFile.Name())
if !globalJSON {
console.Infof("IAM info successfully downloaded as %s\n", downloadPath)
return nil
}
v := struct {
File string `json:"file"`
Key string `json:"key,omitempty"`
}{
File: downloadPath,
}
b, e := json.Marshal(v)
fatalIf(probe.NewError(e), "Unable to serialize data")
console.Println(string(b))
return nil
}
+101
View File
@@ -0,0 +1,101 @@
// Copyright (c) 2022 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
import (
"context"
"fmt"
"io"
"os"
"github.com/klauspost/compress/zip"
"github.com/minio/cli"
"github.com/minio/mc/pkg/probe"
"github.com/minio/pkg/console"
)
var adminClusterIAMImportCmd = cli.Command{
Name: "import",
Usage: "imports IAM info from zipped file",
Action: mainClusterIAMImport,
OnUsageError: onUsageError,
Before: setGlobalsFromContext,
Flags: globalFlags,
HideHelpCommand: true,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} [FLAGS] TARGET/BUCKET /path/to/myminio-iam-info.zip
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Set IAM info from previously exported metadata zip file.
{{.Prompt}} {{.HelpName}} myminio /tmp/myminio-iam-info.zip
`,
}
func checkIAMImportSyntax(ctx *cli.Context) {
if len(ctx.Args()) != 2 {
cli.ShowCommandHelpAndExit(ctx, "import", 1) // last argument is exit code
}
}
// mainClusterIAMImport - iam info import command
func mainClusterIAMImport(ctx *cli.Context) error {
// Check for command syntax
checkIAMImportSyntax(ctx)
// Get the alias parameter from cli
args := ctx.Args()
aliasedURL := args.Get(0)
var r io.Reader
var sz int64
f, e := os.Open(args.Get(1))
if e != nil {
fatalIf(probe.NewError(e).Trace(args...), "Unable to get IAM info")
}
if st, e := f.Stat(); e == nil {
sz = st.Size()
}
defer f.Close()
r = f
_, e = zip.NewReader(r.(io.ReaderAt), sz)
fatalIf(probe.NewError(e).Trace(args...), fmt.Sprintf("Unable to read zip file %s", args.Get(1)))
f, e = os.Open(args.Get(1))
fatalIf(probe.NewError(e).Trace(args...), "Unable to get IAM info")
// Create a new MinIO Admin Client
client, err := newAdminClient(aliasedURL)
if err != nil {
fatalIf(err.Trace(aliasedURL), "Unable to initialize admin client.")
return nil
}
ierr := client.ImportIAM(context.Background(), f)
fatalIf(probe.NewError(ierr).Trace(aliasedURL), "Unable to import IAM info.")
if !globalJSON {
console.Infof("IAM info imported to %s from %s\n", aliasedURL, args.Get(1))
}
return nil
}
+42
View File
@@ -0,0 +1,42 @@
// Copyright (c) 2022 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
import "github.com/minio/cli"
var adminClusterIAMSubcommands = []cli.Command{
adminClusterIAMImportCmd,
adminClusterIAMExportCmd,
}
var adminClusterIAMCmd = cli.Command{
Name: "iam",
Usage: "manage IAM info on MinIO cluster",
Action: mainadminClusterIAM,
Before: setGlobalsFromContext,
Flags: globalFlags,
Subcommands: adminClusterIAMSubcommands,
HideHelpCommand: true,
}
// mainadminClusterIAM is the handle for "mc admin cluster bucket" command.
func mainadminClusterIAM(ctx *cli.Context) error {
commandNotFound(ctx, adminClusterIAMSubcommands)
return nil
// Sub-commands like "export", "import" have their own main.
}
+42
View File
@@ -0,0 +1,42 @@
// Copyright (c) 2022 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
import "github.com/minio/cli"
var adminClusterSubcommands = []cli.Command{
adminClusterBucketCmd,
adminClusterIAMCmd,
}
var adminClusterCmd = cli.Command{
Name: "cluster",
Usage: "manage MinIO cluster metadata",
Action: mainAdminCluster,
Before: setGlobalsFromContext,
Flags: globalFlags,
Subcommands: adminClusterSubcommands,
HideHelpCommand: true,
}
// mainAdminCluster is the handle for "mc admin cluster" command.
func mainAdminCluster(ctx *cli.Context) error {
commandNotFound(ctx, adminClusterSubcommands)
return nil
// Sub-commands like "bucket", "iam" have their own main.
}
+24 -23
View File
@@ -1,33 +1,35 @@
/*
* 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.
*/
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
import (
"github.com/minio/cli"
json "github.com/minio/mc/pkg/colorjson"
json "github.com/minio/colorjson"
"github.com/minio/mc/pkg/probe"
)
var adminConfigExportCmd = cli.Command{
Name: "export",
Usage: "export all config keys to STDOUT",
Before: setGlobalsFromContext,
Action: mainAdminConfigExport,
Flags: globalFlags,
Name: "export",
Usage: "export all config keys to STDOUT",
Before: setGlobalsFromContext,
Action: mainAdminConfigExport,
OnUsageError: onUsageError,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
@@ -71,7 +73,6 @@ func checkAdminConfigExportSyntax(ctx *cli.Context) {
}
func mainAdminConfigExport(ctx *cli.Context) error {
checkAdminConfigExportSyntax(ctx)
// Export the alias parameter from cli
@@ -84,7 +85,7 @@ func mainAdminConfigExport(ctx *cli.Context) error {
// Call get config API
buf, e := client.GetConfig(globalContext)
fatalIf(probe.NewError(e), "Cannot get server config")
fatalIf(probe.NewError(e), "Unable to get server config")
// Print
printMsg(configExportMessage{
+51 -33
View File
@@ -1,18 +1,19 @@
/*
* MinIO Client (C) 2017-2019 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
@@ -20,16 +21,18 @@ import (
"strings"
"github.com/minio/cli"
json "github.com/minio/mc/pkg/colorjson"
json "github.com/minio/colorjson"
"github.com/minio/madmin-go"
"github.com/minio/mc/pkg/probe"
)
var adminConfigGetCmd = cli.Command{
Name: "get",
Usage: "interactively retrieve a config key parameters",
Before: setGlobalsFromContext,
Action: mainAdminConfigGet,
Flags: globalFlags,
Name: "get",
Usage: "interactively retrieve a config key parameters",
Before: setGlobalsFromContext,
Action: mainAdminConfigGet,
OnUsageError: onUsageError,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
@@ -56,13 +59,14 @@ EXAMPLES:
// configGetMessage container to hold locks information.
type configGetMessage struct {
Status string `json:"status"`
Value []byte `json:"value"`
Status string `json:"status"`
Value *madmin.Target `json:"value"`
value []byte
}
// String colorized service status message.
func (u configGetMessage) String() string {
return string(u.Value)
return string(u.value)
}
// JSON jsonified service status Message message.
@@ -82,7 +86,6 @@ func checkAdminConfigGetSyntax(ctx *cli.Context) {
}
func mainAdminConfigGet(ctx *cli.Context) error {
checkAdminConfigGetSyntax(ctx)
// Get the alias parameter from cli
@@ -96,7 +99,7 @@ func mainAdminConfigGet(ctx *cli.Context) error {
if len(ctx.Args()) == 1 {
// Call get config API
hr, e := client.HelpConfigKV(globalContext, "", "", false)
fatalIf(probe.NewError(e), "Cannot get help for the sub-system")
fatalIf(probe.NewError(e), "Unable to get help for the sub-system")
// Print
printMsg(configHelpMessage{
@@ -107,14 +110,29 @@ func mainAdminConfigGet(ctx *cli.Context) error {
return nil
}
// Call get config API
buf, e := client.GetConfigKV(globalContext, strings.Join(args.Tail(), " "))
fatalIf(probe.NewError(e), "Cannot get server '%s' config", args.Tail())
subSys := strings.Join(args.Tail(), " ")
// Print
printMsg(configGetMessage{
Value: buf,
})
// Call get config API
buf, e := client.GetConfigKV(globalContext, subSys)
fatalIf(probe.NewError(e), "Unable to get server '%s' config", args.Tail())
if globalJSON {
hr, e := client.HelpConfigKV(globalContext, subSys, "", false)
fatalIf(probe.NewError(e), "Unable to get help for "+subSys+" the sub-system")
tgt, e := madmin.ParseSubSysTarget(buf, hr)
fatalIf(probe.NewError(e), "Unable to parse sub-system target "+subSys)
printMsg(configGetMessage{
Value: tgt,
value: buf,
})
} else {
// Print
printMsg(configGetMessage{
value: buf,
})
}
return nil
}
+19 -18
View File
@@ -1,18 +1,19 @@
/*
* 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.
*/
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
@@ -22,9 +23,9 @@ import (
"text/template"
"github.com/fatih/color"
json "github.com/minio/mc/pkg/colorjson"
json "github.com/minio/colorjson"
"github.com/minio/madmin-go"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio/pkg/madmin"
)
// HelpTmpl template used by all sub-systems
@@ -66,7 +67,7 @@ func (u configHelpMessage) String() string {
} else {
e = HelpEnvTemplate.Execute(w, u.Value)
}
fatalIf(probe.NewError(e), "Cannot initialize template writer")
fatalIf(probe.NewError(e), "Unable to initialize template writer")
w.Flush()
+27 -26
View File
@@ -1,18 +1,19 @@
/*
* 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.
*/
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
@@ -23,9 +24,9 @@ import (
"github.com/fatih/color"
"github.com/minio/cli"
json "github.com/minio/mc/pkg/colorjson"
json "github.com/minio/colorjson"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio/pkg/console"
"github.com/minio/pkg/console"
)
var historyListFlags = []cli.Flag{
@@ -41,11 +42,12 @@ var historyListFlags = []cli.Flag{
}
var adminConfigHistoryCmd = cli.Command{
Name: "history",
Usage: "show all historic configuration changes",
Before: setGlobalsFromContext,
Action: mainAdminConfigHistory,
Flags: append(append([]cli.Flag{}, globalFlags...), historyListFlags...),
Name: "history",
Usage: "show all historic configuration changes",
Before: setGlobalsFromContext,
Action: mainAdminConfigHistory,
OnUsageError: onUsageError,
Flags: append(append([]cli.Flag{}, globalFlags...), historyListFlags...),
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
@@ -89,7 +91,7 @@ func (u configHistoryMessage) String() string {
var s strings.Builder
w := tabwriter.NewWriter(&s, 1, 8, 2, ' ', 0)
e := HistoryTemplate.Execute(w, u.Entries)
fatalIf(probe.NewError(e), "Cannot initialize template writer")
fatalIf(probe.NewError(e), "Unable to initialize template writer")
w.Flush()
return s.String()
@@ -112,7 +114,6 @@ func checkAdminConfigHistorySyntax(ctx *cli.Context) {
}
func mainAdminConfigHistory(ctx *cli.Context) error {
checkAdminConfigHistorySyntax(ctx)
console.SetColor("ConfigHistoryMessageRestoreID", color.New(color.Bold))
@@ -127,7 +128,7 @@ func mainAdminConfigHistory(ctx *cli.Context) error {
fatalIf(err, "Unable to initialize admin connection.")
if ctx.IsSet("clear") {
fatalIf(probe.NewError(client.ClearConfigHistoryKV(globalContext, "all")), "Cannot clear server configuration.")
fatalIf(probe.NewError(client.ClearConfigHistoryKV(globalContext, "all")), "Unable to clear server configuration.")
// Print
printMsg(configHistoryMessage{})
@@ -135,7 +136,7 @@ func mainAdminConfigHistory(ctx *cli.Context) error {
}
chEntries, e := client.ListConfigHistoryKV(globalContext, ctx.Int("count"))
fatalIf(probe.NewError(e), "Cannot list server history configuration.")
fatalIf(probe.NewError(e), "Unable to list server history configuration.")
hentries := make([]historyEntry, len(chEntries))
for i, chEntry := range chEntries {
+25 -24
View File
@@ -1,18 +1,19 @@
/*
* 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.
*/
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
@@ -22,17 +23,18 @@ import (
"github.com/fatih/color"
"github.com/minio/cli"
json "github.com/minio/mc/pkg/colorjson"
json "github.com/minio/colorjson"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio/pkg/console"
"github.com/minio/pkg/console"
)
var adminConfigImportCmd = cli.Command{
Name: "import",
Usage: "import multiple config keys from STDIN",
Before: setGlobalsFromContext,
Action: mainAdminConfigImport,
Flags: globalFlags,
Name: "import",
Usage: "import multiple config keys from STDIN",
Before: setGlobalsFromContext,
Action: mainAdminConfigImport,
OnUsageError: onUsageError,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
@@ -81,7 +83,6 @@ func checkAdminConfigImportSyntax(ctx *cli.Context) {
}
func mainAdminConfigImport(ctx *cli.Context) error {
checkAdminConfigImportSyntax(ctx)
// Set color preference of command outputs
@@ -96,7 +97,7 @@ func mainAdminConfigImport(ctx *cli.Context) error {
fatalIf(err, "Unable to initialize admin connection.")
// Call set config API
fatalIf(probe.NewError(client.SetConfig(globalContext, os.Stdin)), "Cannot set server config")
fatalIf(probe.NewError(client.SetConfig(globalContext, os.Stdin)), "Unable to set server config")
// Print
printMsg(configImportMessage{
+33 -28
View File
@@ -1,18 +1,19 @@
/*
* 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.
*/
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
@@ -22,9 +23,9 @@ import (
"github.com/fatih/color"
"github.com/minio/cli"
json "github.com/minio/mc/pkg/colorjson"
json "github.com/minio/colorjson"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio/pkg/console"
"github.com/minio/pkg/console"
)
var adminConfigEnvFlags = []cli.Flag{
@@ -35,11 +36,12 @@ var adminConfigEnvFlags = []cli.Flag{
}
var adminConfigResetCmd = cli.Command{
Name: "reset",
Usage: "interactively reset a config key parameters",
Before: setGlobalsFromContext,
Action: mainAdminConfigReset,
Flags: append(adminConfigEnvFlags, globalFlags...),
Name: "reset",
Usage: "interactively reset a config key parameters",
Before: setGlobalsFromContext,
Action: mainAdminConfigReset,
OnUsageError: onUsageError,
Flags: append(adminConfigEnvFlags, globalFlags...),
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
@@ -59,6 +61,7 @@ EXAMPLES:
type configResetMessage struct {
Status string `json:"status"`
targetAlias string
restart bool
}
// String colorized service status message.
@@ -66,8 +69,10 @@ func (u configResetMessage) String() (msg string) {
msg += console.Colorize("ResetConfigSuccess",
"Key is successfully reset.\n")
suggestion := fmt.Sprintf("mc admin service restart %s", u.targetAlias)
msg += console.Colorize("ResetConfigSuccess",
fmt.Sprintf("Please restart your server with `%s`.\n", suggestion))
if u.restart {
msg += console.Colorize("ResetConfigSuccess",
fmt.Sprintf("Please restart your server with `%s`.\n", suggestion))
}
return
}
@@ -89,7 +94,6 @@ func checkAdminConfigResetSyntax(ctx *cli.Context) {
// main config set function
func mainAdminConfigReset(ctx *cli.Context) error {
// Check command arguments
checkAdminConfigResetSyntax(ctx)
@@ -108,7 +112,7 @@ func mainAdminConfigReset(ctx *cli.Context) error {
if len(ctx.Args()) == 1 {
// Call get config API
hr, e := client.HelpConfigKV(globalContext, "", "", ctx.IsSet("env"))
fatalIf(probe.NewError(e), "Cannot get help for the sub-system")
fatalIf(probe.NewError(e), "Unable to get help for the sub-system")
// Print
printMsg(configHelpMessage{
@@ -121,12 +125,13 @@ func mainAdminConfigReset(ctx *cli.Context) error {
// Call reset config API
input := strings.Join(args.Tail(), " ")
fatalIf(probe.NewError(client.DelConfigKV(globalContext, input)),
"Cannot reset '%s' on the server", input)
restart, e := client.DelConfigKV(globalContext, input)
fatalIf(probe.NewError(e), "Unable to reset '%s' on the server", input)
// Print set config result
printMsg(configResetMessage{
targetAlias: aliasedURL,
restart: restart,
})
return nil
+25 -24
View File
@@ -1,18 +1,19 @@
/*
* 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.
*/
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
@@ -21,17 +22,18 @@ import (
"github.com/fatih/color"
"github.com/minio/cli"
json "github.com/minio/mc/pkg/colorjson"
json "github.com/minio/colorjson"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio/pkg/console"
"github.com/minio/pkg/console"
)
var adminConfigRestoreCmd = cli.Command{
Name: "restore",
Usage: "rollback back changes to a specific config history",
Before: setGlobalsFromContext,
Action: mainAdminConfigRestore,
Flags: globalFlags,
Name: "restore",
Usage: "rollback back changes to a specific config history",
Before: setGlobalsFromContext,
Action: mainAdminConfigRestore,
OnUsageError: onUsageError,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
@@ -80,7 +82,6 @@ func checkAdminConfigRestoreSyntax(ctx *cli.Context) {
}
func mainAdminConfigRestore(ctx *cli.Context) error {
checkAdminConfigRestoreSyntax(ctx)
console.SetColor("ConfigRestoreMessage", color.New(color.FgGreen))
@@ -94,7 +95,7 @@ func mainAdminConfigRestore(ctx *cli.Context) error {
fatalIf(err, "Unable to initialize admin connection.")
// Call get config API
fatalIf(probe.NewError(client.RestoreConfigHistoryKV(globalContext, args.Get(1))), "Cannot restore server configuration.")
fatalIf(probe.NewError(client.RestoreConfigHistoryKV(globalContext, args.Get(1))), "Unable to restore server configuration.")
// Print
printMsg(configRestoreMessage{
+39 -31
View File
@@ -1,18 +1,19 @@
/*
* MinIO Client (C) 2017-2019 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
@@ -22,18 +23,19 @@ import (
"github.com/fatih/color"
"github.com/minio/cli"
json "github.com/minio/mc/pkg/colorjson"
json "github.com/minio/colorjson"
"github.com/minio/madmin-go"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio/pkg/console"
"github.com/minio/minio/pkg/madmin"
"github.com/minio/pkg/console"
)
var adminConfigSetCmd = cli.Command{
Name: "set",
Usage: "interactively set a config key parameters",
Before: setGlobalsFromContext,
Action: mainAdminConfigSet,
Flags: append(adminConfigEnvFlags, globalFlags...),
Name: "set",
Usage: "interactively set a config key parameters",
Before: setGlobalsFromContext,
Action: mainAdminConfigSet,
OnUsageError: onUsageError,
Flags: append(adminConfigEnvFlags, globalFlags...),
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
@@ -49,6 +51,9 @@ EXAMPLES:
2. Change region name for the MinIO server to 'us-west-1'.
{{.Prompt}} {{.HelpName}} myminio/ region name=us-west-1
3. Change healing settings on a distributed MinIO server setup.
{{.Prompt}} {{.HelpName}} mydist/ heal max_delay=300ms max_io=50
`,
}
@@ -56,15 +61,18 @@ EXAMPLES:
type configSetMessage struct {
Status string `json:"status"`
targetAlias string
restart bool
}
// String colorized service status message.
func (u configSetMessage) String() (msg string) {
msg += console.Colorize("SetConfigSuccess",
"Setting new key has been successful.\n")
suggestion := fmt.Sprintf("mc admin service restart %s", u.targetAlias)
msg += console.Colorize("SetConfigSuccess",
fmt.Sprintf("Please restart your server with `%s`.\n", suggestion))
"Successfully applied new settings.")
if u.restart {
suggestion := color.RedString("mc admin service restart %s", u.targetAlias)
msg += console.Colorize("SetConfigSuccess",
fmt.Sprintf("\nPlease restart your server '%s'.", suggestion))
}
return
}
@@ -86,7 +94,6 @@ func checkAdminConfigSetSyntax(ctx *cli.Context) {
// main config set function
func mainAdminConfigSet(ctx *cli.Context) error {
// Check command arguments
checkAdminConfigSetSyntax(ctx)
@@ -106,7 +113,7 @@ func mainAdminConfigSet(ctx *cli.Context) error {
if !strings.Contains(input, madmin.KvSeparator) {
// Call get config API
hr, e := client.HelpConfigKV(globalContext, args.Get(1), args.Get(2), ctx.IsSet("env"))
fatalIf(probe.NewError(e), "Cannot get help for the sub-system")
fatalIf(probe.NewError(e), "Unable to get help for the sub-system")
// Print
printMsg(configHelpMessage{
@@ -119,12 +126,13 @@ func mainAdminConfigSet(ctx *cli.Context) error {
}
// Call set config API
fatalIf(probe.NewError(client.SetConfigKV(globalContext, input)),
"Cannot set '%s' to server", input)
restart, e := client.SetConfigKV(globalContext, input)
fatalIf(probe.NewError(e), "Unable to set '%s' to server", input)
// Print set config result
printMsg(configSetMessage{
targetAlias: aliasedURL,
restart: restart,
})
return nil
+33 -30
View File
@@ -1,44 +1,47 @@
/*
* MinIO Client (C) 2017-2019 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
import "github.com/minio/cli"
var adminConfigSubcommands = []cli.Command{
adminConfigGetCmd,
adminConfigSetCmd,
adminConfigResetCmd,
adminConfigHistoryCmd,
adminConfigRestoreCmd,
adminConfigExportCmd,
adminConfigImportCmd,
}
var adminConfigCmd = cli.Command{
Name: "config",
Usage: "manage MinIO server configuration",
Action: mainAdminConfig,
Before: setGlobalsFromContext,
Flags: globalFlags,
Subcommands: []cli.Command{
adminConfigGetCmd,
adminConfigSetCmd,
adminConfigResetCmd,
adminConfigHistoryCmd,
adminConfigRestoreCmd,
adminConfigExportCmd,
adminConfigImportCmd,
},
Name: "config",
Usage: "manage MinIO server configuration",
Action: mainAdminConfig,
Before: setGlobalsFromContext,
Flags: globalFlags,
Subcommands: adminConfigSubcommands,
HideHelpCommand: true,
}
// mainAdminConfig is the handle for "mc admin config" command.
func mainAdminConfig(ctx *cli.Context) error {
cli.ShowCommandHelp(ctx, ctx.Args().First())
commandNotFound(ctx, adminConfigSubcommands)
return nil
// Sub-commands like "get", "set" have their own main.
}
+39 -181
View File
@@ -1,37 +1,30 @@
/*
* 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.
*/
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
import (
"context"
"fmt"
"strings"
"time"
"github.com/fatih/color"
"github.com/minio/cli"
json "github.com/minio/mc/pkg/colorjson"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio/pkg/console"
"github.com/minio/minio/pkg/madmin"
"github.com/minio/pkg/console"
)
const logTimeFormat string = "15:04:05 MST 01/02/2006"
var adminConsoleFlags = []cli.Flag{
cli.IntFlag{
Name: "limit, l",
@@ -46,170 +39,35 @@ var adminConsoleFlags = []cli.Flag{
}
var adminConsoleCmd = cli.Command{
Name: "console",
Usage: "show console logs for MinIO server",
Action: mainAdminConsole,
Before: setGlobalsFromContext,
Flags: append(adminConsoleFlags, globalFlags...),
HideHelpCommand: true,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} [FLAGS] TARGET [NODENAME]
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Show console logs for a MinIO server with alias 'play'
{{.Prompt}} {{.HelpName}} play
2. Show last 5 log entries for node 'node1' on MinIO server with alias 'cluster1'
{{.Prompt}} {{.HelpName}} --limit 5 cluster1 node1
3. Show application error logs on MinIO server with alias 'play'
{{.Prompt}} {{.HelpName}} --type application play
`,
}
func checkAdminLogSyntax(ctx *cli.Context) {
if len(ctx.Args()) == 0 || len(ctx.Args()) > 3 {
cli.ShowCommandHelpAndExit(ctx, "console", 1) // last argument is exit code
}
}
// Extend madmin.LogInfo to add String() and JSON() methods
type logMessage struct {
madmin.LogInfo
}
// JSON - jsonify loginfo
func (l logMessage) JSON() string {
logJSON, err := json.MarshalIndent(&l, "", " ")
fatalIf(probe.NewError(err), "Unable to marshal into JSON.")
return string(logJSON)
}
func getLogTime(lt string) string {
tm, err := time.Parse(time.RFC3339Nano, lt)
if err != nil {
return lt
}
return tm.Format(logTimeFormat)
}
// String - return colorized loginfo as string.
func (l logMessage) String() string {
var hostStr string
var b = &strings.Builder{}
if l.NodeName != "" {
hostStr = fmt.Sprintf("%s ", colorizedNodeName(l.NodeName))
}
log := l.LogInfo
if log.ConsoleMsg != "" {
if strings.HasPrefix(log.ConsoleMsg, "\n") {
fmt.Fprintf(b, "%s\n", hostStr)
log.ConsoleMsg = strings.TrimPrefix(log.ConsoleMsg, "\n")
}
fmt.Fprintf(b, "%s %s", hostStr, log.ConsoleMsg)
return b.String()
}
if l.API != nil {
apiString := "API: " + l.API.Name + "("
if l.API.Args != nil && l.API.Args.Bucket != "" {
apiString = apiString + "bucket=" + l.API.Args.Bucket
}
if l.API.Args != nil && l.API.Args.Object != "" {
apiString = apiString + ", object=" + l.API.Args.Object
}
apiString += ")"
fmt.Fprintf(b, "\n%s %s", hostStr, console.Colorize("API", apiString))
}
if l.Time != "" {
fmt.Fprintf(b, "\n%s Time: %s", hostStr, getLogTime(l.Time))
}
if l.DeploymentID != "" {
fmt.Fprintf(b, "\n%s DeploymentID: %s", hostStr, l.DeploymentID)
}
if l.RequestID != "" {
fmt.Fprintf(b, "\n%s RequestID: %s", hostStr, l.RequestID)
}
if l.RemoteHost != "" {
fmt.Fprintf(b, "\n%s RemoteHost: %s", hostStr, l.RemoteHost)
}
if l.UserAgent != "" {
fmt.Fprintf(b, "\n%s UserAgent: %s", hostStr, l.UserAgent)
}
if l.Trace != nil {
if l.Trace.Message != "" {
fmt.Fprintf(b, "\n%s Error: %s", hostStr, console.Colorize("LogMessage", l.Trace.Message))
}
if l.Trace.Variables != nil {
for key, value := range l.Trace.Variables {
if value != "" {
fmt.Fprintf(b, "\n%s %s=%s", hostStr, key, value)
}
}
}
if l.Trace.Source != nil {
traceLength := len(l.Trace.Source)
for i, element := range l.Trace.Source {
fmt.Fprintf(b, "\n%s %8v: %s", hostStr, traceLength-i, element)
}
}
}
logMsg := strings.TrimPrefix(b.String(), "\n")
return fmt.Sprintf("%s\n", logMsg)
Name: "console",
Usage: "show MinIO logs",
Action: mainAdminConsole,
OnUsageError: onUsageError,
Before: setGlobalsFromContext,
Flags: append(adminConsoleFlags, globalFlags...),
Hidden: true,
HideHelpCommand: true,
CustomHelpTemplate: "This command is not supported now and replaced by 'support logs show' command. Please use 'mc support logs show'.\n",
}
// mainAdminConsole - the entry function of console command
func mainAdminConsole(ctx *cli.Context) error {
// Check for command syntax
checkAdminLogSyntax(ctx)
console.SetColor("LogMessage", color.New(color.Bold, color.FgRed))
console.SetColor("Api", color.New(color.Bold, color.FgWhite))
for _, c := range colors {
console.SetColor(fmt.Sprintf("Node%d", c), color.New(c))
}
aliasedURL := ctx.Args().Get(0)
var node string
if len(ctx.Args()) > 1 {
node = ctx.Args().Get(1)
}
var limit int
newCmd := []string{"mc support logs show"}
var flgStr string
if ctx.IsSet("limit") {
limit = ctx.Int("limit")
if limit <= 0 {
fatalIf(errInvalidArgument().Trace(ctx.Args()...), "please set a proper limit, for example: '--limit 5' to display last 5 logs, omit this flag to display all available logs")
}
}
logType := strings.ToLower(ctx.String("type"))
if logType != "minio" && logType != "application" && logType != "all" {
fatalIf(errInvalidArgument().Trace(ctx.Args()...), "Invalid value for --type flag. Valid options are [minio, application, all]")
}
// Create a new MinIO Admin Client
client, err := newAdminClient(aliasedURL)
if err != nil {
fatalIf(err.Trace(aliasedURL), "Cannot initialize admin client.")
return nil
flgStr = fmt.Sprintf("%s %d", "--last", ctx.Int("limit"))
newCmd = append(newCmd, flgStr)
}
ctxt, cancel := context.WithCancel(globalContext)
defer cancel()
// Start listening on all console log activity.
logCh := client.GetLogs(ctxt, node, limit, logType)
for logInfo := range logCh {
if logInfo.Err != nil {
fatalIf(probe.NewError(logInfo.Err), "Cannot listen to console logs")
}
// drop nodeName from output if specified as cli arg
if node != "" {
logInfo.NodeName = ""
}
printMsg(logMessage{logInfo})
if ctx.IsSet("type") {
flgStr = fmt.Sprintf("%s %s", "--type", strings.ToLower(ctx.String("type")))
newCmd = append(newCmd, flgStr)
}
newCmd = append(newCmd, ctx.Args()...)
msg := fmt.Sprintf("Please use '%s'", strings.Join(newCmd, " "))
console.Infoln(msg)
return nil
}
+139
View File
@@ -0,0 +1,139 @@
// Copyright (c) 2015-2022 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
import (
"path/filepath"
humanize "github.com/dustin/go-humanize"
"github.com/fatih/color"
"github.com/minio/cli"
"github.com/minio/madmin-go"
"github.com/minio/mc/pkg/probe"
"github.com/minio/pkg/console"
)
var adminDecommissionCancelCmd = cli.Command{
Name: "cancel",
Usage: "cancel an ongoing decommissioning of a pool",
Action: mainAdminDecommissionCancel,
OnUsageError: onUsageError,
Before: setGlobalsFromContext,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} TARGET
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Cancel an ongoing decommissioning of a pool.
{{.Prompt}} {{.HelpName}} myminio/ http://server{5...8}/disk{1...4}
2. List all ongoing decommissioning of pools.
{{.Prompt}} {{.HelpName}} myminio/
`,
}
// checkAdminDecommissionCancelSyntax - validate all the passed arguments
func checkAdminDecommissionCancelSyntax(ctx *cli.Context) {
if len(ctx.Args()) > 2 || len(ctx.Args()) == 0 {
cli.ShowCommandHelpAndExit(ctx, ctx.Command.Name, 1) // last argument is exit code
}
}
// mainAdminDecommissionCancel is the handle for "mc admin decommission cancel" command.
func mainAdminDecommissionCancel(ctx *cli.Context) error {
checkAdminDecommissionCancelSyntax(ctx)
// Get the alias parameter from cli
args := ctx.Args()
aliasedURL := args.Get(0)
aliasedURL = filepath.Clean(aliasedURL)
// Create a new MinIO Admin Client
client, err := newAdminClient(aliasedURL)
fatalIf(err, "Unable to initialize admin connection.")
if pool := args.Get(1); pool != "" {
e := client.CancelDecommissionPool(globalContext, pool)
fatalIf(probe.NewError(e).Trace(args...), "Unable to cancel decommissioning, please try again")
return nil
}
poolStatuses, e := client.ListPoolsStatus(globalContext)
fatalIf(probe.NewError(e).Trace(args...), "Unable to get status for all pools")
var newPoolStatuses []madmin.PoolStatus
for _, pool := range poolStatuses {
if pool.Decommission != nil {
if pool.Decommission.StartTime.IsZero() {
continue
}
if pool.Decommission.Complete {
continue
}
}
newPoolStatuses = append(newPoolStatuses, pool)
}
dspOrder := []col{colGreen} // Header
for i := 0; i < len(newPoolStatuses); i++ {
dspOrder = append(dspOrder, colGrey)
}
var printColors []*color.Color
for _, c := range dspOrder {
printColors = append(printColors, getPrintCol(c))
}
tbl := console.NewTable(printColors, []bool{false, false, false, false}, 0)
cellText := make([][]string, len(newPoolStatuses)+1)
cellText[0] = []string{
"ID",
"Pools",
"Capacity",
"Status",
}
for idx, pool := range poolStatuses {
idx++
totalSize := uint64(pool.Decommission.TotalSize)
currentSize := uint64(pool.Decommission.CurrentSize)
capacity := humanize.IBytes(totalSize-currentSize) + " (used) / " + humanize.IBytes(totalSize) + " (total)"
status := ""
if pool.Decommission != nil {
if pool.Decommission.StartTime.IsZero() {
continue
}
if pool.Decommission.Complete {
continue
}
status = "Draining"
}
cellText[idx] = []string{
humanize.Ordinal(pool.ID + 1),
pool.CmdLine,
capacity,
status,
}
}
return tbl.DisplayTable(cellText)
}
+102
View File
@@ -0,0 +1,102 @@
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
import (
"path/filepath"
"github.com/fatih/color"
"github.com/minio/cli"
json "github.com/minio/colorjson"
"github.com/minio/mc/pkg/probe"
"github.com/minio/pkg/console"
)
var adminDecommissionStartCmd = cli.Command{
Name: "start",
Usage: "start decommissioning a pool",
Action: mainAdminDecommissionStart,
OnUsageError: onUsageError,
Before: setGlobalsFromContext,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} TARGET
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Start decommissioning a pool for removal.
{{.Prompt}} {{.HelpName}} myminio/ http://server{5...8}/disk{1...4}
`,
}
// checkAdminDecommissionStartSyntax - validate all the passed arguments
func checkAdminDecommissionStartSyntax(ctx *cli.Context) {
if len(ctx.Args()) != 2 {
cli.ShowCommandHelpAndExit(ctx, ctx.Command.Name, 1) // last argument is exit code
}
}
// startDecomMessage is container for make bucket success and failure messages.
type startDecomMessage struct {
Status string `json:"status"`
Pool string `json:"pool"`
}
// String colorized construct a string message.
func (s startDecomMessage) String() string {
return console.Colorize("DecomPool", "Decommission started successfully for `"+s.Pool+"`.")
}
// JSON jsonified decom message.
func (s startDecomMessage) JSON() string {
startDecomBytes, e := json.MarshalIndent(s, "", " ")
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
return string(startDecomBytes)
}
// mainAdminDecommissionStart is the handle for "mc admin decommission start" command.
func mainAdminDecommissionStart(ctx *cli.Context) error {
checkAdminDecommissionStartSyntax(ctx)
// Additional command speific theme customization.
console.SetColor("DecomPool", color.New(color.FgGreen, color.Bold))
// Get the alias parameter from cli
args := ctx.Args()
aliasedURL := args.Get(0)
aliasedURL = filepath.Clean(aliasedURL)
// Create a new MinIO Admin Client
client, err := newAdminClient(aliasedURL)
fatalIf(err, "Unable to initialize admin connection.")
e := client.DecommissionPool(globalContext, args.Get(1))
fatalIf(probe.NewError(e).Trace(args...), "Unable to start decommission on the specified pool")
printMsg(startDecomMessage{
Status: "success",
Pool: args.Get(1),
})
return nil
}
+170
View File
@@ -0,0 +1,170 @@
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
import (
"fmt"
"path/filepath"
"time"
"github.com/dustin/go-humanize"
"github.com/fatih/color"
"github.com/minio/cli"
json "github.com/minio/colorjson"
"github.com/minio/mc/pkg/probe"
"github.com/minio/pkg/console"
)
var adminDecommissionStatusCmd = cli.Command{
Name: "status",
Usage: "show current decommissioning status",
Action: mainAdminDecommissionStatus,
OnUsageError: onUsageError,
Before: setGlobalsFromContext,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} TARGET
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Show current decommissioning status.
{{.Prompt}} {{.HelpName}} myminio/ http://server{5...8}/disk{1...4}
2. List all current decommissioning status of all pools.
{{.Prompt}} {{.HelpName}} myminio/
`,
}
// checkAdminDecommissionStatusSyntax - validate all the passed arguments
func checkAdminDecommissionStatusSyntax(ctx *cli.Context) {
if len(ctx.Args()) > 2 || len(ctx.Args()) == 0 {
cli.ShowCommandHelpAndExit(ctx, ctx.Command.Name, 1) // last argument is exit code
}
}
// mainAdminDecommissionStatus is the handle for "mc admin decomission status" command.
func mainAdminDecommissionStatus(ctx *cli.Context) error {
checkAdminDecommissionStatusSyntax(ctx)
// Get the alias parameter from cli
args := ctx.Args()
aliasedURL := args.Get(0)
aliasedURL = filepath.Clean(aliasedURL)
// Create a new MinIO Admin Client
client, err := newAdminClient(aliasedURL)
fatalIf(err, "Unable to initialize admin connection.")
if pool := args.Get(1); pool != "" {
poolStatus, e := client.StatusPool(globalContext, pool)
fatalIf(probe.NewError(e).Trace(args...), "Unable to get status per pool")
if globalJSON {
statusJSONBytes, e := json.MarshalIndent(poolStatus, "", " ")
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
console.Println(string(statusJSONBytes))
return nil
}
var msg string
if poolStatus.Decommission.Complete {
msg = color.GreenString(fmt.Sprintf("Decommission of pool %s is complete, you may now remove it from server command line", poolStatus.CmdLine))
} else if poolStatus.Decommission.Failed {
msg = color.GreenString(fmt.Sprintf("Decommission of pool %s failed, please retry again", poolStatus.CmdLine))
} else if poolStatus.Decommission.Canceled {
msg = color.GreenString(fmt.Sprintf("Decommission of pool %s was canceled, you may start again", poolStatus.CmdLine))
} else if !poolStatus.Decommission.StartTime.IsZero() {
usedStart := (poolStatus.Decommission.TotalSize - poolStatus.Decommission.StartSize)
usedCurrent := (poolStatus.Decommission.TotalSize - poolStatus.Decommission.CurrentSize)
if usedStart > usedCurrent {
duration := uint64(time.Since(poolStatus.Decommission.StartTime).Seconds())
copied := uint64(usedStart - usedCurrent)
speed := copied / duration
msg = "Decommissioning rate at " + humanize.IBytes(speed) + "/sec " + "[" + humanize.IBytes(
uint64(usedCurrent)) + "/" + humanize.IBytes(uint64(poolStatus.Decommission.TotalSize)) + "]"
msg += "\nStarted: " + humanize.RelTime(time.Now().UTC(), poolStatus.Decommission.StartTime, "", "ago")
} else {
msg = "Decommissioning is starting..."
}
msg = color.GreenString(msg)
} else {
errorIf(errDummy().Trace(args...), "This pool is currently not scheduled for decomissioning")
return nil
}
fmt.Println(msg)
return nil
}
poolStatuses, e := client.ListPoolsStatus(globalContext)
fatalIf(probe.NewError(e).Trace(args...), "Unable to get status for all pools")
if globalJSON {
statusJSONBytes, e := json.MarshalIndent(poolStatuses, "", " ")
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
console.Println(string(statusJSONBytes))
return nil
}
dspOrder := []col{colGreen} // Header
for i := 0; i < len(poolStatuses); i++ {
dspOrder = append(dspOrder, colGrey)
}
var printColors []*color.Color
for _, c := range dspOrder {
printColors = append(printColors, getPrintCol(c))
}
tbl := console.NewTable(printColors, []bool{false, false, false, false}, 0)
cellText := make([][]string, len(poolStatuses)+1)
cellText[0] = []string{
"ID",
"Pools",
"Capacity",
"Status",
}
for idx, pool := range poolStatuses {
idx++
totalSize := uint64(pool.Decommission.TotalSize)
currentSize := uint64(pool.Decommission.CurrentSize)
capacity := humanize.IBytes(totalSize-currentSize) + " (used) / " + humanize.IBytes(totalSize) + " (total)"
status := "Active"
if pool.Decommission != nil {
if pool.Decommission.Complete {
status = "Complete"
} else if pool.Decommission.Failed {
status = "Draining(Failed)"
} else if pool.Decommission.Canceled {
status = "Draining(Canceled)"
} else if !pool.Decommission.StartTime.IsZero() {
status = "Draining"
}
}
cellText[idx] = []string{
humanize.Ordinal(pool.ID + 1),
pool.CmdLine,
capacity,
status,
}
}
return tbl.DisplayTable(cellText)
}
+46
View File
@@ -0,0 +1,46 @@
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
import (
"github.com/minio/cli"
)
var adminDecommissionSubcommands = []cli.Command{
adminDecommissionStartCmd,
adminDecommissionStatusCmd,
adminDecommissionCancelCmd,
}
var adminDecommissionCmd = cli.Command{
Name: "decommission",
Aliases: []string{"decom"},
Usage: "manage MinIO server pool decommissioning",
Action: mainAdminDecommission,
Before: setGlobalsFromContext,
Flags: globalFlags,
Subcommands: adminDecommissionSubcommands,
HideHelpCommand: true,
}
// mainAdminDecommission is the handle for "mc admin decommission" command.
func mainAdminDecommission(ctx *cli.Context) error {
commandNotFound(ctx, adminDecommissionSubcommands)
return nil
// Sub-commands like "get", "set" have their own main.
}
+26 -24
View File
@@ -1,18 +1,19 @@
/*
* 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.
*/
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
@@ -22,18 +23,19 @@ import (
"github.com/fatih/color"
"github.com/minio/cli"
json "github.com/minio/mc/pkg/colorjson"
json "github.com/minio/colorjson"
"github.com/minio/madmin-go"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio/pkg/console"
"github.com/minio/minio/pkg/madmin"
"github.com/minio/pkg/console"
)
var adminGroupAddCmd = cli.Command{
Name: "add",
Usage: "add users to a new or existing group",
Action: mainAdminGroupAdd,
Before: setGlobalsFromContext,
Flags: globalFlags,
Name: "add",
Usage: "add users to a new or existing group",
Action: mainAdminGroupAdd,
OnUsageError: onUsageError,
Before: setGlobalsFromContext,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
@@ -131,7 +133,7 @@ func mainAdminGroupAdd(ctx *cli.Context) error {
Members: members,
IsRemove: false,
}
fatalIf(probe.NewError(client.UpdateGroupMembers(globalContext, gAddRemove)).Trace(args...), "Cannot add new group")
fatalIf(probe.NewError(client.UpdateGroupMembers(globalContext, gAddRemove)).Trace(args...), "Unable to add new group")
printMsg(groupMessage{
op: "add",
+22 -20
View File
@@ -1,18 +1,19 @@
/*
* 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.
*/
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
@@ -21,11 +22,12 @@ import (
)
var adminGroupDisableCmd = cli.Command{
Name: "disable",
Usage: "Disable a group",
Action: mainAdminGroupEnableDisable,
Before: setGlobalsFromContext,
Flags: globalFlags,
Name: "disable",
Usage: "disable a group",
Action: mainAdminGroupEnableDisable,
OnUsageError: onUsageError,
Before: setGlobalsFromContext,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
+24 -22
View File
@@ -1,18 +1,19 @@
/*
* 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.
*/
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
@@ -21,17 +22,18 @@ import (
"github.com/fatih/color"
"github.com/minio/cli"
"github.com/minio/madmin-go"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio/pkg/console"
"github.com/minio/minio/pkg/madmin"
"github.com/minio/pkg/console"
)
var adminGroupEnableCmd = cli.Command{
Name: "enable",
Usage: "Enable a group",
Action: mainAdminGroupEnableDisable,
Before: setGlobalsFromContext,
Flags: globalFlags,
Name: "enable",
Usage: "enable a group",
Action: mainAdminGroupEnableDisable,
OnUsageError: onUsageError,
Before: setGlobalsFromContext,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
+23 -21
View File
@@ -1,18 +1,19 @@
/*
* 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.
*/
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
@@ -20,15 +21,16 @@ import (
"github.com/fatih/color"
"github.com/minio/cli"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio/pkg/console"
"github.com/minio/pkg/console"
)
var adminGroupInfoCmd = cli.Command{
Name: "info",
Usage: "display group info",
Action: mainAdminGroupInfo,
Before: setGlobalsFromContext,
Flags: globalFlags,
Name: "info",
Usage: "display group info",
Action: mainAdminGroupInfo,
OnUsageError: onUsageError,
Before: setGlobalsFromContext,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
+23 -21
View File
@@ -1,18 +1,19 @@
/*
* 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.
*/
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
@@ -20,15 +21,16 @@ import (
"github.com/fatih/color"
"github.com/minio/cli"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio/pkg/console"
"github.com/minio/pkg/console"
)
var adminGroupListCmd = cli.Command{
Name: "list",
Usage: "display list of groups",
Action: mainAdminGroupList,
Before: setGlobalsFromContext,
Flags: globalFlags,
Name: "list",
Usage: "display list of groups",
Action: mainAdminGroupList,
OnUsageError: onUsageError,
Before: setGlobalsFromContext,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
+24 -22
View File
@@ -1,35 +1,37 @@
/*
* MinIO Client (C) 2019 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
import (
"github.com/fatih/color"
"github.com/minio/cli"
"github.com/minio/madmin-go"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio/pkg/console"
"github.com/minio/minio/pkg/madmin"
"github.com/minio/pkg/console"
)
var adminGroupRemoveCmd = cli.Command{
Name: "remove",
Usage: "remove group or members from a group",
Action: mainAdminGroupRemove,
Before: setGlobalsFromContext,
Flags: globalFlags,
Name: "remove",
Usage: "remove group or members from a group",
Action: mainAdminGroupRemove,
OnUsageError: onUsageError,
Before: setGlobalsFromContext,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
+32 -29
View File
@@ -1,43 +1,46 @@
/*
* MinIO Client (C) 2019 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
import "github.com/minio/cli"
var adminGroupSubcommands = []cli.Command{
adminGroupAddCmd,
adminGroupRemoveCmd,
adminGroupInfoCmd,
adminGroupListCmd,
adminGroupEnableCmd,
adminGroupDisableCmd,
}
var adminGroupCmd = cli.Command{
Name: "group",
Usage: "manage groups",
Action: mainAdminGroup,
Before: setGlobalsFromContext,
Flags: globalFlags,
Subcommands: []cli.Command{
adminGroupAddCmd,
adminGroupRemoveCmd,
adminGroupInfoCmd,
adminGroupListCmd,
adminGroupEnableCmd,
adminGroupDisableCmd,
},
Name: "group",
Usage: "manage groups",
Action: mainAdminGroup,
Before: setGlobalsFromContext,
Flags: globalFlags,
Subcommands: adminGroupSubcommands,
HideHelpCommand: true,
}
// mainAdminGroup is the handle for "mc admin config" command.
func mainAdminGroup(ctx *cli.Context) error {
cli.ShowCommandHelp(ctx, ctx.Args().First())
commandNotFound(ctx, adminGroupSubcommands)
return nil
// Sub-commands like "get", "set" have their own main.
}
+23 -17
View File
@@ -1,25 +1,26 @@
/*
* 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.
*/
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
import (
"fmt"
"github.com/minio/minio/pkg/madmin"
"github.com/minio/madmin-go"
)
type hri struct {
@@ -42,11 +43,16 @@ func (h hri) getObjectHCCChange() (b, a col, err error) {
b, err = getHColCode(surplusShardsBeforeHeal, parityShards)
if err != nil {
err = fmt.Errorf("%w: surplusShardsBeforeHeal: %d, parityShards: %d",
err, surplusShardsBeforeHeal, parityShards)
return
}
a, err = getHColCode(surplusShardsAfterHeal, parityShards)
if err != nil {
err = fmt.Errorf("%w: surplusShardsBeforeHeal: %d, parityShards: %d",
err, surplusShardsAfterHeal, parityShards)
}
return
}
// getReplicatedFileHCCChange - fetches health color code for metadata
+24 -26
View File
@@ -1,18 +1,19 @@
/*
* 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.
*/
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
@@ -25,10 +26,10 @@ import (
humanize "github.com/dustin/go-humanize"
"github.com/fatih/color"
json "github.com/minio/mc/pkg/colorjson"
json "github.com/minio/colorjson"
"github.com/minio/madmin-go"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio/pkg/console"
"github.com/minio/minio/pkg/madmin"
"github.com/minio/pkg/console"
)
const (
@@ -259,11 +260,12 @@ func (ui *uiData) printItemsJSON(s *madmin.HealTaskStatus) (err error) {
} `json:"after"`
Size int64 `json:"size"`
}
makeHR := func(h *hri) (r healRec, err error) {
makeHR := func(h *hri) (r healRec) {
r.Status = "success"
r.Type, r.Name = h.getHRTypeAndName()
var b, a col
var err error
switch h.Type {
case madmin.HealItemMetadata, madmin.HealItemBucket:
b, a, err = h.getReplicatedFileHCCChange()
@@ -274,7 +276,7 @@ func (ui *uiData) printItemsJSON(s *madmin.HealTaskStatus) (err error) {
b, a, err = h.getObjectHCCChange()
}
if err != nil {
return r, err
r.Error = err.Error()
}
r.Before.Color = strings.ToLower(string(b))
r.After.Color = strings.ToLower(string(a))
@@ -284,16 +286,12 @@ func (ui *uiData) printItemsJSON(s *madmin.HealTaskStatus) (err error) {
r.Before.Offline, r.After.Offline = h.GetOfflineCounts()
r.Before.Drives = h.Before.Drives
r.After.Drives = h.After.Drives
return r, nil
return r
}
for _, item := range s.Items {
h := newHRI(&item)
r, err := makeHR(h)
if err != nil {
return err
}
jsonBytes, err := json.MarshalIndent(r, "", " ")
jsonBytes, err := json.MarshalIndent(makeHR(h), "", " ")
fatalIf(probe.NewError(err), "Unable to marshal to JSON.")
console.Println(string(jsonBytes))
}
+465 -76
View File
@@ -1,33 +1,37 @@
/*
* 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.
*/
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
import (
"fmt"
"net/url"
"path/filepath"
"sort"
"strings"
"time"
humanize "github.com/dustin/go-humanize"
"github.com/fatih/color"
"github.com/minio/cli"
json "github.com/minio/mc/pkg/colorjson"
json "github.com/minio/colorjson"
"github.com/minio/madmin-go"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio/pkg/console"
"github.com/minio/minio/pkg/madmin"
"github.com/minio/pkg/console"
)
const (
@@ -55,18 +59,27 @@ var adminHealFlags = []cli.Flag{
},
cli.BoolFlag{
Name: "force-stop, s",
Usage: "Force stop a running heal sequence",
Usage: "force stop a running heal sequence",
},
cli.BoolFlag{
Name: "remove",
Usage: "remove dangling objects in heal sequence",
},
cli.StringFlag{
Name: "storage-class",
Usage: "show server/disks failure tolerance with the given storage class",
},
cli.BoolFlag{
Name: "verbose, v",
Usage: "show verbose information",
},
}
var adminHealCmd = cli.Command{
Name: "heal",
Usage: "heal disks, buckets and objects on MinIO server",
Action: mainAdminHeal,
OnUsageError: onUsageError,
Before: setGlobalsFromContext,
Flags: append(adminHealFlags, globalFlags...),
HideHelpCommand: true,
@@ -79,34 +92,9 @@ USAGE:
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
SCAN MODES:
normal (default): Heal objects which are missing on one or more disks.
deep : Heal objects which are missing or with silent data corruption on one or more disks.
EXAMPLES:
1. To format newly replaced disks in a MinIO server with alias 'myminio'
{{.Prompt}} {{.HelpName}} myminio
2. Heal 'testbucket' in a MinIO server with alias 'myminio'
{{.Prompt}} {{.HelpName}} myminio/testbucket/
3. Heal all objects under 'dir' prefix
{{.Prompt}} {{.HelpName}} --recursive myminio/testbucket/dir/
4. Issue a dry-run heal operation to inspect objects health but not heal them
{{.Prompt}} {{.HelpName}} --dry-run myminio
5. Issue a dry-run heal operation to inspect objects health under 'dir' prefix
{{.Prompt}} {{.HelpName}} --recursive --dry-run myminio/testbucket/dir/
6. Force start a running heal sequence (meaning it will force kill the running heal sequence and start a new one)
{{.Prompt}} {{.HelpName}} --force-start myminio/testbucket/dir/
7. Force stop a running heal sequence (meaning it will force kill the running heal sequence)
{{.Prompt}} {{.HelpName}} --force-stop myminio/testbucket/dir/
8. Issue a dry-run heal operation to inspect objects health under 'dir' prefix
{{.Prompt}} {{.HelpName}} --dry-run myminio/testbucket/dir/
1. Monitor healing status on a running server at alias 'myminio':
{{.Prompt}} {{.HelpName}} myminio/
`,
}
@@ -142,37 +130,422 @@ func (s stopHealMessage) JSON() string {
return string(stopHealJSONBytes)
}
// backgroundHealStatusMessage is container for stop heal success and failure messages.
type backgroundHealStatusMessage struct {
type setIndex struct {
pool, set int
}
type poolInfo struct {
tolerance int
endpoints []string
}
type diskInfo struct {
set setIndex
path string
state string
healStarted, healLastUpdate time.Time
usedSpace, totalSpace uint64
}
type setInfo struct {
maxUsedSpace uint64
totalDisks int
incapableDisks int
}
type serverInfo struct {
pool int
disks []diskInfo
}
func (s serverInfo) onlineDisksForSet(index setIndex) (setFound bool, count int) {
for _, disk := range s.disks {
if disk.set != index {
continue
}
setFound = true
if disk.state == "ok" && disk.healStarted.IsZero() {
count++
}
}
return
}
// Get all disks from set statuses
func getAllDisks(sets []madmin.SetStatus) []madmin.Disk {
var disks []madmin.Disk
for _, set := range sets {
disks = append(disks, set.Disks...)
}
return disks
}
// Get all pools id from all disks
func getPoolsIndexes(disks []madmin.Disk) []int {
m := make(map[int]struct{})
for _, d := range disks {
m[d.PoolIndex] = struct{}{}
}
var pools []int
for pool := range m {
pools = append(pools, pool)
}
sort.Ints(pools)
return pools
}
// Generate sets info from disks
func generateSetsStatus(disks []madmin.Disk) map[setIndex]setInfo {
m := make(map[setIndex]setInfo)
for _, d := range disks {
idx := setIndex{pool: d.PoolIndex, set: d.SetIndex}
setSt, ok := m[idx]
if !ok {
setSt = setInfo{}
}
setSt.totalDisks++
if d.UsedSpace > setSt.maxUsedSpace {
setSt.maxUsedSpace = d.UsedSpace
}
if d.State != "ok" || d.Healing {
setSt.incapableDisks++
}
m[idx] = setSt
}
return m
}
// Return a map of server endpoints and the corresponding status
func generateServersStatus(disks []madmin.Disk) map[string]serverInfo {
m := make(map[string]serverInfo)
for _, d := range disks {
u, err := url.Parse(d.Endpoint)
if err != nil {
continue
}
endpoint := u.Host
if endpoint == "" {
endpoint = "local-pool" + humanize.Ordinal(d.PoolIndex+1)
}
serverSt, ok := m[endpoint]
if !ok {
serverSt = serverInfo{
pool: d.PoolIndex,
}
}
setIndex := setIndex{pool: d.PoolIndex, set: d.SetIndex}
di := diskInfo{
set: setIndex,
path: u.Path,
state: d.State,
usedSpace: d.UsedSpace,
totalSpace: d.TotalSpace,
}
if d.HealInfo != nil {
di.healStarted = d.HealInfo.Started
di.healLastUpdate = d.HealInfo.LastUpdate
}
serverSt.disks = append(serverSt.disks, di)
m[endpoint] = serverSt
}
return m
}
// Return the list of endpoints of a given pool index
func computePoolEndpoints(pool int, serversStatus map[string]serverInfo) []string {
var endpoints []string
for endpoint, server := range serversStatus {
if server.pool != pool {
continue
}
endpoints = append(endpoints, endpoint)
}
return endpoints
}
// Compute the tolerance of each node in a given pool
func computePoolTolerance(pool, parity int, setsStatus map[setIndex]setInfo, serversStatus map[string]serverInfo) int {
var (
onlineDisksPerSet = make(map[setIndex]int)
tolerancePerSet = make(map[setIndex]int)
)
for set, setStatus := range setsStatus {
if set.pool != pool {
continue
}
onlineDisksPerSet[set] = setStatus.totalDisks - setStatus.incapableDisks
tolerancePerSet[set] = 0
for _, server := range serversStatus {
if server.pool != pool {
continue
}
canShutdown := true
setFound, count := server.onlineDisksForSet(set)
if !setFound {
continue
}
minDisks := setStatus.totalDisks - parity
if onlineDisksPerSet[set]-count < minDisks {
canShutdown = false
}
if canShutdown {
tolerancePerSet[set]++
onlineDisksPerSet[set] -= count
} else {
break
}
}
}
minServerTolerance := len(serversStatus)
for _, tolerance := range tolerancePerSet {
if tolerance < minServerTolerance {
minServerTolerance = tolerance
}
}
return minServerTolerance
}
// Extract offline nodes from offline full path endpoints
func getOfflineNodes(endpoints []string) map[string]struct{} {
offlineNodes := make(map[string]struct{})
for _, endpoint := range endpoints {
offlineNodes[endpoint] = struct{}{}
}
return offlineNodes
}
// verboseBackgroundHealStatusMessage is container for stop heal success and failure messages.
type verboseBackgroundHealStatusMessage struct {
Status string `json:"status"`
HealInfo madmin.BgHealState
// Specify storage class to show servers/disks tolerance
ToleranceForSC string `json:"-"`
}
// String colorized to show background heal status message.
func (s verboseBackgroundHealStatusMessage) String() string {
var msg strings.Builder
parity, showTolerance := s.HealInfo.SCParity[s.ToleranceForSC]
offlineEndpoints := getOfflineNodes(s.HealInfo.OfflineEndpoints)
allDisks := getAllDisks(s.HealInfo.Sets)
pools := getPoolsIndexes(allDisks)
setsStatus := generateSetsStatus(allDisks)
serversStatus := generateServersStatus(allDisks)
poolsInfo := make(map[int]poolInfo)
for _, pool := range pools {
tolerance := computePoolTolerance(pool, parity, setsStatus, serversStatus)
endpoints := computePoolEndpoints(pool, serversStatus)
poolsInfo[pool] = poolInfo{tolerance: tolerance, endpoints: endpoints}
}
distributed := len(serversStatus) > 1
plural := ""
if distributed {
plural = "s"
}
fmt.Fprintf(&msg, "Server%s status:\n", plural)
fmt.Fprintf(&msg, "==============\n")
for _, pool := range pools {
fmt.Fprintf(&msg, "Pool %s:\n", humanize.Ordinal(pool+1))
// Sort servers in this pool by name
orderedEndpoints := make([]string, len(poolsInfo[pool].endpoints))
copy(orderedEndpoints, poolsInfo[pool].endpoints)
sort.Strings(orderedEndpoints)
for _, endpoint := range orderedEndpoints {
// Print offline status if node is offline
_, ok := offlineEndpoints[endpoint]
if ok {
stateText := console.Colorize("NodeFailed", "OFFLINE")
fmt.Fprintf(&msg, fmt.Sprintf(" %s: %s\n", endpoint, stateText))
continue
}
serverStatus := serversStatus[endpoint]
switch {
case showTolerance:
serverHeader := " %s: (Tolerance: %d server(s))\n"
fmt.Fprintf(&msg, fmt.Sprintf(serverHeader, endpoint, poolsInfo[serverStatus.pool].tolerance))
default:
serverHeader := " %s:\n"
fmt.Fprintf(&msg, fmt.Sprintf(serverHeader, endpoint))
}
for _, d := range serverStatus.disks {
if d.set.pool != pool {
continue
}
stateText := ""
switch {
case d.state == "ok" && !d.healStarted.IsZero():
stateText = console.Colorize("DiskHealing", "HEALING")
case d.state == "ok":
stateText = console.Colorize("DiskOK", "OK")
default:
stateText = console.Colorize("DiskFailed", d.state)
}
fmt.Fprintf(&msg, " + %s : %s\n", d.path, stateText)
if !d.healStarted.IsZero() {
now := time.Now().UTC()
scanSpeed := float64(d.usedSpace) / float64(now.Sub(d.healStarted))
remainingTime := time.Duration(float64(setsStatus[d.set].maxUsedSpace-d.usedSpace) / scanSpeed)
estimationText := humanize.RelTime(now, now.Add(remainingTime), "", "")
fmt.Fprintf(&msg, " |__ Estimated: %s\n", estimationText)
}
fmt.Fprintf(&msg, " |__ Capacity: %s/%s\n", humanize.IBytes(d.usedSpace), humanize.IBytes(d.totalSpace))
if showTolerance {
fmt.Fprintf(&msg, " |__ Tolerance: %d disk(s)\n", parity-setsStatus[d.set].incapableDisks)
}
}
fmt.Fprintf(&msg, "\n")
}
}
if showTolerance {
fmt.Fprintf(&msg, "\n")
fmt.Fprintf(&msg, "Server Failure Tolerance:\n")
fmt.Fprintf(&msg, "========================\n")
for i, pool := range poolsInfo {
fmt.Fprintf(&msg, "Pool %s:\n", humanize.Ordinal(i+1))
fmt.Fprintf(&msg, " Tolerance : %d server(s)\n", pool.tolerance)
fmt.Fprintf(&msg, " Nodes :")
for _, endpoint := range pool.endpoints {
fmt.Fprintf(&msg, " %s", endpoint)
}
fmt.Fprintf(&msg, "\n")
}
}
summary := shortBackgroundHealStatusMessage{HealInfo: s.HealInfo}
fmt.Fprintf(&msg, "\n")
fmt.Fprintf(&msg, "Summary:\n")
fmt.Fprintf(&msg, "=======\n")
fmt.Fprintf(&msg, summary.String())
fmt.Fprintf(&msg, "\n")
return msg.String()
}
// JSON jsonified stop heal message.
func (s verboseBackgroundHealStatusMessage) JSON() string {
healJSONBytes, e := json.MarshalIndent(s, "", " ")
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
return string(healJSONBytes)
}
// shortBackgroundHealStatusMessage is container for stop heal success and failure messages.
type shortBackgroundHealStatusMessage struct {
Status string `json:"status"`
HealInfo madmin.BgHealState
}
// String colorized to show background heal status message.
func (s backgroundHealStatusMessage) String() string {
dot := console.Colorize("Dot", " ● ")
func (s shortBackgroundHealStatusMessage) String() string {
healPrettyMsg := ""
var (
totalItems uint64
totalBytes uint64
itemsHealed uint64
bytesHealed uint64
startedAt time.Time
healPrettyMsg := console.Colorize("HealBackgroundTitle", "Background healing status:\n")
healPrettyMsg += dot + fmt.Sprintf("%s item(s) scanned in total\n",
console.Colorize("HealBackground", s.HealInfo.ScannedItemsCount))
// The addition of Elapsed time of each parallel healing operation
// this is needed to calculate the rate of healing
accumulatedElapsedTime time.Duration
lastHealingTime := dot + "Never executed"
if !s.HealInfo.LastHealActivity.IsZero() {
lastHealingTime = dot + "Completed " + timeDurationToHumanizedDuration(time.Since(s.HealInfo.LastHealActivity)).StringShort() + " ago"
// ETA of healing - it is the latest ETA of all disks currently healing
healingRemaining time.Duration
)
dedup := make(map[setIndex]struct{})
for _, set := range s.HealInfo.Sets {
setsStatus := generateSetsStatus(set.Disks)
for _, disk := range set.Disks {
if disk.HealInfo != nil {
// Avoid counting two disks beloning to the same pool/set
diskSet := setIndex{pool: disk.PoolIndex, set: disk.SetIndex}
_, found := dedup[diskSet]
if found {
continue
}
dedup[diskSet] = struct{}{}
// Approximate values
totalItems += disk.HealInfo.ObjectsTotalCount
totalBytes += disk.HealInfo.ObjectsTotalSize
itemsHealed += disk.HealInfo.ItemsHealed
bytesHealed += disk.HealInfo.BytesDone
if !disk.HealInfo.Started.IsZero() {
if !disk.HealInfo.Started.Before(startedAt) {
startedAt = disk.HealInfo.Started
}
if !disk.HealInfo.LastUpdate.IsZero() {
accumulatedElapsedTime += disk.HealInfo.LastUpdate.Sub(disk.HealInfo.Started)
}
scanSpeed := float64(disk.UsedSpace) / float64(time.Now().Sub(disk.HealInfo.Started))
remainingTime := time.Duration(float64(setsStatus[diskSet].maxUsedSpace-disk.UsedSpace) / scanSpeed)
if remainingTime > healingRemaining {
healingRemaining = remainingTime
}
}
}
}
}
healPrettyMsg += console.Colorize("HealBackground", lastHealingTime) + "\n"
if startedAt.IsZero() && itemsHealed == 0 {
healPrettyMsg += "No active healing in progress."
return healPrettyMsg
}
if totalItems > 0 && totalBytes > 0 {
// Objects healed information
itemsPct := 100 * float64(itemsHealed) / float64(totalItems)
bytesPct := 100 * float64(bytesHealed) / float64(totalBytes)
healPrettyMsg += fmt.Sprintf("Objects Healed: %s/%s (%s), %s/%s (%s)\n",
humanize.Comma(int64(itemsHealed)), humanize.Comma(int64(totalItems)), humanize.CommafWithDigits(itemsPct, 1)+"%%",
humanize.Bytes(bytesHealed), humanize.Bytes(totalBytes), humanize.CommafWithDigits(bytesPct, 1)+"%%")
} else {
healPrettyMsg += fmt.Sprintf("Objects Healed: %s, %s\n", humanize.Comma(int64(itemsHealed)), humanize.Bytes(bytesHealed))
}
if accumulatedElapsedTime > 0 {
bytesHealedPerSec := float64(uint64(time.Second)*bytesHealed) / float64(accumulatedElapsedTime)
itemsHealedPerSec := float64(uint64(time.Second)*itemsHealed) / float64(accumulatedElapsedTime)
healPrettyMsg += fmt.Sprintf("Heal rate: %d obj/s, %s/s\n", int64(itemsHealedPerSec), humanize.IBytes(uint64(bytesHealedPerSec)))
}
// Estimation completion
now := time.Now()
if !s.HealInfo.NextHealRound.IsZero() && s.HealInfo.NextHealRound.After(now) {
nextHealingRound := timeDurationToHumanizedDuration(s.HealInfo.NextHealRound.Sub(now)).StringShort()
healPrettyMsg += dot + fmt.Sprintf("Next scheduled in %s\n", console.Colorize("HealBackground", nextHealingRound))
}
healPrettyMsg += fmt.Sprintf("Estimated Completion: %s\n", humanize.RelTime(now, now.Add(healingRemaining), "", ""))
return healPrettyMsg
}
// JSON jsonified stop heal message.
func (s backgroundHealStatusMessage) JSON() string {
func (s shortBackgroundHealStatusMessage) JSON() string {
healJSONBytes, e := json.MarshalIndent(s, "", " ")
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
@@ -189,7 +562,6 @@ func transformScanArg(scanArg string) madmin.HealScanMode {
// mainAdminHeal - the entry function of heal command
func mainAdminHeal(ctx *cli.Context) error {
// Check for command syntax
checkAdminHealSyntax(ctx)
@@ -204,10 +576,15 @@ func mainAdminHeal(ctx *cli.Context) error {
console.SetColor("HealUpdateUI", color.New(color.FgYellow, color.Bold))
console.SetColor("HealStopped", color.New(color.FgGreen, color.Bold))
console.SetColor("DiskHealing", color.New(color.FgYellow, color.Bold))
console.SetColor("DiskOK", color.New(color.FgGreen, color.Bold))
console.SetColor("DiskFailed", color.New(color.FgRed, color.Bold))
console.SetColor("NodeFailed", color.New(color.FgRed, color.Bold))
// Create a new MinIO Admin Client
client, err := newAdminClient(aliasedURL)
adminClnt, err := newAdminClient(aliasedURL)
if err != nil {
fatalIf(err.Trace(aliasedURL), "Cannot initialize admin client.")
fatalIf(err.Trace(aliasedURL), "Unable to initialize admin client.")
return nil
}
@@ -221,22 +598,34 @@ func mainAdminHeal(ctx *cli.Context) error {
fatalIf(err.Trace(clnt.GetURL().String()), "Unable to create client for URL ", aliasedURL)
return nil
}
for content := range clnt.List(false, false, false, DirNone) {
if content.Err != nil {
fatalIf(content.Err.Trace(clnt.GetURL().String()), "Unable to heal bucket `"+bucket+"`.")
return nil
}
}
// Return the background heal status when the user
// doesn't pass a bucket or --recursive flag.
if bucket == "" && !ctx.Bool("recursive") {
bgHealStatus, berr := client.BackgroundHealStatus(globalContext)
bgHealStatus, berr := adminClnt.BackgroundHealStatus(globalContext)
fatalIf(probe.NewError(berr), "Failed to get the status of the background heal.")
printMsg(backgroundHealStatusMessage{Status: "success", HealInfo: bgHealStatus})
if ctx.Bool("verbose") {
printMsg(verboseBackgroundHealStatusMessage{
Status: "success",
HealInfo: bgHealStatus,
ToleranceForSC: strings.ToUpper(ctx.String("storage-class")),
})
} else {
printMsg(shortBackgroundHealStatusMessage{
Status: "success",
HealInfo: bgHealStatus,
})
}
return nil
}
for content := range clnt.List(globalContext, ListOptions{Recursive: false, ShowDir: DirNone}) {
if content.Err != nil {
fatalIf(content.Err.Trace(clnt.GetURL().String()), "Unable to heal bucket `"+bucket+"`.")
return nil
}
}
opts := madmin.HealOpts{
ScanMode: transformScanArg(ctx.String("scan")),
Remove: ctx.Bool("remove"),
@@ -247,19 +636,19 @@ func mainAdminHeal(ctx *cli.Context) error {
forceStart := ctx.Bool("force-start")
forceStop := ctx.Bool("force-stop")
if forceStop {
_, _, herr := client.Heal(globalContext, bucket, prefix, opts, "", forceStart, forceStop)
_, _, herr := adminClnt.Heal(globalContext, bucket, prefix, opts, "", forceStart, forceStop)
fatalIf(probe.NewError(herr), "Failed to stop heal sequence.")
printMsg(stopHealMessage{Status: "success", Alias: aliasedURL})
return nil
}
healStart, _, herr := client.Heal(globalContext, bucket, prefix, opts, "", forceStart, false)
healStart, _, herr := adminClnt.Heal(globalContext, bucket, prefix, opts, "", forceStart, false)
fatalIf(probe.NewError(herr), "Failed to start heal sequence.")
ui := uiData{
Bucket: bucket,
Prefix: prefix,
Client: client,
Client: adminClnt,
ClientToken: healStart.ClientToken,
ForceStart: forceStart,
HealOpts: &opts,
+139
View File
@@ -0,0 +1,139 @@
// Copyright (c) 2015-2022 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
import (
"errors"
"fmt"
"strings"
"github.com/charmbracelet/lipgloss"
"github.com/minio/cli"
json "github.com/minio/colorjson"
"github.com/minio/madmin-go"
"github.com/minio/mc/pkg/probe"
)
var adminIDPInfoCmd = cli.Command{
Name: "info",
Usage: "Show IDP server config info",
Before: setGlobalsFromContext,
Action: mainAdminIDPGet,
OnUsageError: onUsageError,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} TARGET ID_TYPE [CFG_NAME]
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Show configuration info for default (un-named) openid configuration.
{{.Prompt}} {{.HelpName}} play/ openid
2. Show configuration info for openid configuration named "dex_test".
{{.Prompt}} {{.HelpName}} play/ openid dex_test
`,
}
func mainAdminIDPGet(ctx *cli.Context) error {
if len(ctx.Args()) < 2 || len(ctx.Args()) > 3 {
cli.ShowCommandHelpAndExit(ctx, "get", 1)
}
args := ctx.Args()
aliasedURL := args.Get(0)
// Create a new MinIO Admin Client
client, err := newAdminClient(aliasedURL)
fatalIf(err, "Unable to initialize admin connection.")
idpType := args.Get(1)
if idpType != "openid" {
fatalIf(probe.NewError(errors.New("not implemented")), "This feature is not yet available")
}
var cfgName string
if len(args) == 3 {
cfgName = args.Get(2)
}
result, e := client.GetIDPConfig(globalContext, idpType, cfgName)
fatalIf(probe.NewError(e), "Unable to get IDP config for '%s' to server", idpType)
// Print set config result
printMsg(idpConfig(result))
return nil
}
type idpConfig madmin.IDPConfig
func (i idpConfig) JSON() string {
bs, e := json.MarshalIndent(i, "", " ")
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
return string(bs)
}
func (i idpConfig) String() string {
// Determine required width for key column.
fieldColWidth := 0
for _, kv := range i.Info {
if fieldColWidth < len(kv.Key) {
fieldColWidth = len(kv.Key)
}
}
// Add 1 for the colon-suffix in each entry.
fieldColWidth++
fieldColStyle := lipgloss.NewStyle().
Width(fieldColWidth).
Foreground(lipgloss.Color("#04B575")). // green
Bold(true).
Align(lipgloss.Right)
valueColStyle := lipgloss.NewStyle().
PaddingLeft(1).
Align(lipgloss.Left)
envMarkStyle := lipgloss.NewStyle().
Foreground(lipgloss.Color("201")). // pinkish-red
PaddingLeft(1)
var lines []string
for _, kv := range i.Info {
envStr := ""
if kv.IsCfg && kv.IsEnv {
envStr = " (environment)"
}
lines = append(lines, fmt.Sprintf("%s%s%s",
fieldColStyle.Render(kv.Key+":"),
valueColStyle.Render(kv.Value),
envMarkStyle.Render(envStr),
))
}
boxContent := strings.Join(lines, "\n")
boxStyle := lipgloss.NewStyle().
BorderStyle(lipgloss.RoundedBorder())
return boxStyle.Render(boxContent)
}
+171
View File
@@ -0,0 +1,171 @@
// Copyright (c) 2015-2022 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
import (
"encoding/json"
"errors"
"strings"
"github.com/charmbracelet/lipgloss"
"github.com/minio/cli"
"github.com/minio/madmin-go"
"github.com/minio/mc/pkg/probe"
)
var adminIDPLsCmd = cli.Command{
Name: "ls",
Usage: "List IDP configurations",
Before: setGlobalsFromContext,
Action: mainAdminIDPList,
OnUsageError: onUsageError,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} TARGET ID_TYPE
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. List the available openid configurations.
{{.Prompt}} {{.HelpName}} play/ openid
`,
}
func mainAdminIDPList(ctx *cli.Context) error {
if len(ctx.Args()) != 2 {
cli.ShowCommandHelpAndExit(ctx, "ls", 1)
}
args := ctx.Args()
aliasedURL := args.Get(0)
// Create a new MinIO Admin Client
client, err := newAdminClient(aliasedURL)
fatalIf(err, "Unable to initialize admin connection.")
idpType := args.Get(1)
if idpType != "openid" {
fatalIf(probe.NewError(errors.New("not implemented")), "This feature is not yet available")
}
result, e := client.ListIDPConfig(globalContext, idpType)
fatalIf(probe.NewError(e), "Unable to list IDP config for '%s'", idpType)
printMsg(idpCfgList(result))
return nil
}
type idpCfgList []madmin.IDPListItem
func (i idpCfgList) JSON() string {
bs, e := json.MarshalIndent(i, "", " ")
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
return string(bs)
}
func (i idpCfgList) String() string {
maxNameWidth := len("Name")
maxRoleARNWidth := len("RoleArn")
for _, item := range i {
name := item.Name
if name == "_" {
name = "(default)" // for the un-named config, don't show `_`
}
if maxNameWidth < len(name) {
maxNameWidth = len(name)
}
if maxRoleARNWidth < len(item.RoleARN) {
maxRoleARNWidth = len(item.RoleARN)
}
}
enabledWidth := 5
// Add 2 for padding
maxNameWidth += 2
maxRoleARNWidth += 2
enabledColStyle := lipgloss.NewStyle().
Align(lipgloss.Center).
PaddingLeft(1).
PaddingRight(1).
Width(enabledWidth)
nameColStyle := lipgloss.NewStyle().
Align(lipgloss.Right).
PaddingLeft(1).
PaddingRight(1).
Width(maxNameWidth)
arnColStyle := lipgloss.NewStyle().
Align(lipgloss.Left).
PaddingLeft(1).
PaddingRight(1).
Foreground(lipgloss.Color("#04B575")). // green
Width(maxRoleARNWidth)
styles := []lipgloss.Style{enabledColStyle, nameColStyle, arnColStyle}
headers := []string{"On?", "Name", "RoleARN"}
headerRow := []string{}
// Override some style settings for the header
for ii, hdr := range headers {
headerRow = append(headerRow,
styles[ii].Copy().
Bold(true).
Foreground(lipgloss.Color("#6495ed")). // green
Align(lipgloss.Center).
Render(hdr),
)
}
lines := []string{strings.Join(headerRow, "")}
enabledOff := "🔴"
enabledOn := "🟢"
for _, item := range i {
enabled := enabledOff
if item.Enabled {
enabled = enabledOn
}
line := []string{
styles[0].Render(enabled),
styles[1].Render(item.Name),
styles[2].Render(item.RoleARN),
}
if item.Name == "_" {
// For default config, don't display `_` and make it look faint.
line[1] = styles[1].Copy().
Faint(true).
Render("(default)")
}
lines = append(lines, strings.Join(line, ""))
}
boxContent := strings.Join(lines, "\n")
boxStyle := lipgloss.NewStyle().
BorderStyle(lipgloss.RoundedBorder())
return boxStyle.Render(boxContent)
}
+78
View File
@@ -0,0 +1,78 @@
// Copyright (c) 2015-2022 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
import (
"errors"
"github.com/minio/cli"
"github.com/minio/mc/pkg/probe"
)
var adminIDPRmCmd = cli.Command{
Name: "rm",
Usage: "Remove an IDP configuration",
Before: setGlobalsFromContext,
Action: mainAdminIDPRemove,
OnUsageError: onUsageError,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} TARGET IDP_TYPE CFG_NAME
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Remove an OpenID configuration from the server.
{{.Prompt}} {{.HelpName}} play/ openid myidp
`,
}
func mainAdminIDPRemove(ctx *cli.Context) error {
if len(ctx.Args()) != 3 {
cli.ShowCommandHelpAndExit(ctx, "rm", 1)
}
args := ctx.Args()
aliasedURL := args.Get(0)
// Create a new MinIO Admin Client
client, err := newAdminClient(aliasedURL)
fatalIf(err, "Unable to initialize admin connection.")
idpType := args.Get(1)
if idpType != "openid" {
fatalIf(probe.NewError(errors.New("not implemented")), "This feature is not yet available")
}
cfgName := args.Get(2)
restart, e := client.DeleteIDPConfig(globalContext, idpType, cfgName)
fatalIf(probe.NewError(e), "Unable to remove %s IDP config '%s'", idpType, cfgName)
printMsg(configSetMessage{
targetAlias: aliasedURL,
restart: restart,
})
return nil
}
+102
View File
@@ -0,0 +1,102 @@
// Copyright (c) 2015-2022 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
import (
"errors"
"strings"
"github.com/minio/cli"
"github.com/minio/mc/pkg/probe"
)
var adminIDPSetCmd = cli.Command{
Name: "set",
Usage: "Create/Update an IDP server configuration",
Before: setGlobalsFromContext,
Action: mainAdminIDPSet,
OnUsageError: onUsageError,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} TARGET ID_TYPE [CFG_NAME] [CFG_PARAMS...]
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Create/Update the default OpenID IDP configuration (CFG_NAME is omitted).
{{.Prompt}} {{.HelpName}} play/ openid \
client_id=minio-client-app \
client_secret=minio-client-app-secret \
config_url="http://localhost:5556/dex/.well-known/openid-configuration" \
scopes="openid,groups" \
redirect_uri="http://127.0.0.1:10000/oauth_callback" \
role_policy="consoleAdmin"
2. Create/Update configuration for OpenID IDP configuration named "dex_test".
{{.Prompt}} {{.HelpName}} play/ openid dex_test \
client_id=minio-client-app \
client_secret=minio-client-app-secret \
config_url="http://localhost:5556/dex/.well-known/openid-configuration" \
scopes="openid,groups" \
redirect_uri="http://127.0.0.1:10000/oauth_callback" \
role_policy="consoleAdmin"
`,
}
func mainAdminIDPSet(ctx *cli.Context) error {
if len(ctx.Args()) < 3 {
cli.ShowCommandHelpAndExit(ctx, "set", 1)
}
args := ctx.Args()
aliasedURL := args.Get(0)
// Create a new MinIO Admin Client
client, err := newAdminClient(aliasedURL)
fatalIf(err, "Unable to initialize admin connection.")
idpType := args.Get(1)
if idpType != "openid" {
fatalIf(probe.NewError(errors.New("not implemented")), "This feature is not yet available")
}
var cfgName string
input := args[2:]
if !strings.Contains(args.Get(2), "=") {
cfgName = args.Get(2)
input = args[3:]
}
inputCfg := strings.Join(input, " ")
restart, e := client.SetIDPConfig(globalContext, idpType, cfgName, inputCfg)
fatalIf(probe.NewError(e), "Unable to set IDP config for '%s' to server", idpType)
// Print set config result
printMsg(configSetMessage{
targetAlias: aliasedURL,
restart: restart,
})
return nil
}
+42
View File
@@ -0,0 +1,42 @@
// Copyright (c) 2015-2022 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
import "github.com/minio/cli"
var adminIDPSubcommands = []cli.Command{
adminIDPSetCmd,
adminIDPInfoCmd,
adminIDPLsCmd,
adminIDPRmCmd,
}
var adminIDPCmd = cli.Command{
Name: "idp",
Usage: "manage MinIO IDentity Provider server configuration",
Action: mainAdminIDP,
Before: setGlobalsFromContext,
Flags: globalFlags,
Subcommands: adminIDPSubcommands,
HideHelpCommand: true,
}
func mainAdminIDP(ctx *cli.Context) error {
commandNotFound(ctx, adminIDPSubcommands)
return nil
}
+182 -54
View File
@@ -1,25 +1,26 @@
/*
* 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.
*/
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
import (
"errors"
"fmt"
"reflect"
"sort"
"strconv"
"strings"
"time"
@@ -28,18 +29,20 @@ import (
"github.com/dustin/go-humanize/english"
"github.com/fatih/color"
"github.com/minio/cli"
json "github.com/minio/mc/pkg/colorjson"
json "github.com/minio/colorjson"
"github.com/minio/madmin-go"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio/pkg/console"
"github.com/minio/minio/pkg/madmin"
"github.com/minio/minio-go/v7/pkg/set"
"github.com/minio/pkg/console"
)
var adminInfoCmd = cli.Command{
Name: "info",
Usage: "display MinIO server information",
Action: mainAdminInfo,
Before: setGlobalsFromContext,
Flags: globalFlags,
Name: "info",
Usage: "display MinIO server information",
Action: mainAdminInfo,
OnUsageError: onUsageError,
Before: setGlobalsFromContext,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
@@ -55,6 +58,54 @@ EXAMPLES:
`,
}
type poolSummary struct {
setsCount int
disksPerSet int
endpoints set.StringSet
}
type clusterInfo map[int]*poolSummary
func clusterSummaryInfo(info madmin.InfoMessage) clusterInfo {
summary := make(clusterInfo)
for _, srv := range info.Servers {
for _, disk := range srv.Disks {
pool := summary[disk.PoolIndex]
if pool == nil {
pool = &poolSummary{endpoints: set.NewStringSet()}
}
pool.endpoints.Add(srv.Endpoint)
for _, disk := range srv.Disks {
if disk.SetIndex > pool.setsCount {
pool.setsCount = disk.SetIndex
}
if disk.DiskIndex > pool.disksPerSet {
pool.disksPerSet = disk.DiskIndex
}
}
summary[disk.PoolIndex] = pool
}
}
// We calculated max set index and max disk index
// increase by one to show the number of sets and disks
for _, pool := range summary {
pool.setsCount++
pool.disksPerSet++
}
return summary
}
func endpointToPools(endpoint string, c clusterInfo) (pools []int) {
for poolNumber, poolSummary := range c {
if poolSummary.endpoints.Contains(endpoint) {
pools = append(pools, poolNumber)
}
}
sort.Ints(pools)
return
}
// Wrap "Info" message together with fields "Status" and "Error"
type clusterStruct struct {
Status string `json:"status"`
@@ -78,12 +129,12 @@ type clusterStruct struct {
func (u clusterStruct) String() (msg string) {
// Check cluster level "Status" field for error
if u.Status == "error" {
fatal(probe.NewError(errors.New(u.Error)), "Cannot get service status")
fatal(probe.NewError(errors.New(u.Error)), "Unable to get service status")
}
// If nothing has been collected, error out
if u.Info.Servers == nil {
fatal(probe.NewError(errors.New("Cannot get service status")), "")
fatal(probe.NewError(errors.New("Unable to get service status")), "")
}
// Initialization
@@ -93,21 +144,39 @@ func (u clusterStruct) String() (msg string) {
// Color palette initialization
console.SetColor("Info", color.New(color.FgGreen, color.Bold))
console.SetColor("InfoFail", color.New(color.FgRed, color.Bold))
console.SetColor("InfoWarning", color.New(color.FgYellow, color.Bold))
// MinIO server type default
backendType := "Unknown"
backendType := madmin.Unknown
// Set the type of MinIO server ("FS", "Erasure", "Unknown")
v := reflect.ValueOf(u.Info.Backend)
if v.Kind() == reflect.Map {
for _, key := range v.MapKeys() {
val := v.MapIndex(key)
switch t := val.Interface().(type) {
case string:
backendType = t
switch v := u.Info.Backend.(type) {
case madmin.FSBackend:
backendType = madmin.FS
case madmin.ErasureBackend:
backendType = madmin.Erasure
case map[string]interface{}:
vt, ok := v["backendType"]
if ok {
backendTypeS, _ := vt.(string)
switch backendTypeS {
case "Erasure":
backendType = madmin.Erasure
}
}
}
coloredDot := console.Colorize("Info", dot)
if madmin.ItemState(u.Info.Mode) == madmin.ItemInitializing {
coloredDot = console.Colorize("InfoWarning", dot)
}
sort.Slice(u.Info.Servers, func(i, j int) bool {
return u.Info.Servers[i].Endpoint < u.Info.Servers[j].Endpoint
})
clusterSummary := clusterSummaryInfo(u.Info)
// Loop through each server and put together info for each one
for _, srv := range u.Info.Servers {
// Check if MinIO server is offline ("Mode" field),
@@ -115,13 +184,38 @@ func (u clusterStruct) String() (msg string) {
if srv.State == "offline" {
// "PrintB" is color blue in console library package
msg += fmt.Sprintf("%s %s\n", console.Colorize("InfoFail", dot), console.Colorize("PrintB", srv.Endpoint))
msg += fmt.Sprintf(" Uptime: %s\n\n", console.Colorize("InfoFail", "offline"))
msg += fmt.Sprintf(" Uptime: %s\n", console.Colorize("InfoFail", "offline"))
if backendType == madmin.Erasure {
// Info about drives on a server, only available for non-FS types
var OffDisks int
var OnDisks int
var dispNoOfDisks string
for _, disk := range srv.Disks {
switch disk.State {
case madmin.DriveStateOk, madmin.DriveStateUnformatted:
OnDisks++
default:
OffDisks++
}
}
totalDisksPerServer := OnDisks + OffDisks
totalOnlineDisksCluster += OnDisks
totalOfflineDisksCluster += OffDisks
dispNoOfDisks = strconv.Itoa(OnDisks) + "/" + strconv.Itoa(totalDisksPerServer)
msg += fmt.Sprintf(" Drives: %s %s\n", dispNoOfDisks, console.Colorize("InfoFail", "OK "))
}
msg += "\n"
// Continue to the next server
continue
}
// Print server title
msg += fmt.Sprintf("%s %s\n", console.Colorize("Info", dot), console.Colorize("PrintB", srv.Endpoint))
msg += fmt.Sprintf("%s %s\n", coloredDot, console.Colorize("PrintB", srv.Endpoint))
// Uptime
msg += fmt.Sprintf(" Uptime: %s\n", console.Colorize("Info",
@@ -133,29 +227,33 @@ func (u clusterStruct) String() (msg string) {
version = "<development>"
}
msg += fmt.Sprintf(" Version: %s\n", version)
// Network info, only available for non-FS types
var connectionAlive int
totalNodes := strconv.Itoa(len(srv.Network))
if srv.Network != nil {
connectionAlive := 0
totalNodes := len(srv.Network)
if srv.Network != nil && backendType == madmin.Erasure {
for _, v := range srv.Network {
if v == "online" {
connectionAlive++
}
}
displayNwInfo := strconv.Itoa(connectionAlive) + "/" + totalNodes
msg += fmt.Sprintf(" Network: %s %s\n", displayNwInfo, console.Colorize("Info", "OK "))
clr := "Info"
if connectionAlive != totalNodes {
clr = "InfoWarning"
}
displayNwInfo := strconv.Itoa(connectionAlive) + "/" + strconv.Itoa(totalNodes)
msg += fmt.Sprintf(" Network: %s %s\n", displayNwInfo, console.Colorize(clr, "OK "))
}
if backendType != "FS" {
if backendType == madmin.Erasure {
// Info about drives on a server, only available for non-FS types
var OffDisks int
var OnDisks int
var dispNoOfDisks string
for _, disk := range srv.Disks {
if disk.State == "ok" {
switch disk.State {
case madmin.DriveStateOk, madmin.DriveStateUnformatted:
OnDisks++
} else {
default:
OffDisks++
}
}
@@ -163,29 +261,59 @@ func (u clusterStruct) String() (msg string) {
totalDisksPerServer := OnDisks + OffDisks
totalOnlineDisksCluster += OnDisks
totalOfflineDisksCluster += OffDisks
clr := "Info"
if OnDisks != totalDisksPerServer {
clr = "InfoWarning"
}
dispNoOfDisks = strconv.Itoa(OnDisks) + "/" + strconv.Itoa(totalDisksPerServer)
msg += fmt.Sprintf(" Drives: %s %s\n", dispNoOfDisks, console.Colorize("Info", "OK "))
msg += fmt.Sprintf(" Drives: %s %s\n", dispNoOfDisks, console.Colorize(clr, "OK "))
// Print pools belonging to this server
var prettyPools []string
for _, pool := range endpointToPools(srv.Endpoint, clusterSummary) {
prettyPools = append(prettyPools, strconv.Itoa(pool+1))
}
msg += fmt.Sprintf(" Pool: %s\n", console.Colorize("Info", fmt.Sprintf("%+v", strings.Join(prettyPools, ", "))))
}
msg += "\n"
}
if backendType == madmin.Erasure {
msg += fmt.Sprintf("Pools:\n")
for pool, summary := range clusterSummary {
msg += fmt.Sprintf(" %s, Erasure sets: %d, Disks per erasure set: %d\n",
console.Colorize("Info", humanize.Ordinal(pool+1)), summary.setsCount, summary.disksPerSet)
}
}
msg += "\n"
// Summary on used space, total no of buckets and
// total no of objects at the Cluster level
usedTotal := humanize.IBytes(uint64(u.Info.Usage.Size))
usedTotal := humanize.IBytes(u.Info.Usage.Size)
if u.Info.Buckets.Count > 0 {
msg += fmt.Sprintf("%s Used, %s, %s\n", usedTotal,
msg += fmt.Sprintf("%s Used, %s, %s", usedTotal,
english.Plural(int(u.Info.Buckets.Count), "Bucket", ""),
english.Plural(int(u.Info.Objects.Count), "Object", ""))
if u.Info.Versions.Count > 0 {
msg += ", " + english.Plural(int(u.Info.Versions.Count), "Version", "")
}
msg += "\n"
}
if backendType != "FS" {
if backendType == madmin.Erasure {
// Summary on total no of online and total
// number of offline disks at the Cluster level
msg += fmt.Sprintf("%s online, %s offline\n",
english.Plural(totalOnlineDisksCluster, "drive", ""),
english.Plural(totalOfflineDisksCluster, "drive", ""))
bkInfo, ok := u.Info.Backend.(madmin.ErasureBackend)
if ok {
msg += fmt.Sprintf("%s online, %s offline\n",
english.Plural(bkInfo.OnlineDisks, "drive", ""),
english.Plural(bkInfo.OfflineDisks, "drive", ""))
} else {
msg += fmt.Sprintf("%s online, %s offline\n",
english.Plural(totalOnlineDisksCluster, "drive", ""),
english.Plural(totalOfflineDisksCluster, "drive", ""))
}
}
// Remove the last new line if any
@@ -231,7 +359,7 @@ func mainAdminInfo(ctx *cli.Context) error {
clusterInfo.Error = ""
}
clusterInfo.Info = admInfo
printMsg(clusterStruct(clusterInfo))
printMsg(clusterInfo)
return nil
}
+40
View File
@@ -0,0 +1,40 @@
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
import (
"github.com/minio/cli"
"github.com/minio/pkg/console"
)
var adminInspectCmd = cli.Command{
Name: "inspect",
Usage: "inspect files on MinIO server",
Action: mainAdminInspect,
OnUsageError: onUsageError,
Before: setGlobalsFromContext,
HideHelpCommand: true,
Hidden: true,
CustomHelpTemplate: "Please use 'mc support inspect'",
}
// mainAdminHeal - the entry function of heal command
func mainAdminInspect(ctx *cli.Context) error {
console.Infoln("Please use 'mc support inspect'")
return nil
}
+70
View File
@@ -0,0 +1,70 @@
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
import (
"fmt"
"os"
"github.com/fatih/color"
"github.com/minio/cli"
"github.com/minio/mc/pkg/probe"
"github.com/minio/pkg/console"
"golang.org/x/crypto/ssh/terminal"
)
var adminKMSCreateKeyCmd = cli.Command{
Name: "create",
Usage: "creates a new master key at the KMS",
Action: mainAdminKMSCreateKey,
OnUsageError: onUsageError,
Before: setGlobalsFromContext,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} TARGET [KEY_NAME]
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Create a new master key named 'my-key' default master key.
$ {{.HelpName}} play my-key
`,
}
// adminKMSCreateKeyCmd is the handler for the "mc admin kms key create" command.
func mainAdminKMSCreateKey(ctx *cli.Context) error {
if len(ctx.Args()) != 2 {
cli.ShowCommandHelpAndExit(ctx, "create", 1) // last argument is exit code
}
client, err := newAdminClient(ctx.Args().Get(0))
fatalIf(err, "Cannot get a configured admin connection.")
keyID := ctx.Args().Get(1)
e := client.CreateKey(globalContext, keyID)
fatalIf(probe.NewError(e), "Failed to create master key")
if terminal.IsTerminal(int(os.Stdout.Fd())) {
console.Println(color.GreenString(fmt.Sprintf("Created master key `%s` successfully", keyID)))
}
return nil
}
+68 -42
View File
@@ -1,35 +1,39 @@
/*
* MinIO Client (C) 2020 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
import (
"fmt"
"github.com/fatih/color"
"github.com/minio/cli"
json "github.com/minio/colorjson"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio/pkg/madmin"
"github.com/minio/pkg/console"
)
var adminKMSKeyStatusCmd = cli.Command{
Name: "status",
Usage: "request status information for a KMS master key",
Action: mainAdminKMSKeyStatus,
Before: setGlobalsFromContext,
Flags: globalFlags,
Name: "status",
Usage: "request status information for a KMS master key",
Action: mainAdminKMSKeyStatus,
OnUsageError: onUsageError,
Before: setGlobalsFromContext,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
@@ -43,7 +47,7 @@ EXAMPLES:
1. Get default master key and its status from a MinIO server/cluster.
$ {{.HelpName}} play
2. Get the status of one particular master key from a MinIO server/cluster.
$ {{.HelpName}} play my-master-key
$ {{.HelpName}} play my-master-key
`,
}
@@ -53,8 +57,11 @@ func mainAdminKMSKeyStatus(ctx *cli.Context) error {
cli.ShowCommandHelpAndExit(ctx, "status", 1) // last argument is exit code
}
console.SetColor("StatusSuccess", color.New(color.FgGreen, color.Bold))
console.SetColor("StatusError", color.New(color.FgRed, color.Bold))
client, err := newAdminClient(ctx.Args().Get(0))
fatalIf(err, "Cannot get a configured admin connection.")
fatalIf(err, "Unable to get a configured admin connection.")
var keyID string
if len(ctx.Args()) == 2 {
@@ -63,29 +70,48 @@ func mainAdminKMSKeyStatus(ctx *cli.Context) error {
status, e := client.GetKeyStatus(globalContext, keyID)
fatalIf(probe.NewError(e), "Failed to get status information")
printMsg(kmsKeyStatusMsg(*status))
printMsg(kmsKeyStatusMsg{
KeyID: status.KeyID,
Encryption: status.EncryptionErr == "",
Decryption: status.DecryptionErr == "",
EncryptionErr: status.EncryptionErr,
DecryptionErr: status.DecryptionErr,
})
return nil
}
type kmsKeyStatusMsg madmin.KMSKeyStatus
func (s kmsKeyStatusMsg) String() string {
msg := fmt.Sprintf("Key: %s\n", s.KeyID)
if s.EncryptionErr == "" {
msg = fmt.Sprintf("%s %s", msg, "\t • Encryption ✔\n")
} else {
return fmt.Sprintf("%s \t • Encryption failed: %s\n", msg, s.EncryptionErr)
}
if s.DecryptionErr == "" {
msg = fmt.Sprintf("%s %s", msg, "\t • Decryption ✔\n")
} else {
return fmt.Sprintf("%s \t • Decryption failed: %s\n", msg, s.DecryptionErr)
}
return msg
type kmsKeyStatusMsg struct {
KeyID string `json:"keyId"`
Encryption bool `json:"encryption"`
Decryption bool `json:"decryption"`
EncryptionErr string `json:"encryptionError,omitempty"`
DecryptionErr string `json:"decryptionError,omitempty"`
Status string `json:"status"`
}
func (s kmsKeyStatusMsg) JSON() string {
const fmtStr = `{"key-id":"%s","encryption-error":"%s","decryption-error":"%s"}`
return fmt.Sprintf(fmtStr, s.KeyID, s.EncryptionErr, s.DecryptionErr)
s.Status = "success"
if !s.Encryption && !s.Decryption {
s.Status = "error"
}
kmsBytes, e := json.MarshalIndent(s, "", " ")
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
return string(kmsBytes)
}
func (s kmsKeyStatusMsg) String() string {
msg := fmt.Sprintf("Key: %s\n", s.KeyID)
if s.Encryption {
msg += " - Encryption " + console.Colorize("StatusSuccess", "✔") + "\n"
} else {
msg += fmt.Sprintf(" - Encryption %s (%s)\n", console.Colorize("StatusError", "✗"), s.EncryptionErr)
}
if s.Decryption {
msg += " - Decryption " + console.Colorize("StatusSuccess", "✔") + "\n"
} else {
msg += fmt.Sprintf(" - Decryption %s (%s)\n", console.Colorize("StatusError", "✗"), s.DecryptionErr)
}
return msg
}
+28 -24
View File
@@ -1,37 +1,41 @@
/*
* MinIO Client (C) 2020 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
import "github.com/minio/cli"
var adminKMSKeySubcommands = []cli.Command{
adminKMSCreateKeyCmd,
adminKMSKeyStatusCmd,
}
var adminKMSKeyCmd = cli.Command{
Name: "key",
Usage: "Manage KMS master keys: Request key status information",
Action: mainAdminKMSKey,
Before: setGlobalsFromContext,
Flags: globalFlags,
Subcommands: []cli.Command{
adminKMSKeyStatusCmd,
},
Name: "key",
Usage: "manage KMS master keys: Request key status information",
Action: mainAdminKMSKey,
Before: setGlobalsFromContext,
Flags: globalFlags,
Subcommands: adminKMSKeySubcommands,
HideHelpCommand: true,
}
// mainAdminKMSKey is the handle for the "mc admin kms key" command.
func mainAdminKMSKey(ctx *cli.Context) error {
cli.ShowCommandHelp(ctx, ctx.Args().First())
commandNotFound(ctx, adminKMSKeySubcommands)
return nil
}
+27 -24
View File
@@ -1,37 +1,40 @@
/*
* MinIO Client (C) 2020 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
import "github.com/minio/cli"
var adminKMSSubcommands = []cli.Command{
adminKMSKeyCmd,
}
var adminKMSCmd = cli.Command{
Name: "kms",
Usage: "perform KMS management operations",
Action: mainAdminKMS,
Before: setGlobalsFromContext,
Flags: globalFlags,
Subcommands: []cli.Command{
adminKMSKeyCmd,
},
Name: "kms",
Usage: "perform KMS management operations",
Action: mainAdminKMS,
Before: setGlobalsFromContext,
Flags: globalFlags,
Subcommands: adminKMSSubcommands,
HideHelpCommand: true,
}
// mainAdminKMS is the handle for the "mc admin kms" command.
func mainAdminKMS(ctx *cli.Context) error {
cli.ShowCommandHelp(ctx, ctx.Args().First())
commandNotFound(ctx, adminKMSSubcommands)
return nil
}
+47 -37
View File
@@ -1,26 +1,25 @@
/*
* 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.
*/
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
import "github.com/minio/cli"
var (
adminFlags = []cli.Flag{}
)
var adminFlags = []cli.Flag{}
const (
// dot represents a list item, for eg. server status - online (green) or offline (red)
@@ -29,38 +28,49 @@ const (
check = "✔"
)
var adminCmdSubcommands = []cli.Command{
adminServiceCmd,
adminServerUpdateCmd,
adminInfoCmd,
adminInspectCmd,
adminUserCmd,
adminGroupCmd,
adminPolicyCmd,
adminReplicateCmd,
adminIDPCmd,
adminConfigCmd,
adminDecommissionCmd,
adminHealCmd,
adminPrometheusCmd,
adminKMSCmd,
adminHealthCmd(),
adminSubnetCmd,
adminBucketCmd,
adminTierCmd,
adminSpeedtestCmd,
adminProfileCmd,
adminScannerCmd,
adminTopCmd,
adminTraceCmd,
adminConsoleCmd,
adminClusterCmd,
}
var adminCmd = cli.Command{
Name: "admin",
Usage: "manage MinIO servers",
Action: mainAdmin,
Subcommands: adminCmdSubcommands,
HideHelpCommand: true,
Before: setGlobalsFromContext,
Flags: append(adminFlags, globalFlags...),
Subcommands: []cli.Command{
adminServiceCmd,
adminServerUpdateCmd,
adminInfoCmd,
adminUserCmd,
adminGroupCmd,
adminPolicyCmd,
adminConfigCmd,
adminHealCmd,
adminProfileCmd,
adminTopCmd,
adminTraceCmd,
adminConsoleCmd,
adminPrometheusCmd,
adminKMSCmd,
adminOBDCmd,
adminBucketCmd,
},
}
const dateTimeFormatFilename = "2006-01-02T15-04-05.999999-07-00"
// mainAdmin is the handle for "mc admin" command.
func mainAdmin(ctx *cli.Context) error {
cli.ShowCommandHelp(ctx, ctx.Args().First())
commandNotFound(ctx, adminCmdSubcommands)
return nil
// Sub-commands like "service", "heal", "top" have their own main.
}
-418
View File
@@ -1,418 +0,0 @@
/*
* MinIO Client (C) 2020 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cmd
import (
"context"
"encoding/json"
"flag"
"fmt"
"os"
"path/filepath"
"strings"
"syscall"
"time"
"github.com/fatih/color"
"github.com/klauspost/compress/gzip"
"github.com/minio/cli"
cjson "github.com/minio/mc/pkg/colorjson"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio/pkg/console"
"github.com/minio/minio/pkg/madmin"
)
var adminOBDFlags = []cli.Flag{
OBDDataTypeFlag{
Name: "tests",
Usage: "choose OBD tests to run [" + options.String() + "]",
Value: nil,
EnvVar: "MC_OBD_DATA",
Hidden: true,
},
cli.DurationFlag{
Name: "deadline",
Usage: "maximum duration that OBD tests should be allowed to run",
Value: 3600 * time.Second,
EnvVar: "MC_OBD_DEADLINE",
},
}
var adminOBDCmd = cli.Command{
Name: "obd",
Usage: "run on-board diagnostics",
Action: mainAdminOBD,
Before: setGlobalsFromContext,
Flags: append(adminOBDFlags, globalFlags...),
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} TARGET
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Get server information of the 'play' MinIO server.
{{.Prompt}} {{.HelpName}} play/
`,
}
type clusterOBDStruct struct {
Status string `json:"status"`
Error string `json:"error,omitempty"`
Info madmin.OBDInfo `json:"obdInfo,omitempty"`
}
func (u clusterOBDStruct) String() string {
u.Status = ""
data, err := json.Marshal(u)
if err != nil {
fatalIf(probe.NewError(err), "unable to marshal into JSON.")
}
return string(data)
}
// JSON jsonifies service status message.
func (u clusterOBDStruct) JSON() string {
statusJSONBytes, e := json.MarshalIndent(u, " ", " ")
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
return string(statusJSONBytes)
}
// checkAdminInfoSyntax - validate arguments passed by a user
func checkAdminOBDSyntax(ctx *cli.Context) {
if len(ctx.Args()) == 0 || len(ctx.Args()) > 1 {
cli.ShowCommandHelpAndExit(ctx, "obd", 1) // last argument is exit code
}
}
//compress and tar obd output
func tarGZ(c clusterOBDStruct, alias string) error {
filename := fmt.Sprintf("%s-obd_%s.json.gz", filepath.Clean(alias), time.Now().Format("20060102150405"))
f, err := os.OpenFile(filename, os.O_CREATE|os.O_RDWR, 0666)
if err != nil {
return err
}
defer f.Close()
defer func() {
fmt.Println("OBD data saved to", filename)
}()
gzWriter := gzip.NewWriter(f)
defer gzWriter.Close()
enc := json.NewEncoder(gzWriter)
if err := enc.Encode(c); err != nil {
return err
}
warningMsgBoundary := "*********************************************************************************"
warning := warnText(" WARNING!!")
warningContents := infoText(` ** THIS FILE MAY CONTAIN SENSITIVE INFORMATION ABOUT YOUR ENVIRONMENT **
** PLEASE INSPECT CONTENTS BEFORE SHARING IT ON ANY PUBLIC FORUM **`)
warningMsgHeader := infoText(warningMsgBoundary)
warningMsgTrailer := infoText(warningMsgBoundary)
fmt.Printf("%s\n%s\n%s\n%s\n", warningMsgHeader, warning, warningContents, warningMsgTrailer)
return nil
}
func infoText(s string) string {
console.SetColor("INFO", color.New(color.FgGreen, color.Bold))
return console.Colorize("INFO", s)
}
func greenText(s string) string {
console.SetColor("GREEN", color.New(color.FgGreen))
return console.Colorize("GREEN", s)
}
func warnText(s string) string {
console.SetColor("WARN", color.New(color.FgRed, color.Bold))
return console.Colorize("WARN", s)
}
func mainAdminOBD(ctx *cli.Context) error {
checkAdminOBDSyntax(ctx)
// Get the alias parameter from cli
args := ctx.Args()
aliasedURL := args.Get(0)
// Create a new MinIO Admin Client
client, err := newAdminClient(aliasedURL)
fatalIf(err, "Unable to initialize admin connection.")
spinners := []string{"/", "|", "\\", "--", "|"}
cont, cancel := context.WithCancel(globalContext)
defer cancel()
startSpinner := func(s string) func() {
ctx, cancel := context.WithCancel(cont)
printText := func(t string, sp string, rewind int) {
console.RewindLines(rewind)
dot := infoText(dot)
t = fmt.Sprintf("%s ...", t)
t = greenText(t)
sp = infoText(sp)
toPrint := fmt.Sprintf("%s %s %s ", dot, t, sp)
fmt.Printf("%s\n", toPrint)
}
i := 0
sp := func() string {
i = i + 1
i = i % len(spinners)
return spinners[i]
}
done := make(chan bool)
doneToggle := false
go func() {
printText(s, sp(), 0)
for {
<-time.After(500 * time.Millisecond) //2 fps
if ctx.Err() != nil {
printText(s, check, 1)
done <- true
return
}
printText(s, sp(), 1)
}
}()
return func() {
cancel()
if !doneToggle {
<-done
os.Stdout.Sync()
doneToggle = true
}
}
}
spinner := func(resource string) func(bool) bool {
var spinStopper func()
done := false
if globalJSON {
return func(bool) bool {
return true
}
}
return func(cond bool) bool {
if done {
return done
}
if spinStopper == nil {
spinStopper = startSpinner(resource)
}
if cond {
spinStopper()
done = true
}
return done
}
}
clusterOBDInfo := clusterOBDStruct{}
admin := spinner("Admin Info")
cpu := spinner("CPU")
diskHw := spinner("Disk Hardware")
osInfo := spinner("Os Info")
mem := spinner("Mem Info")
process := spinner("Process Info")
config := spinner("Config")
drive := spinner("Drive")
net := spinner("Net")
progress := func(info madmin.OBDInfo) bool {
return admin(len(info.Minio.Info.Servers) > 0) &&
cpu(len(info.Sys.CPUInfo) > 0) &&
diskHw(len(info.Sys.DiskHwInfo) > 0) &&
osInfo(len(info.Sys.OsInfo) > 0) &&
mem(len(info.Sys.MemInfo) > 0) &&
process(len(info.Sys.ProcInfo) > 0) &&
config(info.Minio.Config != nil) &&
drive(len(info.Perf.DriveInfo) > 0) &&
net(len(info.Perf.Net) > 1)
}
// Fetch info of all servers (cluster or single server)
obdChan := client.ServerOBDInfo(cont, options, ctx.Duration("deadline"))
for adminOBDInfo := range obdChan {
if adminOBDInfo.Error != "" {
clusterOBDInfo.Status = "Error"
clusterOBDInfo.Error = adminOBDInfo.Error
clusterOBDInfo.Info.Error = ""
clusterOBDInfo.Info.Minio.Info = madmin.InfoMessage{}
break
}
clusterOBDInfo.Status = "Success"
clusterOBDInfo.Info = adminOBDInfo
progress(adminOBDInfo)
}
// If MinIO is not a global distXL cluster, net will never stop spinning.
// add this extra check to ensure that doesn't happen
if clusterOBDInfo.Error == "" && !progress(clusterOBDInfo.Info) {
net(true)
}
if globalJSON {
jsonBytes, err := cjson.MarshalIndent(clusterOBDInfo, "", " ")
if err != nil {
return err
}
fmt.Println(string(jsonBytes))
return nil
}
if clusterOBDInfo.Error != "" {
fmt.Println(warnText("Error obtaining obd information:"), clusterOBDInfo.Error)
return nil
}
return tarGZ(clusterOBDInfo, aliasedURL)
}
// OBDDataTypeSlice is a typed list of OBD tests
type OBDDataTypeSlice []madmin.OBDDataType
// Set - sets the flag to the given value
func (d *OBDDataTypeSlice) Set(value string) error {
for _, v := range strings.Split(value, ",") {
if obdData, ok := madmin.OBDDataTypesMap[strings.Trim(v, " ")]; ok {
*d = append(*d, obdData)
} else {
return fmt.Errorf("valid options include %s", options.String())
}
}
return nil
}
// String - returns the string representation of the OBD datatypes
func (d *OBDDataTypeSlice) String() string {
val := ""
for _, obdData := range *d {
formatStr := "%s"
if val != "" {
formatStr = fmt.Sprintf("%s,%%s", formatStr)
} else {
formatStr = fmt.Sprintf("%s%%s", formatStr)
}
val = fmt.Sprintf(formatStr, val, string(obdData))
}
return val
}
// Value - returns the value
func (d *OBDDataTypeSlice) Value() []madmin.OBDDataType {
return *d
}
// Get - returns the value
func (d *OBDDataTypeSlice) Get() interface{} {
return *d
}
// OBDDataTypeFlag is a typed flag to represent OBD datatypes
type OBDDataTypeFlag struct {
Name string
Usage string
EnvVar string
Hidden bool
Value *OBDDataTypeSlice
}
// String - returns the string to be shown in the help message
func (f OBDDataTypeFlag) String() string {
return fmt.Sprintf("--%s %s", f.Name, f.Usage)
}
// GetName - returns the name of the flag
func (f OBDDataTypeFlag) GetName() string {
return f.Name
}
// GetOBDDataTypeSlice - returns the list of set OBD tests
func GetOBDDataTypeSlice(c *cli.Context, name string) *OBDDataTypeSlice {
generic := c.Generic(name)
if generic == nil {
return nil
}
if obdData, ok := generic.(*OBDDataTypeSlice); ok {
return obdData
}
return nil
}
// GetGlobalOBDDataTypeSlice - returns the list of set OBD tests set globally
func GetGlobalOBDDataTypeSlice(c *cli.Context, name string) *OBDDataTypeSlice {
generic := c.GlobalGeneric(name)
if generic == nil {
return nil
}
if obdData, ok := generic.(*OBDDataTypeSlice); ok {
return obdData
}
return nil
}
// Apply - applies the flag
func (f OBDDataTypeFlag) Apply(set *flag.FlagSet) {
f.ApplyWithError(set)
}
// ApplyWithError - applies with error
func (f OBDDataTypeFlag) ApplyWithError(set *flag.FlagSet) error {
if f.EnvVar != "" {
for _, envVar := range strings.Split(f.EnvVar, ",") {
envVar = strings.TrimSpace(envVar)
if envVal, ok := syscall.Getenv(envVar); ok {
newVal := &OBDDataTypeSlice{}
for _, s := range strings.Split(envVal, ",") {
s = strings.TrimSpace(s)
if err := newVal.Set(s); err != nil {
return fmt.Errorf("could not parse %s as OBD datatype value for flag %s: %s", envVal, f.Name, err)
}
}
f.Value = newVal
break
}
}
}
for _, name := range strings.Split(f.Name, ",") {
name = strings.Trim(name, " ")
if f.Value == nil {
f.Value = &OBDDataTypeSlice{}
}
set.Var(f.Value, name, f.Usage)
}
return nil
}
var options = OBDDataTypeSlice(madmin.OBDDataTypesList)
+46 -37
View File
@@ -1,40 +1,41 @@
/*
* 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.
*/
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
import (
"bytes"
"fmt"
"io/ioutil"
"github.com/fatih/color"
"github.com/minio/cli"
json "github.com/minio/mc/pkg/colorjson"
json "github.com/minio/colorjson"
"github.com/minio/madmin-go"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio/pkg/console"
iampolicy "github.com/minio/minio/pkg/iam/policy"
"github.com/minio/pkg/console"
)
var adminPolicyAddCmd = cli.Command{
Name: "add",
Usage: "add new policy",
Action: mainAdminPolicyAdd,
Before: setGlobalsFromContext,
Flags: globalFlags,
Name: "add",
Usage: "add new policy",
Action: mainAdminPolicyAdd,
OnUsageError: onUsageError,
Before: setGlobalsFromContext,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
@@ -68,16 +69,27 @@ type userPolicyMessage struct {
op string
Status string `json:"status"`
Policy string `json:"policy,omitempty"`
PolicyJSON *iampolicy.Policy `json:"policyJSON,omitempty"`
PolicyInfo madmin.PolicyInfo `json:"policyInfo,omitempty"`
UserOrGroup string `json:"userOrGroup,omitempty"`
IsGroup bool `json:"isGroup"`
}
func (u userPolicyMessage) accountType() string {
switch u.op {
case "set", "unset", "update":
if u.IsGroup {
return "group"
}
return "user"
}
return ""
}
func (u userPolicyMessage) String() string {
switch u.op {
case "info":
buf, e := json.MarshalIndent(u.PolicyJSON, "", " ")
fatalIf(probe.NewError(e), "Unable to parse policy")
buf, e := json.MarshalIndent(u.PolicyInfo, "", " ")
fatalIf(probe.NewError(e), "Unable to marshal to JSON.")
return string(buf)
case "list":
policyFieldMaxLen := 20
@@ -89,14 +101,14 @@ func (u userPolicyMessage) String() string {
return console.Colorize("PolicyMessage", "Removed policy `"+u.Policy+"` successfully.")
case "add":
return console.Colorize("PolicyMessage", "Added policy `"+u.Policy+"` successfully.")
case "set":
fragment := "user"
if u.IsGroup {
fragment = "group"
}
case "set", "unset":
return console.Colorize("PolicyMessage",
fmt.Sprintf("Policy %s is set on %s `%s`", u.Policy, fragment, u.UserOrGroup))
fmt.Sprintf("Policy `%s` is %s on %s `%s`", u.Policy, u.op, u.accountType(), u.UserOrGroup))
case "update":
return console.Colorize("PolicyMessage",
fmt.Sprintf("Policy `%s` is added to %s `%s`", u.Policy, u.accountType(), u.UserOrGroup))
}
return ""
}
@@ -125,10 +137,7 @@ func mainAdminPolicyAdd(ctx *cli.Context) error {
client, err := newAdminClient(aliasedURL)
fatalIf(err, "Unable to initialize admin connection.")
iamp, e := iampolicy.ParseConfig(bytes.NewReader(policy))
fatalIf(probe.NewError(e).Trace(args...), "Unable to parse the input policy")
fatalIf(probe.NewError(client.AddCannedPolicy(globalContext, args.Get(1), iamp)).Trace(args...), "Unable to add new policy")
fatalIf(probe.NewError(client.AddCannedPolicy(globalContext, args.Get(1), policy)).Trace(args...), "Unable to add new policy")
printMsg(userPolicyMessage{
op: "add",
+72 -34
View File
@@ -1,41 +1,51 @@
/*
* 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.
*/
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
import (
"fmt"
"os"
"github.com/fatih/color"
"github.com/minio/cli"
"github.com/minio/madmin-go"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio/pkg/console"
"github.com/minio/pkg/console"
)
var policyInfoFlags = []cli.Flag{
cli.StringFlag{
Name: "policy-file, f",
Usage: "additionally (over-)write policy JSON to given file",
},
}
var adminPolicyInfoCmd = cli.Command{
Name: "info",
Usage: "show info on a policy",
Action: mainAdminPolicyInfo,
Before: setGlobalsFromContext,
Flags: globalFlags,
Name: "info",
Usage: "show info on a policy",
Action: mainAdminPolicyInfo,
OnUsageError: onUsageError,
Before: setGlobalsFromContext,
Flags: append(policyInfoFlags, globalFlags...),
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} TARGET POLICYNAME
{{.HelpName}} TARGET POLICYNAME [OPTIONS...]
POLICYNAME:
Name of the policy on the MinIO server.
@@ -46,6 +56,9 @@ FLAGS:
EXAMPLES:
1. Show information on a given policy.
{{.Prompt}} {{.HelpName}} myminio writeonly
2. Show information on a given policy and write the policy JSON content to /tmp/policy.json.
{{.Prompt}} {{.HelpName}} myminio writeonly --policy-file /tmp/policy.json
`,
}
@@ -56,6 +69,23 @@ func checkAdminPolicyInfoSyntax(ctx *cli.Context) {
}
}
func getPolicyInfo(client *madmin.AdminClient, policyName string) (*madmin.PolicyInfo, error) {
pinfo, e := client.InfoCannedPolicyV2(globalContext, policyName)
if e != nil {
return nil, e
}
if pinfo.PolicyName == "" {
// Likely server only supports the older version.
pinfo.Policy, e = client.InfoCannedPolicy(globalContext, policyName)
if e != nil {
return nil, e
}
pinfo.PolicyName = policyName
}
return pinfo, nil
}
// mainAdminPolicyInfo is the handler for "mc admin policy info" command.
func mainAdminPolicyInfo(ctx *cli.Context) error {
checkAdminPolicyInfoSyntax(ctx)
@@ -72,18 +102,26 @@ func mainAdminPolicyInfo(ctx *cli.Context) error {
client, err := newAdminClient(aliasedURL)
fatalIf(err, "Unable to initialize admin connection")
policies, e := client.ListCannedPolicies(globalContext)
fatalIf(probe.NewError(e).Trace(args...), "Cannot list policy")
pinfo, e := getPolicyInfo(client, policyName)
fatalIf(probe.NewError(e).Trace(args...), "Unable to fetch policy")
iamp, ok := policies[policyName]
if ok {
printMsg(userPolicyMessage{
op: "info",
Policy: policyName,
PolicyJSON: iamp,
})
} else {
fatalIf(probe.NewError(fmt.Errorf("%s is not found", policyName)), "Unable to display policy")
policyFile := ctx.String("policy-file")
if policyFile != "" {
f, err := os.Create(policyFile)
if err != nil {
fatalIf(probe.NewError(err).Trace(args...), "Could not open given policy file")
}
_, err = f.Write(pinfo.Policy)
if err != nil {
fatalIf(probe.NewError(err).Trace(args...), "Could not write to given policy file")
}
}
printMsg(userPolicyMessage{
op: "info",
Policy: policyName,
PolicyInfo: *pinfo,
})
return nil
}
+24 -22
View File
@@ -1,18 +1,19 @@
/*
* 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.
*/
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
@@ -20,15 +21,16 @@ import (
"github.com/fatih/color"
"github.com/minio/cli"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio/pkg/console"
"github.com/minio/pkg/console"
)
var adminPolicyListCmd = cli.Command{
Name: "list",
Usage: "list all policies",
Action: mainAdminPolicyList,
Before: setGlobalsFromContext,
Flags: globalFlags,
Name: "list",
Usage: "list all policies",
Action: mainAdminPolicyList,
OnUsageError: onUsageError,
Before: setGlobalsFromContext,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
@@ -67,7 +69,7 @@ func mainAdminPolicyList(ctx *cli.Context) error {
fatalIf(err, "Unable to initialize admin connection.")
policies, e := client.ListCannedPolicies(globalContext)
fatalIf(probe.NewError(e).Trace(args...), "Cannot list policy")
fatalIf(probe.NewError(e).Trace(args...), "Unable to list policy")
for k := range policies {
printMsg(userPolicyMessage{
+24 -22
View File
@@ -1,18 +1,19 @@
/*
* 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.
*/
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
@@ -20,15 +21,16 @@ import (
"github.com/fatih/color"
"github.com/minio/cli"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio/pkg/console"
"github.com/minio/pkg/console"
)
var adminPolicyRemoveCmd = cli.Command{
Name: "remove",
Usage: "remove policy",
Action: mainAdminPolicyRemove,
Before: setGlobalsFromContext,
Flags: globalFlags,
Name: "remove",
Usage: "remove policy",
Action: mainAdminPolicyRemove,
OnUsageError: onUsageError,
Before: setGlobalsFromContext,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
@@ -68,7 +70,7 @@ func mainAdminPolicyRemove(ctx *cli.Context) error {
client, err := newAdminClient(aliasedURL)
fatalIf(err, "Unable to initialize admin connection.")
fatalIf(probe.NewError(client.RemoveCannedPolicy(globalContext, args.Get(1))).Trace(args...), "Cannot remove policy")
fatalIf(probe.NewError(client.RemoveCannedPolicy(globalContext, args.Get(1))).Trace(args...), "Unable to remove policy")
printMsg(userPolicyMessage{
op: "remove",
+32 -32
View File
@@ -1,18 +1,19 @@
/*
* 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.
*/
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
@@ -23,15 +24,16 @@ import (
"github.com/fatih/color"
"github.com/minio/cli"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio/pkg/console"
"github.com/minio/pkg/console"
)
var adminPolicySetCmd = cli.Command{
Name: "set",
Usage: "set IAM policy on a user or group",
Action: mainAdminPolicySet,
Before: setGlobalsFromContext,
Flags: globalFlags,
Name: "set",
Usage: "set IAM policy on a user or group",
Action: mainAdminPolicySet,
OnUsageError: onUsageError,
Before: setGlobalsFromContext,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
@@ -39,7 +41,7 @@ USAGE:
{{.HelpName}} TARGET POLICYNAME [ user=username1 | group=groupname1 ]
POLICYNAME:
Name of the policy on the MinIO server.
Name of the policy on the MinIO server. To set multiple policies, separate names with a comma (,).
FLAGS:
{{range .VisibleFlags}}{{.}}
@@ -50,12 +52,13 @@ EXAMPLES:
2. Set the "readonly" policy for group "auditors".
{{.Prompt}} {{.HelpName}} myminio readonly group=auditors
3. Set the "readonly" and the "diagnostics" policies for user "alice"
{{.Prompt}} {{.HelpName}} myminio readonly,diagnostics user=alice
`,
}
var (
errBadUserGroupArg = errors.New("Last argument must be of the form user=xx or group=xx")
)
var errBadUserGroupArg = errors.New("Last argument must be of the form user=xx or group=xx")
func checkAdminPolicySetSyntax(ctx *cli.Context) {
if len(ctx.Args()) != 3 {
@@ -64,11 +67,9 @@ func checkAdminPolicySetSyntax(ctx *cli.Context) {
}
func parseEntityArg(arg string) (userOrGroup string, isGroup bool, err error) {
parts := strings.Split(arg, "=")
parts := strings.SplitN(arg, "=", 2)
switch {
case len(parts) != 2:
fallthrough
case parts[1] == "":
case len(parts) != 2 || parts[1] == "":
err = errBadUserGroupArg
case strings.ToLower(parts[0]) == "user":
userOrGroup = parts[1]
@@ -93,7 +94,7 @@ func mainAdminPolicySet(ctx *cli.Context) error {
// Get the alias parameter from cli
args := ctx.Args()
aliasedURL := args.Get(0)
policyName := args.Get(1)
policyName := strings.TrimSpace(args.Get(1))
entityArg := args.Get(2)
userOrGroup, isGroup, e1 := parseEntityArg(entityArg)
@@ -104,7 +105,6 @@ func mainAdminPolicySet(ctx *cli.Context) error {
fatalIf(err, "Unable to initialize admin connection.")
e := client.SetPolicy(globalContext, policyName, userOrGroup, isGroup)
if e == nil {
printMsg(userPolicyMessage{
op: "set",
@@ -113,7 +113,7 @@ func mainAdminPolicySet(ctx *cli.Context) error {
IsGroup: isGroup,
})
} else {
fatalIf(probe.NewError(e), "Cannot set the policy")
fatalIf(probe.NewError(e), "Unable to set the policy")
}
return nil
}
+137
View File
@@ -0,0 +1,137 @@
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
import (
"errors"
"fmt"
"strings"
"github.com/fatih/color"
"github.com/minio/cli"
"github.com/minio/mc/pkg/probe"
"github.com/minio/pkg/console"
)
var adminPolicyUnsetCmd = cli.Command{
Name: "unset",
Usage: "unset an IAM policy for a user or group",
Action: mainAdminPolicyUnset,
OnUsageError: onUsageError,
Before: setGlobalsFromContext,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} TARGET POLICYNAME [ user=username1 | group=groupname1 ]
POLICYNAME:
Name of the policy on the MinIO server.
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Unset the "diagnostics" policy for user "james".
{{.Prompt}} {{.HelpName}} myminio diagnostics user=james
2. Set the "diagnostics" policy for group "auditors".
{{.Prompt}} {{.HelpName}} myminio diagnostics group=auditors
`,
}
func checkAdminPolicyUnsetSyntax(ctx *cli.Context) {
if len(ctx.Args()) != 3 {
cli.ShowCommandHelpAndExit(ctx, "unset", 1) // last argument is exit code
}
}
func removeCannedPolicies(existingPolicies, policiesToRemove string) (string, error) {
policiesToRemove = strings.TrimSpace(policiesToRemove)
if policiesToRemove == "" {
return "", errors.New("empty policy name is not supported")
}
filteredPolicies := strings.Split(existingPolicies, ",")
for _, p1 := range strings.Split(policiesToRemove, ",") {
found := false
for i, p2 := range filteredPolicies {
if p1 == p2 {
found = true
filteredPolicies = append(filteredPolicies[:i], filteredPolicies[i+1:]...)
break
}
}
if !found {
return "", fmt.Errorf("policy `%s` not found", p1)
}
}
return strings.Join(filteredPolicies, ","), nil
}
// mainAdminPolicyUnset is the handler for "mc admin policy unset" command.
func mainAdminPolicyUnset(ctx *cli.Context) error {
checkAdminPolicyUnsetSyntax(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)
policiesToUnset := args.Get(1)
entityArg := args.Get(2)
userOrGroup, isGroup, e1 := parseEntityArg(entityArg)
fatalIf(probe.NewError(e1).Trace(args...), "Bad last argument")
// Create a new MinIO Admin Client
client, err := newAdminClient(aliasedURL)
fatalIf(err, "Unable to initialize admin connection.")
var existingPolicies string
if !isGroup {
userInfo, e := client.GetUserInfo(globalContext, userOrGroup)
fatalIf(probe.NewError(e).Trace(args...), "Unable to get user policy info")
existingPolicies = userInfo.PolicyName
} else {
groupInfo, e := client.GetGroupDescription(globalContext, userOrGroup)
fatalIf(probe.NewError(e).Trace(args...), "Unable to get group policy info")
existingPolicies = groupInfo.Policy
}
newPolicies, e := removeCannedPolicies(existingPolicies, policiesToUnset)
if e != nil {
fatalIf(probe.NewError(e).Trace(args...), "Unable to unset the policy")
}
e = client.SetPolicy(globalContext, newPolicies, userOrGroup, isGroup)
if e == nil {
printMsg(userPolicyMessage{
op: "unset",
Policy: policiesToUnset,
UserOrGroup: userOrGroup,
IsGroup: isGroup,
})
} else {
fatalIf(probe.NewError(e), "Unable to unset the policy")
}
return nil
}
+142
View File
@@ -0,0 +1,142 @@
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
import (
"errors"
"fmt"
"strings"
"github.com/fatih/color"
"github.com/minio/cli"
"github.com/minio/mc/pkg/probe"
"github.com/minio/pkg/console"
)
var adminPolicyUpdateCmd = cli.Command{
Name: "update",
Usage: "attach a new IAM policy to user or group",
Action: mainAdminPolicyUpdate,
OnUsageError: onUsageError,
Before: setGlobalsFromContext,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} TARGET POLICYNAME [ user=username1 | group=groupname1 ]
POLICYNAME:
Name of the policy on the MinIO server.
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Add the "diagnostics" policy for user "james".
{{.Prompt}} {{.HelpName}} myminio diagnostics user=james
2. Add the "diagnostics" policy for group "auditors".
{{.Prompt}} {{.HelpName}} myminio diagnostics group=auditors
`,
}
func checkAdminPolicyUpdateSyntax(ctx *cli.Context) {
if len(ctx.Args()) != 3 {
cli.ShowCommandHelpAndExit(ctx, "update", 1) // last argument is exit code
}
}
func updateCannedPolicies(existingPolicies, policiesToAdd string) (string, error) {
policiesToAdd = strings.TrimSpace(policiesToAdd)
if policiesToAdd == "" {
return "", errors.New("empty policy name is unsupported")
}
var updatedPolicies []string
if existingPolicies != "" {
updatedPolicies = strings.Split(existingPolicies, ",")
}
for _, p1 := range strings.Split(policiesToAdd, ",") {
found := false
p1 = strings.TrimSpace(p1)
for _, p2 := range updatedPolicies {
if p1 == p2 {
found = true
break
}
}
if found {
return "", fmt.Errorf("policy `%s` already exists", p1)
}
updatedPolicies = append(updatedPolicies, p1)
}
return strings.Join(updatedPolicies, ","), nil
}
// mainAdminPolicyUpdate is the handler for "mc admin policy update" command.
func mainAdminPolicyUpdate(ctx *cli.Context) error {
checkAdminPolicyUpdateSyntax(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)
policiesToAdd := args.Get(1)
entityArg := args.Get(2)
userOrGroup, isGroup, e1 := parseEntityArg(entityArg)
fatalIf(probe.NewError(e1).Trace(args...), "Bad last argument")
// Create a new MinIO Admin Client
client, err := newAdminClient(aliasedURL)
fatalIf(err, "Unable to initialize admin connection.")
var existingPolicies string
if !isGroup {
userInfo, e := client.GetUserInfo(globalContext, userOrGroup)
fatalIf(probe.NewError(e).Trace(args...), "Unable to get user policy info")
existingPolicies = userInfo.PolicyName
} else {
groupInfo, e := client.GetGroupDescription(globalContext, userOrGroup)
fatalIf(probe.NewError(e).Trace(args...), "Unable to get group policy info")
existingPolicies = groupInfo.Policy
}
updatedPolicies, e := updateCannedPolicies(existingPolicies, policiesToAdd)
if e != nil {
fatalIf(probe.NewError(e).Trace(args...), "Unable to update the policy")
}
e = client.SetPolicy(globalContext, updatedPolicies, userOrGroup, isGroup)
if e == nil {
printMsg(userPolicyMessage{
op: "update",
Policy: policiesToAdd,
UserOrGroup: userOrGroup,
IsGroup: isGroup,
})
} else {
fatalIf(probe.NewError(e), "Unable to unset the policy")
}
return nil
}
+33 -28
View File
@@ -1,42 +1,47 @@
/*
* 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.
*/
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
import "github.com/minio/cli"
var adminPolicySubcommands = []cli.Command{
adminPolicyAddCmd,
adminPolicyRemoveCmd,
adminPolicyListCmd,
adminPolicyInfoCmd,
adminPolicySetCmd,
adminPolicyUnsetCmd,
adminPolicyUpdateCmd,
}
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,
adminPolicySetCmd,
},
Name: "policy",
Usage: "manage policies defined in the MinIO server",
Action: mainAdminPolicy,
Before: setGlobalsFromContext,
Flags: globalFlags,
Subcommands: adminPolicySubcommands,
HideHelpCommand: true,
}
// mainAdminPolicy is the handle for "mc admin policy" command.
func mainAdminPolicy(ctx *cli.Context) error {
cli.ShowCommandHelp(ctx, ctx.Args().First())
commandNotFound(ctx, adminPolicySubcommands)
return nil
// Sub-commands like "get", "set" have their own main.
}
+26 -108
View File
@@ -1,122 +1,40 @@
/*
* 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.
*/
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
import (
"strings"
"github.com/minio/cli"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio-go/v6/pkg/set"
"github.com/minio/minio/pkg/console"
"github.com/minio/minio/pkg/madmin"
"github.com/minio/pkg/console"
)
var adminProfileStartFlags = []cli.Flag{
cli.StringFlag{
Name: "type",
Usage: "start profiler type, possible values are 'cpu', 'mem', 'block', 'mutex', 'trace', 'threads' and 'goroutines'",
Value: "cpu,mem,block",
},
}
var adminProfileStartCmd = cli.Command{
Name: "start",
Usage: "start recording profile data",
Action: mainAdminProfileStart,
Before: setGlobalsFromContext,
Flags: append(adminProfileStartFlags, globalFlags...),
HideHelpCommand: true,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} [FLAGS] TARGET
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Start CPU profiling only
{{.Prompt}} {{.HelpName}} --type cpu myminio/
2. Start CPU, Memory and Block profiling concurrently
{{.Prompt}} {{.HelpName}} --type cpu,mem,block myminio/
`,
}
func checkAdminProfileStartSyntax(ctx *cli.Context) {
// Check flags combinations
if len(ctx.Args()) != 1 {
cli.ShowCommandHelpAndExit(ctx, "start", 1) // last argument is exit code
}
s := set.NewStringSet()
supportedProfilerTypes := []madmin.ProfilerType{
madmin.ProfilerCPU,
madmin.ProfilerMEM,
madmin.ProfilerBlock,
madmin.ProfilerMutex,
madmin.ProfilerTrace,
madmin.ProfilerThreads,
madmin.ProfilerGoroutines,
}
for _, profilerType := range supportedProfilerTypes {
s.Add(string(profilerType))
}
// Check if the provided profiler type is known and supported
supportedProfiler := false
profilers := strings.Split(strings.ToLower(ctx.String("type")), ",")
for _, profiler := range profilers {
if profiler != "" {
if s.Contains(profiler) {
supportedProfiler = true
break
}
}
}
if !supportedProfiler {
fatalIf(errDummy().Trace(ctx.String("type")),
"Profiler type unrecognized. Possible values are: %v.", supportedProfilerTypes)
}
Name: "start",
Usage: "start recording profile data",
Action: mainAdminProfileStart,
OnUsageError: onUsageError,
Before: setGlobalsFromContext,
HideHelpCommand: true,
Hidden: true,
CustomHelpTemplate: "Please use 'mc support profile start'",
}
// mainAdminProfileStart - the entry function of profile command
func mainAdminProfileStart(ctx *cli.Context) error {
// Check for command syntax
checkAdminProfileStartSyntax(ctx)
// Get the alias parameter from cli
args := ctx.Args()
aliasedURL := args.Get(0)
profilers := ctx.String("type")
// Create a new MinIO Admin Client
client, err := newAdminClient(aliasedURL)
if err != nil {
fatalIf(err.Trace(aliasedURL), "Cannot initialize admin client.")
return nil
}
// Start profile
_, cmdErr := client.StartProfiling(globalContext, madmin.ProfilerType(profilers))
fatalIf(probe.NewError(cmdErr), "Unable to start profile.")
console.Infoln("Profile data successfully started.")
console.Infoln("Please use 'mc support profile start'")
return nil
}
+27 -119
View File
@@ -1,133 +1,41 @@
/*
* 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.
*/
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
import (
"io"
"io/ioutil"
"os"
"time"
"github.com/minio/cli"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio/pkg/console"
"github.com/minio/pkg/console"
)
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
{{.Prompt}} {{.HelpName}} myminio/
`,
}
func checkAdminProfileStopSyntax(ctx *cli.Context) {
if len(ctx.Args()) != 1 {
cli.ShowCommandHelpAndExit(ctx, "stop", 1) // last argument is exit code
}
}
// moveFile - os.Rename cannot handle cross device renames, in our situation
// it is possible that /tmp is mounted from a separate partition and current
// working directory is a different partition. To allow all situations to
// be handled appropriately use this function instead of os.Rename()
func moveFile(sourcePath, destPath string) error {
inputFile, err := os.Open(sourcePath)
if err != nil {
return err
}
outputFile, err := os.Create(destPath)
if err != nil {
inputFile.Close()
return err
}
defer outputFile.Close()
_, err = io.Copy(outputFile, inputFile)
inputFile.Close()
if err != nil {
return err
}
// The copy was successful, so now delete the original file
return os.Remove(sourcePath)
Name: "stop",
Usage: "stop and download profile data",
Action: mainAdminProfileStop,
OnUsageError: onUsageError,
Before: setGlobalsFromContext,
Flags: globalFlags,
HideHelpCommand: true,
Hidden: true,
CustomHelpTemplate: "Please use 'mc support profile stop'",
}
// mainAdminProfileStop - the entry function of profile stop command
func mainAdminProfileStop(ctx *cli.Context) error {
// Check for command syntax
checkAdminProfileStopSyntax(ctx)
// Get the alias parameter from cli
args := ctx.Args()
aliasedURL := args.Get(0)
// Create a new MinIO Admin Client
client, err := newAdminClient(aliasedURL)
if err != nil {
fatalIf(err.Trace(aliasedURL), "Cannot initialize admin client.")
return nil
}
// Create profile zip file
tmpFile, e := ioutil.TempFile("", "mc-profile-")
fatalIf(probe.NewError(e), "Unable to download profile data.")
// Ask for profile data, which will come compressed with zip format
zippedData, adminErr := client.DownloadProfilingData(globalContext)
fatalIf(probe.NewError(adminErr), "Unable to download profile data.")
// Copy zip content to target download file
_, e = io.Copy(tmpFile, zippedData)
fatalIf(probe.NewError(e), "Unable to download profile data.")
// Close everything
zippedData.Close()
tmpFile.Close()
downloadPath := "profile.zip"
fi, e := os.Stat(downloadPath)
if e == nil && !fi.IsDir() {
e = moveFile(downloadPath, downloadPath+"."+time.Now().Format(dateTimeFormatFilename))
fatalIf(probe.NewError(e), "Unable to create a backup of profile.zip")
} else {
if !os.IsNotExist(e) {
fatal(probe.NewError(e), "Unable to download profile data.")
}
}
fatalIf(probe.NewError(moveFile(tmpFile.Name(), downloadPath)), "Unable to download profile data.")
console.Infof("Profile data successfully downloaded as %s\n", downloadPath)
console.Infoln("Please use 'mc support profile stop'")
return nil
}
+31 -25
View File
@@ -1,40 +1,46 @@
/*
* MinIO Client (C) 2018-2020 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
import (
"github.com/minio/cli"
"github.com/minio/pkg/console"
)
var adminProfileSubcommands = []cli.Command{
adminProfileStartCmd,
adminProfileStopCmd,
}
var adminProfileCmd = cli.Command{
Name: "profile",
Usage: "generate profile data for debugging purposes",
Action: mainAdminProfile,
Before: setGlobalsFromContext,
Flags: globalFlags,
Subcommands: []cli.Command{
adminProfileStartCmd,
adminProfileStopCmd,
},
Name: "profile",
Usage: "generate profile data for debugging purposes",
Action: mainAdminProfile,
OnUsageError: onUsageError,
Before: setGlobalsFromContext,
Flags: globalFlags,
Subcommands: adminProfileSubcommands,
HideHelpCommand: true,
Hidden: true,
}
// mainAdminProfile is the handle for "mc admin profile" command.
func mainAdminProfile(ctx *cli.Context) error {
cli.ShowCommandHelp(ctx, ctx.Args().First())
console.Infoln("Please use 'mc support profile'")
return nil
}
+39 -37
View File
@@ -1,18 +1,19 @@
/*
* 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.
*/
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
@@ -24,24 +25,31 @@ import (
"github.com/fatih/color"
"github.com/minio/cli"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio/pkg/console"
"github.com/minio/pkg/console"
jwtgo "github.com/dgrijalva/jwt-go"
json "github.com/minio/mc/pkg/colorjson"
json "github.com/minio/colorjson"
yaml "gopkg.in/yaml.v2"
)
const (
defaultJobName = "minio-job"
defaultMetricsPath = "/minio/prometheus/metrics"
defaultMetricsPath = "/minio/v2/metrics/cluster"
)
var prometheusFlags = []cli.Flag{
cli.BoolFlag{
Name: "public",
Usage: "disable bearer token generation for scrape_configs",
},
}
var adminPrometheusGenerateCmd = cli.Command{
Name: "generate",
Usage: "generates prometheus config",
Action: mainAdminPrometheusGenerate,
OnUsageError: onUsageError,
Before: setGlobalsFromContext,
Flags: globalFlags,
Flags: append(prometheusFlags, globalFlags...),
HideHelpCommand: true,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
@@ -104,7 +112,7 @@ func (t StatConfig) JSON() string {
// ScrapeConfig configures a scraping unit for Prometheus.
type ScrapeConfig struct {
JobName string `yaml:"job_name" json:"jobName"`
BearerToken string `yaml:"bearer_token" json:"bearerToken"`
BearerToken string `yaml:"bearer_token,omitempty" json:"bearerToken,omitempty"`
MetricsPath string `yaml:"metrics_path,omitempty" json:"metricsPath"`
Scheme string `yaml:"scheme,omitempty" json:"scheme"`
StaticConfigs []StatConfig `yaml:"static_configs,omitempty" json:"staticConfigs"`
@@ -150,24 +158,19 @@ func generatePrometheusConfig(ctx *cli.Context) error {
return nil
}
u, err := url.Parse(hostConfig.URL)
if err != nil {
return err
u, e := url.Parse(hostConfig.URL)
if e != nil {
return e
}
jwt := jwtgo.NewWithClaims(jwtgo.SigningMethodHS512, jwtgo.StandardClaims{
ExpiresAt: UTCNow().Add(defaultPrometheusJWTExpiry).Unix(),
Subject: hostConfig.AccessKey,
Issuer: "prometheus",
})
token, err := jwt.SignedString([]byte(hostConfig.SecretKey))
if err != nil {
return err
if !ctx.Bool("public") {
token, e := getPrometheusToken(hostConfig)
if e != nil {
return e
}
// Setting the values
defaultConfig.ScrapeConfigs[0].BearerToken = token
}
// Setting the values
defaultConfig.ScrapeConfigs[0].BearerToken = token
defaultConfig.ScrapeConfigs[0].Scheme = u.Scheme
defaultConfig.ScrapeConfigs[0].StaticConfigs[0].Targets[0] = u.Host
@@ -178,7 +181,6 @@ func generatePrometheusConfig(ctx *cli.Context) error {
// mainAdminPrometheus is the handle for "mc admin prometheus generate" sub-command.
func mainAdminPrometheusGenerate(ctx *cli.Context) error {
console.SetColor("yaml", color.New(color.FgGreen))
checkAdminPrometheusSyntax(ctx)
+140
View File
@@ -0,0 +1,140 @@
// Copyright (c) 2015-2022 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
import (
"io"
"io/ioutil"
"net/http"
"time"
"github.com/minio/cli"
json "github.com/minio/colorjson"
"github.com/minio/mc/pkg/probe"
dto "github.com/prometheus/client_model/go"
prom2json "github.com/prometheus/prom2json"
)
var adminPrometheusMetricsCmd = cli.Command{
Name: "metrics",
Usage: "print cluster wide prometheus metrics",
OnUsageError: onUsageError,
Action: mainSupportMetrics,
Before: setGlobalsFromContext,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} TARGET
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. List of metrics reported cluster wide.
{{.Prompt}} {{.HelpName}} play
`,
}
const (
metricsRespBodyLimit = 10 << 20 // 10 MiB
metricsEndPoint = "/minio/v2/metrics/cluster"
)
// checkSupportMetricsSyntax - validate arguments passed by a user
func checkSupportMetricsSyntax(ctx *cli.Context) {
if len(ctx.Args()) == 0 || len(ctx.Args()) > 1 {
cli.ShowCommandHelpAndExit(ctx, "metrics", 1) // last argument is exit code
}
}
func printPrometheusMetrics(ctx *cli.Context) error {
// Get the alias parameter from cli
args := ctx.Args()
alias := cleanAlias(args.Get(0))
if !isValidAlias(alias) {
fatalIf(errInvalidAlias(alias), "Invalid alias.")
}
hostConfig := mustGetHostConfig(alias)
if hostConfig == nil {
fatalIf(errInvalidAliasedURL(alias), "No such alias `"+alias+"` found.")
return nil
}
token, e := getPrometheusToken(hostConfig)
if e != nil {
return e
}
req, e := http.NewRequest(http.MethodGet, hostConfig.URL+metricsEndPoint, nil)
if e != nil {
return e
}
req.Header.Add("Authorization", "Bearer "+token)
client := httpClient(10 * time.Second)
resp, e := client.Do(req)
if e != nil {
return e
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusOK {
printMsg(prometheusMetricsReader{Reader: io.LimitReader(resp.Body, metricsRespBodyLimit)})
}
return nil
}
// JSON returns jsonified message
func (pm prometheusMetricsReader) JSON() string {
mfChan := make(chan *dto.MetricFamily)
go func() {
if err := prom2json.ParseReader(pm.Reader, mfChan); err != nil {
fatalIf(probe.NewError(err), "error reading metrics:")
}
}()
result := []*prom2json.Family{}
for mf := range mfChan {
result = append(result, prom2json.NewFamily(mf))
}
jsonMessageBytes, e := json.MarshalIndent(result, "", " ")
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
return string(jsonMessageBytes)
}
// String - returns the string representation of the prometheus metrics
func (pm prometheusMetricsReader) String() string {
respBytes, e := ioutil.ReadAll(pm.Reader)
if e != nil {
fatalIf(probe.NewError(e), "error reading metrics:")
}
return string(respBytes)
}
// prometheusMetricsReader mirrors the MetricFamily proto message.
type prometheusMetricsReader struct {
Reader io.Reader
}
func mainSupportMetrics(ctx *cli.Context) error {
checkSupportMetricsSyntax(ctx)
if err := printPrometheusMetrics(ctx); err != nil {
fatalIf(probe.NewError(err), "Error in listing prometheus metrics")
}
return nil
}
+23 -19
View File
@@ -1,23 +1,29 @@
/*
* 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.
*/
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
import "github.com/minio/cli"
var adminPrometheusSubcommands = []cli.Command{
adminPrometheusGenerateCmd,
adminPrometheusMetricsCmd,
}
var adminPrometheusCmd = cli.Command{
Name: "prometheus",
Usage: "manages prometheus config",
@@ -25,9 +31,7 @@ var adminPrometheusCmd = cli.Command{
Before: setGlobalsFromContext,
Flags: globalFlags,
HideHelpCommand: true,
Subcommands: []cli.Command{
adminPrometheusGenerateCmd,
},
Subcommands: adminPrometheusSubcommands,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
@@ -42,6 +46,6 @@ FLAGS:
// mainAdminPrometheus is the handle for "mc admin prometheus" command.
func mainAdminPrometheus(ctx *cli.Context) error {
cli.ShowCommandHelp(ctx, ctx.Args().First())
commandNotFound(ctx, adminPrometheusSubcommands)
return nil
}
+115
View File
@@ -0,0 +1,115 @@
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
import (
"strings"
"github.com/fatih/color"
"github.com/minio/cli"
json "github.com/minio/colorjson"
"github.com/minio/madmin-go"
"github.com/minio/mc/pkg/probe"
"github.com/minio/pkg/console"
)
var adminReplicateAddCmd = cli.Command{
Name: "add",
Usage: "add one or more sites for replication",
Action: mainAdminReplicateAdd,
OnUsageError: onUsageError,
Before: setGlobalsFromContext,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} ALIAS1 ALIAS2 [ALIAS3...]
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Add a site for cluster-level replication:
{{.Prompt}} {{.HelpName}} minio1 minio2
`,
}
type successMessage madmin.ReplicateAddStatus
func (m successMessage) JSON() string {
bs, e := json.MarshalIndent(madmin.ReplicateAddStatus(m), "", " ")
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
return string(bs)
}
func (m successMessage) String() string {
v := madmin.ReplicateAddStatus(m)
messages := []string{v.Status}
if v.ErrDetail != "" {
messages = append(messages, v.ErrDetail)
}
if v.InitialSyncErrorMessage != "" {
messages = append(messages, v.InitialSyncErrorMessage)
}
return console.Colorize("UserMessage", strings.Join(messages, "\n"))
}
func mainAdminReplicateAdd(ctx *cli.Context) error {
{
// Check argument count
argsNr := len(ctx.Args())
if argsNr < 2 {
fatalIf(errInvalidArgument().Trace(ctx.Args().Tail()...),
"Need at least two arguments to add command.")
}
}
console.SetColor("UserMessage", color.New(color.FgGreen))
// Get the alias parameter from cli
args := ctx.Args()
aliasedURL := args.Get(0)
// Create a new MinIO Admin Client
client, err := newAdminClient(aliasedURL)
fatalIf(err, "Unable to initialize admin connection.")
ps := make([]madmin.PeerSite, 0, len(ctx.Args()))
for _, clusterName := range ctx.Args() {
admClient, err := newAdminClient(clusterName)
fatalIf(err, "unable to initialize admin connection")
ak, sk := admClient.GetAccessAndSecretKey()
ps = append(ps, madmin.PeerSite{
Name: clusterName,
Endpoint: admClient.GetEndpointURL().String(),
AccessKey: ak,
SecretKey: sk,
})
}
res, e := client.SiteReplicationAdd(globalContext, ps)
fatalIf(probe.NewError(e).Trace(args...), "Unable to add sites for replication")
printMsg(successMessage(res))
return nil
}
+128
View File
@@ -0,0 +1,128 @@
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
import (
"net/url"
"strings"
"github.com/fatih/color"
"github.com/minio/cli"
json "github.com/minio/colorjson"
"github.com/minio/madmin-go"
"github.com/minio/mc/pkg/probe"
"github.com/minio/pkg/console"
)
var adminReplicateEditFlags = []cli.Flag{
cli.StringFlag{
Name: "deployment-id",
Usage: "deployment id of the site, should be a unique value",
},
cli.StringFlag{
Name: "endpoint",
Usage: "endpoint for the site",
},
}
var adminReplicateEditCmd = cli.Command{
Name: "edit",
Usage: "edit endpoint of site participating in cluster replication",
Action: mainAdminReplicateEdit,
OnUsageError: onUsageError,
Before: setGlobalsFromContext,
Flags: append(globalFlags, adminReplicateEditFlags...),
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} ALIAS --deployment-id [DEPLOYMENT-ID] --endpoint [NEW-ENDPOINT]
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Edit a site endpoint participating in cluster-level replication:
{{.Prompt}} {{.HelpName}} myminio --deployment-id c1758167-4426-454f-9aae-5c3dfdf6df64 --endpoint https://minio2:9000
`,
}
type editSuccessMessage madmin.ReplicateEditStatus
func (m editSuccessMessage) JSON() string {
bs, e := json.MarshalIndent(madmin.ReplicateEditStatus(m), "", " ")
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
return string(bs)
}
func (m editSuccessMessage) String() string {
v := madmin.ReplicateEditStatus(m)
messages := []string{v.Status}
if v.ErrDetail != "" {
messages = append(messages, v.ErrDetail)
}
return console.Colorize("UserMessage", strings.Join(messages, "\n"))
}
func checkAdminReplicateEditSyntax(ctx *cli.Context) {
// Check argument count
argsNr := len(ctx.Args())
if argsNr < 1 {
cli.ShowCommandHelpAndExit(ctx, ctx.Command.Name, 1) // last argument is exit code
}
if argsNr != 1 {
fatalIf(errInvalidArgument().Trace(ctx.Args().Tail()...),
"Invalid arguments specified for edit command.")
}
}
func mainAdminReplicateEdit(ctx *cli.Context) error {
checkAdminReplicateEditSyntax(ctx)
console.SetColor("UserMessage", color.New(color.FgGreen))
// Get the alias parameter from cli
args := ctx.Args()
aliasedURL := args.Get(0)
// Create a new MinIO Admin Client
client, err := newAdminClient(aliasedURL)
fatalIf(err, "Unable to initialize admin connection.")
if !ctx.IsSet("deployment-id") {
fatalIf(errInvalidArgument(), "--deployment-id is a required flag")
}
if !ctx.IsSet("endpoint") {
fatalIf(errInvalidArgument(), "--endpoint is a required flag")
}
parsedURL := ctx.String("endpoint")
u, e := url.Parse(parsedURL)
if e != nil {
fatalIf(errInvalidArgument().Trace(parsedURL), "Unsupported URL format %v", e)
}
res, e := client.SiteReplicationEdit(globalContext, madmin.PeerInfo{
DeploymentID: ctx.String("deployment-id"),
Endpoint: u.String(),
})
fatalIf(probe.NewError(e).Trace(args...), "Unable to edit cluster replication site endpoint")
printMsg(editSuccessMessage(res))
return nil
}
+120
View File
@@ -0,0 +1,120 @@
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
import (
"strings"
"github.com/fatih/color"
"github.com/minio/cli"
json "github.com/minio/colorjson"
"github.com/minio/madmin-go"
"github.com/minio/mc/pkg/probe"
"github.com/minio/pkg/console"
)
var adminReplicateInfoCmd = cli.Command{
Name: "info",
Usage: "get site replication information",
Action: mainAdminReplicationInfo,
OnUsageError: onUsageError,
Before: setGlobalsFromContext,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} ALIAS1
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Get Site Replication information:
{{.Prompt}} {{.HelpName}} minio1
`,
}
type srInfo madmin.SiteReplicationInfo
func (i srInfo) JSON() string {
bs, e := json.MarshalIndent(madmin.SiteReplicationInfo(i), "", " ")
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
return string(bs)
}
func (i srInfo) String() string {
var messages []string
info := madmin.SiteReplicationInfo(i)
if info.Enabled {
messages = []string{
"SiteReplication enabled for:\n",
}
r := console.Colorize("THeaders", newPrettyTable(" | ",
Field{"Deployment ID", 36},
Field{"Name", 15},
Field{"Endpoint", 50},
).buildRow("Deployment ID", "Site Name", "Endpoint"))
messages = append(messages, r)
for _, peer := range info.Sites {
r := console.Colorize("TDetail", newPrettyTable(" | ",
Field{"Deployment ID", 36},
Field{"Name", 15},
Field{"Endpoint", 50},
).buildRow(peer.DeploymentID, peer.Name, peer.Endpoint))
messages = append(messages, r)
}
} else {
messages = []string{"SiteReplication is not enabled"}
}
return console.Colorize("UserMessage", strings.Join(messages, "\n"))
}
func mainAdminReplicationInfo(ctx *cli.Context) error {
{
// Check argument count
argsNr := len(ctx.Args())
if argsNr != 1 {
fatalIf(errInvalidArgument().Trace(ctx.Args().Tail()...),
"Need exactly one alias argument.")
}
}
console.SetColor("UserMessage", color.New(color.FgGreen))
console.SetColor("THeaders", color.New(color.Bold, color.FgHiWhite))
console.SetColor("TDetail", color.New(color.Bold, color.FgCyan))
// Get the alias parameter from cli
args := ctx.Args()
aliasedURL := args.Get(0)
// Create a new MinIO Admin Client
client, err := newAdminClient(aliasedURL)
fatalIf(err, "Unable to initialize admin connection.")
info, e := client.SiteReplicationInfo(globalContext)
fatalIf(probe.NewError(e).Trace(args...), "Unable to get cluster replication information")
printMsg(srInfo(info))
return nil
}
+129
View File
@@ -0,0 +1,129 @@
// Copyright (c) 2015-2022 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
import (
"fmt"
"strings"
"github.com/fatih/color"
"github.com/minio/cli"
json "github.com/minio/colorjson"
"github.com/minio/madmin-go"
"github.com/minio/mc/pkg/probe"
"github.com/minio/pkg/console"
)
var adminReplicateRemoveFlags = []cli.Flag{
cli.BoolFlag{
Name: "all",
Usage: "remove site replication from all participating sites",
},
cli.BoolFlag{
Name: "force",
Usage: "force removal of site(s) from site replication configuration",
},
}
var adminReplicateRemoveCmd = cli.Command{
Name: "remove",
Usage: "remove one or more sites from site replication",
Action: mainAdminReplicationRemoveStatus,
OnUsageError: onUsageError,
Before: setGlobalsFromContext,
Flags: append(globalFlags, adminReplicateRemoveFlags...),
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} TARGET
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Remove site replication for all sites:
{{.Prompt}} {{.HelpName}} minio2 --all --force
2. Remove site replication for site with site names alpha, baker from active cluster minio2:
{{.Prompt}} {{.HelpName}} minio2 alpha baker --force
`,
}
type srRemoveStatus struct {
madmin.ReplicateRemoveStatus
sites []string
RemoveAll bool
}
func (i srRemoveStatus) JSON() string {
ds, e := json.MarshalIndent(i.ReplicateRemoveStatus, "", " ")
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
return string(ds)
}
func (i srRemoveStatus) String() string {
if i.RemoveAll {
return console.Colorize("UserMessage", fmt.Sprintf("All site(s) were removed successfully"))
}
return console.Colorize("UserMessage", fmt.Sprintf("Following site(s) %s were removed successfully", strings.Join(i.sites, ", ")))
}
func checkAdminReplicateRemoveSyntax(ctx *cli.Context) {
// Check argument count
argsNr := len(ctx.Args())
if ctx.IsSet("all") && argsNr > 1 {
fatalIf(errInvalidArgument().Trace(ctx.Args().Tail()...),
"")
}
if argsNr < 2 && !ctx.IsSet("all") {
fatalIf(errInvalidArgument().Trace(ctx.Args().Tail()...),
"Need at least two arguments to remove command.")
}
if !ctx.IsSet("force") {
fatalIf(errDummy().Trace(),
"Site removal requires --force flag. This operation is *IRREVERSIBLE*. Please review carefully before performing this *DANGEROUS* operation.")
}
}
func mainAdminReplicationRemoveStatus(ctx *cli.Context) error {
checkAdminReplicateRemoveSyntax(ctx)
console.SetColor("UserMessage", color.New(color.FgGreen))
// Get the alias parameter from cli
args := ctx.Args()
aliasedURL := args.Get(0)
var rreq madmin.SRRemoveReq
rreq.SiteNames = append(rreq.SiteNames, args.Tail()...)
rreq.RemoveAll = ctx.Bool("all")
// Create a new MinIO Admin Client
client, err := newAdminClient(aliasedURL)
fatalIf(err, "Unable to initialize admin connection.")
st, e := client.SiteReplicationRemove(globalContext, rreq)
fatalIf(probe.NewError(e).Trace(args...), "Unable to remove cluster replication")
printMsg(srRemoveStatus{
ReplicateRemoveStatus: st,
sites: args.Tail(),
RemoveAll: rreq.RemoveAll,
})
return nil
}
+723
View File
@@ -0,0 +1,723 @@
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
import (
"fmt"
"sort"
"strings"
"github.com/fatih/color"
"github.com/minio/cli"
json "github.com/minio/colorjson"
"github.com/minio/madmin-go"
"github.com/minio/mc/pkg/probe"
"github.com/minio/pkg/console"
)
var adminReplicateStatusFlags = []cli.Flag{
cli.BoolFlag{
Name: "buckets",
Usage: "display only buckets",
},
cli.BoolFlag{
Name: "policies",
Usage: "display only policies",
},
cli.BoolFlag{
Name: "users",
Usage: "display only users",
},
cli.BoolFlag{
Name: "groups",
Usage: "display only groups",
},
cli.BoolFlag{
Name: "all",
Usage: "display all available site replication status",
},
cli.StringFlag{
Name: "bucket",
Usage: "display bucket sync status",
},
cli.StringFlag{
Name: "policy",
Usage: "display policy sync status",
},
cli.StringFlag{
Name: "user",
Usage: "display user sync status",
},
cli.StringFlag{
Name: "group",
Usage: "display group sync status",
},
}
// Some cell values
const (
tickCell string = "✔ "
crossTickCell string = "✗ "
blankCell string = " "
fieldLen = 15
)
var adminReplicateStatusCmd = cli.Command{
Name: "status",
Usage: "display site replication status",
Action: mainAdminReplicationStatus,
OnUsageError: onUsageError,
Before: setGlobalsFromContext,
Flags: append(globalFlags, adminReplicateStatusFlags...),
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} TARGET
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Display overall site replication status:
{{.Prompt}} {{.HelpName}} minio1
2. Display site replication status of buckets across sites
{{.Prompt}} {{.HelpName}} minio1 --buckets
3. Drill down and view site replication status of bucket "bucket"
{{.Prompt}} {{.HelpName}} minio1 --bucket bucket
4. Drill down and view site replication status of user "foo"
{{.Prompt}} {{.HelpName}} minio1 --user foo
`,
}
type srStatus struct {
madmin.SRStatusInfo
opts madmin.SRStatusOptions
}
func (i srStatus) JSON() string {
bs, e := json.MarshalIndent(madmin.SRStatusInfo(i.SRStatusInfo), "", " ")
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
return string(bs)
}
func (i srStatus) String() string {
var messages []string
// Color palette initialization
console.SetColor("Summary", color.New(color.FgWhite, color.Bold))
console.SetColor("SummaryHdr", color.New(color.FgCyan, color.Bold))
console.SetColor("SummaryDtl", color.New(color.FgGreen, color.Bold))
coloredDot := console.Colorize("Status", dot)
nameIDMap := make(map[string]string)
var siteNames []string
info := i.SRStatusInfo
for dID := range info.Sites {
sname := strings.ToTitle(info.Sites[dID].Name)
siteNames = append(siteNames, sname)
nameIDMap[sname] = dID
}
if !info.Enabled {
messages = []string{"SiteReplication is not enabled"}
return console.Colorize("UserMessage", strings.Join(messages, "\n"))
}
sort.Strings(siteNames)
legendHdr := []string{"Site"}
legendFields := []Field{{"Entity", 15}}
for _, sname := range siteNames {
legendHdr = append(legendHdr, sname)
legendFields = append(legendFields, Field{"sname", 15})
}
if i.opts.Buckets {
messages = append(messages,
console.Colorize("SummaryHdr", "Bucket replication status:"))
switch {
case i.MaxBuckets == 0:
messages = append(messages, console.Colorize("Summary", "No Buckets present\n"))
default:
msg := console.Colorize(i.getTheme(len(info.BucketStats) == 0), fmt.Sprintf("%d/%d Buckets in sync", info.MaxBuckets-len(info.BucketStats), info.MaxBuckets)) + "\n"
messages = append(messages, fmt.Sprintf("%s %s", coloredDot, msg))
if len(i.BucketStats) > 0 {
messages = append(messages, i.siteHeader(siteNames, "Bucket"))
}
var detailFields []Field
for b, ssMap := range i.BucketStats {
var details []string
details = append(details, b)
detailFields = append(detailFields, legendFields[0])
for _, sname := range siteNames {
detailFields = append(detailFields, legendFields[0])
dID := nameIDMap[sname]
ss := ssMap[dID]
switch {
case !ss.HasBucket:
details = append(details, fmt.Sprintf("%s Bucket", blankCell))
case ss.OLockConfigMismatch, ss.PolicyMismatch, ss.QuotaCfgMismatch, ss.ReplicationCfgMismatch, ss.TagMismatch:
details = append(details, fmt.Sprintf("%s in-sync", crossTickCell))
default:
details = append(details, fmt.Sprintf("%s in-sync", tickCell))
}
}
messages = append(messages, newPrettyTable(" | ",
detailFields...).buildRow(details...))
messages = append(messages, "")
}
}
}
if i.opts.Policies {
messages = append(messages,
console.Colorize("SummaryHdr", "Policy replication status:"))
switch {
case i.MaxPolicies == 0:
messages = append(messages, console.Colorize("Summary", "No Policies present\n"))
default:
msg := console.Colorize(i.getTheme(len(i.PolicyStats) == 0), fmt.Sprintf("%d/%d Policies in sync", info.MaxPolicies-len(info.PolicyStats), info.MaxPolicies)) + "\n"
messages = append(messages, fmt.Sprintf("%s %s", coloredDot, msg))
if len(i.PolicyStats) > 0 {
messages = append(messages, i.siteHeader(siteNames, "Policy"))
}
var detailFields []Field
for b, ssMap := range i.PolicyStats {
var details []string
details = append(details, b)
detailFields = append(detailFields, legendFields[0])
for _, sname := range siteNames {
detailFields = append(detailFields, legendFields[0])
dID := nameIDMap[sname]
ss := ssMap[dID]
switch {
case !ss.HasPolicy:
details = append(details, fmt.Sprintf("%s Policy", blankCell))
case ss.PolicyMismatch:
details = append(details, fmt.Sprintf("%s in-sync", crossTickCell))
default:
details = append(details, fmt.Sprintf("%s in-sync", tickCell))
}
}
messages = append(messages, newPrettyTable(" | ",
detailFields...).buildRow(details...))
}
if len(i.PolicyStats) > 0 {
messages = append(messages, "")
}
}
}
if i.opts.Users {
messages = append(messages,
console.Colorize("SummaryHdr", "User replication status:"))
switch {
case i.MaxUsers == 0:
messages = append(messages, console.Colorize("Summary", "No Users present\n"))
default:
msg := console.Colorize(i.getTheme(len(i.UserStats) == 0), fmt.Sprintf("%d/%d Users in sync", info.MaxUsers-len(i.UserStats), info.MaxUsers)) + "\n"
messages = append(messages, fmt.Sprintf("%s %s", coloredDot, msg))
if len(i.UserStats) > 0 {
messages = append(messages, i.siteHeader(siteNames, "User"))
}
var detailFields []Field
for b, ssMap := range i.UserStats {
var details []string
details = append(details, b)
detailFields = append(detailFields, legendFields[0])
for _, sname := range siteNames {
detailFields = append(detailFields, legendFields[0])
dID := nameIDMap[sname]
ss, ok := ssMap[dID]
switch {
case !ss.HasUser:
details = append(details, fmt.Sprintf("%s", blankCell))
case !ok, ss.UserInfoMismatch:
details = append(details, fmt.Sprintf("%s in-sync", crossTickCell))
default:
details = append(details, fmt.Sprintf("%s in-sync", tickCell))
}
}
messages = append(messages, newPrettyTable(" | ",
detailFields...).buildRow(details...))
}
if len(i.UserStats) > 0 {
messages = append(messages, "")
}
}
}
if i.opts.Groups {
messages = append(messages,
console.Colorize("SummaryHdr", "Group replication status:"))
switch {
case i.MaxGroups == 0:
messages = append(messages, console.Colorize("Summary", "No Groups present\n"))
default:
msg := console.Colorize(i.getTheme(len(i.GroupStats) == 0), fmt.Sprintf("%d/%d Groups in sync", i.MaxGroups-len(i.GroupStats), i.MaxGroups)) + "\n"
messages = append(messages, fmt.Sprintf("%s %s", coloredDot, msg))
if len(i.GroupStats) > 0 {
messages = append(messages, i.siteHeader(siteNames, "Group"))
}
var detailFields []Field
for b, ssMap := range i.GroupStats {
var details []string
details = append(details, b)
detailFields = append(detailFields, legendFields[0])
for _, sname := range siteNames {
detailFields = append(detailFields, legendFields[0])
dID := nameIDMap[sname]
ss := ssMap[dID]
switch {
case !ss.HasGroup:
details = append(details, fmt.Sprintf("%s", blankCell))
case ss.GroupDescMismatch:
details = append(details, fmt.Sprintf("%s in-sync", crossTickCell))
default:
details = append(details, fmt.Sprintf("%s in-sync", tickCell))
}
}
messages = append(messages, newPrettyTable(" | ",
detailFields...).buildRow(details...))
}
if len(i.GroupStats) > 0 {
messages = append(messages, "")
}
}
}
switch i.opts.Entity {
case madmin.SRBucketEntity:
messages = append(messages, i.getBucketStatusSummary(siteNames, nameIDMap, "Bucket")...)
case madmin.SRPolicyEntity:
messages = append(messages, i.getPolicyStatusSummary(siteNames, nameIDMap, "Policy")...)
case madmin.SRUserEntity:
messages = append(messages, i.getUserStatusSummary(siteNames, nameIDMap, "User")...)
case madmin.SRGroupEntity:
messages = append(messages, i.getGroupStatusSummary(siteNames, nameIDMap, "Group")...)
}
return console.Colorize("UserMessage", strings.Join(messages, "\n"))
}
func (i srStatus) siteHeader(siteNames []string, legend string) string {
legendHdr := []string{legend}
legendFields := []Field{{"Entity", 15}}
for _, sname := range siteNames {
legendHdr = append(legendHdr, sname)
legendFields = append(legendFields, Field{"sname", 15})
}
return console.Colorize("SummaryHdr", newPrettyTable(" | ",
legendFields...,
).buildRow(legendHdr...))
}
func (i srStatus) getTheme(match bool) string {
theme := "UserMessage"
if !match {
theme = "WarningMessage"
}
return theme
}
func (i srStatus) getBucketStatusSummary(siteNames []string, nameIDMap map[string]string, legend string) []string {
var messages []string
coloredDot := console.Colorize("Status", dot)
var found bool
for _, st := range i.SRStatusInfo.BucketStats[i.opts.EntityValue] {
if st.HasBucket {
found = true
break
}
}
if !found {
messages = append(messages, console.Colorize("Summary", fmt.Sprintf("Bucket %s not found\n", i.opts.EntityValue)))
return messages
}
messages = append(messages,
console.Colorize("SummaryHdr", fmt.Sprintf("%s %s\n", coloredDot, console.Colorize("Summary", "Bucket config replication summary for: ")+console.Colorize("UserMessage", i.opts.EntityValue))))
siteHdr := i.siteHeader(siteNames, legend)
messages = append(messages, siteHdr)
rowLegend := []string{"Tags", "Policy", "Quota", "Retention", "Encryption", "Replication"}
detailFields := make([][]Field, len(rowLegend))
var retention, encryption, tags, bpolicies, quota, replication []string
for i, row := range rowLegend {
detailFields[i] = make([]Field, len(siteNames)+1)
detailFields[i][0] = Field{"Entity", 15}
switch i {
case 0:
tags = append(tags, row)
case 1:
bpolicies = append(bpolicies, row)
case 2:
quota = append(quota, row)
case 3:
retention = append(retention, row)
case 4:
encryption = append(encryption, row)
case 5:
replication = append(replication, row)
}
}
rows := make([]string, len(rowLegend))
for j, sname := range siteNames {
dID := nameIDMap[sname]
ss := i.SRStatusInfo.BucketStats[i.opts.EntityValue][dID]
var theme, msgStr string
for r := range rowLegend {
switch r {
case 0:
theme, msgStr = syncStatus(ss.TagMismatch, ss.HasTagsSet)
tags = append(tags, msgStr)
detailFields[r][j+1] = Field{theme, fieldLen}
case 1:
theme, msgStr = syncStatus(ss.PolicyMismatch, ss.HasPolicySet)
bpolicies = append(bpolicies, msgStr)
detailFields[r][j+1] = Field{theme, fieldLen}
case 2:
theme, msgStr = syncStatus(ss.QuotaCfgMismatch, ss.HasQuotaCfgSet)
quota = append(quota, msgStr)
detailFields[r][j+1] = Field{theme, fieldLen}
case 3:
theme, msgStr = syncStatus(ss.OLockConfigMismatch, ss.HasOLockConfigSet)
retention = append(retention, msgStr)
detailFields[r][j+1] = Field{theme, fieldLen}
case 4:
theme, msgStr = syncStatus(ss.SSEConfigMismatch, ss.HasSSECfgSet)
encryption = append(encryption, msgStr)
detailFields[r][j+1] = Field{theme, fieldLen}
case 5:
theme, msgStr = syncStatus(ss.ReplicationCfgMismatch, ss.HasReplicationCfg)
replication = append(replication, msgStr)
detailFields[r][j+1] = Field{theme, fieldLen}
}
}
}
for r := range rowLegend {
switch r {
case 0:
rows[r] = newPrettyTable(" | ",
detailFields[r]...).buildRow(tags...)
case 1:
rows[r] = newPrettyTable(" | ",
detailFields[r]...).buildRow(bpolicies...)
case 2:
rows[r] = newPrettyTable(" | ",
detailFields[r]...).buildRow(quota...)
case 3:
rows[r] = newPrettyTable(" | ",
detailFields[r]...).buildRow(retention...)
case 4:
rows[r] = newPrettyTable(" | ",
detailFields[r]...).buildRow(encryption...)
case 5:
rows[r] = newPrettyTable(" | ",
detailFields[r]...).buildRow(replication...)
}
}
messages = append(messages, rows...)
return messages
}
func (i srStatus) getPolicyStatusSummary(siteNames []string, nameIDMap map[string]string, legend string) []string {
var messages []string
coloredDot := console.Colorize("Status", dot)
var found bool
for _, st := range i.SRStatusInfo.PolicyStats[i.opts.EntityValue] {
if st.HasPolicy {
found = true
break
}
}
if !found {
messages = append(messages, console.Colorize("Summary", fmt.Sprintf("Policy %s not found\n", i.opts.EntityValue)))
return messages
}
rowLegend := []string{"Policy"}
detailFields := make([][]Field, len(rowLegend))
var policies []string
detailFields[0] = make([]Field, len(siteNames)+1)
detailFields[0][0] = Field{"Entity", 15}
policies = append(policies, "Policy")
rows := make([]string, len(rowLegend))
for j, sname := range siteNames {
dID := nameIDMap[sname]
ss := i.SRStatusInfo.PolicyStats[i.opts.EntityValue][dID]
var theme, msgStr string
for r := range rowLegend {
switch r {
case 0:
theme, msgStr = syncStatus(ss.PolicyMismatch, ss.HasPolicy)
policies = append(policies, msgStr)
detailFields[r][j+1] = Field{theme, fieldLen}
}
}
}
for r := range rowLegend {
switch r {
case 0:
rows[r] = newPrettyTable(" | ",
detailFields[r]...).buildRow(policies...)
}
}
messages = append(messages,
console.Colorize("SummaryHdr", fmt.Sprintf("%s %s\n", coloredDot, console.Colorize("Summary", "Policy replication summary for: ")+console.Colorize("UserMessage", i.opts.EntityValue))))
siteHdr := i.siteHeader(siteNames, legend)
messages = append(messages, siteHdr)
messages = append(messages, rows...)
return messages
}
func (i srStatus) getUserStatusSummary(siteNames []string, nameIDMap map[string]string, legend string) []string {
var messages []string
coloredDot := console.Colorize("Status", dot)
var found bool
for _, st := range i.SRStatusInfo.UserStats[i.opts.EntityValue] {
if st.HasUser {
found = true
break
}
}
if !found {
messages = append(messages, console.Colorize("Summary", fmt.Sprintf("User %s not found\n", i.opts.EntityValue)))
return messages
}
rowLegend := []string{"Info", "Policy mapping"}
detailFields := make([][]Field, len(rowLegend))
var users, policyMapping []string
for i, row := range rowLegend {
detailFields[i] = make([]Field, len(siteNames)+1)
detailFields[i][0] = Field{"Entity", 15}
switch i {
case 0:
users = append(users, row)
default:
policyMapping = append(policyMapping, row)
}
}
rows := make([]string, len(rowLegend))
for j, sname := range siteNames {
dID := nameIDMap[sname]
ss := i.SRStatusInfo.UserStats[i.opts.EntityValue][dID]
var theme, msgStr string
for r := range rowLegend {
switch r {
case 0:
theme, msgStr = syncStatus(ss.UserInfoMismatch, ss.HasUser)
users = append(users, msgStr)
detailFields[r][j+1] = Field{theme, fieldLen}
case 1:
theme, msgStr = syncStatus(ss.PolicyMismatch, ss.HasPolicyMapping)
policyMapping = append(policyMapping, msgStr)
detailFields[r][j+1] = Field{theme, fieldLen}
}
}
}
for r := range rowLegend {
switch r {
case 0:
rows[r] = newPrettyTable(" | ",
detailFields[r]...).buildRow(users...)
case 1:
rows[r] = newPrettyTable(" | ",
detailFields[r]...).buildRow(policyMapping...)
}
}
messages = append(messages,
console.Colorize("SummaryHdr", fmt.Sprintf("%s %s\n", coloredDot, console.Colorize("Summary", "User replication summary for: ")+console.Colorize("UserMessage", i.opts.EntityValue))))
siteHdr := i.siteHeader(siteNames, legend)
messages = append(messages, siteHdr)
messages = append(messages, rows...)
return messages
}
func (i srStatus) getGroupStatusSummary(siteNames []string, nameIDMap map[string]string, legend string) []string {
var messages []string
coloredDot := console.Colorize("Status", dot)
rowLegend := []string{"Info", "Policy mapping"}
detailFields := make([][]Field, len(rowLegend))
var found bool
for _, st := range i.SRStatusInfo.GroupStats[i.opts.EntityValue] {
if st.HasGroup {
found = true
break
}
}
if !found {
messages = append(messages, console.Colorize("Summary", fmt.Sprintf("Group %s not found\n", i.opts.EntityValue)))
return messages
}
var groups, policyMapping []string
for i, row := range rowLegend {
detailFields[i] = make([]Field, len(siteNames)+1)
detailFields[i][0] = Field{"Entity", 15}
switch i {
case 0:
groups = append(groups, row)
default:
policyMapping = append(policyMapping, row)
}
}
rows := make([]string, len(rowLegend))
// b := i.opts.EntityValue
for j, sname := range siteNames {
dID := nameIDMap[sname]
ss := i.SRStatusInfo.GroupStats[i.opts.EntityValue][dID]
// sm := i.SRStatusInfo.StatsSummary
var theme, msgStr string
for r := range rowLegend {
switch r {
case 0:
theme, msgStr = syncStatus(ss.GroupDescMismatch, ss.HasGroup)
groups = append(groups, msgStr)
detailFields[r][j+1] = Field{theme, fieldLen}
case 1:
theme, msgStr = syncStatus(ss.PolicyMismatch, ss.HasPolicyMapping)
policyMapping = append(policyMapping, msgStr)
detailFields[r][j+1] = Field{theme, fieldLen}
}
}
}
for r := range rowLegend {
switch r {
case 0:
rows[r] = newPrettyTable(" | ",
detailFields[r]...).buildRow(groups...)
case 1:
rows[r] = newPrettyTable(" | ",
detailFields[r]...).buildRow(policyMapping...)
}
}
messages = append(messages,
console.Colorize("SummaryHdr", fmt.Sprintf("%s %s\n", coloredDot, console.Colorize("Summary", "Group replication summary for: ")+console.Colorize("UserMessage", i.opts.EntityValue))))
siteHdr := i.siteHeader(siteNames, legend)
messages = append(messages, siteHdr)
messages = append(messages, rows...)
return messages
}
// Calculate srstatus options for command line flags
func srStatusOpts(ctx *cli.Context) (opts madmin.SRStatusOptions) {
if !(ctx.IsSet("buckets") ||
ctx.IsSet("users") ||
ctx.IsSet("groups") ||
ctx.IsSet("policies") ||
ctx.IsSet("bucket") ||
ctx.IsSet("user") ||
ctx.IsSet("group") ||
ctx.IsSet("policy") ||
ctx.IsSet("all")) || ctx.IsSet("all") {
opts.Buckets = true
opts.Users = true
opts.Groups = true
opts.Policies = true
return
}
opts.Buckets = ctx.Bool("buckets")
opts.Policies = ctx.Bool("policies")
opts.Users = ctx.Bool("users")
opts.Groups = ctx.Bool("groups")
for _, name := range []string{"bucket", "user", "group", "policy"} {
if ctx.IsSet(name) {
opts.Entity = madmin.GetSREntityType(name)
opts.EntityValue = ctx.String(name)
break
}
}
return
}
func mainAdminReplicationStatus(ctx *cli.Context) error {
{
// Check argument count
argsNr := len(ctx.Args())
if argsNr != 1 {
fatalIf(errInvalidArgument().Trace(ctx.Args().Tail()...),
"Need exactly one alias argument.")
}
groupStatus := ctx.IsSet("buckets") || ctx.IsSet("groups") || ctx.IsSet("users") || ctx.IsSet("policies")
indivStatus := ctx.IsSet("bucket") || ctx.IsSet("group") || ctx.IsSet("user") || ctx.IsSet("policy")
if groupStatus && indivStatus {
fatalIf(errInvalidArgument().Trace(ctx.Args().Tail()...),
"Cannot specify both (bucket|group|policy|user) flag and one or more of buckets|groups|policies|users) flag(s)")
}
setSlc := []bool{ctx.IsSet("bucket"), ctx.IsSet("user"), ctx.IsSet("group"), ctx.IsSet("policy")}
count := 0
for _, s := range setSlc {
if s {
count++
}
}
if count > 1 {
fatalIf(errInvalidArgument().Trace(ctx.Args().Tail()...),
"Cannot specify more than one of --bucket, --policy, --user, --group flags at the same time")
}
}
console.SetColor("UserMessage", color.New(color.FgGreen))
console.SetColor("WarningMessage", color.New(color.FgYellow))
// Get the alias parameter from cli
args := ctx.Args()
aliasedURL := args.Get(0)
// Create a new MinIO Admin Client
client, err := newAdminClient(aliasedURL)
fatalIf(err, "Unable to initialize admin connection.")
opts := srStatusOpts(ctx)
info, e := client.SRStatusInfo(globalContext, opts)
fatalIf(probe.NewError(e).Trace(args...), "Unable to get cluster replication status")
printMsg(srStatus{
SRStatusInfo: info,
opts: opts,
})
return nil
}
func syncStatus(mismatch, set bool) (string, string) {
if !set {
return "Entity", fmt.Sprintf("%s", blankCell)
}
if mismatch {
return "Entity", fmt.Sprintf("%s", crossTickCell)
}
return "Entity", fmt.Sprintf("%s", tickCell)
}
+43
View File
@@ -0,0 +1,43 @@
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
import "github.com/minio/cli"
var adminReplicateSubcommands = []cli.Command{
adminReplicateAddCmd,
adminReplicateEditCmd,
adminReplicateRemoveCmd,
adminReplicateInfoCmd,
adminReplicateStatusCmd,
}
var adminReplicateCmd = cli.Command{
Name: "replicate",
Usage: "manage MinIO site replication",
Action: mainAdminReplicate,
Before: setGlobalsFromContext,
Flags: globalFlags,
Subcommands: adminReplicateSubcommands,
HideHelpCommand: true,
}
func mainAdminReplicate(ctx *cli.Context) error {
commandNotFound(ctx, adminReplicateSubcommands)
return nil
}
+382
View File
@@ -0,0 +1,382 @@
// Copyright (c) 2015-2022 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
import (
"bytes"
"context"
"errors"
"fmt"
"os"
"sort"
"strings"
"time"
"github.com/charmbracelet/bubbles/spinner"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/lipgloss"
"github.com/fatih/color"
"github.com/minio/cli"
json "github.com/minio/colorjson"
"github.com/minio/madmin-go"
"github.com/minio/mc/pkg/probe"
"github.com/minio/pkg/console"
"github.com/olekukonko/tablewriter"
)
var adminScannerInfoFlags = []cli.Flag{
cli.StringFlag{
Name: "nodes",
Usage: "show only on matching servers, comma separate multiple",
},
cli.IntFlag{
Name: "n",
Usage: "number of requests to run before exiting. 0 for endless",
Value: 0,
},
cli.IntFlag{
Name: "interval",
Usage: "interval between requests in seconds",
Value: 3,
},
cli.IntFlag{
Name: "max-paths",
Usage: "maximum number of active paths to show. -1 for unlimited",
Value: -1,
},
}
var adminScannerInfo = cli.Command{
Name: "info",
Usage: "summarize scanner events on MinIO server in real-time",
Action: mainAdminScannerInfo,
OnUsageError: onUsageError,
Before: setGlobalsFromContext,
Flags: append(adminScannerInfoFlags, globalFlags...),
HideHelpCommand: true,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} [FLAGS] TARGET
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Display current in-progress all scanner operations.
{{.Prompt}} {{.HelpName}} myminio/
`,
}
// checkAdminTopAPISyntax - validate all the passed arguments
func checkAdminScannerInfoSyntax(ctx *cli.Context) {
if len(ctx.Args()) == 0 || len(ctx.Args()) > 1 {
cli.ShowCommandHelpAndExit(ctx, "info", 1) // last argument is exit code
}
}
func mainAdminScannerInfo(ctx *cli.Context) error {
checkAdminScannerInfoSyntax(ctx)
aliasedURL := ctx.Args().Get(0)
// Create a new MinIO Admin Client
client, err := newAdminClient(aliasedURL)
if err != nil {
fatalIf(err.Trace(aliasedURL), "Unable to initialize admin client.")
return nil
}
ctxt, cancel := context.WithCancel(globalContext)
defer cancel()
opts := madmin.MetricsOptions{
Type: madmin.MetricsScanner,
N: ctx.Int("n"),
Interval: time.Duration(ctx.Int("interval")) * time.Second,
Hosts: strings.Split(ctx.String("nodes"), ","),
ByHost: false,
}
ui := tea.NewProgram(initScannerMetricsUI(ctx.Int("max-paths")))
if !globalJSON {
go func() {
if e := ui.Start(); e != nil {
cancel()
os.Exit(1)
}
os.Exit(0)
}()
}
cerr := client.Metrics(ctxt, opts, func(metrics madmin.RealtimeMetrics) {
if globalJSON {
printMsg(metricsMessage{RealtimeMetrics: metrics})
return
}
ui.Send(metrics)
})
if cerr != nil && !errors.Is(cerr, context.Canceled) {
fatalIf(probe.NewError(cerr).Trace(aliasedURL), "Error making request")
return nil
}
return nil
}
type metricsMessage struct {
madmin.RealtimeMetrics
}
func (s metricsMessage) JSON() string {
buf := &bytes.Buffer{}
enc := json.NewEncoder(buf)
enc.SetIndent("", " ")
enc.SetEscapeHTML(false)
fatalIf(probe.NewError(enc.Encode(s)), "Unable to marshal into JSON.")
return buf.String()
}
func (s metricsMessage) String() string {
return s.JSON()
}
func initScannerMetricsUI(maxPaths int) *scannerMetricsUI {
s := spinner.New()
s.Spinner = spinner.Points
s.Style = lipgloss.NewStyle().Foreground(lipgloss.Color("205"))
console.SetColor("metrics-duration", color.New(color.FgHiWhite))
console.SetColor("metrics-path", color.New(color.FgGreen))
console.SetColor("metrics-error", color.New(color.FgHiRed))
console.SetColor("metrics-title", color.New(color.FgCyan))
console.SetColor("metrics-top-title", color.New(color.FgHiCyan))
console.SetColor("metrics-number", color.New(color.FgHiWhite))
console.SetColor("metrics-zero", color.New(color.FgHiWhite))
console.SetColor("metrics-date", color.New(color.FgHiWhite))
return &scannerMetricsUI{
spinner: s,
maxPaths: maxPaths,
}
}
type scannerMetricsUI struct {
current madmin.RealtimeMetrics
spinner spinner.Model
quitting bool
maxPaths int
}
func (m *scannerMetricsUI) Init() tea.Cmd {
return m.spinner.Tick
}
func (m *scannerMetricsUI) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
switch msg := msg.(type) {
case tea.KeyMsg:
switch msg.String() {
case "ctrl+c":
m.quitting = true
return m, tea.Quit
default:
return m, nil
}
case madmin.RealtimeMetrics:
m.current = msg
if msg.Final {
m.quitting = true
return m, tea.Quit
}
return m, nil
case spinner.TickMsg:
var cmd tea.Cmd
m.spinner, cmd = m.spinner.Update(msg)
return m, cmd
default:
return m, nil
}
}
func (m *scannerMetricsUI) View() string {
var s strings.Builder
if !m.quitting {
s.WriteString(fmt.Sprintf("%s %s\n", console.Colorize("metrics-top-title", "Scanner Activity:"), m.spinner.View()))
}
// Set table header
table := tablewriter.NewWriter(&s)
table.SetAutoWrapText(false)
table.SetHeaderAlignment(tablewriter.ALIGN_LEFT)
table.SetAlignment(tablewriter.ALIGN_LEFT)
table.SetBorder(true)
table.SetRowLine(false)
addRow := func(s string) {
table.Append([]string{s})
}
_ = addRow
addRowF := func(format string, vals ...interface{}) {
s := fmt.Sprintf(format, vals...)
table.Append([]string{s})
}
sc := m.current.Aggregated.Scanner
if sc == nil {
s.WriteString("(waiting for data)")
return s.String()
}
title := metricsTitle
ui := metricsUint64
const wantCycles = 16
if len(sc.CyclesCompletedAt) < 2 {
addRow("Scan time: Unknown (not enough data)")
} else {
sort.Slice(sc.CyclesCompletedAt, func(i, j int) bool {
return sc.CyclesCompletedAt[i].After(sc.CyclesCompletedAt[j])
})
if len(sc.CyclesCompletedAt) >= wantCycles {
sinceLast := sc.CyclesCompletedAt[0].Sub(sc.CyclesCompletedAt[wantCycles-1])
perMonth := float64(30*24*time.Hour) / float64(sinceLast)
cycleTime := console.Colorize("metrics-number", fmt.Sprintf("%dd%dh%dm", int(sinceLast.Hours()/24), int(sinceLast.Hours())%24, int(sinceLast.Minutes())%60))
perms := console.Colorize("metrics-number", fmt.Sprintf("%.02f", perMonth))
addRowF(title("Last full scan time:")+" %s; Estimated %s/month", cycleTime, perms)
} else {
sinceLast := sc.CyclesCompletedAt[0].Sub(sc.CyclesCompletedAt[1]) * time.Duration(wantCycles)
perMonth := float64(30*24*time.Hour) / float64(sinceLast)
cycleTime := console.Colorize("metrics-number", fmt.Sprintf("%dd%dh%dm", int(sinceLast.Hours()/24), int(sinceLast.Hours())%24, int(sinceLast.Minutes())%60))
perms := console.Colorize("metrics-number", fmt.Sprintf("%.02f", perMonth))
addRowF(title("Est. full scan time:")+" %s; Estimated %s/month", cycleTime, perms)
}
}
if sc.CurrentCycle > 0 {
addRowF(title("Current cycle:")+" %s; Started: %v", ui(sc.CurrentCycle), console.Colorize("metrics-date", sc.CurrentStarted))
addRowF(title("Active disks:")+" %s", ui(uint64(len(sc.ActivePaths))))
} else {
addRowF(title("Current cycle:") + " (between cycles)")
addRowF(title("Active disks:")+" %s", ui(uint64(len(sc.ActivePaths))))
}
addRow("-------------------------------------- Last Minute Statistics ---------------------------------------")
objs := uint64(0)
x := sc.LastMinute.Actions["ScanObject"]
{
avg := x.Avg()
rate := ""
if x.AccTime > 0 {
rate = fmt.Sprintf("; Rate: %v/day", ui(uint64(float64(24*time.Hour)/(float64(time.Minute)/float64(x.Count)))))
}
addRowF(title("Objects Scanned:")+" %s objects; Avg: %v%s", ui(x.Count), metricsDuration(avg), rate)
objs = x.Count
}
x = sc.LastMinute.Actions["ApplyVersion"]
{
avg := x.Avg()
rate := ""
if x.AccTime > 0 {
rate = fmt.Sprintf("; Rate: %s/day", ui(uint64(float64(24*time.Hour)/(float64(time.Minute)/float64(x.Count)))))
}
addRowF(title("Versions Scanned:")+" %s versions; Avg: %v%s", ui(x.Count), metricsDuration(avg), rate)
}
x = sc.LastMinute.Actions["HealCheck"]
{
avg := x.Avg()
rate := ""
if x.AccTime > 0 {
rate = fmt.Sprintf("; Rate: %s/day", ui(uint64(float64(24*time.Hour)/(float64(time.Minute)/float64(x.Count)))))
}
addRowF(title("Versions Heal Checked:")+" %s versions; Avg: %v%s", ui(x.Count), metricsDuration(avg), rate)
}
x = sc.LastMinute.Actions["ReadMetadata"]
addRowF(title("Read Metadata:")+" %s objects; Avg: %v, Size: %v bytes/obj", ui(x.Count), metricsDuration(x.Avg()), ui(x.AvgBytes()))
x = sc.LastMinute.Actions["ILM"]
addRowF(title("ILM checks:")+" %s versions; Avg: %v", ui(x.Count), metricsDuration(x.Avg()))
x = sc.LastMinute.Actions["CheckReplication"]
addRowF(title("Check Replication:")+" %s versions; Avg: %v", ui(x.Count), metricsDuration(x.Avg()))
x = sc.LastMinute.Actions["TierObjSweep"]
if x.Count > 0 {
addRowF(title("Sweep Tiered:")+" %s versions; Avg: %v", ui(x.Count), metricsDuration(x.Avg()))
}
x = sc.LastMinute.Actions["CheckMissing"]
addRowF(title("Verify Deleted:")+" %s folders; Avg: %v", ui(x.Count), metricsDuration(x.Avg()))
for k, x := range sc.LastMinute.ILM {
const length = 17
k += ":"
if len(k) < length {
k += strings.Repeat(" ", length-len(k))
}
addRowF(title("ILM, %s")+" %s actions; Avg: %v.", k, ui(x.Count), metricsDuration(x.Avg()))
}
x = sc.LastMinute.Actions["Yield"]
{
avg := fmt.Sprintf("%v", metricsDuration(x.Avg()))
if objs > 0 {
avg = console.Colorize("metrics-duration", fmt.Sprintf("%v/obj", metricsDuration(time.Duration(x.AccTime/objs))))
}
addRowF(title("Yield:")+" %v total; Avg: %s", metricsDuration(time.Duration(x.AccTime)), avg)
}
if m.maxPaths != 0 && len(sc.ActivePaths) > 0 {
addRow("------------------------------------- Currently Scanning Paths --------------------------------------")
const length = 100
for i, s := range sc.ActivePaths {
if i == m.maxPaths {
break
}
if len(s) > length {
s = s[:length-3] + "..."
}
s = strings.ReplaceAll(s, "\\", "/")
addRow(console.Colorize("metrics-path", s))
}
}
if errs := m.current.Errors; len(errs) > 0 {
addRow("------------------------------------------- Errors --------------------------------------------------")
for _, s := range errs {
addRow(console.Colorize("metrics-error", s))
}
}
table.Render()
return s.String()
}
func metricsDuration(d time.Duration) string {
if d == 0 {
return console.Colorize("metrics-zero", "0ms")
}
if d > time.Millisecond {
d = d.Round(time.Microsecond)
}
if d > time.Second {
d = d.Round(time.Millisecond)
}
if d > time.Minute {
d = d.Round(time.Second / 10)
}
return console.Colorize("metrics-duration", d)
}
func metricsUint64(v uint64) string {
if v == 0 {
return console.Colorize("metrics-zero", v)
}
return console.Colorize("metrics-number", v)
}
func metricsTitle(s string) string {
return console.Colorize("metrics-title", s)
}
+136
View File
@@ -0,0 +1,136 @@
// Copyright (c) 2015-2022 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
import (
"context"
"fmt"
"github.com/fatih/color"
"github.com/minio/cli"
"github.com/minio/mc/pkg/probe"
"github.com/minio/pkg/console"
)
var adminScannerTraceFlags = []cli.Flag{
cli.StringFlag{
Name: "response-threshold",
Usage: "trace calls only with response duration greater than this threshold (e.g. `5ms`)",
},
cli.StringSliceFlag{
Name: "funcname",
Usage: "trace only matching func name (eg 'scanner.ScanObject')",
},
cli.StringSliceFlag{
Name: "node",
Usage: "trace only matching servers",
},
}
var adminScannerTraceCmd = cli.Command{
Name: "trace",
Usage: "show trace for MinIO scanner operations",
Action: mainAdminScannerTrace,
OnUsageError: onUsageError,
Before: setGlobalsFromContext,
Flags: append(adminScannerTraceFlags, globalFlags...),
HideHelpCommand: true,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} [FLAGS] TARGET
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Show scanner trace for MinIO server
{{.Prompt}} {{.HelpName}} myminio
2. Show scanner trace for a specific path
{{.Prompt}} {{.HelpName}} --path my-bucket/my-prefix/* myminio
3. Show trace for only ScanObject operations
{{.Prompt}} {{.HelpName}} --funcname=scanner.ScanObject myminio
`,
}
func checkAdminScannerTraceSyntax(ctx *cli.Context) {
if len(ctx.Args()) != 1 {
cli.ShowCommandHelpAndExit(ctx, "trace", 1) // last argument is exit code
}
}
// mainAdminScannerTrace - the entry function of trace command
func mainAdminScannerTrace(ctx *cli.Context) error {
// Check for command syntax
checkAdminScannerTraceSyntax(ctx)
verbose := ctx.Bool("verbose")
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), "Unable to initialize admin client.")
return nil
}
ctxt, cancel := context.WithCancel(globalContext)
defer cancel()
opts, e := tracingOpts(ctx, []string{"scanner"})
fatalIf(probe.NewError(e), "Unable to start tracing")
mopts := matchOpts{
funcNames: ctx.StringSlice("funcname"),
apiPaths: ctx.StringSlice("path"),
nodes: ctx.StringSlice("node"),
}
// Start listening on all trace activity.
traceCh := client.ServiceTrace(ctxt, opts)
for traceInfo := range traceCh {
if traceInfo.Err != nil {
fatalIf(probe.NewError(traceInfo.Err), "Unable to listen to http trace")
}
if matchTrace(mopts, traceInfo) {
printTrace(verbose, traceInfo)
}
}
return nil
}
+41
View File
@@ -0,0 +1,41 @@
// Copyright (c) 2015-2022 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
import "github.com/minio/cli"
var adminScannerSubcommands = []cli.Command{
adminScannerInfo,
adminScannerTraceCmd,
}
var adminScannerCmd = cli.Command{
Name: "scanner",
Usage: "provide MinIO scanner info",
Action: mainAdminScanner,
Before: setGlobalsFromContext,
Flags: globalFlags,
Subcommands: adminScannerSubcommands,
HideHelpCommand: true,
}
// mainAdminScanner is the handle for "mc admin scanner" command.
func mainAdminScanner(ctx *cli.Context) error {
commandNotFound(ctx, adminScannerSubcommands)
return nil
}
+99
View File
@@ -0,0 +1,99 @@
// Copyright (c) 2022 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
import (
"github.com/fatih/color"
"github.com/minio/cli"
json "github.com/minio/colorjson"
"github.com/minio/mc/pkg/probe"
"github.com/minio/pkg/console"
)
var adminServiceFreezeCmd = cli.Command{
Name: "freeze",
Usage: "freeze S3 API calls on MinIO cluster",
Action: mainAdminServiceFreeze,
OnUsageError: onUsageError,
Before: setGlobalsFromContext,
Flags: globalFlags,
Hidden: true, // this command is hidden on purpose, please do not enable it.
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} TARGET
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Freeze all S3 API calls on MinIO server at 'myminio/'.
{{.Prompt}} {{.HelpName}} myminio/
`,
}
// serviceFreezeCommand is container for service freeze command success and failure messages.
type serviceFreezeCommand struct {
Status string `json:"status"`
ServerURL string `json:"serverURL"`
}
// String colorized service freeze command message.
func (s serviceFreezeCommand) String() string {
return console.Colorize("ServiceFreeze", "Freeze command successfully sent to `"+s.ServerURL+"`.")
}
// JSON jsonified service freeze command message.
func (s serviceFreezeCommand) JSON() string {
serviceFreezeJSONBytes, e := json.MarshalIndent(s, "", " ")
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
return string(serviceFreezeJSONBytes)
}
// checkAdminServiceFreezeSyntax - validate all the passed arguments
func checkAdminServiceFreezeSyntax(ctx *cli.Context) {
if len(ctx.Args()) != 1 {
cli.ShowCommandHelpAndExit(ctx, "freeze", 1) // last argument is exit code
}
}
func mainAdminServiceFreeze(ctx *cli.Context) error {
// Validate serivce freeze syntax.
checkAdminServiceFreezeSyntax(ctx)
// Set color.
console.SetColor("ServiceFreeze", color.New(color.FgGreen, color.Bold))
console.SetColor("FailedServiceFreeze", color.New(color.FgRed, color.Bold))
// Get the alias parameter from cli
args := ctx.Args()
aliasedURL := args.Get(0)
client, err := newAdminClient(aliasedURL)
fatalIf(err, "Unable to initialize admin connection.")
// Freeze the specified MinIO server
fatalIf(probe.NewError(client.ServiceFreeze(globalContext)), "Unable to freeze the server.")
// Success..
printMsg(serviceFreezeCommand{Status: "success", ServerURL: aliasedURL})
return nil
}
+79 -43
View File
@@ -1,37 +1,42 @@
/*
* 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.
*/
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
import (
"context"
"fmt"
"time"
"github.com/fatih/color"
"github.com/minio/cli"
json "github.com/minio/mc/pkg/colorjson"
json "github.com/minio/colorjson"
"github.com/minio/madmin-go"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio/pkg/console"
"github.com/minio/pkg/console"
)
var adminServiceRestartCmd = cli.Command{
Name: "restart",
Usage: "restart all MinIO servers",
Action: mainAdminServiceRestart,
Before: setGlobalsFromContext,
Flags: globalFlags,
Name: "restart",
Usage: "restart a MinIO cluster",
Action: mainAdminServiceRestart,
OnUsageError: onUsageError,
Before: setGlobalsFromContext,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
@@ -55,7 +60,7 @@ type serviceRestartCommand struct {
// String colorized service restart command message.
func (s serviceRestartCommand) String() string {
return console.Colorize("ServiceRestart", "Restart command successfully sent to `"+s.ServerURL+"`.")
return console.Colorize("ServiceRestart", "Restart command successfully sent to `"+s.ServerURL+"`. Type Ctrl-C to quit or wait to follow the status of the restart process.")
}
// JSON jsonified service restart command message.
@@ -68,15 +73,16 @@ func (s serviceRestartCommand) JSON() string {
// 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"`
Status string `json:"status"`
ServerURL string `json:"serverURL"`
TimeTaken time.Duration `json:"timeTaken"`
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("ServiceRestart", fmt.Sprintf("\nRestarted `%s` successfully in %s", s.ServerURL, timeDurationToHumanizedDuration(s.TimeTaken).StringShort()))
}
return console.Colorize("FailedServiceRestart", "Failed to restart `"+s.ServerURL+"`. error: "+s.Err.Error())
}
@@ -91,17 +97,18 @@ func (s serviceRestartMessage) JSON() string {
// checkAdminServiceRestartSyntax - validate all the passed arguments
func checkAdminServiceRestartSyntax(ctx *cli.Context) {
if len(ctx.Args()) == 0 || len(ctx.Args()) > 2 {
if len(ctx.Args()) != 1 {
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("ServiceOffline", color.New(color.FgRed, color.Bold))
console.SetColor("ServiceInitializing", color.New(color.FgYellow, color.Bold))
console.SetColor("ServiceRestart", color.New(color.FgGreen, color.Bold))
console.SetColor("FailedServiceRestart", color.New(color.FgRed, color.Bold))
@@ -113,25 +120,54 @@ func mainAdminServiceRestart(ctx *cli.Context) error {
fatalIf(err, "Unable to initialize admin connection.")
// Restart the specified MinIO server
fatalIf(probe.NewError(client.ServiceRestart(globalContext)), "Cannot restart the server.")
fatalIf(probe.NewError(client.ServiceRestart(globalContext)), "Unable to restart the server.")
// Success..
printMsg(serviceRestartCommand{Status: "success", ServerURL: aliasedURL})
// Max. time taken by the server to shutdown is 5 seconds.
// This can happen when there are lot of s3 requests pending when the server
// receives a restart command.
// Sleep for 6 seconds and then check if the server is online.
time.Sleep(6 * time.Second)
coloring := color.New(color.FgRed)
mark := "..."
// Fetch the service status of the specified MinIO server
_, e := client.ServerInfo(globalContext)
if e != nil {
printMsg(serviceRestartMessage{Status: "failure", Err: e, ServerURL: aliasedURL})
} else {
printMsg(serviceRestartMessage{Status: "success", ServerURL: aliasedURL})
// Print restart progress
printProgress := func() {
if !globalQuiet && !globalJSON {
coloring.Printf(mark)
}
}
return nil
printProgress()
mark = "."
timer := time.NewTimer(time.Second)
defer timer.Stop()
t := time.Now()
for {
select {
case <-globalContext.Done():
return globalContext.Err()
case <-timer.C:
ctx, cancel := context.WithTimeout(globalContext, 3*time.Second)
// Fetch the service status of the specified MinIO server
info, e := client.ServerInfo(ctx)
cancel()
switch {
case e == nil && info.Mode == string(madmin.ItemOnline):
printMsg(serviceRestartMessage{
Status: "success",
ServerURL: aliasedURL,
TimeTaken: time.Since(t),
})
return nil
case err == nil && info.Mode == string(madmin.ItemInitializing):
coloring = color.New(color.FgYellow)
mark = "!"
fallthrough
default:
printProgress()
}
timer.Reset(time.Second)
}
}
}
+24 -23
View File
@@ -1,35 +1,37 @@
/*
* 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.
*/
// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
import (
"github.com/fatih/color"
"github.com/minio/cli"
json "github.com/minio/mc/pkg/colorjson"
json "github.com/minio/colorjson"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio/pkg/console"
"github.com/minio/pkg/console"
)
var adminServiceStopCmd = cli.Command{
Name: "stop",
Usage: "stop MinIO server",
Action: mainAdminServiceStop,
Before: setGlobalsFromContext,
Flags: globalFlags,
Name: "stop",
Usage: "stop a MinIO cluster",
Action: mainAdminServiceStop,
OnUsageError: onUsageError,
Before: setGlobalsFromContext,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
@@ -72,7 +74,6 @@ func checkAdminServiceStopSyntax(ctx *cli.Context) {
}
func mainAdminServiceStop(ctx *cli.Context) error {
// Validate serivce stop syntax.
checkAdminServiceStopSyntax(ctx)

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