Compare commits

..
Author SHA1 Message Date
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
163 changed files with 6274 additions and 5455 deletions
+1444 -3797
View File
File diff suppressed because it is too large Load Diff
+3 -2
View File
@@ -4,9 +4,10 @@ FROM arm32v7/alpine:3.12
LABEL maintainer="MinIO Inc <dev@min.io>"
COPY --from=qemu /usr/bin/qemu-arm-static /usr/bin
COPY mc /usr/bin/mc
RUN apk add --no-cache ca-certificates 'curl>7.61.0' && \
curl -s -q https://dl.minio.io/client/mc/release/linux-arm/mc -o /usr/bin/mc && \
chmod +x /usr/bin/mc && \
curl -s -q -O https://raw.githubusercontent.com/minio/minio/release/CREDITS
ENTRYPOINT ["mc"]
+5 -4
View File
@@ -1,12 +1,13 @@
FROM multiarch/qemu-user-static:x86_64-arm as qemu
FROM multiarch/qemu-user-static:x86_64-aarch64 as qemu
FROM arm64v8/alpine:3.12
LABEL maintainer="MinIO Inc <dev@min.io>"
COPY --from=qemu /usr/bin/qemu-arm-static /usr/bin
COPY mc /usr/bin/mc
COPY --from=qemu /usr/bin/qemu-aarch64-static /usr/bin
RUN apk add --no-cache ca-certificates 'curl>7.61.0' && \
curl -s -q https://dl.minio.io/client/mc/release/linux-arm64/mc -o /usr/bin/mc && \
chmod +x /usr/bin/mc && \
curl -s -q -O https://raw.githubusercontent.com/minio/minio/release/CREDITS
ENTRYPOINT ["mc"]
+5 -4
View File
@@ -1,12 +1,13 @@
FROM multiarch/qemu-user-static:x86_64-arm as qemu
FROM multiarch/qemu-user-static:x86_64-ppc64le as qemu
FROM ppc64le/alpine:3.12
LABEL maintainer="MinIO Inc <dev@min.io>"
COPY --from=qemu /usr/bin/qemu-arm-static /usr/bin
COPY mc /usr/bin/mc
COPY --from=qemu /usr/bin/qemu-ppc64le-static /usr/bin
RUN apk add --no-cache ca-certificates 'curl>7.61.0' && \
curl -s -q https://dl.minio.io/client/mc/release/linux-ppc64le/mc -o /usr/bin/mc && \
chmod +x /usr/bin/mc && \
curl -s -q -O https://raw.githubusercontent.com/minio/minio/release/CREDITS
ENTRYPOINT ["mc"]
+3 -3
View File
@@ -2,9 +2,9 @@ FROM alpine:3.12
MAINTAINER MinIO Inc <dev@min.io>
COPY mc /usr/bin/mc
RUN apk add --no-cache ca-certificates 'curl>7.61.0' && \
curl -s -q https://dl.minio.io/client/mc/release/linux-amd64/mc -o /usr/bin/mc && \
chmod +x /usr/bin/mc && \
curl -s -q -O https://raw.githubusercontent.com/minio/minio/release/CREDITS
ENTRYPOINT ["mc"]
+5 -4
View File
@@ -1,12 +1,13 @@
FROM multiarch/qemu-user-static:x86_64-arm as qemu
FROM multiarch/qemu-user-static:x86_64-s390x as qemu
FROM s390x/alpine:3.12
LABEL maintainer="MinIO Inc <dev@min.io>"
COPY --from=qemu /usr/bin/qemu-arm-static /usr/bin
COPY mc /usr/bin/mc
COPY --from=qemu /usr/bin/qemu-s390x-static /usr/bin
RUN apk add --no-cache ca-certificates 'curl>7.61.0' && \
curl -s -q https://dl.minio.io/client/mc/release/linux-s390x/mc -o /usr/bin/mc && \
chmod +x /usr/bin/mc && \
curl -s -q -O https://raw.githubusercontent.com/minio/minio/release/CREDITS
ENTRYPOINT ["mc"]
+37 -32
View File
@@ -4,31 +4,36 @@
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
event manage object notifications
watch listen for object notification events
policy manage anonymous access to buckets and objects
tag manage tags for bucket(s) and object(s)
lock manage default bucket object lock configuration
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
@@ -97,25 +102,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.
```
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,7 +154,7 @@ 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
```
## Test Your Setup
@@ -221,4 +226,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 Apache 2.0 License found at [LICENSE](./LICENSE).
+3 -3
View File
@@ -77,7 +77,7 @@ var adminBucketQuotaCmd = cli.Command{
Name: "quota",
Usage: "Manage bucket quota",
Action: mainAdminBucketQuota,
Before: initBeforeRunningCmd,
Before: setGlobalsFromContext,
Flags: append(adminQuotaFlags, globalFlags...),
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
@@ -100,10 +100,10 @@ EXAMPLES:
{{.Prompt}} {{.HelpName}} myminio/mybucket
2. Set FIFO quota for a bucket "mybucket" on MinIO.
{{.Prompt}} {{.HelpName}} myminio/mybucket --fifo 64kB
{{.Prompt}} {{.HelpName}} myminio/mybucket --fifo 10GB
3. Set hard quota of 1gb for a bucket "mybucket" on MinIO.
{{.Prompt}} {{.HelpName}} myminio/mybucket --hard 1gb
{{.Prompt}} {{.HelpName}} myminio/mybucket --hard 1GB
4. Clear bucket quota configured for bucket "mybucket" on MinIO.
{{.Prompt}} {{.HelpName}} myminio/mybucket --clear
+230
View File
@@ -0,0 +1,230 @@
/*
* MinIO Client (C) 2020 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cmd
import (
"fmt"
"net/url"
"regexp"
"strconv"
"strings"
"github.com/fatih/color"
"github.com/minio/cli"
json "github.com/minio/mc/pkg/colorjson"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio/pkg/auth"
"github.com/minio/minio/pkg/console"
"github.com/minio/minio/pkg/madmin"
)
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)",
},
}
var adminBucketRemoteAddCmd = cli.Command{
Name: "add",
Usage: "add a new remote target",
Action: mainAdminBucketRemoteAdd,
Before: setGlobalsFromContext,
Flags: append(globalFlags, adminBucketRemoteAddFlags...),
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} TARGET http(s)://ACCESSKEY:SECRETKEY@DEST_URL/DEST_BUCKET [--path | --region ] --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 'replicabucket' in region "us-west-1" on https://minio2:9000 for bucket 'srcbucket' on MinIO server.
{{.DisableHistory}}
{{.Prompt}} {{.HelpName}} myminio/srcbucket https://foobar:foo12345@minio2:9000/replicabucket --service "replication" \
--region "us-west-1"
{{.EnableHistory}}
`,
}
// checkAdminBucketRemoteAddSyntax - validate all the passed arguments
func checkAdminBucketRemoteAddSyntax(ctx *cli.Context) {
argsNr := len(ctx.Args())
if argsNr < 2 {
cli.ShowCommandHelpAndExit(ctx, "add", 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"`
}
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)
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+"`.")
}
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)
}
var targetKeys = regexp.MustCompile("^(https?://)(.*?):(.*?)@(.*?)/(.*?)$")
// 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])
TargetURL := args[1]
path := cli.String("path")
if !isValidPath(path) {
fatalIf(errInvalidArgument().Trace(path),
"Unrecognized bucket path style. Valid options are `[on,off, auto]`.")
}
parts := targetKeys.FindStringSubmatch(TargetURL)
if len(parts) != 6 {
fatalIf(probe.NewError(fmt.Errorf("invalid url format")), "Malformed Remote target URL")
}
accessKey := parts[2]
secretKey := parts[3]
parsedURL := fmt.Sprintf("%s%s", parts[1], parts[4])
TargetBucket := strings.TrimSuffix(parts[5], slashSeperator)
TargetBucket = strings.TrimPrefix(TargetBucket, slashSeperator)
u, cerr := url.Parse(parsedURL)
if cerr != nil {
fatalIf(probe.NewError(cerr), "Malformed Remote target URL")
}
secure := u.Scheme == "https"
host := u.Host
if u.Port() == "" {
port := 80
if secure {
port = 443
}
host = host + ":" + strconv.Itoa(port)
}
serviceType := cli.String("service")
if !madmin.ServiceType(serviceType).IsValid() {
fatalIf(errInvalidArgument().Trace(serviceType), "Invalid service type. Valid option is `[replication]`.")
}
console.SetColor(cred, color.New(color.FgYellow, color.Italic))
creds := &auth.Credentials{AccessKey: accessKey, SecretKey: secretKey}
bktTarget = &madmin.BucketTarget{
TargetBucket: TargetBucket,
Secure: secure,
Credentials: creds,
Endpoint: host,
Path: path,
API: "s3v4",
Type: madmin.ServiceType(serviceType),
Region: cli.String("region"),
}
return sourceBucket, bktTarget
}
// 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), "Cannot add new Remote target")
}
printMsg(RemoteMessage{
op: "add",
TargetURL: bktTarget.URL(),
TargetBucket: bktTarget.TargetBucket,
AccessKey: bktTarget.Credentials.AccessKey,
SourceBucket: sourceBucket,
RemoteARN: arn,
})
return nil
}
+151
View File
@@ -0,0 +1,151 @@
/*
* MinIO Client (C) 2020 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cmd
import (
"fmt"
"github.com/fatih/color"
"github.com/minio/cli"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio/pkg/console"
"github.com/minio/minio/pkg/madmin"
)
var 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,
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, "ls", 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.FgRed))
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))
// Get the alias parameter from cli
args := ctx.Args()
aliasedURL := args.Get(0)
_, sourceBucket := url2Alias(aliasedURL)
// Create a new MinIO Admin Client
client, err := newAdminClient(aliasedURL)
fatalIf(err, "Unable to initialize admin connection.")
svcType := ctx.String("service")
targets, e := client.ListRemoteTargets(globalContext, sourceBucket, svcType)
fatalIf(probe.NewError(e).Trace(args...), "Cannot list remote target(s)")
printRemotes(aliasedURL, targets)
return nil
}
func printRemotes(urlStr string, targets []madmin.BucketTarget) {
maxURLLen := 10
maxTgtLen := 6
maxSrcLen := 6
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 maxURLLen > 0 {
console.Println(console.Colorize("RemoteListMessage", fmt.Sprintf("%-*.*s %-*.*s->%-*.*s %s", maxURLLen+8, maxURLLen+8, "Remote URL", maxSrcLen, maxSrcLen, "Source", maxTgtLen, maxTgtLen, "Target", "ARN")))
}
}
for _, target := range targets {
targetURL := target.URL()
if !globalJSON {
if maxURLLen > 0 {
targetURL = fmt.Sprintf("%-*.*s", maxURLLen+8, maxURLLen+8, target.URL())
}
if maxTgtLen > 0 {
target.TargetBucket = fmt.Sprintf("%-*.*s", maxTgtLen, maxTgtLen, target.TargetBucket)
}
if maxSrcLen > 0 {
target.SourceBucket = fmt.Sprintf("%-*.*s", maxSrcLen, maxSrcLen, target.SourceBucket)
}
}
printMsg(RemoteMessage{
op: "ls",
AccessKey: target.Credentials.AccessKey,
TargetBucket: target.TargetBucket,
TargetURL: targetURL,
SourceBucket: target.SourceBucket,
RemoteARN: target.Arn,
ServiceType: string(target.Type),
})
}
}
+40
View File
@@ -0,0 +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.
*/
package cmd
import "github.com/minio/cli"
var adminBucketRemoteCmd = cli.Command{
Name: "remote",
Usage: "configure remote target buckets",
Action: mainadminBucketRemote,
Before: setGlobalsFromContext,
Flags: globalFlags,
Subcommands: []cli.Command{
adminBucketRemoteAddCmd,
adminBucketRemoteListCmd,
adminBucketRemoteRmCmd,
},
HideHelpCommand: true,
}
// mainadminBucketRemote is the handle for "mc admin bucket remote" command.
func mainadminBucketRemote(ctx *cli.Context) error {
cli.ShowCommandHelp(ctx, ctx.Args().First())
return nil
// Sub-commands like "add", "ls", "rm" have their own main.
}
+91
View File
@@ -0,0 +1,91 @@
/*
* MinIO Client (C) 2020 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cmd
import (
"github.com/fatih/color"
"github.com/minio/cli"
"github.com/minio/mc/pkg/probe"
"github.com/minio/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,
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, "rm", 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, "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...), "Cannot remove Remote target")
printMsg(RemoteMessage{
op: "rm",
SourceBucket: sourceBucket,
RemoteARN: arn,
})
return nil
}
+3 -1
View File
@@ -22,9 +22,11 @@ var adminBucketCmd = cli.Command{
Name: "bucket",
Usage: "manage buckets defined in the MinIO server",
Action: mainAdminBucket,
Before: setGlobalsFromContext,
Flags: globalFlags,
Subcommands: []cli.Command{
adminBucketQuotaCmd,
adminBucketRemoteCmd,
},
HideHelpCommand: true,
}
@@ -33,5 +35,5 @@ var adminBucketCmd = cli.Command{
func mainAdminBucket(ctx *cli.Context) error {
cli.ShowCommandHelp(ctx, ctx.Args().First())
return nil
// Sub-commands like "quota", "usage" have their own main.
// Sub-commands like "quota", "remote" have their own main.
}
+1 -1
View File
@@ -25,7 +25,7 @@ import (
var adminConfigExportCmd = cli.Command{
Name: "export",
Usage: "export all config keys to STDOUT",
Before: initBeforeRunningCmd,
Before: setGlobalsFromContext,
Action: mainAdminConfigExport,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
+1 -1
View File
@@ -27,7 +27,7 @@ import (
var adminConfigGetCmd = cli.Command{
Name: "get",
Usage: "interactively retrieve a config key parameters",
Before: initBeforeRunningCmd,
Before: setGlobalsFromContext,
Action: mainAdminConfigGet,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
+1 -1
View File
@@ -43,7 +43,7 @@ var historyListFlags = []cli.Flag{
var adminConfigHistoryCmd = cli.Command{
Name: "history",
Usage: "show all historic configuration changes",
Before: initBeforeRunningCmd,
Before: setGlobalsFromContext,
Action: mainAdminConfigHistory,
Flags: append(append([]cli.Flag{}, globalFlags...), historyListFlags...),
CustomHelpTemplate: `NAME:
+1 -1
View File
@@ -30,7 +30,7 @@ import (
var adminConfigImportCmd = cli.Command{
Name: "import",
Usage: "import multiple config keys from STDIN",
Before: initBeforeRunningCmd,
Before: setGlobalsFromContext,
Action: mainAdminConfigImport,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
+1 -1
View File
@@ -37,7 +37,7 @@ var adminConfigEnvFlags = []cli.Flag{
var adminConfigResetCmd = cli.Command{
Name: "reset",
Usage: "interactively reset a config key parameters",
Before: initBeforeRunningCmd,
Before: setGlobalsFromContext,
Action: mainAdminConfigReset,
Flags: append(adminConfigEnvFlags, globalFlags...),
CustomHelpTemplate: `NAME:
+1 -1
View File
@@ -29,7 +29,7 @@ import (
var adminConfigRestoreCmd = cli.Command{
Name: "restore",
Usage: "rollback back changes to a specific config history",
Before: initBeforeRunningCmd,
Before: setGlobalsFromContext,
Action: mainAdminConfigRestore,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
+1 -1
View File
@@ -31,7 +31,7 @@ import (
var adminConfigSetCmd = cli.Command{
Name: "set",
Usage: "interactively set a config key parameters",
Before: initBeforeRunningCmd,
Before: setGlobalsFromContext,
Action: mainAdminConfigSet,
Flags: append(adminConfigEnvFlags, globalFlags...),
CustomHelpTemplate: `NAME:
+1
View File
@@ -22,6 +22,7 @@ var adminConfigCmd = cli.Command{
Name: "config",
Usage: "manage MinIO server configuration",
Action: mainAdminConfig,
Before: setGlobalsFromContext,
Flags: globalFlags,
Subcommands: []cli.Command{
adminConfigGetCmd,
+1 -1
View File
@@ -49,7 +49,7 @@ var adminConsoleCmd = cli.Command{
Name: "console",
Usage: "show console logs for MinIO server",
Action: mainAdminConsole,
Before: initBeforeRunningCmd,
Before: setGlobalsFromContext,
Flags: append(adminConsoleFlags, globalFlags...),
HideHelpCommand: true,
CustomHelpTemplate: `NAME:
+1 -1
View File
@@ -32,7 +32,7 @@ var adminGroupAddCmd = cli.Command{
Name: "add",
Usage: "add users to a new or existing group",
Action: mainAdminGroupAdd,
Before: initBeforeRunningCmd,
Before: setGlobalsFromContext,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
+1 -1
View File
@@ -24,7 +24,7 @@ var adminGroupDisableCmd = cli.Command{
Name: "disable",
Usage: "Disable a group",
Action: mainAdminGroupEnableDisable,
Before: initBeforeRunningCmd,
Before: setGlobalsFromContext,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
+1 -1
View File
@@ -30,7 +30,7 @@ var adminGroupEnableCmd = cli.Command{
Name: "enable",
Usage: "Enable a group",
Action: mainAdminGroupEnableDisable,
Before: initBeforeRunningCmd,
Before: setGlobalsFromContext,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
+1 -1
View File
@@ -27,7 +27,7 @@ var adminGroupInfoCmd = cli.Command{
Name: "info",
Usage: "display group info",
Action: mainAdminGroupInfo,
Before: initBeforeRunningCmd,
Before: setGlobalsFromContext,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
+1 -1
View File
@@ -27,7 +27,7 @@ var adminGroupListCmd = cli.Command{
Name: "list",
Usage: "display list of groups",
Action: mainAdminGroupList,
Before: initBeforeRunningCmd,
Before: setGlobalsFromContext,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
+1 -1
View File
@@ -28,7 +28,7 @@ var adminGroupRemoveCmd = cli.Command{
Name: "remove",
Usage: "remove group or members from a group",
Action: mainAdminGroupRemove,
Before: initBeforeRunningCmd,
Before: setGlobalsFromContext,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
+1
View File
@@ -22,6 +22,7 @@ var adminGroupCmd = cli.Command{
Name: "group",
Usage: "manage groups",
Action: mainAdminGroup,
Before: setGlobalsFromContext,
Flags: globalFlags,
Subcommands: []cli.Command{
adminGroupAddCmd,
+2 -2
View File
@@ -67,7 +67,7 @@ var adminHealCmd = cli.Command{
Name: "heal",
Usage: "heal disks, buckets and objects on MinIO server",
Action: mainAdminHeal,
Before: initBeforeRunningCmd,
Before: setGlobalsFromContext,
Flags: append(adminHealFlags, globalFlags...),
HideHelpCommand: true,
CustomHelpTemplate: `NAME:
@@ -221,7 +221,7 @@ 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(globalContext, false, false, false, DirNone) {
for content := range clnt.List(globalContext, ListOptions{isRecursive: false, showDir: DirNone}) {
if content.Err != nil {
fatalIf(content.Err.Trace(clnt.GetURL().String()), "Unable to heal bucket `"+bucket+"`.")
return nil
+1 -1
View File
@@ -38,7 +38,7 @@ var adminInfoCmd = cli.Command{
Name: "info",
Usage: "display MinIO server information",
Action: mainAdminInfo,
Before: initBeforeRunningCmd,
Before: setGlobalsFromContext,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
+1 -1
View File
@@ -28,7 +28,7 @@ var adminKMSKeyStatusCmd = cli.Command{
Name: "status",
Usage: "request status information for a KMS master key",
Action: mainAdminKMSKeyStatus,
Before: initBeforeRunningCmd,
Before: setGlobalsFromContext,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
+1
View File
@@ -22,6 +22,7 @@ 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,
+1
View File
@@ -22,6 +22,7 @@ var adminKMSCmd = cli.Command{
Name: "kms",
Usage: "perform KMS management operations",
Action: mainAdminKMS,
Before: setGlobalsFromContext,
Flags: globalFlags,
Subcommands: []cli.Command{
adminKMSKeyCmd,
+1
View File
@@ -34,6 +34,7 @@ var adminCmd = cli.Command{
Usage: "manage MinIO servers",
Action: mainAdmin,
HideHelpCommand: true,
Before: setGlobalsFromContext,
Flags: append(adminFlags, globalFlags...),
Subcommands: []cli.Command{
adminServiceCmd,
+1 -1
View File
@@ -56,7 +56,7 @@ var adminOBDCmd = cli.Command{
Name: "obd",
Usage: "run on-board diagnostics",
Action: mainAdminOBD,
Before: initBeforeRunningCmd,
Before: setGlobalsFromContext,
Flags: append(adminOBDFlags, globalFlags...),
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
+1 -1
View File
@@ -33,7 +33,7 @@ var adminPolicyAddCmd = cli.Command{
Name: "add",
Usage: "add new policy",
Action: mainAdminPolicyAdd,
Before: initBeforeRunningCmd,
Before: setGlobalsFromContext,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
+1 -1
View File
@@ -29,7 +29,7 @@ var adminPolicyInfoCmd = cli.Command{
Name: "info",
Usage: "show info on a policy",
Action: mainAdminPolicyInfo,
Before: initBeforeRunningCmd,
Before: setGlobalsFromContext,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
+1 -1
View File
@@ -27,7 +27,7 @@ var adminPolicyListCmd = cli.Command{
Name: "list",
Usage: "list all policies",
Action: mainAdminPolicyList,
Before: initBeforeRunningCmd,
Before: setGlobalsFromContext,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
+1 -1
View File
@@ -27,7 +27,7 @@ var adminPolicyRemoveCmd = cli.Command{
Name: "remove",
Usage: "remove policy",
Action: mainAdminPolicyRemove,
Before: initBeforeRunningCmd,
Before: setGlobalsFromContext,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
+1 -1
View File
@@ -30,7 +30,7 @@ var adminPolicySetCmd = cli.Command{
Name: "set",
Usage: "set IAM policy on a user or group",
Action: mainAdminPolicySet,
Before: initBeforeRunningCmd,
Before: setGlobalsFromContext,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
+1
View File
@@ -22,6 +22,7 @@ var adminPolicyCmd = cli.Command{
Name: "policy",
Usage: "manage policies defined in the MinIO server",
Action: mainAdminPolicy,
Before: setGlobalsFromContext,
Flags: globalFlags,
Subcommands: []cli.Command{
adminPolicyAddCmd,
+2 -2
View File
@@ -21,7 +21,7 @@ import (
"github.com/minio/cli"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio-go/v6/pkg/set"
"github.com/minio/minio-go/v7/pkg/set"
"github.com/minio/minio/pkg/console"
"github.com/minio/minio/pkg/madmin"
)
@@ -38,7 +38,7 @@ var adminProfileStartCmd = cli.Command{
Name: "start",
Usage: "start recording profile data",
Action: mainAdminProfileStart,
Before: initBeforeRunningCmd,
Before: setGlobalsFromContext,
Flags: append(adminProfileStartFlags, globalFlags...),
HideHelpCommand: true,
CustomHelpTemplate: `NAME:
+1 -1
View File
@@ -31,7 +31,7 @@ var adminProfileStopCmd = cli.Command{
Name: "stop",
Usage: "stop and download profile data",
Action: mainAdminProfileStop,
Before: initBeforeRunningCmd,
Before: setGlobalsFromContext,
Flags: globalFlags,
HideHelpCommand: true,
CustomHelpTemplate: `NAME:
+1
View File
@@ -24,6 +24,7 @@ var adminProfileCmd = cli.Command{
Name: "profile",
Usage: "generate profile data for debugging purposes",
Action: mainAdminProfile,
Before: setGlobalsFromContext,
Flags: globalFlags,
Subcommands: []cli.Command{
adminProfileStartCmd,
+1 -1
View File
@@ -40,7 +40,7 @@ var adminPrometheusGenerateCmd = cli.Command{
Name: "generate",
Usage: "generates prometheus config",
Action: mainAdminPrometheusGenerate,
Before: initBeforeRunningCmd,
Before: setGlobalsFromContext,
Flags: globalFlags,
HideHelpCommand: true,
CustomHelpTemplate: `NAME:
+1
View File
@@ -22,6 +22,7 @@ var adminPrometheusCmd = cli.Command{
Name: "prometheus",
Usage: "manages prometheus config",
Action: mainAdminPrometheus,
Before: setGlobalsFromContext,
Flags: globalFlags,
HideHelpCommand: true,
Subcommands: []cli.Command{
+1 -1
View File
@@ -30,7 +30,7 @@ var adminServiceRestartCmd = cli.Command{
Name: "restart",
Usage: "restart all MinIO servers",
Action: mainAdminServiceRestart,
Before: initBeforeRunningCmd,
Before: setGlobalsFromContext,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
+1 -1
View File
@@ -28,7 +28,7 @@ var adminServiceStopCmd = cli.Command{
Name: "stop",
Usage: "stop MinIO server",
Action: mainAdminServiceStop,
Before: initBeforeRunningCmd,
Before: setGlobalsFromContext,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
+1
View File
@@ -22,6 +22,7 @@ var adminServiceCmd = cli.Command{
Name: "service",
Usage: "restart and stop all MinIO servers",
Action: mainAdminService,
Before: setGlobalsFromContext,
Flags: globalFlags,
HideHelpCommand: true,
Subcommands: []cli.Command{
+3 -7
View File
@@ -31,7 +31,7 @@ import (
var adminTopLocksCmd = cli.Command{
Name: "locks",
Usage: "Get a list of the 10 oldest locks on a MinIO cluster.",
Before: initBeforeRunningCmd,
Before: setGlobalsFromContext,
Action: mainAdminTopLocks,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
@@ -75,15 +75,13 @@ func (u lockMessage) String() string {
timeFieldMaxLen := 20
resourceFieldMaxLen := -1
typeFieldMaxLen := 6
ownerFieldMaxLen := 20
lockState, timeDiff := getTimeDiff(u.Lock.Timestamp)
return console.Colorize(lockState, newPrettyTable(" ",
Field{"Time", timeFieldMaxLen},
Field{"Type", typeFieldMaxLen},
Field{"Owner", ownerFieldMaxLen},
Field{"Resource", resourceFieldMaxLen},
).buildRow(timeDiff, u.Lock.Type, u.Lock.Owner, u.Lock.Resource))
).buildRow(timeDiff, u.Lock.Type, u.Lock.Resource))
}
// JSON jsonified top oldest locks message.
@@ -130,13 +128,11 @@ func printHeaders() {
timeFieldMaxLen := 20
resourceFieldMaxLen := -1
typeFieldMaxLen := 6
ownerFieldMaxLen := 20
console.Println(console.Colorize("Headers", newPrettyTable(" ",
Field{"Time", timeFieldMaxLen},
Field{"Type", typeFieldMaxLen},
Field{"Owner", ownerFieldMaxLen},
Field{"Resource", resourceFieldMaxLen},
).buildRow("Time", "Type", "Owner", "Resource")))
).buildRow("Time", "Type", "Resource")))
}
// Prints oldest locks.
+1
View File
@@ -22,6 +22,7 @@ var adminTopCmd = cli.Command{
Name: "top",
Usage: "provide top like statistics for MinIO",
Action: mainAdminTop,
Before: setGlobalsFromContext,
Flags: globalFlags,
Subcommands: []cli.Command{
adminTopLocksCmd,
+1 -1
View File
@@ -53,7 +53,7 @@ var adminTraceCmd = cli.Command{
Name: "trace",
Usage: "show http trace for MinIO server",
Action: mainAdminTrace,
Before: initBeforeRunningCmd,
Before: setGlobalsFromContext,
Flags: append(adminTraceFlags, globalFlags...),
HideHelpCommand: true,
CustomHelpTemplate: `NAME:
+1 -1
View File
@@ -30,7 +30,7 @@ var adminServerUpdateCmd = cli.Command{
Name: "update",
Usage: "update all MinIO servers",
Action: mainAdminServerUpdate,
Before: initBeforeRunningCmd,
Before: setGlobalsFromContext,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
+1 -1
View File
@@ -34,7 +34,7 @@ var adminUserAddCmd = cli.Command{
Name: "add",
Usage: "add a new user",
Action: mainAdminUserAdd,
Before: initBeforeRunningCmd,
Before: setGlobalsFromContext,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
+1 -1
View File
@@ -28,7 +28,7 @@ var adminUserDisableCmd = cli.Command{
Name: "disable",
Usage: "disable user",
Action: mainAdminUserDisable,
Before: initBeforeRunningCmd,
Before: setGlobalsFromContext,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
+1 -1
View File
@@ -28,7 +28,7 @@ var adminUserEnableCmd = cli.Command{
Name: "enable",
Usage: "enable user",
Action: mainAdminUserEnable,
Before: initBeforeRunningCmd,
Before: setGlobalsFromContext,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
+1 -1
View File
@@ -27,7 +27,7 @@ var adminUserInfoCmd = cli.Command{
Name: "info",
Usage: "display info of a user",
Action: mainAdminUserInfo,
Before: initBeforeRunningCmd,
Before: setGlobalsFromContext,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
+1 -1
View File
@@ -27,7 +27,7 @@ var adminUserListCmd = cli.Command{
Name: "list",
Usage: "list all users",
Action: mainAdminUserList,
Before: initBeforeRunningCmd,
Before: setGlobalsFromContext,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
+1 -1
View File
@@ -27,7 +27,7 @@ var adminUserRemoveCmd = cli.Command{
Name: "remove",
Usage: "remove user",
Action: mainAdminUserRemove,
Before: initBeforeRunningCmd,
Before: setGlobalsFromContext,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
+1
View File
@@ -22,6 +22,7 @@ var adminUserCmd = cli.Command{
Name: "user",
Usage: "manage users",
Action: mainAdminUser,
Before: setGlobalsFromContext,
Flags: globalFlags,
Subcommands: []cli.Command{
adminUserAddCmd,
+62 -48
View File
@@ -1,5 +1,5 @@
/*
* MinIO Client (C) 2017 MinIO, Inc.
* MinIO Client (C) 2017-2020 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -25,12 +25,14 @@ import (
"github.com/minio/minio/pkg/console"
)
var configHostListCmd = cli.Command{
Name: "list",
ShortName: "ls",
Usage: "list hosts in configuration file",
Action: mainConfigHostList,
Before: initBeforeRunningCmd,
var aliasListCmd = cli.Command{
Name: "list",
ShortName: "ls",
Usage: "list aliases in configuration file",
Action: func(ctx *cli.Context) error {
return mainAliasList(ctx, false)
},
Before: setGlobalsFromContext,
Flags: globalFlags,
HideHelpCommand: true,
CustomHelpTemplate: `NAME:
@@ -43,110 +45,122 @@ FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. List all hosts.
1. List all aliases.
{{.Prompt}} {{.HelpName}}
2. List a specific host.
2. List a specific alias.
{{.Prompt}} {{.HelpName}} s3
`,
}
// Input argument validator..
func checkConfigHostListSyntax(ctx *cli.Context) {
func checkAliasListSyntax(ctx *cli.Context) {
args := ctx.Args()
if len(ctx.Args()) > 1 {
fatalIf(errInvalidArgument().Trace(args...),
"Incorrect number of arguments to list hosts.")
"Incorrect number of arguments to alias list command.")
}
}
func mainConfigHostList(ctx *cli.Context) error {
checkConfigHostListSyntax(ctx)
func mainAliasList(ctx *cli.Context, deprecated bool) error {
checkAliasListSyntax(ctx)
// Additional command speific theme customization.
// Additional command specific theme customization.
console.SetColor("Alias", color.New(color.FgCyan, color.Bold))
console.SetColor("URL", color.New(color.FgYellow))
console.SetColor("AccessKey", color.New(color.FgCyan))
console.SetColor("SecretKey", color.New(color.FgCyan))
console.SetColor("API", color.New(color.FgBlue))
console.SetColor("Lookup", color.New(color.FgCyan))
console.SetColor("Path", color.New(color.FgCyan))
alias := cleanAlias(ctx.Args().Get(0))
listHosts(alias) // List all configured hosts.
aliasesMsgs := listAliases(alias, deprecated) // List all configured hosts.
for i := range aliasesMsgs {
aliasesMsgs[i].op = "list"
}
printAliases(aliasesMsgs...)
return nil
}
// Prints all the hosts.
func printHosts(hosts ...hostMessage) {
// Prints all the aliases
func printAliases(aliases ...aliasMessage) {
var maxAlias = 0
for _, host := range hosts {
if len(host.Alias) > maxAlias {
maxAlias = len(host.Alias)
for _, alias := range aliases {
if len(alias.Alias) > maxAlias {
maxAlias = len(alias.Alias)
}
}
for _, host := range hosts {
for _, alias := range aliases {
if !globalJSON {
// Format properly for alignment based on alias length only in non json mode.
host.Alias = fmt.Sprintf("%-*.*s", maxAlias, maxAlias, host.Alias)
alias.Alias = fmt.Sprintf("%-*.*s", maxAlias, maxAlias, alias.Alias)
}
if host.AccessKey == "" || host.SecretKey == "" {
host.AccessKey = ""
host.SecretKey = ""
host.API = ""
if alias.AccessKey == "" || alias.SecretKey == "" {
alias.AccessKey = ""
alias.SecretKey = ""
alias.API = ""
}
printMsg(host)
printMsg(alias)
}
}
// byAlias is a collection satisfying sort.Interface
type byAlias []hostMessage
type byAlias []aliasMessage
func (d byAlias) Len() int { return len(d) }
func (d byAlias) Swap(i, j int) { d[i], d[j] = d[j], d[i] }
func (d byAlias) Less(i, j int) bool { return d[i].Alias < d[j].Alias }
// listHosts - list all host URLs or a requested host.
func listHosts(alias string) {
// listAliases - list one or all aliases
func listAliases(alias string, deprecated bool) (aliases []aliasMessage) {
conf, err := loadMcConfig()
fatalIf(err.Trace(globalMCConfigVersion), "Unable to load config version `"+globalMCConfigVersion+"`.")
// If specific alias is requested, look for it and print.
if alias != "" {
if v, ok := conf.Hosts[alias]; ok {
printHosts(hostMessage{
op: "list",
if v, ok := conf.Aliases[alias]; ok {
aliasMsg := aliasMessage{
prettyPrint: false,
Alias: alias,
URL: v.URL,
AccessKey: v.AccessKey,
SecretKey: v.SecretKey,
API: v.API,
Lookup: v.Lookup,
})
return
}
if deprecated {
aliasMsg.Lookup = v.Path
} else {
aliasMsg.Path = v.Path
}
return []aliasMessage{aliasMsg}
}
fatalIf(errInvalidAliasedURL(alias), "No such alias `"+alias+"` found.")
}
var hosts []hostMessage
for k, v := range conf.Hosts {
hosts = append(hosts, hostMessage{
op: "list",
for k, v := range conf.Aliases {
aliasMsg := aliasMessage{
prettyPrint: true,
Alias: k,
URL: v.URL,
AccessKey: v.AccessKey,
SecretKey: v.SecretKey,
API: v.API,
Lookup: v.Lookup,
})
}
if deprecated {
aliasMsg.Lookup = v.Path
} else {
aliasMsg.Path = v.Path
}
aliases = append(aliases, aliasMsg)
}
// Sort hosts by alias names lexically.
sort.Sort(byAlias(hosts))
// Display all the hosts.
printHosts(hosts...)
// Sort by alias names lexically.
sort.Sort(byAlias(aliases))
return
}
+49 -24
View File
@@ -1,5 +1,5 @@
/*
* MinIO Client (C) 2017 MinIO, Inc.
* MinIO Client (C) 2014-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.
@@ -23,28 +23,44 @@ import (
"github.com/minio/minio/pkg/console"
)
var configHostCmd = cli.Command{
Name: "host",
Usage: "add, remove and list hosts in configuration file",
Action: mainConfigHost,
Flags: globalFlags,
Subcommands: []cli.Command{
configHostAddCmd,
configHostRemoveCmd,
configHostListCmd,
},
// Configure an alias in MinIO Client
//
// ----
// NOTE: that the alias command only writes values to the config file.
// It does not use any configuration values from the environment variables.
//
// One needs to edit configuration file manually, this is purposefully done
// so to avoid taking credentials over cli arguments. It is a security precaution
// ----
//
var (
aliasFlags = []cli.Flag{}
)
var aliasCmd = cli.Command{
Name: "alias",
Usage: "set, remove and list aliases in configuration file",
Action: mainAlias,
Before: setGlobalsFromContext,
HideHelpCommand: true,
Flags: append(aliasFlags, globalFlags...),
Subcommands: []cli.Command{
aliasSetCmd,
aliasListCmd,
aliasRemoveCmd,
},
}
// mainConfigHost is the handle for "mc config host" command.
func mainConfigHost(ctx *cli.Context) error {
// mainAlias is the handle for "mc alias" command. provides sub-commands which write configuration data in json format to config file.
func mainAlias(ctx *cli.Context) error {
cli.ShowCommandHelp(ctx, ctx.Args().First())
return nil
// Sub-commands like "remove", "list" have their own main.
// Sub-commands like add, list and remove have their own main.
}
// hostMessage container for content message structure
type hostMessage struct {
// aliasMessage container for content message structure
type aliasMessage struct {
op string
prettyPrint bool
Status string `json:"status"`
@@ -53,13 +69,15 @@ type hostMessage struct {
AccessKey string `json:"accessKey,omitempty"`
SecretKey string `json:"secretKey,omitempty"`
API string `json:"api,omitempty"`
Lookup string `json:"lookup,omitempty"`
Path string `json:"path,omitempty"`
// Deprecated field, replaced by Path
Lookup string `json:"lookup,omitempty"`
}
// Print the config information of one alias, when prettyPrint flag
// is activated, fields contents are cut and '...' will be added to
// show a pretty table of all aliases configurations
func (h hostMessage) String() string {
func (h aliasMessage) String() string {
switch h.op {
case "list":
// Create a new pretty table with cols configuration
@@ -69,20 +87,27 @@ func (h hostMessage) String() string {
Row{"AccessKey", "AccessKey"},
Row{"SecretKey", "SecretKey"},
Row{"API", "API"},
Row{"Lookup", "Lookup"},
Row{"Path", "Path"},
)
return t.buildRecord(h.Alias, h.URL, h.AccessKey, h.SecretKey, h.API, h.Lookup)
// Handle deprecated lookup
path := h.Path
if path == "" {
path = h.Lookup
}
return t.buildRecord(h.Alias, h.URL, h.AccessKey, h.SecretKey, h.API, path)
case "remove":
return console.Colorize("HostMessage", "Removed `"+h.Alias+"` successfully.")
case "add":
return console.Colorize("HostMessage", "Added `"+h.Alias+"` successfully.")
return console.Colorize("AliasMessage", "Removed `"+h.Alias+"` successfully.")
case "add": // add is deprecated
fallthrough
case "set":
return console.Colorize("AliasMessage", "Added `"+h.Alias+"` successfully.")
default:
return ""
}
}
// JSON jsonified host message
func (h hostMessage) JSON() string {
func (h aliasMessage) JSON() string {
h.Status = "success"
jsonMessageBytes, e := json.MarshalIndent(h, "", " ")
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
@@ -1,5 +1,5 @@
/*
* MinIO Client (C) 2017 MinIO, Inc.
* MinIO Client (C) 2017-2020 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -22,12 +22,14 @@ import (
"github.com/minio/minio/pkg/console"
)
var configHostRemoveCmd = cli.Command{
Name: "remove",
ShortName: "rm",
Usage: "remove a host from configuration file",
Action: mainConfigHostRemove,
Before: initBeforeRunningCmd,
var aliasRemoveCmd = cli.Command{
Name: "remove",
ShortName: "rm",
Usage: "remove an alias from configuration file",
Action: func(ctx *cli.Context) error {
return mainAliasRemove(ctx, false)
},
Before: setGlobalsFromContext,
Flags: globalFlags,
HideHelpCommand: true,
CustomHelpTemplate: `NAME:
@@ -40,19 +42,19 @@ FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Remove "goodisk" from config.
1. Remove "goodisk" alias from the configuration.
{{.Prompt}} {{.HelpName}} goodisk
`,
}
// checkConfigHostRemoveSyntax - verifies input arguments to 'config host remove'.
func checkConfigHostRemoveSyntax(ctx *cli.Context) {
// checkAliasRemoveSyntax - verifies input arguments to 'alias remove'.
func checkAliasRemoveSyntax(ctx *cli.Context) {
args := ctx.Args()
if len(ctx.Args()) != 1 {
fatalIf(errInvalidArgument().Trace(args...),
"Incorrect number of arguments for remove host command.")
"Incorrect number of arguments for alias remove command.")
}
alias := cleanAlias(args.Get(0))
@@ -61,28 +63,31 @@ func checkConfigHostRemoveSyntax(ctx *cli.Context) {
}
}
// mainConfigHost is the handle for "mc config host rm" command.
func mainConfigHostRemove(ctx *cli.Context) error {
checkConfigHostRemoveSyntax(ctx)
// mainAliasRemove is the handle for "mc alias rm" command.
func mainAliasRemove(ctx *cli.Context, deprecated bool) error {
checkAliasRemoveSyntax(ctx)
console.SetColor("HostMessage", color.New(color.FgGreen))
console.SetColor("AliasMessage", color.New(color.FgGreen))
args := ctx.Args()
alias := args.Get(0)
removeHost(alias) // Remove a host.
aliasMsg := removeAlias(alias) // Remove an alias
aliasMsg.op = "remove"
printMsg(aliasMsg)
return nil
}
// removeHost - removes a host.
func removeHost(alias string) {
// removeAlias - removes an alias.
func removeAlias(alias string) aliasMessage {
conf, err := loadMcConfig()
fatalIf(err.Trace(globalMCConfigVersion), "Unable to load config version `"+globalMCConfigVersion+"`.")
// Remove host.
delete(conf.Hosts, alias)
// Remove the alias from the config.
delete(conf.Aliases, alias)
err = saveMcConfig(conf)
fatalIf(err.Trace(alias), "Unable to save deleted hosts in config version `"+globalMCConfigVersion+"`.")
fatalIf(err.Trace(alias), "Unable to save the delete alias in config version `"+globalMCConfigVersion+"`.")
printMsg(hostMessage{op: "remove", Alias: alias})
return aliasMessage{Alias: alias}
}
+91 -60
View File
@@ -1,5 +1,5 @@
/*
* MinIO Client (C) 2017 MinIO, Inc.
* MinIO Client (C) 2017-2020 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -22,36 +22,40 @@ import (
"fmt"
"math/rand"
"os"
"strings"
"time"
"github.com/fatih/color"
"github.com/minio/cli"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio-go/v6"
"github.com/minio/minio-go/v7"
"github.com/minio/minio/pkg/console"
"golang.org/x/crypto/ssh/terminal"
)
const cred = "YellowItalics"
var hostAddFlags = []cli.Flag{
var aliasSetFlags = []cli.Flag{
cli.StringFlag{
Name: "lookup",
Name: "path",
Value: "auto",
Usage: "bucket lookup supported by the server. Valid options are '[dns,path,auto]'",
Usage: "bucket path lookup supported by the server. Valid options are '[auto, on, off]'",
},
cli.StringFlag{
Name: "api",
Usage: "API signature. Valid options are '[S3v4, S3v2]'",
},
}
var configHostAddCmd = cli.Command{
Name: "add",
ShortName: "a",
Usage: "add a new host to configuration file",
Action: mainConfigHostAdd,
Before: initBeforeRunningCmd,
Flags: append(hostAddFlags, globalFlags...),
var aliasSetCmd = cli.Command{
Name: "set",
ShortName: "s",
Usage: "set a new alias to configuration file",
Action: func(cli *cli.Context) error {
return mainAliasSet(cli, false)
},
Before: setGlobalsFromContext,
Flags: append(aliasSetFlags, globalFlags...),
HideHelpCommand: true,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
@@ -68,10 +72,10 @@ EXAMPLES:
{{.Prompt}} {{.HelpName}} myminio http://localhost:9000 minio minio123
{{.EnableHistory}}
2. Add MinIO service under "myminio" alias, to use dns style bucket lookup. For security reasons
2. Add MinIO service under "myminio" alias, to use dns style bucket lookup. For security reasons
turn off bash history momentarily.
{{.DisableHistory}}
{{.Prompt}} {{.HelpName}} myminio http://localhost:9000 minio minio123 --api "s3v4" --lookup "dns"
{{.Prompt}} {{.HelpName}} myminio http://localhost:9000 minio minio123 --api "s3v4" --path "off"
{{.EnableHistory}}
3. Add Amazon S3 storage service under "mys3" alias. For security reasons turn off bash history momentarily.
@@ -81,30 +85,31 @@ EXAMPLES:
{{.EnableHistory}}
4. Add Amazon S3 storage service under "mys3" alias, prompting for keys.
{{.Prompt}} {{.HelpName}} mys3 https://s3.amazonaws.com --api "s3v4" --lookup "dns"
{{.Prompt}} {{.HelpName}} mys3 https://s3.amazonaws.com --api "s3v4" --path "off"
Enter Access Key: BKIKJAA5BMMU2RHO6IBB
Enter Secret Key: V8f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12
5. Add Amazon S3 storage service under "mys3" alias using piped keys.
{{.DisableHistory}}
{{.Prompt}} echo -e "BKIKJAA5BMMU2RHO6IBB\nV8f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12" | \
{{.HelpName}} mys3 https://s3.amazonaws.com --api "s3v4" --lookup "dns"
{{.HelpName}} mys3 https://s3.amazonaws.com --api "s3v4" --path "off"
{{.EnableHistory}}
`,
}
// checkConfigHostAddSyntax - verifies input arguments to 'config host add'.
func checkConfigHostAddSyntax(ctx *cli.Context, accessKey string, secretKey string) {
// checkAliasSetSyntax - verifies input arguments to 'alias set'.
func checkAliasSetSyntax(ctx *cli.Context, accessKey string, secretKey string, deprecated bool) {
args := ctx.Args()
argsNr := len(args)
if argsNr > 4 || argsNr < 2 {
fatalIf(errInvalidArgument().Trace(ctx.Args().Tail()...),
"Incorrect number of arguments for host add command.")
"Incorrect number of arguments for alias set command.")
}
alias := cleanAlias(args.Get(0))
url := args.Get(1)
api := ctx.String("api")
path := ctx.String("path")
bucketLookup := ctx.String("lookup")
if !isValidAlias(alias) {
@@ -130,32 +135,38 @@ func checkConfigHostAddSyntax(ctx *cli.Context, accessKey string, secretKey stri
"Unrecognized API signature. Valid options are `[S3v4, S3v2]`.")
}
if !isValidLookup(bucketLookup) {
fatalIf(errInvalidArgument().Trace(bucketLookup),
"Unrecognized bucket lookup. Valid options are `[dns,auto, path]`.")
if deprecated {
if !isValidLookup(bucketLookup) {
fatalIf(errInvalidArgument().Trace(bucketLookup),
"Unrecognized bucket lookup. Valid options are `[dns,auto, path]`.")
}
} else {
if !isValidPath(path) {
fatalIf(errInvalidArgument().Trace(bucketLookup),
"Unrecognized path value. Valid options are `[auto, on, off]`.")
}
}
}
// addHost - add a host config.
func addHost(alias string, hostCfgV9 hostConfigV9) {
mcCfgV9, err := loadMcConfig()
// setAlias - set an alias config.
func setAlias(alias string, aliasCfgV10 aliasConfigV10) aliasMessage {
mcCfgV10, err := loadMcConfig()
fatalIf(err.Trace(globalMCConfigVersion), "Unable to load config `"+mustGetMcConfigPath()+"`.")
// Add new host.
mcCfgV9.Hosts[alias] = hostCfgV9
mcCfgV10.Aliases[alias] = aliasCfgV10
err = saveMcConfig(mcCfgV9)
err = saveMcConfig(mcCfgV10)
fatalIf(err.Trace(alias), "Unable to update hosts in config version `"+mustGetMcConfigPath()+"`.")
printMsg(hostMessage{
op: "add",
return aliasMessage{
Alias: alias,
URL: hostCfgV9.URL,
AccessKey: hostCfgV9.AccessKey,
SecretKey: hostCfgV9.SecretKey,
API: hostCfgV9.API,
Lookup: hostCfgV9.Lookup,
})
URL: aliasCfgV10.URL,
AccessKey: aliasCfgV10.AccessKey,
SecretKey: aliasCfgV10.SecretKey,
API: aliasCfgV10.API,
Path: aliasCfgV10.Path,
}
}
// probeS3Signature - auto probe S3 server signature: issue a Stat call
@@ -179,7 +190,7 @@ func probeS3Signature(ctx context.Context, accessKey, secretKey, url string) (st
return "", err
}
if _, err := s3Client.Stat(ctx, false, false, nil); err != nil {
if _, err := s3Client.Stat(ctx, StatOptions{}); err != nil {
e := err.ToGoError()
if _, ok := e.(BucketDoesNotExist); ok {
// Bucket doesn't exist, means signature probing worked successfully.
@@ -210,13 +221,12 @@ func probeS3Signature(ctx context.Context, accessKey, secretKey, url string) (st
// BuildS3Config constructs an S3 Config and does
// signature auto-probe when needed.
func BuildS3Config(ctx context.Context, url, accessKey, secretKey, api, lookup string) (*Config, *probe.Error) {
s3Config := NewS3Config(url, &hostConfigV9{
func BuildS3Config(ctx context.Context, url, accessKey, secretKey, api, path string) (*Config, *probe.Error) {
s3Config := NewS3Config(url, &aliasConfigV10{
AccessKey: accessKey,
SecretKey: secretKey,
URL: url,
Lookup: lookup,
Path: path,
})
// If api is provided we do not auto probe signature, this is
@@ -228,7 +238,7 @@ func BuildS3Config(ctx context.Context, url, accessKey, secretKey, api, lookup s
// Probe S3 signature version
api, err := probeS3Signature(ctx, accessKey, secretKey, url)
if err != nil {
return nil, err.Trace(url, accessKey, secretKey, api, lookup)
return nil, err.Trace(url, accessKey, secretKey, api, path)
}
s3Config.Signature = api
@@ -236,8 +246,8 @@ func BuildS3Config(ctx context.Context, url, accessKey, secretKey, api, lookup s
return s3Config, nil
}
// fetchHostKeys - returns the user accessKey and secretKey
func fetchHostKeys(args cli.Args) (string, string) {
// fetchAliasKeys - returns the user accessKey and secretKey
func fetchAliasKeys(args cli.Args) (string, string) {
accessKey := ""
secretKey := ""
console.SetColor(cred, color.New(color.FgYellow, color.Italic))
@@ -273,31 +283,52 @@ func fetchHostKeys(args cli.Args) (string, string) {
return accessKey, secretKey
}
func mainConfigHostAdd(cli *cli.Context) error {
console.SetColor("HostMessage", color.New(color.FgGreen))
func mainAliasSet(cli *cli.Context, deprecated bool) error {
console.SetColor("AliasMessage", color.New(color.FgGreen))
var (
args = cli.Args()
alias = cleanAlias(args.Get(0))
url = trimTrailingSeparator(args.Get(1))
api = cli.String("api")
lookup = cli.String("lookup")
args = cli.Args()
alias = cleanAlias(args.Get(0))
url = trimTrailingSeparator(args.Get(1))
api = cli.String("api")
path = cli.String("path")
)
accessKey, secretKey := fetchHostKeys(args)
checkConfigHostAddSyntax(cli, accessKey, secretKey)
ctx, cancelHostAdd := context.WithCancel(globalContext)
defer cancelHostAdd()
// Support deprecated lookup flag
if deprecated {
lookup := strings.ToLower(strings.TrimSpace(cli.String("lookup")))
switch lookup {
case "", "auto":
path = "auto"
case "path":
path = "on"
case "dns":
path = "off"
default:
}
}
s3Config, err := BuildS3Config(ctx, url, accessKey, secretKey, api, lookup)
fatalIf(err.Trace(cli.Args()...), "Unable to initialize new config from the provided credentials.")
accessKey, secretKey := fetchAliasKeys(args)
checkAliasSetSyntax(cli, accessKey, secretKey, deprecated)
addHost(alias, hostConfigV9{
ctx, cancelAliasAdd := context.WithCancel(globalContext)
defer cancelAliasAdd()
s3Config, err := BuildS3Config(ctx, url, accessKey, secretKey, api, path)
fatalIf(err.Trace(cli.Args()...), "Unable to initialize new alias from the provided credentials.")
msg := setAlias(alias, aliasConfigV10{
URL: s3Config.HostURL,
AccessKey: s3Config.AccessKey,
SecretKey: s3Config.SecretKey,
API: s3Config.Signature,
Lookup: lookup,
}) // Add a host with specified credentials.
Path: path,
}) // Add an alias with specified credentials.
msg.op = "set"
if deprecated {
msg.op = "add"
}
printMsg(msg)
return nil
}
+39 -11
View File
@@ -96,7 +96,7 @@ func completeS3Path(s3Path string) (prediction []string) {
// List dirPath content and only pick elements that corresponds
// to the path that we want to complete
for content := range clnt.List(globalContext, false, false, false, DirFirst) {
for content := range clnt.List(globalContext, ListOptions{isRecursive: false, showDir: DirFirst}) {
cmplS3Path := alias + getKey(content)
if content.Type.IsDir() {
if !strings.HasSuffix(cmplS3Path, "/") {
@@ -136,10 +136,10 @@ func (adm adminConfigComplete) Predict(a complete.Args) (prediction []string) {
arg := a.Last
lastArg := a.LastCompleted
if _, ok := conf.Hosts[filepath.Clean(a.LastCompleted)]; !ok {
if _, ok := conf.Aliases[filepath.Clean(a.LastCompleted)]; !ok {
if strings.IndexByte(arg, '/') == -1 {
// Only predict alias since '/' is not found
for alias := range conf.Hosts {
for alias := range conf.Aliases {
if strings.HasPrefix(alias, arg) {
prediction = append(prediction, alias+"/")
}
@@ -173,7 +173,7 @@ func (s3 s3Complete) Predict(a complete.Args) (prediction []string) {
if strings.IndexByte(arg, '/') == -1 {
// Only predict alias since '/' is not found
for alias := range conf.Hosts {
for alias := range conf.Aliases {
if strings.HasPrefix(alias, arg) {
prediction = append(prediction, alias+"/")
}
@@ -210,7 +210,7 @@ func (al aliasComplete) Predict(a complete.Args) (prediction []string) {
}
arg := a.Last
for alias := range conf.Hosts {
for alias := range conf.Aliases {
if strings.HasPrefix(alias, arg) {
prediction = append(prediction, alias+"/")
}
@@ -245,21 +245,46 @@ var completeCmds = map[string]complete.Predictor{
"/du": complete.PredictOr(s3Complete{deepLevel: 2}, fsCompleter),
"/retention": s3Completer,
"/sql": s3Completer,
"/lock": complete.PredictOr(s3Complete{deepLevel: 2}),
"/mb": aliasCompleter,
"/event/add": aliasCompleter,
"/event/list": aliasCompleter,
"/event/remove": aliasCompleter,
"/event/add": s3Complete{deepLevel: 2},
"/event/list": s3Complete{deepLevel: 2},
"/event/remove": s3Complete{deepLevel: 2},
"/encrypt/set": s3Complete{deepLevel: 2},
"/encrypt/info": s3Complete{deepLevel: 2},
"/encrypt/clear": s3Complete{deepLevel: 2},
"/replicate/add": s3Complete{deepLevel: 2},
"/replicate/set": s3Complete{deepLevel: 2},
"/replicate/ls": s3Complete{deepLevel: 2},
"/replicate/rm": s3Complete{deepLevel: 2},
"/replicate/export": s3Complete{deepLevel: 2},
"/replicate/import": s3Complete{deepLevel: 2},
"/tag/list": s3Completer,
"/tag/remove": s3Completer,
"/tag/set": s3Completer,
"/version/info": s3Complete{deepLevel: 2},
"/version/enable": s3Complete{deepLevel: 2},
"/version/suspend": s3Complete{deepLevel: 2},
"/lock/compliance": s3Completer,
"/lock/governance": s3Completer,
"/lock/clear": s3Completer,
"/lock/info": s3Completer,
"/share/download": s3Completer,
"/share/list": nil,
"/share/upload": s3Completer,
"/ilm/list": s3Complete{deepLevel: 2},
"/ilm/add": s3Complete{deepLevel: 2},
"/ilm/remove": s3Complete{deepLevel: 2},
"/ilm/export": s3Complete{deepLevel: 2},
"/ilm/import": s3Complete{deepLevel: 2},
// Admin API commands MinIO only.
"/admin/heal": s3Completer,
@@ -306,12 +331,15 @@ var completeCmds = map[string]complete.Predictor{
"/admin/group/remove": aliasCompleter,
"/admin/group/info": aliasCompleter,
"/admin/bucket/remote/add": aliasCompleter,
"/admin/bucket/remote/ls": aliasCompleter,
"/admin/bucket/remote/rm": aliasCompleter,
"/config/host/add": nil,
"/config/host/list": aliasCompleter,
"/config/host/remove": aliasCompleter,
"/update": nil,
"/version": nil,
"/update": nil,
}
// flagsToCompleteFlags transforms a cli.Flag to complete.Flags
+24 -32
View File
@@ -26,25 +26,16 @@ import (
"github.com/minio/cli"
json "github.com/minio/mc/pkg/colorjson"
"github.com/minio/mc/pkg/probe"
minio "github.com/minio/minio-go/v6"
minio "github.com/minio/minio-go/v7"
"github.com/minio/minio/pkg/console"
)
var (
lockFlags = []cli.Flag{
cli.BoolFlag{
Name: "clear, c",
Usage: "clears previously stored object lock configuration",
},
}
)
var lockCmd = cli.Command{
var bucketLockCmd = cli.Command{
Name: "lock",
Usage: "set and get object lock configuration",
Usage: "manage default bucket object lock configuration",
Action: mainLock,
Before: initBeforeRunningCmd,
Flags: append(lockFlags, globalFlags...),
Before: setGlobalsFromContext,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
@@ -62,10 +53,10 @@ EXAMPLES:
$ {{.HelpName}} myminio/mybucket compliance 30d
2. Get object lock configuration
$ {{.HelpName}} myminio/mybucket
$ {{.HelpName}} myminio/mybucket info
3. Clear object lock configuration
$ {{.HelpName}} --clear myminio/mybucket
$ {{.HelpName}} myminio/mybucket clear
`,
}
@@ -80,7 +71,7 @@ type lockCmdMessage struct {
// Colorized message for console printing.
func (m lockCmdMessage) String() string {
if m.Mode == "" {
return "Object lock configuration cleared successfully"
return console.Colorize("Clear", "Object lock configuration cleared successfully")
}
return fmt.Sprintf("%s mode is enabled for %s", console.Colorize("Mode", m.Mode), console.Colorize("Validity", m.Validity))
@@ -94,7 +85,7 @@ func (m lockCmdMessage) JSON() string {
}
// lock - set/get object lock configuration.
func lock(urlStr string, mode minio.RetentionMode, validity uint64, unit minio.ValidityUnit, clearLock bool) error {
func lock(urlStr string, mode minio.RetentionMode, validity uint64, unit minio.ValidityUnit, op string) error {
client, err := newClient(urlStr)
if err != nil {
fatalIf(err.Trace(), "Cannot parse the provided url.")
@@ -102,8 +93,7 @@ func lock(urlStr string, mode minio.RetentionMode, validity uint64, unit minio.V
ctx, cancelLock := context.WithCancel(globalContext)
defer cancelLock()
if clearLock || mode != "" {
if op == "clear" || mode != "" {
err = client.SetObjectLockConfig(ctx, mode, validity, unit)
fatalIf(err, "Cannot enable object lock configuration on the specified bucket.")
} else {
@@ -150,10 +140,7 @@ func parseRetentionValidity(validityStr string, m minio.RetentionMode) (uint64,
func mainLock(ctx *cli.Context) error {
console.SetColor("Mode", color.New(color.FgCyan, color.Bold))
console.SetColor("Validity", color.New(color.FgYellow))
// lock specific flags.
clearLock := ctx.Bool("clear")
console.SetColor("Clear", color.New(color.FgGreen))
args := ctx.Args()
var urlStr string
@@ -161,16 +148,21 @@ func mainLock(ctx *cli.Context) error {
var validity uint64
var unit minio.ValidityUnit
var err *probe.Error
var op string
switch l := len(args); l {
case 1:
case 2:
urlStr = args[0]
case 3:
urlStr = args[0]
if clearLock {
fatalIf(errInvalidArgument().Trace(urlStr), "clear flag must be passed with target alone")
switch args[1] {
case "info":
op = "info"
case "clear":
op = "clear"
default:
fatalIf(err.Trace(args...), "unable to parse input arguments")
}
case 3:
op = "set"
urlStr = args[0]
mode = minio.RetentionMode(strings.ToUpper(args[1]))
validity, unit, err = parseRetentionValidity(args[2], mode)
if err != nil {
@@ -180,5 +172,5 @@ func mainLock(ctx *cli.Context) error {
cli.ShowCommandHelpAndExit(ctx, "lock", 1)
}
return lock(urlStr, mode, validity, unit, clearLock)
return lock(urlStr, mode, validity, unit, op)
}
+36 -22
View File
@@ -1,5 +1,5 @@
/*
* MinIO Client, (C) 2015, 2016, 2017 MinIO, Inc.
* MinIO Client, (C) 2015-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.
@@ -25,6 +25,7 @@ import (
"os"
"strings"
"syscall"
"time"
"unicode"
"unicode/utf8"
@@ -33,10 +34,12 @@ import (
)
var (
// This is kept dummy for future purposes
// and also to add ioFlags and globalFlags
// in CLI registration.
catFlags = []cli.Flag{}
catFlags = []cli.Flag{
cli.StringFlag{
Name: "rewind",
Usage: "back in time",
},
}
)
// Display contents of a file.
@@ -44,7 +47,7 @@ var catCmd = cli.Command{
Name: "cat",
Usage: "display object contents",
Action: mainCat,
Before: initBeforeRunningCmd,
Before: setGlobalsFromContext,
Flags: append(append(catFlags, ioFlags...), globalFlags...),
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
@@ -74,6 +77,9 @@ EXAMPLES:
5. Display the content of encrypted object. In case the encryption key contains non-printable character like tab, pass the
base64 encoded string as key.
{{.Prompt}} {{.HelpName}} --encrypt-key "play/my-bucket/=MzJieXRlc2xvbmdzZWNyZXRrZQltdXN0YmVnaXZlbjE=" play/my-bucket/my-object
6. Display the content of an object 10 days earlier
{{.Prompt}} {{.HelpName}} --rewind 10d play/my-bucket/my-object
`,
}
@@ -126,10 +132,10 @@ func (s prettyStdout) Write(input []byte) (int, error) {
return inputLen, nil
}
// checkCatSyntax performs command-line input validation for cat command.
func checkCatSyntax(ctx *cli.Context) {
args := ctx.Args()
if !args.Present() {
// parseCatSyntax performs command-line input validation for cat command.
func parseCatSyntax(ctx *cli.Context) (args []string, rewind time.Time) {
args = ctx.Args()
if len(args) == 0 {
args = []string{"-"}
}
for _, arg := range args {
@@ -137,27 +143,36 @@ func checkCatSyntax(ctx *cli.Context) {
fatalIf(probe.NewError(errors.New("")), fmt.Sprintf("Unknown flag `%s` passed.", arg))
}
}
rewind = parseRewindFlag(ctx.String("rewind"))
return args, rewind
}
// catURL displays contents of a URL to stdout.
func catURL(ctx context.Context, sourceURL string, encKeyDB map[string][]prefixSSEPair) *probe.Error {
func catURL(ctx context.Context, sourceURL string, timeRef time.Time, encKeyDB map[string][]prefixSSEPair) *probe.Error {
var reader io.ReadCloser
size := int64(-1)
switch sourceURL {
case "-":
reader = os.Stdin
default:
var versionID string
var err *probe.Error
// Try to stat the object, the purpose is to extract the
// size of S3 object so we can check if the size of the
// Try to stat the object, the purpose is to:
// 1. extract the size of S3 object so we can check if the size of the
// downloaded object is equal to the original one. FS files
// are ignored since some of them have zero size though they
// have contents like files under /proc.
client, content, err := url2Stat(ctx, sourceURL, false, encKeyDB)
if err == nil && client.GetURL().Type == objectStorage {
size = content.Size
// 2. extract the version ID if rewind flag is passed
if client, content, err := url2Stat(ctx, sourceURL, "", false, encKeyDB, timeRef); err == nil {
versionID = content.VersionID
if client.GetURL().Type == objectStorage {
size = content.Size
}
} else {
return err.Trace(sourceURL)
}
if reader, err = getSourceStreamFromURL(ctx, sourceURL, encKeyDB); err != nil {
if reader, err = getSourceStreamFromURL(ctx, sourceURL, versionID, encKeyDB); err != nil {
return err.Trace(sourceURL)
}
defer reader.Close()
@@ -220,11 +235,11 @@ func mainCat(cliCtx *cli.Context) error {
fatalIf(err, "Unable to parse encryption keys.")
// check 'cat' cli arguments.
checkCatSyntax(cliCtx)
args, rewind := parseCatSyntax(cliCtx)
// Set command flags from context.
stdinMode := false
if !cliCtx.Args().Present() {
if len(args) == 0 {
stdinMode = true
}
@@ -235,8 +250,7 @@ func mainCat(cliCtx *cli.Context) error {
}
// if Args contain `-`, we need to preserve its order specially.
args := []string(cliCtx.Args())
if cliCtx.Args().First() == "-" {
if len(args) > 0 && args[0] == "-" {
for i, arg := range os.Args {
if arg == "cat" {
// Overwrite cliCtx.Args with os.Args.
@@ -248,7 +262,7 @@ func mainCat(cliCtx *cli.Context) error {
// Convert arguments to URLs: expand alias, fix format.
for _, url := range args {
fatalIf(catURL(ctx, url, encKeyDB).Trace(url), "Unable to read from `"+url+"`.")
fatalIf(catURL(ctx, url, rewind, encKeyDB).Trace(url), "Unable to read from `"+url+"`.")
}
return nil
+5 -5
View File
@@ -29,7 +29,7 @@ import (
"github.com/mattn/go-ieproxy"
"github.com/minio/mc/pkg/httptracer"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio-go/v6/pkg/credentials"
"github.com/minio/minio-go/v7/pkg/credentials"
"github.com/minio/minio/pkg/madmin"
)
@@ -131,21 +131,21 @@ func NewAdminFactory() func(config *Config) (*madmin.AdminClient, *probe.Error)
// newAdminClient gives a new client interface
func newAdminClient(aliasedURL string) (*madmin.AdminClient, *probe.Error) {
alias, urlStrFull, hostCfg, err := expandAlias(aliasedURL)
alias, urlStrFull, aliasCfg, err := expandAlias(aliasedURL)
if err != nil {
return nil, err.Trace(aliasedURL)
}
// Verify if the aliasedURL is a real URL, fail in those cases
// indicating the user to add alias.
if hostCfg == nil && urlRgx.MatchString(aliasedURL) {
if aliasCfg == nil && urlRgx.MatchString(aliasedURL) {
return nil, errInvalidAliasedURL(aliasedURL).Trace(aliasedURL)
}
if hostCfg == nil {
if aliasCfg == nil {
return nil, probe.NewError(fmt.Errorf("No valid configuration found for '%s' host alias", urlStrFull))
}
s3Config := NewS3Config(urlStrFull, hostCfg)
s3Config := NewS3Config(urlStrFull, aliasCfg)
s3Client, err := s3AdminNew(s3Config)
if err != nil {
+10 -2
View File
@@ -16,7 +16,10 @@
package cmd
import "fmt"
import (
"fmt"
"time"
)
/// Collection of standard errors
@@ -154,9 +157,14 @@ func (e EmptyPath) Error() string {
}
// ObjectMissing (EINVAL) - object key missing.
type ObjectMissing struct{}
type ObjectMissing struct {
timeRef time.Time
}
func (e ObjectMissing) Error() string {
if !e.timeRef.IsZero() {
return "Object did not exist at `" + e.timeRef.Format(time.RFC1123) + "`"
}
return "Object does not exist"
}
+100 -40
View File
@@ -33,14 +33,14 @@ import (
"github.com/pkg/xattr"
"github.com/rjeczalik/notify"
"github.com/minio/mc/cmd/ilm"
"github.com/minio/mc/pkg/disk"
"github.com/minio/mc/pkg/hookreader"
"github.com/minio/mc/pkg/ioutils"
"github.com/minio/mc/pkg/probe"
minio "github.com/minio/minio-go/v6"
"github.com/minio/minio-go/v6/pkg/encrypt"
"github.com/minio/minio-go/v6/pkg/tags"
minio "github.com/minio/minio-go/v7"
"github.com/minio/minio-go/v7/pkg/encrypt"
"github.com/minio/minio-go/v7/pkg/lifecycle"
"github.com/minio/minio-go/v7/pkg/replication"
)
// filesystem client
@@ -51,7 +51,7 @@ type fsClient struct {
const (
partSuffix = ".part.minio"
slashSeperator = "/"
metaDataKey = "X-Amz-Meta-Mc-Attrs"
metadataKey = "X-Amz-Meta-Mc-Attrs"
)
var ( // GOOS specific ignore list.
@@ -275,7 +275,7 @@ func preserveAttributes(fd *os.File, attr map[string]string) *probe.Error {
/// Object operations.
func (f *fsClient) put(ctx context.Context, reader io.Reader, size int64, metadata map[string][]string, progress io.Reader, preserve bool) (int64, *probe.Error) {
func (f *fsClient) put(ctx context.Context, reader io.Reader, size int64, meta map[string]string, progress io.Reader, preserve bool) (int64, *probe.Error) {
// ContentType is not handled on purpose.
// For filesystem this is a redundant information.
@@ -311,8 +311,8 @@ func (f *fsClient) put(ctx context.Context, reader io.Reader, size int64, metada
}
attr := make(map[string]string)
if len(metadata[metaDataKey]) != 0 && preserve {
attr, e = parseAttribute(metadata[metaDataKey][0])
if _, ok := meta[metadataKey]; ok && preserve {
attr, e = parseAttribute(meta[metadataKey])
if e != nil {
tmpFile.Close()
return 0, probe.NewError(e)
@@ -402,12 +402,7 @@ func (f *fsClient) put(ctx context.Context, reader io.Reader, size int64, metada
// Put - create a new file with metadata.
func (f *fsClient) Put(ctx context.Context, reader io.Reader, size int64, metadata map[string]string, progress io.Reader, sse encrypt.ServerSide, md5, disableMultipart, preserve bool) (int64, *probe.Error) {
if metadata[metaDataKey] != "" {
meta := make(map[string][]string)
meta[metaDataKey] = append(meta[metaDataKey], metadata[metaDataKey])
return f.put(ctx, reader, size, meta, progress, preserve)
}
return f.put(ctx, reader, size, nil, progress, preserve)
return f.put(ctx, reader, size, metadata, progress, preserve)
}
// ShareDownload - share download not implemented for filesystem.
@@ -419,7 +414,7 @@ func (f *fsClient) ShareDownload(ctx context.Context, expires time.Duration) (st
}
// ShareUpload - share upload not implemented for filesystem.
func (f *fsClient) ShareUpload(startsWith bool, expires time.Duration, contentType string) (string, map[string]string, *probe.Error) {
func (f *fsClient) ShareUpload(ctx context.Context, startsWith bool, expires time.Duration, contentType string) (string, map[string]string, *probe.Error) {
return "", nil, probe.NewError(APINotImplemented{
API: "ShareUpload",
APIType: "filesystem",
@@ -427,7 +422,7 @@ func (f *fsClient) ShareUpload(startsWith bool, expires time.Duration, contentTy
}
// Copy - copy data from source to destination
func (f *fsClient) Copy(ctx context.Context, source string, size int64, progress io.Reader, srcSSE, tgtSSE encrypt.ServerSide, metadata map[string]string, disableMultipart, preserve bool) *probe.Error {
func (f *fsClient) Copy(ctx context.Context, source string, opts CopyOptions, progress io.Reader) *probe.Error {
rc, e := os.Open(source)
if e != nil {
err := f.toClientError(e, source)
@@ -436,14 +431,14 @@ func (f *fsClient) Copy(ctx context.Context, source string, size int64, progress
defer rc.Close()
destination := f.PathURL.Path
if _, err := f.put(ctx, rc, size, map[string][]string{}, progress, preserve); err != nil {
if _, err := f.put(ctx, rc, opts.size, opts.metadata, progress, opts.isPreserve); err != nil {
return err.Trace(destination, source)
}
return nil
}
// Get returns reader and any additional metadata.
func (f *fsClient) Get(ctx context.Context, sse encrypt.ServerSide) (io.ReadCloser, *probe.Error) {
func (f *fsClient) Get(ctx context.Context, opts GetOptions) (io.ReadCloser, *probe.Error) {
fileData, e := os.Open(f.PathURL.Path)
if e != nil {
err := f.toClientError(e, f.PathURL.Path)
@@ -536,18 +531,18 @@ func (f *fsClient) Remove(ctx context.Context, isIncomplete, isRemoveBucket, isB
}
// List - list files and folders.
func (f *fsClient) List(ctx context.Context, isRecursive, isIncomplete, isMetadata bool, showDir DirOpt) <-chan *ClientContent {
func (f *fsClient) List(ctx context.Context, opts ListOptions) <-chan *ClientContent {
contentCh := make(chan *ClientContent)
filteredCh := make(chan *ClientContent)
if isRecursive {
if showDir == DirNone {
go f.listRecursiveInRoutine(contentCh, isMetadata)
if opts.isRecursive {
if opts.showDir == DirNone {
go f.listRecursiveInRoutine(contentCh, opts.isFetchMeta)
} else {
go f.listDirOpt(contentCh, isIncomplete, isMetadata, showDir)
go f.listDirOpt(contentCh, opts.isIncomplete, opts.isFetchMeta, opts.showDir)
}
} else {
go f.listInRoutine(contentCh, isMetadata)
go f.listInRoutine(contentCh, opts.isFetchMeta)
}
// This function filters entries from any listing go routine
@@ -555,7 +550,7 @@ func (f *fsClient) List(ctx context.Context, isRecursive, isIncomplete, isMetada
// only show partly uploaded files,
go func() {
for c := range contentCh {
if isIncomplete {
if opts.isIncomplete {
if !strings.HasSuffix(c.URL.Path, partSuffix) {
continue
}
@@ -1020,8 +1015,8 @@ func (f *fsClient) SetAccess(ctx context.Context, access string, isJSON bool) *p
}
// Stat - get metadata from path.
func (f *fsClient) Stat(ctx context.Context, isIncomplete, isPreserve bool, sse encrypt.ServerSide) (content *ClientContent, err *probe.Error) {
st, err := f.fsStat(isIncomplete)
func (f *fsClient) Stat(ctx context.Context, opts StatOptions) (content *ClientContent, err *probe.Error) {
st, err := f.fsStat(opts.incomplete)
if err != nil {
return nil, err.Trace(f.PathURL.String())
}
@@ -1036,21 +1031,21 @@ func (f *fsClient) Stat(ctx context.Context, isIncomplete, isPreserve bool, sse
}
path := f.PathURL.String()
metaData, pErr := getAllXattrs(path)
if pErr != nil {
return content, nil
}
for k, v := range metaData {
content.Metadata[k] = v
}
// Populates meta data with file system attribute only in case of
// when preserve flag is passed.
if isPreserve {
if opts.preserve {
fileAttr, err := disk.GetFileSystemAttrs(path)
if err != nil {
return content, nil
}
content.Metadata[metaDataKey] = fileAttr
metaData, pErr := getAllXattrs(path)
if pErr != nil {
return content, nil
}
for k, v := range metaData {
content.Metadata[k] = v
}
content.Metadata[metadataKey] = fileAttr
}
return content, nil
@@ -1096,7 +1091,7 @@ func (f *fsClient) AddUserAgent(_, _ string) {
}
// Get Object Tags
func (f *fsClient) GetTags(ctx context.Context) (*tags.Tags, *probe.Error) {
func (f *fsClient) GetTags(ctx context.Context) (map[string]string, *probe.Error) {
return nil, probe.NewError(APINotImplemented{
API: "GetObjectTagging",
APIType: "filesystem",
@@ -1120,17 +1115,82 @@ func (f *fsClient) DeleteTags(ctx context.Context) *probe.Error {
}
// Get lifecycle configuration for a given bucket, not implemented.
func (f *fsClient) GetLifecycle(ctx context.Context) (ilm.LifecycleConfiguration, *probe.Error) {
return ilm.LifecycleConfiguration{}, probe.NewError(APINotImplemented{
func (f *fsClient) GetLifecycle(ctx context.Context) (*lifecycle.Configuration, *probe.Error) {
return nil, probe.NewError(APINotImplemented{
API: "GetLifecycle",
APIType: "filesystem",
})
}
// Set lifecycle configuration for a given bucket, not implemented.
func (f *fsClient) SetLifecycle(ctx context.Context, _ ilm.LifecycleConfiguration) *probe.Error {
func (f *fsClient) SetLifecycle(ctx context.Context, _ *lifecycle.Configuration) *probe.Error {
return probe.NewError(APINotImplemented{
API: "SetLifecycle",
APIType: "filesystem",
})
}
// Get version info for a bucket, not implemented.
func (f *fsClient) GetVersion(ctx context.Context) (minio.BucketVersioningConfiguration, *probe.Error) {
return minio.BucketVersioningConfiguration{}, probe.NewError(APINotImplemented{
API: "GetVersion",
APIType: "filesystem",
})
}
// SetVersion - Set version configuration on a bucket, not implemented
func (f *fsClient) SetVersion(ctx context.Context, status string) *probe.Error {
return probe.NewError(APINotImplemented{
API: "SetVersion",
APIType: "filesystem",
})
}
// Get replication configuration for a given bucket, not implemented.
func (f *fsClient) GetReplication(ctx context.Context) (replication.Config, *probe.Error) {
return replication.Config{}, probe.NewError(APINotImplemented{
API: "GetReplication",
APIType: "filesystem",
})
}
// Set replication configuration for a given bucket, not implemented.
func (f *fsClient) SetReplication(ctx context.Context, cfg *replication.Config, opts replication.Options) *probe.Error {
return probe.NewError(APINotImplemented{
API: "SetReplication",
APIType: "filesystem",
})
}
// Remove replication configuration for a given bucket. Not implemented
func (f *fsClient) RemoveReplication(ctx context.Context) *probe.Error {
return probe.NewError(APINotImplemented{
API: "RemoveReplication",
APIType: "filesystem",
})
}
// Get encryption info for a bucket, not implemented.
func (f *fsClient) GetEncryption(ctx context.Context) (string, string, *probe.Error) {
return "", "", probe.NewError(APINotImplemented{
API: "GetEncryption",
APIType: "filesystem",
})
}
// SetEncryption - Set encryption configuration on a bucket, not implemented
func (f *fsClient) SetEncryption(ctx context.Context, algorithm, keyID string) *probe.Error {
return probe.NewError(APINotImplemented{
API: "SetEncryption",
APIType: "filesystem",
})
}
// DeleteEncryption - removes encryption configuration on a bucket, not implemented
func (f *fsClient) DeleteEncryption(ctx context.Context) *probe.Error {
return probe.NewError(APINotImplemented{
API: "DeleteEncryption",
APIType: "filesystem",
})
}
+9 -10
View File
@@ -65,7 +65,7 @@ func (s *TestSuite) TestList(c *C) {
// Verify previously create files and list them.
var contents []*ClientContent
for content := range fsClient.List(globalContext, false, false, false, DirNone) {
for content := range fsClient.List(globalContext, ListOptions{showDir: DirNone}) {
if content.Err != nil {
err = content.Err
break
@@ -93,7 +93,7 @@ func (s *TestSuite) TestList(c *C) {
contents = nil
// List non recursive to list only top level files.
for content := range fsClient.List(globalContext, false, false, false, DirNone) {
for content := range fsClient.List(globalContext, ListOptions{showDir: DirNone}) {
if content.Err != nil {
err = content.Err
break
@@ -109,7 +109,7 @@ func (s *TestSuite) TestList(c *C) {
contents = nil
// List recursively all files and verify.
for content := range fsClient.List(globalContext, true, false, false, DirNone) {
for content := range fsClient.List(globalContext, ListOptions{isRecursive: true, showDir: DirNone}) {
if content.Err != nil {
err = content.Err
break
@@ -153,7 +153,7 @@ func (s *TestSuite) TestList(c *C) {
contents = nil
// List recursively all files and verify.
for content := range fsClient.List(globalContext, true, false, false, DirNone) {
for content := range fsClient.List(globalContext, ListOptions{isRecursive: true, showDir: DirNone}) {
if content.Err != nil {
err = content.Err
break
@@ -210,7 +210,7 @@ func (s *TestSuite) TestStatBucket(c *C) {
c.Assert(err, IsNil)
err = fsClient.MakeBucket(context.Background(), "us-east-1", true, false)
c.Assert(err, IsNil)
_, err = fsClient.Stat(context.Background(), false, false, nil)
_, err = fsClient.Stat(context.Background(), StatOptions{})
c.Assert(err, IsNil)
}
@@ -275,7 +275,7 @@ func (s *TestSuite) TestGet(c *C) {
c.Assert(err, IsNil)
c.Assert(n, Equals, int64(len(data)))
reader, err = fsClient.Get(context.Background(), nil)
reader, err = fsClient.Get(context.Background(), GetOptions{})
c.Assert(err, IsNil)
var results bytes.Buffer
_, e = io.Copy(&results, reader)
@@ -303,7 +303,7 @@ func (s *TestSuite) TestGetRange(c *C) {
c.Assert(err, IsNil)
c.Assert(n, Equals, int64(len(data)))
reader, err = fsClient.Get(context.Background(), nil)
reader, err = fsClient.Get(context.Background(), GetOptions{})
c.Assert(err, IsNil)
var results bytes.Buffer
buf := make([]byte, 5)
@@ -334,7 +334,7 @@ func (s *TestSuite) TestStatObject(c *C) {
c.Assert(err, IsNil)
c.Assert(n, Equals, int64(len(data)))
content, err := fsClient.Stat(context.Background(), false, false, nil)
content, err := fsClient.Stat(context.Background(), StatOptions{})
c.Assert(err, IsNil)
c.Assert(content.Size, Equals, int64(dataLen))
}
@@ -358,7 +358,6 @@ func (s *TestSuite) TestCopy(c *C) {
}, nil, nil, false, false, false)
c.Assert(err, IsNil)
c.Assert(n, Equals, int64(len(data)))
err = fsClientTarget.Copy(context.Background(), sourcePath, int64(len(data)), nil, nil, nil, nil, false, false)
err = fsClientTarget.Copy(context.Background(), sourcePath, CopyOptions{size: int64(len(data))}, nil)
c.Assert(err, IsNil)
}
+444 -216
View File
File diff suppressed because it is too large Load Diff
+5 -5
View File
@@ -25,7 +25,7 @@ import (
"net/http/httptest"
"strconv"
minio "github.com/minio/minio-go/v6"
minio "github.com/minio/minio-go/v7"
. "gopkg.in/check.v1"
)
@@ -178,7 +178,7 @@ func (s *TestSuite) TestBucketOperations(c *C) {
s3c, err = S3New(conf)
c.Assert(err, IsNil)
for content := range s3c.List(globalContext, false, false, false, DirNone) {
for content := range s3c.List(globalContext, ListOptions{showDir: DirNone}) {
c.Assert(content.Err, IsNil)
c.Assert(content.Type.IsDir(), Equals, true)
}
@@ -187,7 +187,7 @@ func (s *TestSuite) TestBucketOperations(c *C) {
s3c, err = S3New(conf)
c.Assert(err, IsNil)
for content := range s3c.List(globalContext, false, false, false, DirNone) {
for content := range s3c.List(globalContext, ListOptions{showDir: DirNone}) {
c.Assert(content.Err, IsNil)
c.Assert(content.Type.IsDir(), Equals, true)
}
@@ -196,7 +196,7 @@ func (s *TestSuite) TestBucketOperations(c *C) {
s3c, err = S3New(conf)
c.Assert(err, IsNil)
for content := range s3c.List(globalContext, false, false, false, DirNone) {
for content := range s3c.List(globalContext, ListOptions{showDir: DirNone}) {
c.Assert(content.Err, IsNil)
c.Assert(content.Type.IsRegular(), Equals, true)
}
@@ -227,7 +227,7 @@ func (s *TestSuite) TestObjectOperations(c *C) {
c.Assert(err, IsNil)
c.Assert(n, Equals, int64(len(object.data)))
reader, err = s3c.Get(context.Background(), nil)
reader, err = s3c.Get(context.Background(), GetOptions{})
c.Assert(err, IsNil)
var buffer bytes.Buffer
{
+4 -6
View File
@@ -23,6 +23,7 @@ import (
"regexp"
"runtime"
"strings"
"time"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio/pkg/mimedb"
@@ -184,7 +185,7 @@ func urlJoinPath(url1, url2 string) string {
}
// url2Stat returns stat info for URL.
func url2Stat(ctx context.Context, urlStr string, fileAttr bool, encKeyDB map[string][]prefixSSEPair) (client Client, content *ClientContent, err *probe.Error) {
func url2Stat(ctx context.Context, urlStr, versionID string, fileAttr bool, encKeyDB map[string][]prefixSSEPair, timeRef time.Time) (client Client, content *ClientContent, err *probe.Error) {
client, err = newClient(urlStr)
if err != nil {
return nil, nil, err.Trace(urlStr)
@@ -192,7 +193,7 @@ func url2Stat(ctx context.Context, urlStr string, fileAttr bool, encKeyDB map[st
alias, _ := url2Alias(urlStr)
sse := getSSE(urlStr, encKeyDB[alias])
content, err = client.Stat(ctx, false, fileAttr, sse)
content, err = client.Stat(ctx, StatOptions{preserve: fileAttr, sse: sse, timeRef: timeRef, versionID: versionID})
if err != nil {
return nil, nil, err.Trace(urlStr)
}
@@ -229,10 +230,7 @@ func isURLPrefixExists(urlPrefix string, incomplete bool) bool {
if err != nil {
return false
}
isRecursive := false
isIncomplete := incomplete
isFetchMeta := false
for entry := range clnt.List(globalContext, isRecursive, isIncomplete, isFetchMeta, DirNone) {
for entry := range clnt.List(globalContext, ListOptions{isRecursive: false, isIncomplete: incomplete, isFetchMeta: false, showDir: DirNone}) {
return entry.Err == nil
}
return false
+78 -21
View File
@@ -22,11 +22,11 @@ import (
"os"
"time"
"github.com/minio/mc/cmd/ilm"
"github.com/minio/mc/pkg/probe"
minio "github.com/minio/minio-go/v6"
"github.com/minio/minio-go/v6/pkg/encrypt"
"github.com/minio/minio-go/v6/pkg/tags"
minio "github.com/minio/minio-go/v7"
"github.com/minio/minio-go/v7/pkg/encrypt"
"github.com/minio/minio-go/v7/pkg/lifecycle"
"github.com/minio/minio-go/v7/pkg/replication"
)
// DirOpt - list directory option.
@@ -44,11 +44,48 @@ const (
// Default number of multipart workers for a Put operation.
const defaultMultipartThreadsNum = 4
// GetOptions holds options of the GET operation
type GetOptions struct {
sse encrypt.ServerSide
versionID string
}
// StatOptions holds options of the HEAD operation
type StatOptions struct {
incomplete bool
preserve bool
sse encrypt.ServerSide
timeRef time.Time
versionID string
}
// ListOptions holds options for listing operation
type ListOptions struct {
isRecursive bool
isIncomplete bool
isFetchMeta bool
withOlderVersions bool
withDeleteMarkers bool
timeRef time.Time
showDir DirOpt
}
// CopyOptions holds options for copying operation
type CopyOptions struct {
versionID string
size int64
srcSSE, tgtSSE encrypt.ServerSide
metadata map[string]string
disableMultipart bool
isPreserve bool
}
// Client - client interface
type Client interface {
// Common operations
Stat(ctx context.Context, isIncomplete, isPreserve bool, sse encrypt.ServerSide) (content *ClientContent, err *probe.Error)
List(ctx context.Context, isRecursive, isIncomplete, isFetchMeta bool, showDir DirOpt) <-chan *ClientContent
Stat(ctx context.Context, opts StatOptions) (content *ClientContent, err *probe.Error)
List(ctx context.Context, opts ListOptions) <-chan *ClientContent
// Bucket operations
MakeBucket(ctx context.Context, region string, ignoreExisting, withLock bool) *probe.Error
@@ -62,13 +99,14 @@ type Client interface {
SetAccess(ctx context.Context, access string, isJSON bool) *probe.Error
// I/O operations
Copy(ctx context.Context, source string, size int64, progress io.Reader, srcSSE, tgtSSE encrypt.ServerSide, metadata map[string]string, disableMultipart, isPreserve bool) *probe.Error
Copy(ctx context.Context, source string, opts CopyOptions, progress io.Reader) *probe.Error
// Runs select expression on object storage on specific files.
Select(ctx context.Context, expression string, sse encrypt.ServerSide, opts SelectObjectOpts) (io.ReadCloser, *probe.Error)
// I/O operations with metadata.
Get(ctx context.Context, sse encrypt.ServerSide) (reader io.ReadCloser, err *probe.Error)
Get(ctx context.Context, opts GetOptions) (reader io.ReadCloser, err *probe.Error)
Put(ctx context.Context, reader io.Reader, size int64, metadata map[string]string, progress io.Reader, sse encrypt.ServerSide, md5, disableMultipart, isPreserve bool) (n int64, err *probe.Error)
// Object Locking related API
@@ -77,7 +115,7 @@ type Client interface {
// I/O operations with expiration
ShareDownload(ctx context.Context, expires time.Duration) (string, *probe.Error)
ShareUpload(bool, time.Duration, string) (string, map[string]string, *probe.Error)
ShareUpload(context.Context, bool, time.Duration, string) (string, map[string]string, *probe.Error)
// Watch events
Watch(ctx context.Context, options WatchOptions) (*WatchObject, *probe.Error)
@@ -90,32 +128,51 @@ type Client interface {
AddUserAgent(app, version string)
// Tagging operations
GetTags(ctx context.Context) (*tags.Tags, *probe.Error)
GetTags(ctx context.Context) (map[string]string, *probe.Error)
SetTags(ctx context.Context, tags string) *probe.Error
DeleteTags(ctx context.Context) *probe.Error
// Lifecycle operations
GetLifecycle(ctx context.Context) (ilm.LifecycleConfiguration, *probe.Error)
SetLifecycle(ctx context.Context, lfcCfg ilm.LifecycleConfiguration) *probe.Error
GetLifecycle(ctx context.Context) (*lifecycle.Configuration, *probe.Error)
SetLifecycle(ctx context.Context, config *lifecycle.Configuration) *probe.Error
// Versioning operations
GetVersion(ctx context.Context) (minio.BucketVersioningConfiguration, *probe.Error)
SetVersion(ctx context.Context, status string) *probe.Error
// Replication operations
GetReplication(ctx context.Context) (replication.Config, *probe.Error)
SetReplication(ctx context.Context, cfg *replication.Config, opts replication.Options) *probe.Error
RemoveReplication(ctx context.Context) *probe.Error
// Encryption operations
GetEncryption(ctx context.Context) (string, string, *probe.Error)
SetEncryption(ctx context.Context, algorithm, kmsKeyID string) *probe.Error
DeleteEncryption(ctx context.Context) *probe.Error
}
// ClientContent - Content container for content metadata
type ClientContent struct {
URL ClientURL
Time time.Time
Size int64
Type os.FileMode
StorageClass string
Metadata map[string]string
UserMetadata map[string]string
ETag string
Expires time.Time
URL ClientURL
Time time.Time
Size int64
Type os.FileMode
StorageClass string
Metadata map[string]string
UserMetadata map[string]string
ETag string
Expires time.Time
Expiration time.Time
ExpirationRuleID string
RetentionEnabled bool
RetentionMode string
RetentionDuration string
BypassGovernance bool
LegalHoldEnabled bool
LegalHold string
VersionID string
IsDeleteMarker bool
IsLatest bool
Err *probe.Error
}
+39 -25
View File
@@ -33,8 +33,8 @@ import (
"github.com/minio/cli"
"github.com/minio/mc/pkg/probe"
minio "github.com/minio/minio-go/v6"
"github.com/minio/minio-go/v6/pkg/encrypt"
minio "github.com/minio/minio-go/v7"
"github.com/minio/minio-go/v7/pkg/encrypt"
)
// decode if the key is encoded key and returns the key
@@ -104,10 +104,10 @@ func getEncKeys(ctx *cli.Context) (map[string][]prefixSSEPair, *probe.Error) {
// Check if the passed URL represents a folder. It may or may not exist yet.
// If it exists, we can easily check if it is a folder, if it doesn't exist,
// we can guess if the url is a folder from how it looks.
func isAliasURLDir(ctx context.Context, aliasURL string, keys map[string][]prefixSSEPair) bool {
func isAliasURLDir(ctx context.Context, aliasURL string, keys map[string][]prefixSSEPair, timeRef time.Time) bool {
// If the target url exists, check if it is a directory
// and return immediately.
_, targetContent, err := url2Stat(ctx, aliasURL, false, keys)
_, targetContent, err := url2Stat(ctx, aliasURL, "", false, keys, timeRef)
if err == nil {
return targetContent.Type.IsDir()
}
@@ -148,17 +148,17 @@ func getSourceStreamMetadataFromURL(ctx context.Context, urlStr string, encKeyDB
return nil, nil, err.Trace(urlStr)
}
sseKey := getSSE(urlStr, encKeyDB[alias])
return getSourceStream(ctx, alias, urlStrFull, true, sseKey, false)
return getSourceStream(ctx, alias, urlStrFull, "", true, sseKey, false)
}
// getSourceStreamFromURL gets a reader from URL.
func getSourceStreamFromURL(ctx context.Context, urlStr string, encKeyDB map[string][]prefixSSEPair) (reader io.ReadCloser, err *probe.Error) {
func getSourceStreamFromURL(ctx context.Context, urlStr, versionID string, encKeyDB map[string][]prefixSSEPair) (reader io.ReadCloser, err *probe.Error) {
alias, urlStrFull, _, err := expandAlias(urlStr)
if err != nil {
return nil, err.Trace(urlStr)
}
sse := getSSE(urlStr, encKeyDB[alias])
reader, _, err = getSourceStream(ctx, alias, urlStrFull, false, sse, false)
reader, _, err = getSourceStream(ctx, alias, urlStrFull, versionID, false, sse, false)
return reader, err
}
@@ -210,12 +210,12 @@ func isReadAt(reader io.Reader) (ok bool) {
}
// getSourceStream gets a reader from URL.
func getSourceStream(ctx context.Context, alias string, urlStr string, fetchStat bool, sse encrypt.ServerSide, preserve bool) (reader io.ReadCloser, metadata map[string]string, err *probe.Error) {
func getSourceStream(ctx context.Context, alias, urlStr, versionID string, fetchStat bool, sse encrypt.ServerSide, preserve bool) (reader io.ReadCloser, metadata map[string]string, err *probe.Error) {
sourceClnt, err := newClientFromAlias(alias, urlStr)
if err != nil {
return nil, nil, err.Trace(alias, urlStr)
}
reader, err = sourceClnt.Get(ctx, sse)
reader, err = sourceClnt.Get(ctx, GetOptions{sse: sse, versionID: versionID})
if err != nil {
return nil, nil, err.Trace(alias, urlStr)
}
@@ -241,7 +241,7 @@ func getSourceStream(ctx context.Context, alias string, urlStr string, fetchStat
}
st.ETag = oinfo.ETag
} else {
st, err = sourceClnt.Stat(ctx, false, preserve, sse)
st, err = sourceClnt.Stat(ctx, StatOptions{preserve: preserve, sse: sse})
if err != nil {
return nil, nil, err.Trace(alias, urlStr)
}
@@ -334,7 +334,7 @@ func putTargetStreamWithURL(urlStr string, reader io.Reader, size int64, sse enc
}
// copySourceToTargetURL copies to targetURL from source.
func copySourceToTargetURL(ctx context.Context, alias, urlStr, source, mode, until, legalHold string, size int64, progress io.Reader, srcSSE, tgtSSE encrypt.ServerSide, metadata map[string]string, disableMultipart bool) *probe.Error {
func copySourceToTargetURL(ctx context.Context, alias, urlStr, source, sourceVersionID, mode, until, legalHold string, size int64, progress io.Reader, srcSSE, tgtSSE encrypt.ServerSide, metadata map[string]string, disableMultipart, preserve bool) *probe.Error {
targetClnt, err := newClientFromAlias(alias, urlStr)
if err != nil {
@@ -344,8 +344,16 @@ func copySourceToTargetURL(ctx context.Context, alias, urlStr, source, mode, unt
metadata[AmzObjectLockMode] = mode
metadata[AmzObjectLockRetainUntilDate] = until
metadata[AmzObjectLockLegalHold] = legalHold
err = targetClnt.Copy(ctx, source, size, progress, srcSSE, tgtSSE, metadata, disableMultipart, false)
opts := CopyOptions{
versionID: sourceVersionID,
size: size,
srcSSE: srcSSE, tgtSSE: tgtSSE,
metadata: metadata,
disableMultipart: disableMultipart,
isPreserve: preserve}
err = targetClnt.Copy(ctx, source, opts, progress)
if err != nil {
return err.Trace(alias, urlStr)
}
@@ -369,13 +377,14 @@ func filterMetadata(metadata map[string]string) map[string]string {
// getAllMetadata - returns a map of user defined function
// by combining the usermetadata of object and values passed by attr keyword
func getAllMetadata(ctx context.Context, sourceAlias, sourceURLStr string, srcSSE encrypt.ServerSide, urls URLs, preserve bool) (map[string]string, *probe.Error) {
func getAllMetadata(ctx context.Context, sourceAlias, sourceURLStr string, srcSSE encrypt.ServerSide, urls URLs) (map[string]string, *probe.Error) {
metadata := make(map[string]string)
sourceClnt, err := newClientFromAlias(sourceAlias, sourceURLStr)
if err != nil {
return nil, err.Trace(sourceAlias, sourceURLStr)
}
st, err := sourceClnt.Stat(ctx, false, preserve, srcSSE)
st, err := sourceClnt.Stat(ctx, StatOptions{preserve: true, sse: srcSSE})
if err != nil {
return nil, err.Trace(sourceAlias, sourceURLStr)
}
@@ -397,6 +406,7 @@ func getAllMetadata(ctx context.Context, sourceAlias, sourceURLStr string, srcSS
func uploadSourceToTargetURL(ctx context.Context, urls URLs, progress io.Reader, encKeyDB map[string][]prefixSSEPair, preserve bool) URLs {
sourceAlias := urls.SourceAlias
sourceURL := urls.SourceContent.URL
sourceVersion := urls.SourceContent.VersionID
targetAlias := urls.TargetAlias
targetURL := urls.TargetContent.URL
length := urls.SourceContent.Size
@@ -453,13 +463,15 @@ func uploadSourceToTargetURL(ctx context.Context, urls URLs, progress io.Reader,
// Optimize for server side copy if the host is same.
if sourceAlias == targetAlias {
// If no metadata populated already by the caller
// just do a Stat() to obtain the metadata.
if len(metadata) == 0 && preserve {
metadata, err = getAllMetadata(ctx, sourceAlias, sourceURL.String(), srcSSE, urls, preserve)
// preserve new metadata and save existing ones.
if preserve {
currentMetadata, err := getAllMetadata(ctx, sourceAlias, sourceURL.String(), srcSSE, urls)
if err != nil {
return urls.WithError(err.Trace(sourceURL.String()))
}
for k, v := range currentMetadata {
metadata[k] = v
}
}
// Get metadata from target content as well
@@ -478,17 +490,19 @@ func uploadSourceToTargetURL(ctx context.Context, urls URLs, progress io.Reader,
return urls.WithError(err.Trace(sourceURL.String()))
}
err = copySourceToTargetURL(ctx, targetAlias, targetURL.String(), sourcePath, mode, until,
legalHold, length, progress, srcSSE, tgtSSE, filterMetadata(metadata), urls.DisableMultipart)
err = copySourceToTargetURL(ctx, targetAlias, targetURL.String(), sourcePath, sourceVersion, mode, until,
legalHold, length, progress, srcSSE, tgtSSE, filterMetadata(metadata), urls.DisableMultipart, preserve)
} else {
if urls.SourceContent.RetentionEnabled {
// If no metadata populated already by the caller
// just do a Stat() to obtain the metadata.
if len(metadata) == 0 && preserve {
metadata, err = getAllMetadata(ctx, sourceAlias, sourceURL.String(), srcSSE, urls, preserve)
// preserve new metadata and save existing ones.
if preserve {
currentMetadata, err := getAllMetadata(ctx, sourceAlias, sourceURL.String(), srcSSE, urls)
if err != nil {
return urls.WithError(err.Trace(sourceURL.String()))
}
for k, v := range currentMetadata {
metadata[k] = v
}
}
// Get metadata from target content as well
@@ -507,7 +521,7 @@ func uploadSourceToTargetURL(ctx context.Context, urls URLs, progress io.Reader,
var reader io.ReadCloser
// Proceed with regular stream copy.
reader, metadata, err = getSourceStream(ctx, sourceAlias, sourceURL.String(), true, srcSSE, preserve)
reader, metadata, err = getSourceStream(ctx, sourceAlias, sourceURL.String(), sourceVersion, true, srcSSE, preserve)
if err != nil {
return urls.WithError(err.Trace(sourceURL.String()))
}
+100
View File
@@ -0,0 +1,100 @@
/*
* 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.
*/
package cmd
import "github.com/minio/cli"
var configCmd = cli.Command{
Name: "config",
Usage: "configure MinIO client",
Action: func(ctx *cli.Context) error {
cli.ShowCommandHelp(ctx, ctx.Args().First())
return nil
},
Hidden: true,
Before: setGlobalsFromContext,
HideHelpCommand: true,
Flags: globalFlags,
Subcommands: []cli.Command{
configHostCmd,
},
}
var configHostCmd = cli.Command{
Name: "host",
Usage: "add, remove and list hosts in configuration file",
Action: func(ctx *cli.Context) error {
cli.ShowCommandHelp(ctx, ctx.Args().First())
return nil
},
Before: setGlobalsFromContext,
Flags: globalFlags,
Subcommands: []cli.Command{
configHostAddCmd,
configHostRemoveCmd,
configHostListCmd,
},
HideHelpCommand: true,
}
var configHostAddFlags = []cli.Flag{
cli.StringFlag{
Name: "lookup",
Value: "auto",
Usage: "bucket lookup supported by the server. Valid options are '[dns, path, auto]'",
},
cli.StringFlag{
Name: "api",
Usage: "API signature. Valid options are '[S3v4, S3v2]'",
},
}
var configHostAddCmd = cli.Command{
Name: "add",
ShortName: "a",
Usage: "add a new host to configuration file",
Action: func(cli *cli.Context) error {
return mainAliasSet(cli, true)
},
Before: setGlobalsFromContext,
Flags: append(configHostAddFlags, globalFlags...),
HideHelpCommand: true,
}
var configHostListCmd = cli.Command{
Name: "list",
ShortName: "ls",
Usage: "list hosts in configuration file",
Action: func(cli *cli.Context) error {
return mainAliasList(cli, true)
},
Before: setGlobalsFromContext,
Flags: globalFlags,
HideHelpCommand: true,
}
var configHostRemoveCmd = cli.Command{
Name: "remove",
ShortName: "rm",
Usage: "remove a host from configuration file",
Action: func(cli *cli.Context) error {
return mainAliasRemove(cli, true)
},
Before: setGlobalsFromContext,
Flags: globalFlags,
HideHelpCommand: true,
}
+28 -12
View File
@@ -1,5 +1,5 @@
/*
* MinIO Client (C) 2015 MinIO, Inc.
* MinIO Client (C) 2015-2020 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -42,6 +42,12 @@ func fixConfig() {
*/
}
// ConfigAnyVersion is a generic structure to parse any
// config.json version file and only extracts its version number
type ConfigAnyVersion struct {
Version string
}
/////////////////// Broken Config V3 ///////////////////
type brokenHostConfigV3 struct {
AccessKeyID string
@@ -73,14 +79,18 @@ func fixConfigV3() {
if !isMcConfigExists() {
return
}
// Check if this is the correct version to fix
configAllVersions, e := quick.LoadConfig(mustGetMcConfigPath(), nil, &ConfigAnyVersion{})
fatalIf(probe.NewError(e), "Unable to load config.")
if configAllVersions.Version() != "3" {
return
}
brokenCfgV3 := newBrokenConfigV3()
brokenMcCfgV3, e := quick.LoadConfig(mustGetMcConfigPath(), nil, brokenCfgV3)
fatalIf(probe.NewError(e), "Unable to load config.")
if brokenMcCfgV3.Version() != "3" {
return
}
cfgV3 := newConfigV3()
isMutated := false
for k, v := range brokenMcCfgV3.Data().(*brokenConfigV3).Aliases {
@@ -122,13 +132,16 @@ func fixConfigV6ForHosts() {
return
}
brokenMcCfgV6, e := quick.LoadConfig(mustGetMcConfigPath(), nil, newConfigV6())
// Check the current config version
configAllVersions, e := quick.LoadConfig(mustGetMcConfigPath(), nil, &ConfigAnyVersion{})
fatalIf(probe.NewError(e), "Unable to load config.")
if brokenMcCfgV6.Version() != "6" {
if configAllVersions.Version() != "6" {
return
}
brokenMcCfgV6, e := quick.LoadConfig(mustGetMcConfigPath(), nil, newConfigV6())
fatalIf(probe.NewError(e), "Unable to load config.")
newCfgV6 := newConfigV6()
isMutated := false
@@ -175,16 +188,19 @@ func fixConfigV6() {
if !isMcConfigExists() {
return
}
configAllVersions, e := quick.LoadConfig(mustGetMcConfigPath(), nil, &ConfigAnyVersion{})
fatalIf(probe.NewError(e), "Unable to load config.")
if configAllVersions.Version() != "6" {
return
}
config, e := quick.NewConfig(newConfigV6(), nil)
fatalIf(probe.NewError(e), "Unable to initialize config.")
e = config.Load(mustGetMcConfigPath())
fatalIf(probe.NewError(e).Trace(mustGetMcConfigPath()), "Unable to load config.")
if config.Data().(*configV6).Version != "6" {
return
}
newConfig := new(configV6)
isMutated := false
newConfig.Aliases = make(map[string]string)
-52
View File
@@ -1,52 +0,0 @@
/*
* 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.
*/
package cmd
import "github.com/minio/cli"
// Configure MinIO Client
//
// ----
// NOTE: that the configure command only writes values to the config file.
// It does not use any configuration values from the environment variables.
//
// One needs to edit configuration file manually, this is purposefully done
// so to avoid taking credentials over cli arguments. It is a security precaution
// ----
//
var (
configFlags = []cli.Flag{}
)
var configCmd = cli.Command{
Name: "config",
Usage: "configure MinIO client",
Action: mainConfig,
HideHelpCommand: true,
Flags: append(configFlags, globalFlags...),
Subcommands: []cli.Command{
configHostCmd,
},
}
// mainConfig is the handle for "mc config" command. provides sub-commands which write configuration data in json format to config file.
func mainConfig(ctx *cli.Context) error {
cli.ShowCommandHelp(ctx, ctx.Args().First())
return nil
// Sub-commands like "host" and "alias" have their own main.
}
+118 -42
View File
@@ -45,6 +45,8 @@ func migrateConfig() {
migrateConfigV7ToV8()
// Migrate config V8 to V9
migrateConfigV8ToV9()
// Migrate config V9 to V10
migrateConfigV9ToV10()
}
// Migrate from config version 1.0 to 1.0.1. Populate example entries and save it back.
@@ -52,14 +54,17 @@ func migrateConfigV1ToV101() {
if !isMcConfigExists() {
return
}
mcCfgV1, e := quick.LoadConfig(mustGetMcConfigPath(), nil, newConfigV1())
fatalIf(probe.NewError(e), "Unable to load config version `1`.")
// If loaded config version does not match 1.0.0, we do nothing.
if mcCfgV1.Version() != "1.0.0" {
// Check the config version and quit early if the actual version is out of this function scope
anyCfg, e := quick.LoadConfig(mustGetMcConfigPath(), nil, &ConfigAnyVersion{})
fatalIf(probe.NewError(e), "Unable to load config version `1`.")
if anyCfg.Version() != "1.0.0" {
return
}
mcCfgV1, e := quick.LoadConfig(mustGetMcConfigPath(), nil, newConfigV1())
fatalIf(probe.NewError(e), "Unable to load config version `1`.")
// 1.0.1 is compatible to 1.0.0. We are just adding new entries.
cfgV101 := newConfigV101()
@@ -109,13 +114,18 @@ func migrateConfigV101ToV2() {
if !isMcConfigExists() {
return
}
// Check the config version and quit early if the actual version is out of this function scope
anyCfg, e := quick.LoadConfig(mustGetMcConfigPath(), nil, &ConfigAnyVersion{})
fatalIf(probe.NewError(e), "Unable to load config version `1`.")
if anyCfg.Version() != "1.0.1" {
return
}
mcCfgV101, e := quick.LoadConfig(mustGetMcConfigPath(), nil, newConfigV101())
fatalIf(probe.NewError(e), "Unable to load config version `1.0.1`.")
// update to newer version
if mcCfgV101.Version() != "1.0.1" {
return
}
cfgV2 := newConfigV2()
@@ -148,14 +158,16 @@ func migrateConfigV2ToV3() {
return
}
mcCfgV2, e := quick.LoadConfig(mustGetMcConfigPath(), nil, newConfigV2())
fatalIf(probe.NewError(e), "Unable to load mc config V2.")
// update to newer version
if mcCfgV2.Version() != "2" {
// Check the config version and quit early if the actual version is out of this function scope
anyCfg, e := quick.LoadConfig(mustGetMcConfigPath(), nil, &ConfigAnyVersion{})
fatalIf(probe.NewError(e), "Unable to load config version.")
if anyCfg.Version() != "2" {
return
}
mcCfgV2, e := quick.LoadConfig(mustGetMcConfigPath(), nil, newConfigV2())
fatalIf(probe.NewError(e), "Unable to load mc config V2.")
cfgV3 := newConfigV3()
// Copy aliases.
@@ -187,14 +199,17 @@ func migrateConfigV3ToV4() {
if !isMcConfigExists() {
return
}
mcCfgV3, e := quick.LoadConfig(mustGetMcConfigPath(), nil, newConfigV3())
fatalIf(probe.NewError(e), "Unable to load mc config V2.")
// update to newer version
if mcCfgV3.Version() != "3" {
// Check the config version and quit early if the actual version is out of this function scope
anyCfg, e := quick.LoadConfig(mustGetMcConfigPath(), nil, &ConfigAnyVersion{})
fatalIf(probe.NewError(e), "Unable to load config version.")
if anyCfg.Version() != "3" {
return
}
mcCfgV3, e := quick.LoadConfig(mustGetMcConfigPath(), nil, newConfigV3())
fatalIf(probe.NewError(e), "Unable to load mc config V3.")
cfgV4 := newConfigV4()
for k, v := range mcCfgV3.Data().(*configV3).Aliases {
cfgV4.Aliases[k] = v
@@ -226,14 +241,17 @@ func migrateConfigV4ToV5() {
if !isMcConfigExists() {
return
}
mcCfgV4, e := quick.LoadConfig(mustGetMcConfigPath(), nil, newConfigV4())
fatalIf(probe.NewError(e), "Unable to load mc config V4.")
// update to newer version
if mcCfgV4.Version() != "4" {
// Check the config version and quit early if the actual version is out of this function scope
anyCfg, e := quick.LoadConfig(mustGetMcConfigPath(), nil, &ConfigAnyVersion{})
fatalIf(probe.NewError(e), "Unable to load config version.")
if anyCfg.Version() != "4" {
return
}
mcCfgV4, e := quick.LoadConfig(mustGetMcConfigPath(), nil, newConfigV4())
fatalIf(probe.NewError(e), "Unable to load mc config V4.")
cfgV5 := newConfigV5()
for k, v := range mcCfgV4.Data().(*configV4).Aliases {
cfgV5.Aliases[k] = v
@@ -261,14 +279,17 @@ func migrateConfigV5ToV6() {
if !isMcConfigExists() {
return
}
mcCfgV5, e := quick.LoadConfig(mustGetMcConfigPath(), nil, newConfigV5())
fatalIf(probe.NewError(e), "Unable to load mc config V5.")
// update to newer version
if mcCfgV5.Version() != "5" {
// Check the config version and quit early if the actual version is out of this function scope
anyCfg, e := quick.LoadConfig(mustGetMcConfigPath(), nil, &ConfigAnyVersion{})
fatalIf(probe.NewError(e), "Unable to load config version.")
if anyCfg.Version() != "5" {
return
}
mcCfgV5, e := quick.LoadConfig(mustGetMcConfigPath(), nil, newConfigV5())
fatalIf(probe.NewError(e), "Unable to load mc config V5.")
cfgV6 := newConfigV6()
// Add new Google Cloud Storage alias.
@@ -328,13 +349,16 @@ func migrateConfigV6ToV7() {
return
}
mcCfgV6, e := quick.LoadConfig(mustGetMcConfigPath(), nil, newConfigV6())
fatalIf(probe.NewError(e), "Unable to load mc config V6.")
if mcCfgV6.Version() != "6" {
// Check the config version and quit early if the actual version is out of this function scope
anyCfg, e := quick.LoadConfig(mustGetMcConfigPath(), nil, &ConfigAnyVersion{})
fatalIf(probe.NewError(e), "Unable to load config version.")
if anyCfg.Version() != "6" {
return
}
mcCfgV6, e := quick.LoadConfig(mustGetMcConfigPath(), nil, newConfigV6())
fatalIf(probe.NewError(e), "Unable to load mc config V6.")
cfgV7 := newConfigV7()
aliasIndex := 0
@@ -407,13 +431,16 @@ func migrateConfigV7ToV8() {
return
}
mcCfgV7, e := quick.LoadConfig(mustGetMcConfigPath(), nil, newConfigV7())
fatalIf(probe.NewError(e), "Unable to load mc config V7.")
if mcCfgV7.Version() != "7" {
// Check the config version and quit early if the actual version is out of this function scope
anyCfg, e := quick.LoadConfig(mustGetMcConfigPath(), nil, &ConfigAnyVersion{})
fatalIf(probe.NewError(e), "Unable to load config version.")
if anyCfg.Version() != "7" {
return
}
mcCfgV7, e := quick.LoadConfig(mustGetMcConfigPath(), nil, newConfigV7())
fatalIf(probe.NewError(e), "Unable to load mc config V7.")
cfgV8 := newConfigV8()
// We dropped alias support in v7. We only need to migrate host configs.
for host, hostCfgV7 := range mcCfgV7.Data().(*configV7).Hosts {
@@ -445,22 +472,23 @@ func migrateConfigV8ToV9() {
return
}
mcCfgV8, e := quick.LoadConfig(mustGetMcConfigPath(), nil, newConfigV8())
fatalIf(probe.NewError(e), "Unable to load mc config V8.")
if mcCfgV8.Version() != "8" {
// Check the config version and quit early if the actual version is out of this function scope
anyCfg, e := quick.LoadConfig(mustGetMcConfigPath(), nil, &ConfigAnyVersion{})
fatalIf(probe.NewError(e), "Unable to load config version.")
if anyCfg.Version() != "8" {
return
}
mcCfgV8, e := quick.LoadConfig(mustGetMcConfigPath(), nil, newConfigV8())
fatalIf(probe.NewError(e), "Unable to load mc config V8.")
cfgV9 := newConfigV9()
isEmpty := true
// We dropped alias support in v8. We only need to migrate host configs.
for host, hostCfgV8 := range mcCfgV8.Data().(*configV8).Hosts {
// Ignore 'player', 'play' and 'dl' aliases.
if host == "player" || host == "dl" || host == "play" {
continue
}
isEmpty = false
hostCfgV9 := hostConfigV9{}
hostCfgV9.URL = hostCfgV8.URL
hostCfgV9.AccessKey = hostCfgV8.AccessKey
@@ -469,10 +497,6 @@ func migrateConfigV8ToV9() {
hostCfgV9.Lookup = "auto"
cfgV9.Hosts[host] = hostCfgV9
}
if isEmpty {
// Load default settings.
cfgV9.loadDefaults()
}
mcNewCfgV9, e := quick.NewConfig(cfgV9, nil)
fatalIf(probe.NewError(e), "Unable to initialize quick config for config version `9`.")
@@ -482,3 +506,55 @@ func migrateConfigV8ToV9() {
console.Infof("Successfully migrated %s from version `8` to version `9`.\n", mustGetMcConfigPath())
}
// Migrate config version `9` to `10'. Rename 'hosts' to 'aliases' and 'lookup' to 'path'
func migrateConfigV9ToV10() {
if !isMcConfigExists() {
return
}
// Check the config version and quit early if the actual version is out of this function scope
anyCfg, e := quick.LoadConfig(mustGetMcConfigPath(), nil, &ConfigAnyVersion{})
fatalIf(probe.NewError(e), "Unable to load config version.")
if anyCfg.Version() != "9" {
return
}
mcCfgV9, e := quick.LoadConfig(mustGetMcConfigPath(), nil, newConfigV9())
fatalIf(probe.NewError(e), "Unable to load mc config V8.")
cfgV10 := newConfigV10()
isEmpty := true
// We dropped alias support in v8. We only need to migrate host configs.
for host, hostCfgV9 := range mcCfgV9.Data().(*configV9).Hosts {
isEmpty = false
hostCfgV10 := aliasConfigV10{}
hostCfgV10.URL = hostCfgV9.URL
hostCfgV10.AccessKey = hostCfgV9.AccessKey
hostCfgV10.SecretKey = hostCfgV9.SecretKey
hostCfgV10.API = hostCfgV9.API
switch hostCfgV9.Lookup {
case "dns":
hostCfgV10.Path = "off"
case "path":
hostCfgV10.Path = "on"
default:
hostCfgV10.Path = "auto"
}
cfgV10.Aliases[host] = hostCfgV10
}
if isEmpty {
// Load default settings.
cfgV10.loadDefaults()
}
mcNewCfgV10, e := quick.NewConfig(cfgV10, nil)
fatalIf(probe.NewError(e), "Unable to initialize quick config for config version `10`.")
e = mcNewCfgV10.Save(mustGetMcConfigPath())
fatalIf(probe.NewError(e), "Unable to save config version `10`.")
console.Infof("Successfully migrated %s from version `9` to version `10`.\n", mustGetMcConfigPath())
}
+25
View File
@@ -305,4 +305,29 @@ func (c *configV8) loadDefaults() {
}
/////////////////// Config V9 ///////////////////
// hostConfig configuration of a host.
type hostConfigV9 struct {
URL string `json:"url"`
AccessKey string `json:"accessKey"`
SecretKey string `json:"secretKey"`
SessionToken string `json:"sessionToken,omitempty"`
API string `json:"api"`
Lookup string `json:"lookup"`
}
// configV8 config version.
type configV9 struct {
Version string `json:"version"`
Hosts map[string]hostConfigV9 `json:"hosts"`
}
func newConfigV9() *configV9 {
cfg := new(configV9)
cfg.Version = "9"
cfg.Hosts = make(map[string]hostConfigV9)
return cfg
}
/////////////////// Config V10 ///////////////////
// RESERVED FOR FUTURE
+11
View File
@@ -79,3 +79,14 @@ func isValidLookup(lookup string) (ok bool) {
}
return false
}
// isValidPath - validates the alias path config
func isValidPath(path string) (ok bool) {
l := strings.ToLower(strings.TrimSpace(path))
for _, v := range []string{"on", "off", "auto"} {
if l == v {
return true
}
}
return false
}
+38 -38
View File
@@ -1,5 +1,5 @@
/*
* MinIO Client (C) 2015 MinIO, Inc.
* MinIO Client (C) 2020 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -30,89 +30,89 @@ const (
var (
// set once during first load.
cacheCfgV9 *configV9
cacheCfgV10 *configV10
// All access to mc config file should be synchronized.
cfgMutex = &sync.RWMutex{}
)
// hostConfig configuration of a host.
type hostConfigV9 struct {
// aliasConfig configuration of an alias.
type aliasConfigV10 struct {
URL string `json:"url"`
AccessKey string `json:"accessKey"`
SecretKey string `json:"secretKey"`
SessionToken string `json:"sessionToken,omitempty"`
API string `json:"api"`
Lookup string `json:"lookup"`
Path string `json:"path"`
}
// configV8 config version.
type configV9 struct {
Version string `json:"version"`
Hosts map[string]hostConfigV9 `json:"hosts"`
// configV10 config version.
type configV10 struct {
Version string `json:"version"`
Aliases map[string]aliasConfigV10 `json:"aliases"`
}
// newConfigV9 - new config version.
func newConfigV9() *configV9 {
cfg := new(configV9)
// newConfigV10 - new config version.
func newConfigV10() *configV10 {
cfg := new(configV10)
cfg.Version = globalMCConfigVersion
cfg.Hosts = make(map[string]hostConfigV9)
cfg.Aliases = make(map[string]aliasConfigV10)
return cfg
}
// SetHost sets host config if not empty.
func (c *configV9) setHost(alias string, cfg hostConfigV9) {
if _, ok := c.Hosts[alias]; !ok {
c.Hosts[alias] = cfg
// SetAlias sets host config if not empty.
func (c *configV10) setAlias(alias string, cfg aliasConfigV10) {
if _, ok := c.Aliases[alias]; !ok {
c.Aliases[alias] = cfg
}
}
// load default values for missing entries.
func (c *configV9) loadDefaults() {
func (c *configV10) loadDefaults() {
// MinIO server running locally.
c.setHost("local", hostConfigV9{
c.setAlias("local", aliasConfigV10{
URL: "http://localhost:9000",
AccessKey: "",
SecretKey: "",
API: "S3v4",
Lookup: "auto",
Path: "auto",
})
// Amazon S3 cloud storage service.
c.setHost("s3", hostConfigV9{
c.setAlias("s3", aliasConfigV10{
URL: "https://s3.amazonaws.com",
AccessKey: defaultAccessKey,
SecretKey: defaultSecretKey,
API: "S3v4",
Lookup: "dns",
Path: "dns",
})
// Google cloud storage service.
c.setHost("gcs", hostConfigV9{
c.setAlias("gcs", aliasConfigV10{
URL: "https://storage.googleapis.com",
AccessKey: defaultAccessKey,
SecretKey: defaultSecretKey,
API: "S3v2",
Lookup: "dns",
Path: "dns",
})
// MinIO anonymous server for demo.
c.setHost("play", hostConfigV9{
c.setAlias("play", aliasConfigV10{
URL: "https://play.min.io",
AccessKey: "Q3AM3UQ867SPQQA43P2F",
SecretKey: "zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG",
API: "S3v4",
Lookup: "auto",
Path: "auto",
})
}
// loadConfigV9 - loads a new config.
func loadConfigV9() (*configV9, *probe.Error) {
// loadConfigV10 - loads a new config.
func loadConfigV10() (*configV10, *probe.Error) {
cfgMutex.RLock()
defer cfgMutex.RUnlock()
// If already cached, return the cached value.
if cacheCfgV9 != nil {
return cacheCfgV9, nil
if cacheCfgV10 != nil {
return cacheCfgV10, nil
}
if !isMcConfigExists() {
@@ -120,7 +120,7 @@ func loadConfigV9() (*configV9, *probe.Error) {
}
// Initialize a new config loader.
qc, e := quick.NewConfig(newConfigV9(), nil)
qc, e := quick.NewConfig(newConfigV10(), nil)
if e != nil {
return nil, probe.NewError(e)
}
@@ -131,27 +131,27 @@ func loadConfigV9() (*configV9, *probe.Error) {
return nil, probe.NewError(e)
}
cfgV9 := qc.Data().(*configV9)
cfgV10 := qc.Data().(*configV10)
// Cache config.
cacheCfgV9 = cfgV9
cacheCfgV10 = cfgV10
// Success.
return cfgV9, nil
return cfgV10, nil
}
// saveConfigV8 - saves an updated config.
func saveConfigV9(cfgV9 *configV9) *probe.Error {
// saveConfigV10 - saves an updated config.
func saveConfigV10(cfgV10 *configV10) *probe.Error {
cfgMutex.Lock()
defer cfgMutex.Unlock()
qs, e := quick.NewConfig(cfgV9, nil)
qs, e := quick.NewConfig(cfgV10, nil)
if e != nil {
return probe.NewError(e)
}
// update the cache.
cacheCfgV9 = cfgV9
cacheCfgV10 = cfgV10
e = qs.Save(mustGetMcConfigPath())
if e != nil {
+8 -8
View File
@@ -22,7 +22,7 @@ import (
)
// Check if version of the config is valid
func validateConfigVersion(config *configV9) (bool, string) {
func validateConfigVersion(config *configV10) (bool, string) {
if config.Version != globalMCConfigVersion {
return false, fmt.Sprintf("Config version '%s' does not match mc config version '%s', please update your binary.\n",
config.Version, globalMCConfigVersion)
@@ -31,7 +31,7 @@ func validateConfigVersion(config *configV9) (bool, string) {
}
// Verifies the config file of the MinIO Client
func validateConfigFile(config *configV9) (bool, []string) {
func validateConfigFile(config *configV10) (bool, []string) {
ok, err := validateConfigVersion(config)
var validationSuccessful = true
var errors []string
@@ -39,18 +39,18 @@ func validateConfigFile(config *configV9) (bool, []string) {
validationSuccessful = false
errors = append(errors, err)
}
hosts := config.Hosts
for _, hostConfig := range hosts {
hostConfigHealthOk, hostErrors := validateConfigHost(hostConfig)
if !hostConfigHealthOk {
aliases := config.Aliases
for _, aliasConfig := range aliases {
aliasConfigHealthOk, aliasErrors := validateConfigHost(aliasConfig)
if !aliasConfigHealthOk {
validationSuccessful = false
errors = append(errors, hostErrors...)
errors = append(errors, aliasErrors...)
}
}
return validationSuccessful, errors
}
func validateConfigHost(host hostConfigV9) (bool, []string) {
func validateConfigHost(host aliasConfigV10) (bool, []string) {
var validationSuccessful = true
var hostErrors []string
if !isValidAPI(strings.ToLower(host.API)) {
+31 -31
View File
@@ -1,5 +1,5 @@
/*
* MinIO Client (C) 2015 MinIO, Inc.
* MinIO Client (C) 2015-2020 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -105,29 +105,29 @@ func mustGetMcConfigPath() string {
return path
}
// newMcConfig - initializes a new version '9' config.
func newMcConfig() *configV9 {
cfg := newConfigV9()
// newMcConfig - initializes a new version '10' config.
func newMcConfig() *configV10 {
cfg := newConfigV10()
cfg.loadDefaults()
return cfg
}
// loadMcConfigCached - returns loadMcConfig with a closure for config cache.
func loadMcConfigFactory() func() (*configV9, *probe.Error) {
func loadMcConfigFactory() func() (*configV10, *probe.Error) {
// Load once and cache in a closure.
cfgCache, err := loadConfigV9()
cfgCache, err := loadConfigV10()
// loadMcConfig - reads configuration file and returns config.
return func() (*configV9, *probe.Error) {
return func() (*configV10, *probe.Error) {
return cfgCache, err
}
}
// loadMcConfig - returns configuration, initialized later.
var loadMcConfig func() (*configV9, *probe.Error)
var loadMcConfig func() (*configV10, *probe.Error)
// saveMcConfig - saves configuration file and returns error if any.
func saveMcConfig(config *configV9) *probe.Error {
func saveMcConfig(config *configV10) *probe.Error {
if config == nil {
return errInvalidArgument().Trace()
}
@@ -138,7 +138,7 @@ func saveMcConfig(config *configV9) *probe.Error {
}
// Save the config.
if err := saveConfigV9(config); err != nil {
if err := saveConfigV10(config); err != nil {
return err.Trace(mustGetMcConfigPath())
}
@@ -172,16 +172,16 @@ func isValidAlias(alias string) bool {
return regexp.MustCompile("^[a-zA-Z][a-zA-Z0-9-_]+$").MatchString(alias)
}
// getHostConfig retrieves host specific configuration such as access keys, signature type.
func getHostConfig(alias string) (*hostConfigV9, *probe.Error) {
// getAliasConfig retrieves host specific configuration such as access keys, signature type.
func getAliasConfig(alias string) (*aliasConfigV10, *probe.Error) {
mcCfg, err := loadMcConfig()
if err != nil {
return nil, err.Trace(alias)
}
// if host is exact return quickly.
if _, ok := mcCfg.Hosts[alias]; ok {
hostCfg := mcCfg.Hosts[alias]
if _, ok := mcCfg.Aliases[alias]; ok {
hostCfg := mcCfg.Aliases[alias]
return &hostCfg, nil
}
@@ -190,22 +190,22 @@ func getHostConfig(alias string) (*hostConfigV9, *probe.Error) {
}
// mustGetHostConfig retrieves host specific configuration such as access keys, signature type.
func mustGetHostConfig(alias string) *hostConfigV9 {
hostCfg, _ := getHostConfig(alias)
func mustGetHostConfig(alias string) *aliasConfigV10 {
aliasCfg, _ := getAliasConfig(alias)
// If alias is not found,
// look for it in the environment variable.
if hostCfg == nil {
if aliasCfg == nil {
if envConfig, ok := os.LookupEnv(mcEnvHostPrefix + alias); ok {
hostCfg, _ = expandAliasFromEnv(envConfig)
aliasCfg, _ = expandAliasFromEnv(envConfig)
}
}
if hostCfg == nil {
if aliasCfg == nil {
if envConfig, ok := os.LookupEnv(mcEnvHostsDeprecatedPrefix + alias); ok {
errorIf(errInvalidArgument().Trace(mcEnvHostsDeprecatedPrefix+alias), "`MC_HOSTS_<alias>` environment variable is deprecated. Please use `MC_HOST_<alias>` instead for the same functionality.")
hostCfg, _ = expandAliasFromEnv(envConfig)
aliasCfg, _ = expandAliasFromEnv(envConfig)
}
}
return hostCfg
return aliasCfg
}
var (
@@ -265,13 +265,13 @@ const (
mcEnvHostsDeprecatedPrefix = "MC_HOSTS_"
)
func expandAliasFromEnv(envURL string) (*hostConfigV9, *probe.Error) {
func expandAliasFromEnv(envURL string) (*aliasConfigV10, *probe.Error) {
u, accessKey, secretKey, sessionToken, err := parseEnvURLStr(envURL)
if err != nil {
return nil, err.Trace(envURL)
}
return &hostConfigV9{
return &aliasConfigV10{
URL: u.String(),
API: "S3v4",
AccessKey: accessKey,
@@ -281,7 +281,7 @@ func expandAliasFromEnv(envURL string) (*hostConfigV9, *probe.Error) {
}
// expandAlias expands aliased URL if any match is found, returns as is otherwise.
func expandAlias(aliasedURL string) (alias string, urlStr string, hostCfg *hostConfigV9, err *probe.Error) {
func expandAlias(aliasedURL string) (alias string, urlStr string, aliasCfg *aliasConfigV10, err *probe.Error) {
// Extract alias from the URL.
alias, path := url2Alias(aliasedURL)
@@ -296,22 +296,22 @@ func expandAlias(aliasedURL string) (alias string, urlStr string, hostCfg *hostC
}
if ok {
hostCfg, err = expandAliasFromEnv(envConfig)
aliasCfg, err = expandAliasFromEnv(envConfig)
if err != nil {
return "", "", nil, err.Trace(aliasedURL)
}
return alias, urlJoinPath(hostCfg.URL, path), hostCfg, nil
return alias, urlJoinPath(aliasCfg.URL, path), aliasCfg, nil
}
// Find the matching alias entry and expand the URL.
if hostCfg = mustGetHostConfig(alias); hostCfg != nil {
return alias, urlJoinPath(hostCfg.URL, path), hostCfg, nil
if aliasCfg = mustGetHostConfig(alias); aliasCfg != nil {
return alias, urlJoinPath(aliasCfg.URL, path), aliasCfg, nil
}
return "", aliasedURL, nil, nil // No matching entry found. Return original URL as is.
}
// mustExpandAlias expands aliased URL if any match is found, returns as is otherwise.
func mustExpandAlias(aliasedURL string) (alias string, urlStr string, hostCfg *hostConfigV9) {
alias, urlStr, hostCfg, _ = expandAlias(aliasedURL)
return alias, urlStr, hostCfg
func mustExpandAlias(aliasedURL string) (alias string, urlStr string, aliasCfg *aliasConfigV10) {
alias, urlStr, aliasCfg, _ = expandAlias(aliasedURL)
return alias, urlStr, aliasCfg
}
+121 -14
View File
@@ -1,5 +1,5 @@
/*
* MinIO Client (C) 2014-2019 MinIO, Inc.
* MinIO Client (C) 2014-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.
@@ -37,6 +37,10 @@ import (
// cp command flags.
var (
cpFlags = []cli.Flag{
cli.StringFlag{
Name: "rewind",
Usage: "Move back in time",
},
cli.BoolFlag{
Name: "recursive, r",
Usage: "copy recursively",
@@ -104,7 +108,7 @@ var cpCmd = cli.Command{
Name: "cp",
Usage: "copy objects",
Action: mainCopy,
Before: initBeforeRunningCmd,
Before: setGlobalsFromContext,
Flags: append(append(cpFlags, ioFlags...), globalFlags...),
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
@@ -174,6 +178,10 @@ EXAMPLES:
18. Copy a text file to an object storage and disable multipart upload feature.
{{.Prompt}} {{.HelpName}} --disable-multipart myobject.txt play/mybucket
19. Pick versions while copying objects at a specific date/time in the past if the bucket versioning is enabled.
{{.Prompt}} {{.HelpName}} --rewind 10d myobject.txt play/mybucket
`,
}
@@ -273,7 +281,7 @@ func doPrepareCopyURLs(ctx context.Context, session *sessionV8, cancelCopy conte
// Access recursive flag inside the session header.
isRecursive := session.Header.CommandBoolFlags["recursive"]
rewind := session.Header.CommandStringFlags["rewind"]
olderThan := session.Header.CommandStringFlags["older-than"]
newerThan := session.Header.CommandStringFlags["newer-than"]
encryptKeys := session.Header.CommandStringFlags["encrypt-key"]
@@ -289,7 +297,7 @@ func doPrepareCopyURLs(ctx context.Context, session *sessionV8, cancelCopy conte
scanBar = scanBarFactory()
}
URLsCh := prepareCopyURLs(ctx, sourceURLs, targetURL, isRecursive, encKeyDB, olderThan, newerThan)
URLsCh := prepareCopyURLs(ctx, sourceURLs, targetURL, isRecursive, encKeyDB, olderThan, newerThan, parseRewindFlag(rewind))
done := false
for !done {
select {
@@ -397,11 +405,12 @@ func doCopySession(ctx context.Context, cancelCopy context.CancelFunc, cli *cli.
isRecursive := cli.Bool("recursive")
olderThan := cli.String("older-than")
newerThan := cli.String("newer-than")
rewind := cli.String("rewind")
go func() {
totalBytes := int64(0)
for cpURLs := range prepareCopyURLs(ctx, sourceURLs, targetURL, isRecursive,
encKeyDB, olderThan, newerThan) {
encKeyDB, olderThan, newerThan, parseRewindFlag(rewind)) {
if cpURLs.Error != nil {
// Print in new line and adjust to top so that we
// don't print over the ongoing scan bar
@@ -492,14 +501,16 @@ func doCopySession(ctx context.Context, cancelCopy context.CancelFunc, cli *cli.
cpURLs.TargetContent.LegalHoldEnabled = true
}
}
preserve := cli.Bool("preserve")
if cli.String("attr") != "" {
preserve = true
userMetaMap, _ := getMetaDataEntry(cli.String("attr"))
for metaDataKey, metaDataVal := range userMetaMap {
cpURLs.TargetContent.UserMetadata[metaDataKey] = metaDataVal
for metadataKey, metaDataVal := range userMetaMap {
cpURLs.TargetContent.UserMetadata[metadataKey] = metaDataVal
}
}
preserve := cli.Bool("preserve")
cpURLs.MD5 = cli.Bool("md5")
cpURLs.DisableMultipart = cli.Bool("disable-multipart")
@@ -604,14 +615,108 @@ loop:
// validate the passed metadataString and populate the map
func getMetaDataEntry(metadataString string) (map[string]string, *probe.Error) {
metaDataMap := make(map[string]string)
for _, metaData := range strings.Split(metadataString, ";") {
metaDataEntry := strings.SplitN(metaData, "=", 2)
if len(metaDataEntry) != 2 {
return nil, probe.NewError(ErrInvalidMetadata)
r := strings.NewReader(metadataString)
type pToken int
const (
KEY pToken = iota
VALUE
)
type pState int
const (
NORMAL pState = iota
QSTRING
DQSTRING
)
var key, value strings.Builder
writeRune := func(ch rune, pt pToken) {
if pt == KEY {
key.WriteRune(ch)
} else if pt == VALUE {
value.WriteRune(ch)
} else {
panic("Invalid parser token type")
}
metaDataMap[http.CanonicalHeaderKey(metaDataEntry[0])] = metaDataEntry[1]
}
return metaDataMap, nil
ps := NORMAL
pt := KEY
p := 0
for ; ; p++ {
ch, _, err := r.ReadRune()
if err != nil {
//eof
if ps == QSTRING || ps == DQSTRING || pt == KEY {
return nil, probe.NewError(ErrInvalidMetadata)
}
metaDataMap[http.CanonicalHeaderKey(key.String())] = value.String()
return metaDataMap, nil
}
if ch == '"' {
if ps == DQSTRING {
ps = NORMAL
} else if ps == QSTRING {
writeRune(ch, pt)
} else if ps == NORMAL {
ps = DQSTRING
} else {
break
}
continue
}
if ch == '\'' {
if ps == QSTRING {
ps = NORMAL
} else if ps == DQSTRING {
writeRune(ch, pt)
} else if ps == NORMAL {
ps = QSTRING
} else {
break
}
continue
}
if ch == '=' {
if ps == QSTRING || ps == DQSTRING {
writeRune(ch, pt)
} else if pt == KEY {
pt = VALUE
} else if pt == VALUE {
writeRune(ch, pt)
} else {
break
}
continue
}
if ch == ';' {
if ps == QSTRING || ps == DQSTRING {
writeRune(ch, pt)
} else if pt == KEY {
return nil, probe.NewError(ErrInvalidMetadata)
} else if pt == VALUE {
metaDataMap[http.CanonicalHeaderKey(key.String())] = value.String()
key.Reset()
value.Reset()
pt = KEY
} else {
break
}
continue
}
writeRune(ch, pt)
}
fatalErr := fmt.Sprintf("Invalid parser state at index: %d", p)
panic(fatalErr)
}
// mainCopy is the entry point for cp command.
@@ -637,6 +742,7 @@ func mainCopy(cliCtx *cli.Context) error {
console.SetColor("Copy", color.New(color.FgGreen, color.Bold))
recursive := cliCtx.Bool("recursive")
rewind := cliCtx.String("rewind")
olderThan := cliCtx.String("older-than")
newerThan := cliCtx.String("newer-than")
storageClass := cliCtx.String("storage-class")
@@ -665,6 +771,7 @@ func mainCopy(cliCtx *cli.Context) error {
session = newSessionV8(sessionID)
session.Header.CommandType = "cp"
session.Header.CommandBoolFlags["recursive"] = recursive
session.Header.CommandStringFlags["rewind"] = rewind
session.Header.CommandStringFlags["older-than"] = olderThan
session.Header.CommandStringFlags["newer-than"] = newerThan
session.Header.CommandStringFlags["storage-class"] = storageClass
+12
View File
@@ -38,6 +38,18 @@ func TestParseMetaData(t *testing.T) {
{"key1:value1;key2:value2", nil, ErrInvalidMetadata, false},
// using no delimiter
{"key1:value1:key2:value2", nil, ErrInvalidMetadata, false},
//success: use value in quotes
{"Content-Disposition='form-data; name=\"description\"'", map[string]string{"Content-Disposition": "form-data; name=\"description\""}, nil, true},
//success: use value in double quotes
{"Content-Disposition=\"form-data; name='description'\"", map[string]string{"Content-Disposition": "form-data; name='description'"}, nil, true},
//fail: unterminated quote
{"Content-Disposition='form-data; name=\"description\"", nil, ErrInvalidMetadata, false},
//fail: unterminated double quote
{"Content-Disposition=\"form-data; name='description'", nil, ErrInvalidMetadata, false},
//success: use value and key in quotes
{"\"Content-Disposition\"='form-data; name=\"description\"'", map[string]string{"Content-Disposition": "form-data; name=\"description\""}, nil, true},
//success: use value and key in quotes
{"\"Content=Disposition;Other key part=this is also key data\"='form-data; name=\"description\"'", map[string]string{"Content=Disposition;Other key part=this is also key data": "form-data; name=\"description\""}, nil, true},
}
for idx, testCase := range metaDataCases {
+19 -16
View File
@@ -20,6 +20,7 @@ import (
"context"
"fmt"
"runtime"
"time"
"github.com/minio/cli"
"github.com/minio/minio/pkg/console"
@@ -42,10 +43,12 @@ func checkCopySyntax(ctx context.Context, cliCtx *cli.Context, encKeyDB map[stri
srcURLs := URLs[:len(URLs)-1]
tgtURL := URLs[len(URLs)-1]
isRecursive := cliCtx.Bool("recursive")
rewind := cliCtx.String("rewind")
timeRef := parseRewindFlag(rewind)
// Verify if source(s) exists.
for _, srcURL := range srcURLs {
_, _, err := url2Stat(ctx, srcURL, false, encKeyDB)
_, _, err := url2Stat(ctx, srcURL, "", false, encKeyDB, timeRef)
if err != nil {
console.Fatalf("Unable to validate source %s\n", srcURL)
}
@@ -73,20 +76,20 @@ func checkCopySyntax(ctx context.Context, cliCtx *cli.Context, encKeyDB map[stri
}
// Guess CopyURLsType based on source and target URLs.
copyURLsType, err := guessCopyURLType(ctx, srcURLs, tgtURL, isRecursive, encKeyDB)
copyURLsType, _, err := guessCopyURLType(ctx, srcURLs, tgtURL, isRecursive, encKeyDB, timeRef)
if err != nil {
fatalIf(errInvalidArgument().Trace(), "Unable to guess the type of "+operation+" operation.")
}
switch copyURLsType {
case copyURLsTypeA: // File -> File.
checkCopySyntaxTypeA(ctx, srcURLs, tgtURL, encKeyDB, isMvCmd)
checkCopySyntaxTypeA(ctx, srcURLs, tgtURL, encKeyDB, isMvCmd, timeRef)
case copyURLsTypeB: // File -> Folder.
checkCopySyntaxTypeB(ctx, srcURLs, tgtURL, encKeyDB, isMvCmd)
checkCopySyntaxTypeB(ctx, srcURLs, tgtURL, encKeyDB, isMvCmd, timeRef)
case copyURLsTypeC: // Folder... -> Folder.
checkCopySyntaxTypeC(ctx, srcURLs, tgtURL, isRecursive, encKeyDB, isMvCmd)
checkCopySyntaxTypeC(ctx, srcURLs, tgtURL, isRecursive, encKeyDB, isMvCmd, timeRef)
case copyURLsTypeD: // File1...FileN -> Folder.
checkCopySyntaxTypeD(ctx, srcURLs, tgtURL, encKeyDB, isMvCmd)
checkCopySyntaxTypeD(ctx, srcURLs, tgtURL, encKeyDB, isMvCmd, timeRef)
default:
fatalIf(errInvalidArgument().Trace(), "Unable to guess the type of "+operation+" operation.")
}
@@ -98,13 +101,13 @@ func checkCopySyntax(ctx context.Context, cliCtx *cli.Context, encKeyDB map[stri
}
// checkCopySyntaxTypeA verifies if the source and target are valid file arguments.
func checkCopySyntaxTypeA(ctx context.Context, srcURLs []string, tgtURL string, keys map[string][]prefixSSEPair, isMvCmd bool) {
func checkCopySyntaxTypeA(ctx context.Context, srcURLs []string, tgtURL string, keys map[string][]prefixSSEPair, isMvCmd bool, timeRef time.Time) {
// Check source.
if len(srcURLs) != 1 {
fatalIf(errInvalidArgument().Trace(), "Invalid number of source arguments.")
}
srcURL := srcURLs[0]
_, srcContent, err := url2Stat(ctx, srcURL, false, keys)
_, srcContent, err := url2Stat(ctx, srcURL, "", false, keys, timeRef)
fatalIf(err.Trace(srcURL), "Unable to stat source `"+srcURL+"`.")
if !srcContent.Type.IsRegular() {
@@ -113,13 +116,13 @@ func checkCopySyntaxTypeA(ctx context.Context, srcURLs []string, tgtURL string,
}
// checkCopySyntaxTypeB verifies if the source is a valid file and target is a valid folder.
func checkCopySyntaxTypeB(ctx context.Context, srcURLs []string, tgtURL string, keys map[string][]prefixSSEPair, isMvCmd bool) {
func checkCopySyntaxTypeB(ctx context.Context, srcURLs []string, tgtURL string, keys map[string][]prefixSSEPair, isMvCmd bool, timeRef time.Time) {
// Check source.
if len(srcURLs) != 1 {
fatalIf(errInvalidArgument().Trace(), "Invalid number of source arguments.")
}
srcURL := srcURLs[0]
_, srcContent, err := url2Stat(ctx, srcURL, false, keys)
_, srcContent, err := url2Stat(ctx, srcURL, "", false, keys, timeRef)
fatalIf(err.Trace(srcURL), "Unable to stat source `"+srcURL+"`.")
if !srcContent.Type.IsRegular() {
@@ -127,7 +130,7 @@ func checkCopySyntaxTypeB(ctx context.Context, srcURLs []string, tgtURL string,
}
// Check target.
if _, tgtContent, err := url2Stat(ctx, tgtURL, false, keys); err == nil {
if _, tgtContent, err := url2Stat(ctx, tgtURL, "", false, keys, timeRef); err == nil {
if !tgtContent.Type.IsDir() {
fatalIf(errInvalidArgument().Trace(tgtURL), "Target `"+tgtURL+"` is not a folder.")
}
@@ -135,21 +138,21 @@ func checkCopySyntaxTypeB(ctx context.Context, srcURLs []string, tgtURL string,
}
// checkCopySyntaxTypeC verifies if the source is a valid recursive dir and target is a valid folder.
func checkCopySyntaxTypeC(ctx context.Context, srcURLs []string, tgtURL string, isRecursive bool, keys map[string][]prefixSSEPair, isMvCmd bool) {
func checkCopySyntaxTypeC(ctx context.Context, srcURLs []string, tgtURL string, isRecursive bool, keys map[string][]prefixSSEPair, isMvCmd bool, timeRef time.Time) {
// Check source.
if len(srcURLs) != 1 {
fatalIf(errInvalidArgument().Trace(), "Invalid number of source arguments.")
}
// Check target.
if _, tgtContent, err := url2Stat(ctx, tgtURL, false, keys); err == nil {
if _, tgtContent, err := url2Stat(ctx, tgtURL, "", false, keys, timeRef); err == nil {
if !tgtContent.Type.IsDir() {
fatalIf(errInvalidArgument().Trace(tgtURL), "Target `"+tgtURL+"` is not a folder.")
}
}
for _, srcURL := range srcURLs {
c, srcContent, err := url2Stat(ctx, srcURL, false, keys)
c, srcContent, err := url2Stat(ctx, srcURL, "", false, keys, timeRef)
// incomplete uploads are not necessary for copy operation, no need to verify for them.
isIncomplete := false
if err != nil {
@@ -184,10 +187,10 @@ func checkCopySyntaxTypeC(ctx context.Context, srcURLs []string, tgtURL string,
}
// checkCopySyntaxTypeD verifies if the source is a valid list of files and target is a valid folder.
func checkCopySyntaxTypeD(ctx context.Context, srcURLs []string, tgtURL string, keys map[string][]prefixSSEPair, isMvCmd bool) {
func checkCopySyntaxTypeD(ctx context.Context, srcURLs []string, tgtURL string, keys map[string][]prefixSSEPair, isMvCmd bool, timeRef time.Time) {
// Source can be anything: file, dir, dir...
// Check target if it is a dir
if _, tgtContent, err := url2Stat(ctx, tgtURL, false, keys); err == nil {
if _, tgtContent, err := url2Stat(ctx, tgtURL, "", false, keys, timeRef); err == nil {
if !tgtContent.Type.IsDir() {
fatalIf(errInvalidArgument().Trace(tgtURL), "Target `"+tgtURL+"` is not a folder.")
}
+27 -27
View File
@@ -20,6 +20,7 @@ import (
"context"
"path/filepath"
"strings"
"time"
"github.com/minio/mc/pkg/probe"
)
@@ -51,45 +52,45 @@ const (
// guessCopyURLType guesses the type of clientURL. This approach all allows prepareURL
// functions to accurately report failure causes.
func guessCopyURLType(ctx context.Context, sourceURLs []string, targetURL string, isRecursive bool, keys map[string][]prefixSSEPair) (copyURLsType, *probe.Error) {
func guessCopyURLType(ctx context.Context, sourceURLs []string, targetURL string, isRecursive bool, keys map[string][]prefixSSEPair, timeRef time.Time) (copyURLsType, string, *probe.Error) {
if len(sourceURLs) == 1 { // 1 Source, 1 Target
sourceURL := sourceURLs[0]
_, sourceContent, err := url2Stat(ctx, sourceURL, false, keys)
_, sourceContent, err := url2Stat(ctx, sourceURL, "", false, keys, timeRef)
if err != nil {
return copyURLsTypeInvalid, err
return copyURLsTypeInvalid, "", err
}
// If recursion is ON, it is type C.
// If source is a folder, it is Type C.
if sourceContent.Type.IsDir() || isRecursive {
return copyURLsTypeC, nil
return copyURLsTypeC, "", nil
}
// If target is a folder, it is Type B.
if isAliasURLDir(ctx, targetURL, keys) {
return copyURLsTypeB, nil
if isAliasURLDir(ctx, targetURL, keys, timeRef) {
return copyURLsTypeB, sourceContent.VersionID, nil
}
// else Type A.
return copyURLsTypeA, nil
return copyURLsTypeA, sourceContent.VersionID, nil
}
// Multiple source args and target is a folder. It is Type D.
if isAliasURLDir(ctx, targetURL, keys) {
return copyURLsTypeD, nil
if isAliasURLDir(ctx, targetURL, keys, timeRef) {
return copyURLsTypeD, "", nil
}
return copyURLsTypeInvalid, errInvalidArgument().Trace()
return copyURLsTypeInvalid, "", errInvalidArgument().Trace()
}
// SINGLE SOURCE - Type A: copy(f, f) -> copy(f, f)
// prepareCopyURLsTypeA - prepares target and source clientURLs for copying.
func prepareCopyURLsTypeA(ctx context.Context, sourceURL string, targetURL string, encKeyDB map[string][]prefixSSEPair) URLs {
func prepareCopyURLsTypeA(ctx context.Context, sourceURL, sourceVersion string, targetURL string, encKeyDB map[string][]prefixSSEPair) URLs {
// Extract alias before fiddling with the clientURL.
sourceAlias, _, _ := mustExpandAlias(sourceURL)
// Find alias and expanded clientURL.
targetAlias, targetURL, _ := mustExpandAlias(targetURL)
_, sourceContent, err := url2Stat(ctx, sourceURL, false, encKeyDB)
_, sourceContent, err := url2Stat(ctx, sourceURL, sourceVersion, false, encKeyDB, time.Time{})
if err != nil {
// Source does not exist or insufficient privileges.
return URLs{Error: err.Trace(sourceURL)}
@@ -116,13 +117,13 @@ func makeCopyContentTypeA(sourceAlias string, sourceContent *ClientContent, targ
// SINGLE SOURCE - Type B: copy(f, d) -> copy(f, d/f) -> A
// prepareCopyURLsTypeB - prepares target and source clientURLs for copying.
func prepareCopyURLsTypeB(ctx context.Context, sourceURL string, targetURL string, encKeyDB map[string][]prefixSSEPair) URLs {
func prepareCopyURLsTypeB(ctx context.Context, sourceURL, sourceVersion string, targetURL string, encKeyDB map[string][]prefixSSEPair) URLs {
// Extract alias before fiddling with the clientURL.
sourceAlias, _, _ := mustExpandAlias(sourceURL)
// Find alias and expanded clientURL.
targetAlias, targetURL, _ := mustExpandAlias(targetURL)
_, sourceContent, err := url2Stat(ctx, sourceURL, false, encKeyDB)
_, sourceContent, err := url2Stat(ctx, sourceURL, sourceVersion, false, encKeyDB, time.Time{})
if err != nil {
// Source does not exist or insufficient privileges.
return URLs{Error: err.Trace(sourceURL)}
@@ -150,7 +151,7 @@ func makeCopyContentTypeB(sourceAlias string, sourceContent *ClientContent, targ
// SINGLE SOURCE - Type C: copy(d1..., d2) -> []copy(d1/f, d1/d2/f) -> []A
// prepareCopyRecursiveURLTypeC - prepares target and source clientURLs for copying.
func prepareCopyURLsTypeC(ctx context.Context, sourceURL, targetURL string, isRecursive bool, encKeyDB map[string][]prefixSSEPair) <-chan URLs {
func prepareCopyURLsTypeC(ctx context.Context, sourceURL, targetURL string, isRecursive bool, timeRef time.Time, encKeyDB map[string][]prefixSSEPair) <-chan URLs {
// Extract alias before fiddling with the clientURL.
sourceAlias, _, _ := mustExpandAlias(sourceURL)
// Find alias and expanded clientURL.
@@ -165,8 +166,7 @@ func prepareCopyURLsTypeC(ctx context.Context, sourceURL, targetURL string, isRe
return
}
isIncomplete := false
for sourceContent := range sourceClient.List(ctx, isRecursive, isIncomplete, false, DirNone) {
for sourceContent := range sourceClient.List(ctx, ListOptions{isRecursive: isRecursive, timeRef: timeRef, showDir: DirNone}) {
if sourceContent.Err != nil {
// Listing failed.
copyURLsCh <- URLs{Error: sourceContent.Err.Trace(sourceClient.GetURL().String())}
@@ -200,12 +200,12 @@ func makeCopyContentTypeC(sourceAlias string, sourceURL ClientURL, sourceContent
// MULTI-SOURCE - Type D: copy([](f|d...), d) -> []B
// prepareCopyURLsTypeE - prepares target and source clientURLs for copying.
func prepareCopyURLsTypeD(ctx context.Context, sourceURLs []string, targetURL string, isRecursive bool, encKeyDB map[string][]prefixSSEPair) <-chan URLs {
func prepareCopyURLsTypeD(ctx context.Context, sourceURLs []string, targetURL string, isRecursive bool, timeRef time.Time, encKeyDB map[string][]prefixSSEPair) <-chan URLs {
copyURLsCh := make(chan URLs)
go func(sourceURLs []string, targetURL string, copyURLsCh chan URLs) {
defer close(copyURLsCh)
for _, sourceURL := range sourceURLs {
for cpURLs := range prepareCopyURLsTypeC(ctx, sourceURL, targetURL, isRecursive, encKeyDB) {
for cpURLs := range prepareCopyURLsTypeC(ctx, sourceURL, targetURL, isRecursive, timeRef, encKeyDB) {
copyURLsCh <- cpURLs
}
}
@@ -214,30 +214,30 @@ func prepareCopyURLsTypeD(ctx context.Context, sourceURLs []string, targetURL st
}
// prepareCopyURLs - prepares target and source clientURLs for copying.
func prepareCopyURLs(ctx context.Context, sourceURLs []string, targetURL string, isRecursive bool, encKeyDB map[string][]prefixSSEPair, olderThan, newerThan string) chan URLs {
func prepareCopyURLs(ctx context.Context, sourceURLs []string, targetURL string, isRecursive bool, encKeyDB map[string][]prefixSSEPair, olderThan, newerThan string, timeRef time.Time) chan URLs {
copyURLsCh := make(chan URLs)
go func(sourceURLs []string, targetURL string, copyURLsCh chan URLs, encKeyDB map[string][]prefixSSEPair) {
go func(sourceURLs []string, targetURL string, copyURLsCh chan URLs, encKeyDB map[string][]prefixSSEPair, timeRef time.Time) {
defer close(copyURLsCh)
cpType, err := guessCopyURLType(ctx, sourceURLs, targetURL, isRecursive, encKeyDB)
cpType, cpVersion, err := guessCopyURLType(ctx, sourceURLs, targetURL, isRecursive, encKeyDB, timeRef)
fatalIf(err.Trace(), "Unable to guess the type of copy operation.")
switch cpType {
case copyURLsTypeA:
copyURLsCh <- prepareCopyURLsTypeA(ctx, sourceURLs[0], targetURL, encKeyDB)
copyURLsCh <- prepareCopyURLsTypeA(ctx, sourceURLs[0], cpVersion, targetURL, encKeyDB)
case copyURLsTypeB:
copyURLsCh <- prepareCopyURLsTypeB(ctx, sourceURLs[0], targetURL, encKeyDB)
copyURLsCh <- prepareCopyURLsTypeB(ctx, sourceURLs[0], cpVersion, targetURL, encKeyDB)
case copyURLsTypeC:
for cURLs := range prepareCopyURLsTypeC(ctx, sourceURLs[0], targetURL, isRecursive, encKeyDB) {
for cURLs := range prepareCopyURLsTypeC(ctx, sourceURLs[0], targetURL, isRecursive, timeRef, encKeyDB) {
copyURLsCh <- cURLs
}
case copyURLsTypeD:
for cURLs := range prepareCopyURLsTypeD(ctx, sourceURLs, targetURL, isRecursive, encKeyDB) {
for cURLs := range prepareCopyURLsTypeD(ctx, sourceURLs, targetURL, isRecursive, timeRef, encKeyDB) {
copyURLsCh <- cURLs
}
default:
copyURLsCh <- URLs{Error: errInvalidArgument().Trace(sourceURLs...)}
}
}(sourceURLs, targetURL, copyURLsCh, encKeyDB)
}(sourceURLs, targetURL, copyURLsCh, encKeyDB, timeRef)
finalCopyURLsCh := make(chan URLs)
go func() {
+4 -3
View File
@@ -20,6 +20,7 @@ import (
"context"
"fmt"
"strings"
"time"
"github.com/fatih/color"
"github.com/minio/cli"
@@ -38,7 +39,7 @@ var diffCmd = cli.Command{
Name: "diff",
Usage: "list differences in object name, size, and date between two buckets",
Action: mainDiff,
Before: initBeforeRunningCmd,
Before: setGlobalsFromContext,
Flags: append(diffFlags, globalFlags...),
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
@@ -126,7 +127,7 @@ func checkDiffSyntax(ctx context.Context, cliCtx *cli.Context, encKeyDB map[stri
// Diff only works between two directories, verify them below.
// Verify if firstURL is accessible.
_, firstContent, err := url2Stat(ctx, firstURL, false, encKeyDB)
_, firstContent, err := url2Stat(ctx, firstURL, "", false, encKeyDB, time.Time{})
if err != nil {
fatalIf(err.Trace(firstURL), fmt.Sprintf("Unable to stat '%s'.", firstURL))
}
@@ -137,7 +138,7 @@ func checkDiffSyntax(ctx context.Context, cliCtx *cli.Context, encKeyDB map[stri
}
// Verify if secondURL is accessible.
_, secondContent, err := url2Stat(ctx, secondURL, false, encKeyDB)
_, secondContent, err := url2Stat(ctx, secondURL, "", false, encKeyDB, time.Time{})
if err != nil {
fatalIf(err.Trace(secondURL), fmt.Sprintf("Unable to stat '%s'.", secondURL))
}
+3 -4
View File
@@ -25,7 +25,7 @@ import (
// golang does not support flat keys for path matching, find does
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio-go/v6"
"github.com/minio/minio-go/v7"
"golang.org/x/text/unicode/norm"
)
@@ -167,9 +167,8 @@ func dirDifference(ctx context.Context, sourceClnt, targetClnt Client, sourceURL
func differenceInternal(ctx context.Context, sourceClnt, targetClnt Client, sourceURL, targetURL string, isMetadata bool, isRecursive, returnSimilar bool, dirOpt DirOpt, diffCh chan<- diffMessage) *probe.Error {
// Set default values for listing.
isIncomplete := false // we will not compare any incomplete objects.
srcCh := sourceClnt.List(ctx, isRecursive, isIncomplete, isMetadata, dirOpt)
tgtCh := targetClnt.List(ctx, isRecursive, isIncomplete, isMetadata, dirOpt)
srcCh := sourceClnt.List(ctx, ListOptions{isRecursive: isRecursive, isFetchMeta: isMetadata, showDir: dirOpt})
tgtCh := targetClnt.List(ctx, ListOptions{isRecursive: isRecursive, isFetchMeta: isMetadata, showDir: dirOpt})
srcCtnt, srcOk := <-srcCh
tgtCtnt, tgtOk := <-tgtCh
+2 -4
View File
@@ -48,7 +48,7 @@ var duCmd = cli.Command{
Name: "du",
Usage: "summarize disk usage recursively",
Action: mainDu,
Before: initBeforeRunningCmd,
Before: setGlobalsFromContext,
Flags: append(append(duFlags, ioFlags...), globalFlags...),
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
@@ -105,9 +105,7 @@ func du(urlStr string, depth int, encKeyDB map[string][]prefixSSEPair) (int64, e
return 0, exitStatus(globalErrorExitStatus) // End of journey.
}
isRecursive := false
isIncomplete := false
contentCh := clnt.List(globalContext, isRecursive, isIncomplete, false, DirFirst)
contentCh := clnt.List(globalContext, ListOptions{isRecursive: false, showDir: DirFirst})
size := int64(0)
for content := range contentCh {
if content.Err != nil {
+96
View File
@@ -0,0 +1,96 @@
/*
* 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"
"fmt"
"github.com/fatih/color"
"github.com/minio/cli"
json "github.com/minio/mc/pkg/colorjson"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio/pkg/console"
)
var encryptClearCmd = cli.Command{
Name: "clear",
Usage: "Clear encryption config",
Action: mainEncryptClear,
Before: setGlobalsFromContext,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} TARGET
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Remove auto encryption config on bucket "mybucket" for alias "myminio".
{{.Prompt}} {{.HelpName}} myminio/mybucket
`,
}
// checkEncryptClearSyntax - validate all the passed arguments
func checkEncryptClearSyntax(ctx *cli.Context) {
if len(ctx.Args()) != 1 {
cli.ShowCommandHelpAndExit(ctx, "clear", 1) // last argument is exit code
}
}
type encryptClearMessage struct {
Op string `json:"op"`
Status string `json:"status"`
URL string `json:"url"`
}
func (v encryptClearMessage) JSON() string {
v.Status = "success"
jsonMessageBytes, e := json.MarshalIndent(v, "", " ")
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
return string(jsonMessageBytes)
}
func (v encryptClearMessage) String() string {
return console.Colorize("encryptClearMessage", fmt.Sprintf("Auto encryption configuration has been cleared successfully for %s", v.URL))
}
func mainEncryptClear(cliCtx *cli.Context) error {
ctx, cancelencryptClear := context.WithCancel(globalContext)
defer cancelencryptClear()
console.SetColor("encryptClearMessage", color.New(color.FgGreen))
checkEncryptClearSyntax(cliCtx)
// Get the alias parameter from cli
args := cliCtx.Args()
aliasedURL := args.Get(0)
// Create a new Client
client, err := newClient(aliasedURL)
fatalIf(err, "Unable to initialize connection.")
fatalIf(client.DeleteEncryption(ctx), "Cannot clear auto encryption configuration")
printMsg(encryptClearMessage{
Op: "clear",
Status: "success",
URL: aliasedURL,
})
return nil
}
+115
View File
@@ -0,0 +1,115 @@
/*
* 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"
"fmt"
"strings"
"github.com/fatih/color"
"github.com/minio/cli"
json "github.com/minio/mc/pkg/colorjson"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio/pkg/console"
)
var encryptInfoCmd = cli.Command{
Name: "info",
Usage: "Show bucket encryption status",
Action: mainEncryptInfo,
Before: setGlobalsFromContext,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} TARGET
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Display bucket encryption status for bucket "mybucket".
{{.Prompt}} {{.HelpName}} myminio/mybucket
`,
}
// checkversionInfoSyntax - validate all the passed arguments
func checkEncryptInfoSyntax(ctx *cli.Context) {
if len(ctx.Args()) != 1 {
cli.ShowCommandHelpAndExit(ctx, "info", 1) // last argument is exit code
}
}
type encryptInfoMessage struct {
Op string `json:"op"`
Status string `json:"status"`
URL string `json:"url"`
Encryption struct {
Algorithm string `json:"algorithm,omitempty"`
KeyID string `json:"keyId,omitempty"`
} `json:"encryption,omitempty"`
}
func (v encryptInfoMessage) JSON() string {
v.Status = "success"
jsonMessageBytes, e := json.MarshalIndent(v, "", " ")
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
return string(jsonMessageBytes)
}
func (v encryptInfoMessage) String() string {
msg := ""
switch v.Encryption.Algorithm {
case "":
msg = fmt.Sprintf("Auto encryption is not enabled for %s ", v.URL)
default:
msg = fmt.Sprintf("Auto encryption configuration:\n\tAlgorithm: %s ", strings.ToUpper(v.Encryption.Algorithm))
}
if v.Encryption.KeyID != "" {
msg += fmt.Sprintf("\n\tKey ID : %s", v.Encryption.KeyID)
}
return console.Colorize("encryptInfoMessage", msg)
}
func mainEncryptInfo(cliCtx *cli.Context) error {
ctx, cancelEncryptInfo := context.WithCancel(globalContext)
defer cancelEncryptInfo()
console.SetColor("encryptInfoMessage", color.New(color.FgGreen))
checkEncryptInfoSyntax(cliCtx)
// Get the alias parameter from cli
args := cliCtx.Args()
aliasedURL := args.Get(0)
// Create a new Client
client, err := newClient(aliasedURL)
fatalIf(err, "Unable to initialize connection.")
algorithm, keyID, e := client.GetEncryption(ctx)
fatalIf(e, "Cannot get encryption info")
msg := encryptInfoMessage{
Op: "info",
Status: "success",
URL: aliasedURL,
}
msg.Encryption.Algorithm = algorithm
msg.Encryption.KeyID = keyID
printMsg(msg)
return nil
}
+40
View File
@@ -0,0 +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.
*/
package cmd
import "github.com/minio/cli"
var encryptCmd = cli.Command{
Name: "encrypt",
Usage: "manage bucket encryption config",
HideHelpCommand: true,
Action: mainEncrypt,
Before: setGlobalsFromContext,
Flags: globalFlags,
Subcommands: []cli.Command{
encryptSetCmd,
encryptClearCmd,
encryptInfoCmd,
},
}
// mainEncrypt is the handle for "mc encrypt" command.
func mainEncrypt(ctx *cli.Context) error {
cli.ShowCommandHelp(ctx, ctx.Args().First())
return nil
// Sub-commands like "info", "set", "clear" have their own main.
}
+117
View File
@@ -0,0 +1,117 @@
/*
* 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"
"fmt"
"strings"
"github.com/fatih/color"
"github.com/minio/cli"
json "github.com/minio/mc/pkg/colorjson"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio/pkg/console"
)
var encryptSetCmd = cli.Command{
Name: "set",
Usage: "Set encryption config",
Action: mainEncryptSet,
Before: setGlobalsFromContext,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} TARGET
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Enable SSE-S3 auto encryption on bucket "mybucket" for alias "myminio".
{{.Prompt}} {{.HelpName}} sse-s3 myminio/mybucket
2. Enable SSE-KMS auto encryption with kms key on bucket "mybucket" for alias "s3".
{{.Prompt}} {{.HelpName}} sse-kms arn:aws:kms:us-east-1:xxx:key/xxx s3/mybucket
`,
}
// checkEncryptSetSyntax - validate all the passed arguments
func checkEncryptSetSyntax(ctx *cli.Context) {
if len(ctx.Args()) < 2 || len(ctx.Args()) > 3 {
cli.ShowCommandHelpAndExit(ctx, "set", 1) // last argument is exit code
}
}
type encryptSetMessage struct {
Op string `json:"op"`
Status string `json:"status"`
URL string `json:"url"`
Encryption struct {
Algorithm string `json:"algorithm,omitempty"`
KeyID string `json:"keyId,omitempty"`
} `json:"encryption,omitempty"`
}
func (v encryptSetMessage) JSON() string {
v.Status = "success"
jsonMessageBytes, e := json.MarshalIndent(v, "", " ")
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
return string(jsonMessageBytes)
}
func (v encryptSetMessage) String() string {
return console.Colorize("encryptSetMessage", fmt.Sprintf("Auto encryption configuration has been set successfully for %s", v.URL))
}
func mainEncryptSet(cliCtx *cli.Context) error {
ctx, cancelencryptSet := context.WithCancel(globalContext)
defer cancelencryptSet()
console.SetColor("encryptSetMessage", color.New(color.FgGreen))
checkEncryptSetSyntax(cliCtx)
// Get the alias parameter from cli
args := cliCtx.Args()
aliasedURL := args.Get(len(args) - 1)
// Create a new Client
client, err := newClient(aliasedURL)
fatalIf(err, "Unable to initialize connection.")
var algorithm, keyID string
switch len(args) {
case 3:
algorithm = strings.ToLower(args[0])
keyID = args[1]
case 2:
algorithm = strings.ToLower(args[0])
}
if algorithm != "sse-s3" && algorithm != "sse-kms" {
fatalIf(probe.NewError(fmt.Errorf("Unknown argument `%s` passed", algorithm)), "Invalid encryption algorithm")
}
fatalIf(client.SetEncryption(ctx, algorithm, keyID), "Cannot enable auto encryption")
msg := encryptSetMessage{
Op: "set",
Status: "success",
URL: aliasedURL,
}
msg.Encryption.Algorithm = algorithm
printMsg(msg)
return nil
}
+1 -1
View File
@@ -53,7 +53,7 @@ var eventAddCmd = cli.Command{
Name: "add",
Usage: "add a new bucket notification",
Action: mainEventAdd,
Before: initBeforeRunningCmd,
Before: setGlobalsFromContext,
Flags: append(eventAddFlags, globalFlags...),
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
+1 -1
View File
@@ -35,7 +35,7 @@ var eventListCmd = cli.Command{
Name: "list",
Usage: "list bucket notifications",
Action: mainEventList,
Before: initBeforeRunningCmd,
Before: setGlobalsFromContext,
Flags: append(eventListFlags, globalFlags...),
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
+2 -1
View File
@@ -24,9 +24,10 @@ var (
var eventCmd = cli.Command{
Name: "event",
Usage: "configure object notifications",
Usage: "manage object notifications",
HideHelpCommand: true,
Action: mainEvent,
Before: setGlobalsFromContext,
Flags: append(eventFlags, globalFlags...),
Subcommands: []cli.Command{
eventAddCmd,

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