Compare commits
58
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7e52c104be | ||
|
|
588a8fcd17 | ||
|
|
0ba1633a04 | ||
|
|
069968c8aa | ||
|
|
0c4b649369 | ||
|
|
bd03dfbb15 | ||
|
|
9498227542 | ||
|
|
32c13f2977 | ||
|
|
6f8859262c | ||
|
|
cd1f28e20c | ||
|
|
b1aa159838 | ||
|
|
3c0bc7ec33 | ||
|
|
6a98216c53 | ||
|
|
7ffa755cd9 | ||
|
|
0631315535 | ||
|
|
2be7f6dd13 | ||
|
|
ceb216f8a3 | ||
|
|
d93b7f7638 | ||
|
|
ec734d0f71 | ||
|
|
90dc31f6ba | ||
|
|
9c09f78982 | ||
|
|
90d22b271f | ||
|
|
2750c4bfe6 | ||
|
|
c61a26269f | ||
|
|
65d564dd87 | ||
|
|
442facedd1 | ||
|
|
a2592cef84 | ||
|
|
023e56e0a1 | ||
|
|
c8a3b7bff0 | ||
|
|
12acca5abd | ||
|
|
67f2472d24 | ||
|
|
f19a10dce2 | ||
|
|
ea8c0db96e | ||
|
|
0b0acc611f | ||
|
|
7b5d5ea990 | ||
|
|
56c2c1a5c5 | ||
|
|
f3c9e9172a | ||
|
|
9193388568 | ||
|
|
a419bb4130 | ||
|
|
469665f886 | ||
|
|
5d98d19608 | ||
|
|
9d762f5aa6 | ||
|
|
51a3d287bb | ||
|
|
fbb7d75c1c | ||
|
|
53dc65c92a | ||
|
|
d811d416a5 | ||
|
|
ba37e08f1f | ||
|
|
5c713e5ecb | ||
|
|
712ff33319 | ||
|
|
90d6e7df24 | ||
|
|
b8570a9a0b | ||
|
|
360d094828 | ||
|
|
08685bae6a | ||
|
|
4989d51e2c | ||
|
|
a62a539399 | ||
|
|
d5b6931a1e | ||
|
|
397f41c71c | ||
|
|
707f46c32b |
+167
@@ -0,0 +1,167 @@
|
||||
project_name: mc
|
||||
|
||||
release:
|
||||
name_template: "Version {{.Version}}"
|
||||
disable: true
|
||||
github:
|
||||
owner: minio
|
||||
name: mc
|
||||
|
||||
env:
|
||||
- CGO_ENABLED=0
|
||||
- GO111MODULE=on
|
||||
|
||||
before:
|
||||
hooks:
|
||||
- make clean
|
||||
- go generate ./...
|
||||
- go mod tidy
|
||||
- go mod download
|
||||
|
||||
builds:
|
||||
-
|
||||
goos:
|
||||
- linux
|
||||
- darwin
|
||||
- windows
|
||||
- freebsd
|
||||
|
||||
goarch:
|
||||
- amd64
|
||||
- arm64
|
||||
- arm
|
||||
- ppc64le
|
||||
- s390x
|
||||
|
||||
goarm:
|
||||
- 7
|
||||
|
||||
ignore:
|
||||
- goos: darwin
|
||||
goarch: arm64
|
||||
- goos: darwin
|
||||
goarch: arm
|
||||
- goos: darwin
|
||||
goarch: ppc64le
|
||||
- goos: darwin
|
||||
goarch: s390x
|
||||
- goos: windows
|
||||
goarch: arm64
|
||||
- goos: windows
|
||||
goarch: arm
|
||||
- goos: windows
|
||||
goarch: ppc64le
|
||||
- goos: windows
|
||||
goarch: s390x
|
||||
- goos: freebsd
|
||||
goarch: arm
|
||||
- goos: freebsd
|
||||
goarch: arm64
|
||||
- goos: freebsd
|
||||
goarch: ppc64le
|
||||
- goos: freebsd
|
||||
goarch: s390x
|
||||
|
||||
flags:
|
||||
- -tags=kqueue
|
||||
- -trimpath
|
||||
|
||||
ldflags:
|
||||
- "-s -w -X github.com/minio/mc/cmd.Version={{.Version}} -X github.com/minio/mc/cmd.ReleaseTag={{.Tag}} -X github.com/minio/mc/cmd.CommitID={{.FullCommit}} -X github.com/minio/mc/cmd.ShortCommitID={{.ShortCommit}}"
|
||||
|
||||
archives:
|
||||
-
|
||||
format: binary
|
||||
name_template: "{{ .Binary }}-release/{{ .Os }}-{{ .Arch }}/{{ .Binary }}.{{ .Version }}"
|
||||
|
||||
nfpms:
|
||||
-
|
||||
id: minio
|
||||
package_name: mc
|
||||
vendor: MinIO, Inc.
|
||||
homepage: https://min.io/
|
||||
maintainer: dev@min.io
|
||||
description: MinIO Client (mc) provides a modern alternative to UNIX commands like ls, cat, cp, mirror, diff, find etc. It supports filesystems and Amazon S3 compatible cloud storage service (AWS Signature v2 and v4).
|
||||
license: Apache 2.0
|
||||
bindir: /usr/bin
|
||||
formats:
|
||||
- deb
|
||||
- rpm
|
||||
overrides:
|
||||
deb:
|
||||
file_name_template: "{{ .Binary }}-release/debs/{{ .ProjectName }}-{{ .Version }}_{{ .Arch }}"
|
||||
replacements:
|
||||
arm: armv7
|
||||
files:
|
||||
"NOTICE": "/usr/share/mc/NOTICE"
|
||||
"CREDITS": "/usr/share/mc/CREDITS"
|
||||
"LICENSE": "/usr/share/mc/LICENSE"
|
||||
"README.md": "/usr/share/mc/README.md"
|
||||
rpm:
|
||||
file_name_template: "{{ .Binary }}-release/rpms/{{ .ProjectName }}-{{ .Version }}.{{ .Arch }}"
|
||||
replacements:
|
||||
amd64: x86_64
|
||||
arm64: aarch64
|
||||
arm: armv7
|
||||
files:
|
||||
"NOTICE": "/usr/share/mc/NOTICE"
|
||||
"CREDITS": "/usr/share/mc/CREDITS"
|
||||
"LICENSE": "/usr/share/mc/LICENSE"
|
||||
"README.md": "/usr/share/mc/README.md"
|
||||
|
||||
checksum:
|
||||
algorithm: sha256
|
||||
|
||||
signs:
|
||||
-
|
||||
signature: "${artifact}.asc"
|
||||
cmd: "sh"
|
||||
args:
|
||||
- '-c'
|
||||
- 'gpg --quiet --detach-sign -a ${artifact}'
|
||||
artifacts: all
|
||||
|
||||
changelog:
|
||||
sort: asc
|
||||
filters:
|
||||
exclude:
|
||||
- '^Update yaml files'
|
||||
|
||||
dockers:
|
||||
-
|
||||
goos: linux
|
||||
goarch: amd64
|
||||
dockerfile: Dockerfile.release
|
||||
image_templates:
|
||||
- minio/mc:{{ .Tag }}
|
||||
- minio/mc:latest
|
||||
|
||||
-
|
||||
goos: linux
|
||||
goarch: ppc64le
|
||||
dockerfile: Dockerfile.ppc64le.release
|
||||
image_templates:
|
||||
- minio/mc:{{ .Tag }}-ppc64le
|
||||
|
||||
-
|
||||
goos: linux
|
||||
goarch: s390x
|
||||
dockerfile: Dockerfile.s390x.release
|
||||
image_templates:
|
||||
- minio/mc:{{ .Tag }}-s390x
|
||||
|
||||
-
|
||||
goos: linux
|
||||
goarch: arm64
|
||||
goarm: ''
|
||||
dockerfile: Dockerfile.arm64.release
|
||||
image_templates:
|
||||
- minio/mc:{{ .Tag }}-arm64
|
||||
|
||||
-
|
||||
goos: linux
|
||||
goarch: arm
|
||||
goarm: '7'
|
||||
dockerfile: Dockerfile.arm.release
|
||||
image_templates:
|
||||
- minio/mc:{{ .Tag }}-arm
|
||||
+5
-5
@@ -1,4 +1,4 @@
|
||||
FROM golang:1.13-alpine
|
||||
FROM golang:1.13-alpine as build
|
||||
|
||||
LABEL maintainer="MinIO Inc <dev@min.io>"
|
||||
|
||||
@@ -11,12 +11,12 @@ RUN \
|
||||
git clone https://github.com/minio/mc && cd mc && \
|
||||
go install -v -ldflags "$(go run buildscripts/gen-ldflags.go)"
|
||||
|
||||
FROM alpine:3.10
|
||||
FROM alpine:3.12
|
||||
|
||||
COPY --from=0 /go/bin/mc /usr/bin/mc
|
||||
COPY --from=build /go/bin/mc /usr/bin/mc
|
||||
|
||||
RUN \
|
||||
apk add --no-cache ca-certificates && \
|
||||
echo 'hosts: files mdns4_minimal [NOTFOUND=return] dns mdns4' >> /etc/nsswitch.conf
|
||||
apk add --no-cache ca-certificates 'curl>7.61.0' && \
|
||||
curl -s -q -O https://raw.githubusercontent.com/minio/minio/master/CREDITS
|
||||
|
||||
ENTRYPOINT ["mc"]
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
FROM multiarch/qemu-user-static:x86_64-arm as qemu
|
||||
FROM arm32v7/alpine:3.12
|
||||
|
||||
LABEL maintainer="MinIO Inc <dev@min.io>"
|
||||
|
||||
COPY --from=qemu /usr/bin/qemu-arm-static /usr/bin
|
||||
|
||||
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"]
|
||||
@@ -0,0 +1,13 @@
|
||||
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-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"]
|
||||
+3
-5
@@ -1,10 +1,8 @@
|
||||
FROM alpine:3.10
|
||||
FROM alpine:3.12
|
||||
|
||||
COPY mc /usr/bin/
|
||||
COPY CREDITS /
|
||||
|
||||
RUN \
|
||||
apk add --no-cache ca-certificates && \
|
||||
echo 'hosts: files mdns4_minimal [NOTFOUND=return] dns mdns4' >> /etc/nsswitch.conf \
|
||||
chmod +x /usr/bin/mc
|
||||
RUN apk add --no-cache ca-certificates
|
||||
|
||||
ENTRYPOINT ["mc"]
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
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-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"]
|
||||
+5
-6
@@ -1,11 +1,10 @@
|
||||
FROM alpine:3.10
|
||||
FROM alpine:3.12
|
||||
|
||||
MAINTAINER MinIO Inc <dev@min.io>
|
||||
|
||||
RUN \
|
||||
apk add --no-cache ca-certificates && \
|
||||
apk add --no-cache --virtual .build-deps curl && \
|
||||
curl https://dl.min.io/client/mc/release/linux-amd64/mc > /usr/bin/mc && \
|
||||
chmod +x /usr/bin/mc && apk del .build-deps
|
||||
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"]
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
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-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"]
|
||||
@@ -1,4 +1,4 @@
|
||||
MinIO Client (C) 2014, 2015 MinIO, Inc.
|
||||
MinIO Client (C) 2014-2020 MinIO, Inc.
|
||||
|
||||
This product includes software developed at MinIO, Inc.
|
||||
(https://min.io/).
|
||||
|
||||
@@ -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
|
||||
[](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).
|
||||
|
||||
@@ -8,7 +8,7 @@ function _init() {
|
||||
export CGO_ENABLED=0
|
||||
|
||||
## List of architectures and OS to test coss compilation.
|
||||
SUPPORTED_OSARCH="linux/ppc64le linux/arm64 linux/s390x darwin/amd64 freebsd/amd64 linux/arm linux/386"
|
||||
SUPPORTED_OSARCH="linux/ppc64le linux/arm64 linux/s390x darwin/amd64 freebsd/amd64 linux/arm linux/386 windows/amd64"
|
||||
}
|
||||
|
||||
function _build() {
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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),
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -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.
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
+2
-1
@@ -26,6 +26,7 @@ var adminBucketCmd = cli.Command{
|
||||
Flags: globalFlags,
|
||||
Subcommands: []cli.Command{
|
||||
adminBucketQuotaCmd,
|
||||
adminBucketRemoteCmd,
|
||||
},
|
||||
HideHelpCommand: true,
|
||||
}
|
||||
@@ -34,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
@@ -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(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
|
||||
|
||||
@@ -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"
|
||||
)
|
||||
|
||||
@@ -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,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,11 +25,13 @@ import (
|
||||
"github.com/minio/minio/pkg/console"
|
||||
)
|
||||
|
||||
var configHostListCmd = cli.Command{
|
||||
Name: "list",
|
||||
ShortName: "ls",
|
||||
Usage: "list hosts in configuration file",
|
||||
Action: mainConfigHostList,
|
||||
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,
|
||||
@@ -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
|
||||
}
|
||||
@@ -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,29 +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,
|
||||
Before: setGlobalsFromContext,
|
||||
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"`
|
||||
@@ -54,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
|
||||
@@ -70,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,11 +22,13 @@ import (
|
||||
"github.com/minio/minio/pkg/console"
|
||||
)
|
||||
|
||||
var configHostRemoveCmd = cli.Command{
|
||||
Name: "remove",
|
||||
ShortName: "rm",
|
||||
Usage: "remove a host from configuration file",
|
||||
Action: mainConfigHostRemove,
|
||||
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,
|
||||
@@ -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}
|
||||
}
|
||||
@@ -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.
|
||||
@@ -18,39 +18,44 @@ package cmd
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"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,
|
||||
|
||||
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(hostAddFlags, globalFlags...),
|
||||
Flags: append(aliasSetFlags, globalFlags...),
|
||||
HideHelpCommand: true,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
@@ -67,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.
|
||||
@@ -80,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) {
|
||||
@@ -129,37 +135,43 @@ 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
|
||||
// using v4 signature then v2 in case of failure.
|
||||
func probeS3Signature(accessKey, secretKey, url string) (string, *probe.Error) {
|
||||
func probeS3Signature(ctx context.Context, accessKey, secretKey, url string) (string, *probe.Error) {
|
||||
probeBucketName := randString(60, rand.NewSource(time.Now().UnixNano()), "probe-bucket-sign-")
|
||||
// Test s3 connection for API auto probe
|
||||
s3Config := &Config{
|
||||
@@ -178,7 +190,7 @@ func probeS3Signature(accessKey, secretKey, url string) (string, *probe.Error) {
|
||||
return "", err
|
||||
}
|
||||
|
||||
if _, err := s3Client.Stat(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.
|
||||
@@ -209,13 +221,12 @@ func probeS3Signature(accessKey, secretKey, url string) (string, *probe.Error) {
|
||||
|
||||
// BuildS3Config constructs an S3 Config and does
|
||||
// signature auto-probe when needed.
|
||||
func BuildS3Config(url, accessKey, secretKey, api, lookup string) (*Config, *probe.Error) {
|
||||
|
||||
s3Config := NewS3Config(url, &hostConfigV9{
|
||||
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
|
||||
@@ -225,9 +236,9 @@ func BuildS3Config(url, accessKey, secretKey, api, lookup string) (*Config, *pro
|
||||
return s3Config, nil
|
||||
}
|
||||
// Probe S3 signature version
|
||||
api, err := probeS3Signature(accessKey, secretKey, url)
|
||||
api, err := probeS3Signature(ctx, accessKey, secretKey, url)
|
||||
if err != nil {
|
||||
return nil, err.Trace(url, accessKey, secretKey, api, lookup)
|
||||
return nil, err.Trace(url, accessKey, secretKey, api, path)
|
||||
}
|
||||
|
||||
s3Config.Signature = api
|
||||
@@ -235,8 +246,8 @@ func BuildS3Config(url, accessKey, secretKey, api, lookup string) (*Config, *pro
|
||||
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))
|
||||
@@ -272,28 +283,52 @@ func fetchHostKeys(args cli.Args) (string, string) {
|
||||
return accessKey, secretKey
|
||||
}
|
||||
|
||||
func mainConfigHostAdd(ctx *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 = ctx.Args()
|
||||
alias = cleanAlias(args.Get(0))
|
||||
url = trimTrailingSeparator(args.Get(1))
|
||||
api = ctx.String("api")
|
||||
lookup = ctx.String("lookup")
|
||||
args = cli.Args()
|
||||
alias = cleanAlias(args.Get(0))
|
||||
url = trimTrailingSeparator(args.Get(1))
|
||||
api = cli.String("api")
|
||||
path = cli.String("path")
|
||||
)
|
||||
accessKey, secretKey := fetchHostKeys(args)
|
||||
checkConfigHostAddSyntax(ctx, accessKey, secretKey)
|
||||
|
||||
s3Config, err := BuildS3Config(url, accessKey, secretKey, api, lookup)
|
||||
fatalIf(err.Trace(ctx.Args()...), "Unable to initialize new config from the provided credentials.")
|
||||
// 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:
|
||||
}
|
||||
}
|
||||
|
||||
addHost(alias, hostConfigV9{
|
||||
accessKey, secretKey := fetchAliasKeys(args)
|
||||
checkAliasSetSyntax(cli, accessKey, secretKey, deprecated)
|
||||
|
||||
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
@@ -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(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
|
||||
|
||||
@@ -17,6 +17,7 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
@@ -25,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: setGlobalsFromContext,
|
||||
Flags: append(lockFlags, globalFlags...),
|
||||
Flags: globalFlags,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
@@ -61,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
|
||||
`,
|
||||
}
|
||||
|
||||
@@ -79,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))
|
||||
@@ -93,17 +85,19 @@ 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.")
|
||||
}
|
||||
|
||||
if clearLock || mode != "" {
|
||||
err = client.SetObjectLockConfig(mode, validity, unit)
|
||||
ctx, cancelLock := context.WithCancel(globalContext)
|
||||
defer cancelLock()
|
||||
if op == "clear" || mode != "" {
|
||||
err = client.SetObjectLockConfig(ctx, mode, validity, unit)
|
||||
fatalIf(err, "Cannot enable object lock configuration on the specified bucket.")
|
||||
} else {
|
||||
mode, validity, unit, err = client.GetObjectLockConfig()
|
||||
mode, validity, unit, err = client.GetObjectLockConfig(ctx)
|
||||
fatalIf(err, "Cannot get object lock configuration on the specified bucket.")
|
||||
}
|
||||
|
||||
@@ -146,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
|
||||
@@ -157,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 {
|
||||
@@ -176,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)
|
||||
}
|
||||
+42
-24
@@ -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.
|
||||
@@ -18,12 +18,14 @@ package cmd
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"strings"
|
||||
"syscall"
|
||||
"time"
|
||||
"unicode"
|
||||
"unicode/utf8"
|
||||
|
||||
@@ -32,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.
|
||||
@@ -73,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
|
||||
`,
|
||||
}
|
||||
|
||||
@@ -125,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 {
|
||||
@@ -136,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(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(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(sourceURL, encKeyDB); err != nil {
|
||||
if reader, err = getSourceStreamFromURL(ctx, sourceURL, versionID, encKeyDB); err != nil {
|
||||
return err.Trace(sourceURL)
|
||||
}
|
||||
defer reader.Close()
|
||||
@@ -210,17 +226,20 @@ func catOut(r io.Reader, size int64) *probe.Error {
|
||||
}
|
||||
|
||||
// mainCat is the main entry point for cat command.
|
||||
func mainCat(ctx *cli.Context) error {
|
||||
func mainCat(cliCtx *cli.Context) error {
|
||||
ctx, cancelCat := context.WithCancel(globalContext)
|
||||
defer cancelCat()
|
||||
|
||||
// Parse encryption keys per command.
|
||||
encKeyDB, err := getEncKeys(ctx)
|
||||
encKeyDB, err := getEncKeys(cliCtx)
|
||||
fatalIf(err, "Unable to parse encryption keys.")
|
||||
|
||||
// check 'cat' cli arguments.
|
||||
checkCatSyntax(ctx)
|
||||
args, rewind := parseCatSyntax(cliCtx)
|
||||
|
||||
// Set command flags from context.
|
||||
stdinMode := false
|
||||
if !ctx.Args().Present() {
|
||||
if len(args) == 0 {
|
||||
stdinMode = true
|
||||
}
|
||||
|
||||
@@ -231,11 +250,10 @@ func mainCat(ctx *cli.Context) error {
|
||||
}
|
||||
|
||||
// if Args contain `-`, we need to preserve its order specially.
|
||||
args := []string(ctx.Args())
|
||||
if ctx.Args().First() == "-" {
|
||||
if len(args) > 0 && args[0] == "-" {
|
||||
for i, arg := range os.Args {
|
||||
if arg == "cat" {
|
||||
// Overwrite ctx.Args with os.Args.
|
||||
// Overwrite cliCtx.Args with os.Args.
|
||||
args = os.Args[i+1:]
|
||||
break
|
||||
}
|
||||
@@ -244,7 +262,7 @@ func mainCat(ctx *cli.Context) error {
|
||||
|
||||
// Convert arguments to URLs: expand alias, fix format.
|
||||
for _, url := range args {
|
||||
fatalIf(catURL(url, encKeyDB).Trace(url), "Unable to read from `"+url+"`.")
|
||||
fatalIf(catURL(ctx, url, rewind, encKeyDB).Trace(url), "Unable to read from `"+url+"`.")
|
||||
}
|
||||
|
||||
return nil
|
||||
|
||||
+15
-7
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* MinIO Client (C) 2017 MinIO, Inc.
|
||||
* MinIO Client (C) 2017-2020 MinIO, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -26,8 +26,10 @@ import (
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/mattn/go-ieproxy"
|
||||
"github.com/minio/mc/pkg/httptracer"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/minio-go/v7/pkg/credentials"
|
||||
"github.com/minio/minio/pkg/madmin"
|
||||
)
|
||||
|
||||
@@ -63,9 +65,15 @@ func NewAdminFactory() func(config *Config) (*madmin.AdminClient, *probe.Error)
|
||||
var api *madmin.AdminClient
|
||||
var found bool
|
||||
if api, found = clientCache[confSum]; !found {
|
||||
// Admin API only supports signature v4.
|
||||
creds := credentials.NewStaticV4(config.AccessKey, config.SecretKey, config.SessionToken)
|
||||
|
||||
// Not found. Instantiate a new MinIO
|
||||
var e error
|
||||
api, e = madmin.New(hostName, config.AccessKey, config.SecretKey, useTLS)
|
||||
api, e = madmin.NewWithOptions(hostName, &madmin.Options{
|
||||
Creds: creds,
|
||||
Secure: useTLS,
|
||||
})
|
||||
if e != nil {
|
||||
return nil, probe.NewError(e)
|
||||
}
|
||||
@@ -83,7 +91,7 @@ func NewAdminFactory() func(config *Config) (*madmin.AdminClient, *probe.Error)
|
||||
}
|
||||
|
||||
var transport http.RoundTripper = &http.Transport{
|
||||
Proxy: http.ProxyFromEnvironment,
|
||||
Proxy: ieproxy.GetProxyFunc(),
|
||||
DialContext: (&net.Dialer{
|
||||
Timeout: 10 * time.Second,
|
||||
KeepAlive: 15 * time.Second,
|
||||
@@ -123,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
@@ -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"
|
||||
}
|
||||
|
||||
|
||||
+173
-80
@@ -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.
|
||||
@@ -119,7 +119,7 @@ func (f *fsClient) GetURL() ClientURL {
|
||||
}
|
||||
|
||||
// Select replies a stream of query results.
|
||||
func (f *fsClient) Select(expression string, sse encrypt.ServerSide, opts SelectObjectOpts) (io.ReadCloser, *probe.Error) {
|
||||
func (f *fsClient) Select(ctx context.Context, expression string, sse encrypt.ServerSide, opts SelectObjectOpts) (io.ReadCloser, *probe.Error) {
|
||||
return nil, probe.NewError(APINotImplemented{
|
||||
API: "Select",
|
||||
APIType: "filesystem",
|
||||
@@ -127,7 +127,7 @@ func (f *fsClient) Select(expression string, sse encrypt.ServerSide, opts Select
|
||||
}
|
||||
|
||||
// Watches for all fs events on an input path.
|
||||
func (f *fsClient) Watch(options WatchOptions) (*WatchObject, *probe.Error) {
|
||||
func (f *fsClient) Watch(ctx context.Context, options WatchOptions) (*WatchObject, *probe.Error) {
|
||||
eventChan := make(chan []EventInfo)
|
||||
errorChan := make(chan *probe.Error)
|
||||
doneChan := make(chan struct{})
|
||||
@@ -223,29 +223,51 @@ func (f *fsClient) Watch(options WatchOptions) (*WatchObject, *probe.Error) {
|
||||
}
|
||||
|
||||
func preserveAttributes(fd *os.File, attr map[string]string) *probe.Error {
|
||||
mode, e := strconv.ParseUint(attr["mode"], 10, 32)
|
||||
if e != nil {
|
||||
return probe.NewError(e)
|
||||
if val, ok := attr["mode"]; ok {
|
||||
mode, e := strconv.ParseUint(val, 0, 32)
|
||||
if e != nil {
|
||||
return probe.NewError(e)
|
||||
}
|
||||
|
||||
// Attempt to change the file mode.
|
||||
if e := fd.Chmod(os.FileMode(mode)); e != nil {
|
||||
return probe.NewError(e)
|
||||
}
|
||||
}
|
||||
|
||||
// Attempt to change the file mode.
|
||||
if e := fd.Chmod(os.FileMode(mode)); e != nil {
|
||||
return probe.NewError(e)
|
||||
var uid, gid int
|
||||
var gidExists, uidExists bool
|
||||
var e error
|
||||
if val, ok := attr["uid"]; ok {
|
||||
uid, e = strconv.Atoi(val)
|
||||
if e != nil {
|
||||
return probe.NewError(e)
|
||||
}
|
||||
uidExists = true
|
||||
}
|
||||
|
||||
uid, e := strconv.Atoi(attr["uid"])
|
||||
if e != nil {
|
||||
return probe.NewError(e)
|
||||
}
|
||||
|
||||
gid, e := strconv.Atoi(attr["gid"])
|
||||
if e != nil {
|
||||
return probe.NewError(e)
|
||||
if val, ok := attr["gid"]; ok {
|
||||
gid, e = strconv.Atoi(val)
|
||||
if e != nil {
|
||||
return probe.NewError(e)
|
||||
}
|
||||
gidExists = true
|
||||
}
|
||||
|
||||
// Attempt to change the owner.
|
||||
if e := fd.Chown(uid, gid); e != nil {
|
||||
return probe.NewError(e)
|
||||
if gidExists && uidExists {
|
||||
if e := fd.Chown(uid, gid); e != nil {
|
||||
return probe.NewError(e)
|
||||
}
|
||||
} else if uidExists {
|
||||
if e := fd.Chown(uid, -1); e != nil {
|
||||
return probe.NewError(e)
|
||||
}
|
||||
|
||||
} else {
|
||||
if e := fd.Chown(-1, gid); e != nil {
|
||||
return probe.NewError(e)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
@@ -253,7 +275,7 @@ func preserveAttributes(fd *os.File, attr map[string]string) *probe.Error {
|
||||
|
||||
/// Object operations.
|
||||
|
||||
func (f *fsClient) put(reader io.Reader, size int64, metadata map[string][]string, progress io.Reader) (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.
|
||||
|
||||
@@ -289,8 +311,8 @@ func (f *fsClient) put(reader io.Reader, size int64, metadata map[string][]strin
|
||||
}
|
||||
|
||||
attr := make(map[string]string)
|
||||
if len(metadata[metaDataKey]) != 0 {
|
||||
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)
|
||||
@@ -347,20 +369,31 @@ func (f *fsClient) put(reader io.Reader, size int64, metadata map[string][]strin
|
||||
return totalWritten, err.Trace(objectPartPath, objectPath)
|
||||
}
|
||||
|
||||
if len(attr) != 0 {
|
||||
atime, e := strconv.ParseInt(attr["atime"], 10, 64)
|
||||
if e != nil {
|
||||
return totalWritten, probe.NewError(e)
|
||||
if len(attr) != 0 && preserve {
|
||||
var atime, mtime int64
|
||||
var e error
|
||||
var atimeChanged, mtimeChanged bool
|
||||
if val, ok := attr["atime"]; ok {
|
||||
atime, e = strconv.ParseInt(val, 10, 64)
|
||||
if e != nil {
|
||||
return totalWritten, probe.NewError(e)
|
||||
}
|
||||
atimeChanged = true
|
||||
}
|
||||
|
||||
mtime, e := strconv.ParseInt(attr["mtime"], 10, 64)
|
||||
if e != nil {
|
||||
return totalWritten, probe.NewError(e)
|
||||
if val, ok := attr["mtime"]; ok {
|
||||
mtime, e = strconv.ParseInt(val, 10, 64)
|
||||
if e != nil {
|
||||
return totalWritten, probe.NewError(e)
|
||||
}
|
||||
mtimeChanged = true
|
||||
}
|
||||
|
||||
// Attempt to change the access and modify time
|
||||
if e := os.Chtimes(objectPath, time.Unix(atime, 0), time.Unix(mtime, 0)); e != nil {
|
||||
return totalWritten, probe.NewError(e)
|
||||
if atimeChanged && mtimeChanged {
|
||||
if e := os.Chtimes(objectPath, time.Unix(atime, 0), time.Unix(mtime, 0)); e != nil {
|
||||
return totalWritten, probe.NewError(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -368,17 +401,12 @@ func (f *fsClient) put(reader io.Reader, size int64, metadata map[string][]strin
|
||||
}
|
||||
|
||||
// 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 bool) (int64, *probe.Error) {
|
||||
if metadata[metaDataKey] != "" {
|
||||
meta := make(map[string][]string)
|
||||
meta[metaDataKey] = append(meta[metaDataKey], metadata[metaDataKey])
|
||||
return f.put(reader, size, meta, progress)
|
||||
}
|
||||
return f.put(reader, size, nil, progress)
|
||||
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) {
|
||||
return f.put(ctx, reader, size, metadata, progress, preserve)
|
||||
}
|
||||
|
||||
// ShareDownload - share download not implemented for filesystem.
|
||||
func (f *fsClient) ShareDownload(expires time.Duration) (string, *probe.Error) {
|
||||
func (f *fsClient) ShareDownload(ctx context.Context, expires time.Duration) (string, *probe.Error) {
|
||||
return "", probe.NewError(APINotImplemented{
|
||||
API: "ShareDownload",
|
||||
APIType: "filesystem",
|
||||
@@ -386,7 +414,7 @@ func (f *fsClient) ShareDownload(expires time.Duration) (string, *probe.Error) {
|
||||
}
|
||||
|
||||
// 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",
|
||||
@@ -394,7 +422,7 @@ func (f *fsClient) ShareUpload(startsWith bool, expires time.Duration, contentTy
|
||||
}
|
||||
|
||||
// Copy - copy data from source to destination
|
||||
func (f *fsClient) Copy(source string, size int64, progress io.Reader, srcSSE, tgtSSE encrypt.ServerSide, metadata map[string]string, disableMultipart 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)
|
||||
@@ -403,14 +431,14 @@ func (f *fsClient) Copy(source string, size int64, progress io.Reader, srcSSE, t
|
||||
defer rc.Close()
|
||||
|
||||
destination := f.PathURL.Path
|
||||
if _, err := f.put(rc, size, map[string][]string{}, progress); 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(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)
|
||||
@@ -464,7 +492,7 @@ func deleteFile(deletePath string) error {
|
||||
}
|
||||
|
||||
// Remove - remove entry read from clientContent channel.
|
||||
func (f *fsClient) Remove(isIncomplete, isRemoveBucket, isBypass bool, contentCh <-chan *ClientContent) <-chan *probe.Error {
|
||||
func (f *fsClient) Remove(ctx context.Context, isIncomplete, isRemoveBucket, isBypass bool, contentCh <-chan *ClientContent) <-chan *probe.Error {
|
||||
errorCh := make(chan *probe.Error)
|
||||
|
||||
// Goroutine reads from contentCh and removes the entry in content.
|
||||
@@ -503,18 +531,18 @@ func (f *fsClient) Remove(isIncomplete, isRemoveBucket, isBypass bool, contentCh
|
||||
}
|
||||
|
||||
// List - list files and folders.
|
||||
func (f *fsClient) List(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
|
||||
@@ -522,7 +550,7 @@ func (f *fsClient) List(isRecursive, isIncomplete, isMetadata bool, showDir DirO
|
||||
// only show partly uploaded files,
|
||||
go func() {
|
||||
for c := range contentCh {
|
||||
if isIncomplete {
|
||||
if opts.isIncomplete {
|
||||
if !strings.HasSuffix(c.URL.Path, partSuffix) {
|
||||
continue
|
||||
}
|
||||
@@ -877,7 +905,7 @@ func (f *fsClient) listRecursiveInRoutine(contentCh chan *ClientContent, isMetad
|
||||
}
|
||||
|
||||
// MakeBucket - create a new bucket.
|
||||
func (f *fsClient) MakeBucket(region string, ignoreExisting, withLock bool) *probe.Error {
|
||||
func (f *fsClient) MakeBucket(ctx context.Context, region string, ignoreExisting, withLock bool) *probe.Error {
|
||||
// TODO: ignoreExisting has no effect currently. In the future, we want
|
||||
// to call os.Mkdir() when ignoredExisting is disabled and os.MkdirAll()
|
||||
// otherwise.
|
||||
@@ -890,7 +918,7 @@ func (f *fsClient) MakeBucket(region string, ignoreExisting, withLock bool) *pro
|
||||
}
|
||||
|
||||
// Set object lock configuration of bucket.
|
||||
func (f *fsClient) SetObjectLockConfig(mode minio.RetentionMode, validity uint64, unit minio.ValidityUnit) *probe.Error {
|
||||
func (f *fsClient) SetObjectLockConfig(ctx context.Context, mode minio.RetentionMode, validity uint64, unit minio.ValidityUnit) *probe.Error {
|
||||
return probe.NewError(APINotImplemented{
|
||||
API: "SetObjectLockConfig",
|
||||
APIType: "filesystem",
|
||||
@@ -898,7 +926,7 @@ func (f *fsClient) SetObjectLockConfig(mode minio.RetentionMode, validity uint64
|
||||
}
|
||||
|
||||
// Get object lock configuration of bucket.
|
||||
func (f *fsClient) GetObjectLockConfig() (mode minio.RetentionMode, validity uint64, unit minio.ValidityUnit, err *probe.Error) {
|
||||
func (f *fsClient) GetObjectLockConfig(ctx context.Context) (mode minio.RetentionMode, validity uint64, unit minio.ValidityUnit, err *probe.Error) {
|
||||
return "", 0, "", probe.NewError(APINotImplemented{
|
||||
API: "GetObjectLockConfig",
|
||||
APIType: "filesystem",
|
||||
@@ -906,7 +934,7 @@ func (f *fsClient) GetObjectLockConfig() (mode minio.RetentionMode, validity uin
|
||||
}
|
||||
|
||||
// GetAccessRules - unsupported API
|
||||
func (f *fsClient) GetAccessRules() (map[string]string, *probe.Error) {
|
||||
func (f *fsClient) GetAccessRules(ctx context.Context) (map[string]string, *probe.Error) {
|
||||
return map[string]string{}, probe.NewError(APINotImplemented{
|
||||
API: "GetBucketPolicy",
|
||||
APIType: "filesystem",
|
||||
@@ -914,7 +942,7 @@ func (f *fsClient) GetAccessRules() (map[string]string, *probe.Error) {
|
||||
}
|
||||
|
||||
// Set object retention for a given object.
|
||||
func (f *fsClient) PutObjectRetention(mode minio.RetentionMode, retainUntilDate time.Time, bypassGovernance bool) *probe.Error {
|
||||
func (f *fsClient) PutObjectRetention(ctx context.Context, mode minio.RetentionMode, retainUntilDate time.Time, bypassGovernance bool) *probe.Error {
|
||||
return probe.NewError(APINotImplemented{
|
||||
API: "PutObjectRetention",
|
||||
APIType: "filesystem",
|
||||
@@ -922,7 +950,7 @@ func (f *fsClient) PutObjectRetention(mode minio.RetentionMode, retainUntilDate
|
||||
}
|
||||
|
||||
// Set object legal hold for a given object.
|
||||
func (f *fsClient) PutObjectLegalHold(lhold minio.LegalHoldStatus) *probe.Error {
|
||||
func (f *fsClient) PutObjectLegalHold(ctx context.Context, lhold minio.LegalHoldStatus) *probe.Error {
|
||||
return probe.NewError(APINotImplemented{
|
||||
API: "PutObjectLegalHold",
|
||||
APIType: "filesystem",
|
||||
@@ -930,7 +958,7 @@ func (f *fsClient) PutObjectLegalHold(lhold minio.LegalHoldStatus) *probe.Error
|
||||
}
|
||||
|
||||
// GetAccess - get access policy permissions.
|
||||
func (f *fsClient) GetAccess() (access string, policyJSON string, err *probe.Error) {
|
||||
func (f *fsClient) GetAccess(ctx context.Context) (access string, policyJSON string, err *probe.Error) {
|
||||
// For windows this feature is not implemented.
|
||||
if runtime.GOOS == "windows" {
|
||||
return "", "", probe.NewError(APINotImplemented{API: "GetAccess", APIType: "filesystem"})
|
||||
@@ -955,7 +983,7 @@ func (f *fsClient) GetAccess() (access string, policyJSON string, err *probe.Err
|
||||
}
|
||||
|
||||
// SetAccess - set access policy permissions.
|
||||
func (f *fsClient) SetAccess(access string, isJSON bool) *probe.Error {
|
||||
func (f *fsClient) SetAccess(ctx context.Context, access string, isJSON bool) *probe.Error {
|
||||
// For windows this feature is not implemented.
|
||||
// JSON policy for fs is not yet implemented.
|
||||
if runtime.GOOS == "windows" || isJSON {
|
||||
@@ -987,8 +1015,8 @@ func (f *fsClient) SetAccess(access string, isJSON bool) *probe.Error {
|
||||
}
|
||||
|
||||
// Stat - get metadata from path.
|
||||
func (f *fsClient) Stat(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())
|
||||
}
|
||||
@@ -1003,21 +1031,21 @@ func (f *fsClient) Stat(isIncomplete, isPreserve bool, sse encrypt.ServerSide) (
|
||||
}
|
||||
|
||||
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
|
||||
@@ -1063,7 +1091,7 @@ func (f *fsClient) AddUserAgent(_, _ string) {
|
||||
}
|
||||
|
||||
// Get Object Tags
|
||||
func (f *fsClient) GetTags() (*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",
|
||||
@@ -1071,7 +1099,7 @@ func (f *fsClient) GetTags() (*tags.Tags, *probe.Error) {
|
||||
}
|
||||
|
||||
// Set Object tags
|
||||
func (f *fsClient) SetTags(tags string) *probe.Error {
|
||||
func (f *fsClient) SetTags(ctx context.Context, tags string) *probe.Error {
|
||||
return probe.NewError(APINotImplemented{
|
||||
API: "SetObjectTagging",
|
||||
APIType: "filesystem",
|
||||
@@ -1079,7 +1107,7 @@ func (f *fsClient) SetTags(tags string) *probe.Error {
|
||||
}
|
||||
|
||||
// Delete object tags
|
||||
func (f *fsClient) DeleteTags() *probe.Error {
|
||||
func (f *fsClient) DeleteTags(ctx context.Context) *probe.Error {
|
||||
return probe.NewError(APINotImplemented{
|
||||
API: "DeleteObjectTagging",
|
||||
APIType: "filesystem",
|
||||
@@ -1087,17 +1115,82 @@ func (f *fsClient) DeleteTags() *probe.Error {
|
||||
}
|
||||
|
||||
// Get lifecycle configuration for a given bucket, not implemented.
|
||||
func (f *fsClient) GetLifecycle() (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(_ 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",
|
||||
})
|
||||
}
|
||||
|
||||
+23
-24
@@ -45,7 +45,7 @@ func (s *TestSuite) TestList(c *C) {
|
||||
var n int64
|
||||
n, err = fsClient.Put(context.Background(), reader, int64(len(data)), map[string]string{
|
||||
"Content-Type": "application/octet-stream",
|
||||
}, nil, nil, false, false)
|
||||
}, nil, nil, false, false, false)
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(n, Equals, int64(len(data)))
|
||||
|
||||
@@ -56,7 +56,7 @@ func (s *TestSuite) TestList(c *C) {
|
||||
reader = bytes.NewReader([]byte(data))
|
||||
n, err = fsClient.Put(context.Background(), reader, int64(len(data)), map[string]string{
|
||||
"Content-Type": "application/octet-stream",
|
||||
}, nil, nil, false, false)
|
||||
}, nil, nil, false, false, false)
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(n, Equals, int64(len(data)))
|
||||
|
||||
@@ -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(false, false, false, DirNone) {
|
||||
for content := range fsClient.List(globalContext, ListOptions{showDir: DirNone}) {
|
||||
if content.Err != nil {
|
||||
err = content.Err
|
||||
break
|
||||
@@ -84,7 +84,7 @@ func (s *TestSuite) TestList(c *C) {
|
||||
reader = bytes.NewReader([]byte(data))
|
||||
n, err = fsClient.Put(context.Background(), reader, int64(len(data)), map[string]string{
|
||||
"Content-Type": "application/octet-stream",
|
||||
}, nil, nil, false, false)
|
||||
}, nil, nil, false, false, false)
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(n, Equals, int64(len(data)))
|
||||
|
||||
@@ -93,7 +93,7 @@ func (s *TestSuite) TestList(c *C) {
|
||||
|
||||
contents = nil
|
||||
// List non recursive to list only top level files.
|
||||
for content := range fsClient.List(false, false, 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(true, false, false, DirNone) {
|
||||
for content := range fsClient.List(globalContext, ListOptions{isRecursive: true, showDir: DirNone}) {
|
||||
if content.Err != nil {
|
||||
err = content.Err
|
||||
break
|
||||
@@ -144,7 +144,7 @@ func (s *TestSuite) TestList(c *C) {
|
||||
reader = bytes.NewReader([]byte(data))
|
||||
n, err = fsClient.Put(context.Background(), reader, int64(len(data)), map[string]string{
|
||||
"Content-Type": "application/octet-stream",
|
||||
}, nil, nil, false, false)
|
||||
}, nil, nil, false, false, false)
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(n, Equals, int64(len(data)))
|
||||
|
||||
@@ -153,7 +153,7 @@ func (s *TestSuite) TestList(c *C) {
|
||||
|
||||
contents = nil
|
||||
// List recursively all files and verify.
|
||||
for content := range fsClient.List(true, false, false, DirNone) {
|
||||
for content := range fsClient.List(globalContext, ListOptions{isRecursive: true, showDir: DirNone}) {
|
||||
if content.Err != nil {
|
||||
err = content.Err
|
||||
break
|
||||
@@ -194,7 +194,7 @@ func (s *TestSuite) TestPutBucket(c *C) {
|
||||
bucketPath := filepath.Join(root, "bucket")
|
||||
fsClient, err := fsNew(bucketPath)
|
||||
c.Assert(err, IsNil)
|
||||
err = fsClient.MakeBucket("us-east-1", true, false)
|
||||
err = fsClient.MakeBucket(context.Background(), "us-east-1", true, false)
|
||||
c.Assert(err, IsNil)
|
||||
}
|
||||
|
||||
@@ -208,9 +208,9 @@ func (s *TestSuite) TestStatBucket(c *C) {
|
||||
|
||||
fsClient, err := fsNew(bucketPath)
|
||||
c.Assert(err, IsNil)
|
||||
err = fsClient.MakeBucket("us-east-1", true, false)
|
||||
err = fsClient.MakeBucket(context.Background(), "us-east-1", true, false)
|
||||
c.Assert(err, IsNil)
|
||||
_, err = fsClient.Stat(false, false, nil)
|
||||
_, err = fsClient.Stat(context.Background(), StatOptions{})
|
||||
c.Assert(err, IsNil)
|
||||
}
|
||||
|
||||
@@ -223,15 +223,15 @@ func (s *TestSuite) TestBucketACLFails(c *C) {
|
||||
bucketPath := filepath.Join(root, "bucket")
|
||||
fsClient, err := fsNew(bucketPath)
|
||||
c.Assert(err, IsNil)
|
||||
err = fsClient.MakeBucket("us-east-1", true, false)
|
||||
err = fsClient.MakeBucket(context.Background(), "us-east-1", true, false)
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
// On windows setting permissions is not supported.
|
||||
if runtime.GOOS != "windows" {
|
||||
err = fsClient.SetAccess("readonly", false)
|
||||
err = fsClient.SetAccess(context.Background(), "readonly", false)
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
_, _, err = fsClient.GetAccess()
|
||||
_, _, err = fsClient.GetAccess(context.Background())
|
||||
c.Assert(err, IsNil)
|
||||
}
|
||||
}
|
||||
@@ -251,7 +251,7 @@ func (s *TestSuite) TestPut(c *C) {
|
||||
var n int64
|
||||
n, err = fsClient.Put(context.Background(), reader, int64(len(data)), map[string]string{
|
||||
"Content-Type": "application/octet-stream",
|
||||
}, nil, nil, false, false)
|
||||
}, nil, nil, false, false, false)
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(n, Equals, int64(len(data)))
|
||||
}
|
||||
@@ -271,11 +271,11 @@ func (s *TestSuite) TestGet(c *C) {
|
||||
reader = bytes.NewReader([]byte(data))
|
||||
n, err := fsClient.Put(context.Background(), reader, int64(len(data)), map[string]string{
|
||||
"Content-Type": "application/octet-stream",
|
||||
}, nil, nil, false, false)
|
||||
}, nil, nil, false, false, false)
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(n, Equals, int64(len(data)))
|
||||
|
||||
reader, err = fsClient.Get(nil)
|
||||
reader, err = fsClient.Get(context.Background(), GetOptions{})
|
||||
c.Assert(err, IsNil)
|
||||
var results bytes.Buffer
|
||||
_, e = io.Copy(&results, reader)
|
||||
@@ -299,11 +299,11 @@ func (s *TestSuite) TestGetRange(c *C) {
|
||||
reader = bytes.NewReader([]byte(data))
|
||||
n, err := fsClient.Put(context.Background(), reader, int64(len(data)), map[string]string{
|
||||
"Content-Type": "application/octet-stream",
|
||||
}, nil, nil, false, false)
|
||||
}, nil, nil, false, false, false)
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(n, Equals, int64(len(data)))
|
||||
|
||||
reader, err = fsClient.Get(nil)
|
||||
reader, err = fsClient.Get(context.Background(), GetOptions{})
|
||||
c.Assert(err, IsNil)
|
||||
var results bytes.Buffer
|
||||
buf := make([]byte, 5)
|
||||
@@ -330,11 +330,11 @@ func (s *TestSuite) TestStatObject(c *C) {
|
||||
reader := bytes.NewReader([]byte(data))
|
||||
n, err := fsClient.Put(context.Background(), reader, int64(dataLen), map[string]string{
|
||||
"Content-Type": "application/octet-stream",
|
||||
}, nil, nil, false, false)
|
||||
}, nil, nil, false, false, false)
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(n, Equals, int64(len(data)))
|
||||
|
||||
content, err := fsClient.Stat(false, false, nil)
|
||||
content, err := fsClient.Stat(context.Background(), StatOptions{})
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(content.Size, Equals, int64(dataLen))
|
||||
}
|
||||
@@ -355,10 +355,9 @@ func (s *TestSuite) TestCopy(c *C) {
|
||||
reader := bytes.NewReader([]byte(data))
|
||||
n, err := fsClientSource.Put(context.Background(), reader, int64(len(data)), map[string]string{
|
||||
"Content-Type": "application/octet-stream",
|
||||
}, nil, nil, false, false)
|
||||
}, nil, nil, false, false, false)
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(n, Equals, int64(len(data)))
|
||||
|
||||
err = fsClientTarget.Copy(sourcePath, int64(len(data)), nil, nil, nil, nil, false)
|
||||
err = fsClientTarget.Copy(context.Background(), sourcePath, CopyOptions{size: int64(len(data))}, nil)
|
||||
c.Assert(err, IsNil)
|
||||
}
|
||||
|
||||
+485
-250
File diff suppressed because it is too large
Load Diff
@@ -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"
|
||||
)
|
||||
|
||||
@@ -171,14 +171,14 @@ func (s *TestSuite) TestBucketOperations(c *C) {
|
||||
s3c, err := S3New(conf)
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
err = s3c.MakeBucket("us-east-1", true, false)
|
||||
err = s3c.MakeBucket(context.Background(), "us-east-1", true, false)
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
conf.HostURL = server.URL + string(s3c.GetURL().Separator)
|
||||
s3c, err = S3New(conf)
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
for content := range s3c.List(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(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(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)
|
||||
}
|
||||
@@ -223,11 +223,11 @@ func (s *TestSuite) TestObjectOperations(c *C) {
|
||||
reader = bytes.NewReader(object.data)
|
||||
n, err := s3c.Put(context.Background(), reader, int64(len(object.data)), map[string]string{
|
||||
"Content-Type": "application/octet-stream",
|
||||
}, nil, nil, false, false)
|
||||
}, nil, nil, false, false, false)
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(n, Equals, int64(len(object.data)))
|
||||
|
||||
reader, err = s3c.Get(nil)
|
||||
reader, err = s3c.Get(context.Background(), GetOptions{})
|
||||
c.Assert(err, IsNil)
|
||||
var buffer bytes.Buffer
|
||||
{
|
||||
|
||||
+5
-6
@@ -18,10 +18,12 @@ package cmd
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"runtime"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/minio/pkg/mimedb"
|
||||
@@ -183,7 +185,7 @@ func urlJoinPath(url1, url2 string) string {
|
||||
}
|
||||
|
||||
// url2Stat returns stat info for URL.
|
||||
func url2Stat(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)
|
||||
@@ -191,7 +193,7 @@ func url2Stat(urlStr string, fileAttr bool, encKeyDB map[string][]prefixSSEPair)
|
||||
alias, _ := url2Alias(urlStr)
|
||||
sse := getSSE(urlStr, encKeyDB[alias])
|
||||
|
||||
content, err = client.Stat(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)
|
||||
}
|
||||
@@ -228,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(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
|
||||
|
||||
+93
-36
@@ -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,78 +44,135 @@ 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(isIncomplete, isPreserve bool, sse encrypt.ServerSide) (content *ClientContent, err *probe.Error)
|
||||
List(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(region string, ignoreExisting, withLock bool) *probe.Error
|
||||
MakeBucket(ctx context.Context, region string, ignoreExisting, withLock bool) *probe.Error
|
||||
// Object lock config
|
||||
SetObjectLockConfig(mode minio.RetentionMode, validity uint64, unit minio.ValidityUnit) *probe.Error
|
||||
GetObjectLockConfig() (mode minio.RetentionMode, validity uint64, unit minio.ValidityUnit, perr *probe.Error)
|
||||
SetObjectLockConfig(ctx context.Context, mode minio.RetentionMode, validity uint64, unit minio.ValidityUnit) *probe.Error
|
||||
GetObjectLockConfig(ctx context.Context) (mode minio.RetentionMode, validity uint64, unit minio.ValidityUnit, perr *probe.Error)
|
||||
|
||||
// Access policy operations.
|
||||
GetAccess() (access string, policyJSON string, error *probe.Error)
|
||||
GetAccessRules() (policyRules map[string]string, error *probe.Error)
|
||||
SetAccess(access string, isJSON bool) *probe.Error
|
||||
GetAccess(ctx context.Context) (access string, policyJSON string, error *probe.Error)
|
||||
GetAccessRules(ctx context.Context) (policyRules map[string]string, error *probe.Error)
|
||||
SetAccess(ctx context.Context, access string, isJSON bool) *probe.Error
|
||||
|
||||
// I/O operations
|
||||
Copy(source string, size int64, progress io.Reader, srcSSE, tgtSSE encrypt.ServerSide, metadata map[string]string, disableMultipart 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(expression string, sse encrypt.ServerSide, opts SelectObjectOpts) (io.ReadCloser, *probe.Error)
|
||||
Select(ctx context.Context, expression string, sse encrypt.ServerSide, opts SelectObjectOpts) (io.ReadCloser, *probe.Error)
|
||||
|
||||
// I/O operations with metadata.
|
||||
Get(sse encrypt.ServerSide) (reader io.ReadCloser, err *probe.Error)
|
||||
Put(ctx context.Context, reader io.Reader, size int64, metadata map[string]string, progress io.Reader, sse encrypt.ServerSide, md5, disableMultipart bool) (n int64, 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
|
||||
PutObjectRetention(mode minio.RetentionMode, retainUntilDate time.Time, bypassGovernance bool) *probe.Error
|
||||
PutObjectLegalHold(hold minio.LegalHoldStatus) *probe.Error
|
||||
PutObjectRetention(ctx context.Context, mode minio.RetentionMode, retainUntilDate time.Time, bypassGovernance bool) *probe.Error
|
||||
PutObjectLegalHold(ctx context.Context, hold minio.LegalHoldStatus) *probe.Error
|
||||
|
||||
// I/O operations with expiration
|
||||
ShareDownload(expires time.Duration) (string, *probe.Error)
|
||||
ShareUpload(bool, time.Duration, string) (string, map[string]string, *probe.Error)
|
||||
ShareDownload(ctx context.Context, expires time.Duration) (string, *probe.Error)
|
||||
ShareUpload(context.Context, bool, time.Duration, string) (string, map[string]string, *probe.Error)
|
||||
|
||||
// Watch events
|
||||
Watch(options WatchOptions) (*WatchObject, *probe.Error)
|
||||
Watch(ctx context.Context, options WatchOptions) (*WatchObject, *probe.Error)
|
||||
|
||||
// Delete operations
|
||||
Remove(isIncomplete, isRemoveBucket, isBypass bool, contentCh <-chan *ClientContent) (errorCh <-chan *probe.Error)
|
||||
Remove(ctx context.Context, isIncomplete, isRemoveBucket, isBypass bool, contentCh <-chan *ClientContent) (errorCh <-chan *probe.Error)
|
||||
// GetURL returns back internal url
|
||||
GetURL() ClientURL
|
||||
|
||||
AddUserAgent(app, version string)
|
||||
|
||||
// Tagging operations
|
||||
GetTags() (*tags.Tags, *probe.Error)
|
||||
SetTags(tags string) *probe.Error
|
||||
DeleteTags() *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() (ilm.LifecycleConfiguration, *probe.Error)
|
||||
SetLifecycle(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
|
||||
}
|
||||
|
||||
+73
-46
@@ -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(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(aliasURL, false, keys)
|
||||
_, targetContent, err := url2Stat(ctx, aliasURL, "", false, keys, timeRef)
|
||||
if err == nil {
|
||||
return targetContent.Type.IsDir()
|
||||
}
|
||||
@@ -141,24 +141,24 @@ func isAliasURLDir(aliasURL string, keys map[string][]prefixSSEPair) bool {
|
||||
}
|
||||
|
||||
// getSourceStreamMetadataFromURL gets a reader from URL.
|
||||
func getSourceStreamMetadataFromURL(urlStr string, encKeyDB map[string][]prefixSSEPair) (reader io.ReadCloser,
|
||||
func getSourceStreamMetadataFromURL(ctx context.Context, urlStr string, encKeyDB map[string][]prefixSSEPair) (reader io.ReadCloser,
|
||||
metadata map[string]string, err *probe.Error) {
|
||||
alias, urlStrFull, _, err := expandAlias(urlStr)
|
||||
if err != nil {
|
||||
return nil, nil, err.Trace(urlStr)
|
||||
}
|
||||
sseKey := getSSE(urlStr, encKeyDB[alias])
|
||||
return getSourceStream(alias, urlStrFull, true, sseKey, false)
|
||||
return getSourceStream(ctx, alias, urlStrFull, "", true, sseKey, false)
|
||||
}
|
||||
|
||||
// getSourceStreamFromURL gets a reader from URL.
|
||||
func getSourceStreamFromURL(urlStr string, encKeyDB map[string][]prefixSSEPair) (reader io.ReadCloser, err *probe.Error) {
|
||||
func getSourceStreamFromURL(ctx context.Context, urlStr, 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(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(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(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(alias string, urlStr string, fetchStat bool, sse encrypt.Se
|
||||
}
|
||||
st.ETag = oinfo.ETag
|
||||
} else {
|
||||
st, err = sourceClnt.Stat(false, preserve, sse)
|
||||
st, err = sourceClnt.Stat(ctx, StatOptions{preserve: preserve, sse: sse})
|
||||
if err != nil {
|
||||
return nil, nil, err.Trace(alias, urlStr)
|
||||
}
|
||||
@@ -290,14 +290,14 @@ func putTargetRetention(ctx context.Context, alias string, urlStr string, metada
|
||||
retainUntilDate = t.UTC()
|
||||
}
|
||||
}
|
||||
if err := targetClnt.PutObjectRetention(lockMode, retainUntilDate, false); err != nil {
|
||||
if err := targetClnt.PutObjectRetention(ctx, lockMode, retainUntilDate, false); err != nil {
|
||||
return err.Trace(alias, urlStr)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// putTargetStream writes to URL from Reader.
|
||||
func putTargetStream(ctx context.Context, alias, urlStr, mode, until, legalHold string, reader io.Reader, size int64, metadata map[string]string, progress io.Reader, sse encrypt.ServerSide, md5, disableMultipart bool) (int64, *probe.Error) {
|
||||
func putTargetStream(ctx context.Context, alias, urlStr, mode, until, legalHold string, reader io.Reader, size int64, metadata map[string]string, progress io.Reader, sse encrypt.ServerSide, md5, disableMultipart, preserve bool) (int64, *probe.Error) {
|
||||
targetClnt, err := newClientFromAlias(alias, urlStr)
|
||||
if err != nil {
|
||||
return 0, err.Trace(alias, urlStr)
|
||||
@@ -312,7 +312,7 @@ func putTargetStream(ctx context.Context, alias, urlStr, mode, until, legalHold
|
||||
if legalHold != "" {
|
||||
metadata[AmzObjectLockLegalHold] = legalHold
|
||||
}
|
||||
n, err := targetClnt.Put(ctx, reader, size, metadata, progress, sse, md5, disableMultipart)
|
||||
n, err := targetClnt.Put(ctx, reader, size, metadata, progress, sse, md5, disableMultipart, preserve)
|
||||
if err != nil {
|
||||
return n, err.Trace(alias, urlStr)
|
||||
}
|
||||
@@ -320,7 +320,7 @@ func putTargetStream(ctx context.Context, alias, urlStr, mode, until, legalHold
|
||||
}
|
||||
|
||||
// putTargetStreamWithURL writes to URL from reader. If length=-1, read until EOF.
|
||||
func putTargetStreamWithURL(urlStr string, reader io.Reader, size int64, sse encrypt.ServerSide, md5, disableMultipart bool, metadata map[string]string) (int64, *probe.Error) {
|
||||
func putTargetStreamWithURL(urlStr string, reader io.Reader, size int64, sse encrypt.ServerSide, md5, disableMultipart, preserve bool, metadata map[string]string) (int64, *probe.Error) {
|
||||
alias, urlStrFull, _, err := expandAlias(urlStr)
|
||||
if err != nil {
|
||||
return 0, err.Trace(alias, urlStr)
|
||||
@@ -330,11 +330,11 @@ func putTargetStreamWithURL(urlStr string, reader io.Reader, size int64, sse enc
|
||||
metadata = map[string]string{}
|
||||
}
|
||||
metadata["Content-Type"] = contentType
|
||||
return putTargetStream(context.Background(), alias, urlStrFull, "", "", "", reader, size, metadata, nil, sse, md5, disableMultipart)
|
||||
return putTargetStream(context.Background(), alias, urlStrFull, "", "", "", reader, size, metadata, nil, sse, md5, disableMultipart, preserve)
|
||||
}
|
||||
|
||||
// copySourceToTargetURL copies to targetURL from source.
|
||||
func copySourceToTargetURL(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(alias, urlStr, source, mode, until, legalHold string,
|
||||
metadata[AmzObjectLockMode] = mode
|
||||
metadata[AmzObjectLockRetainUntilDate] = until
|
||||
metadata[AmzObjectLockLegalHold] = legalHold
|
||||
err = targetClnt.Copy(source, size, progress, srcSSE, tgtSSE, metadata, disableMultipart)
|
||||
|
||||
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,23 +377,24 @@ 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(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(false, preserve, srcSSE)
|
||||
|
||||
st, err := sourceClnt.Stat(ctx, StatOptions{preserve: true, sse: srcSSE})
|
||||
if err != nil {
|
||||
return nil, err.Trace(sourceAlias, sourceURLStr)
|
||||
}
|
||||
|
||||
for k, v := range st.Metadata {
|
||||
metadata[k] = v
|
||||
metadata[http.CanonicalHeaderKey(k)] = v
|
||||
}
|
||||
|
||||
for k, v := range urls.TargetContent.UserMetadata {
|
||||
metadata[k] = v
|
||||
metadata[http.CanonicalHeaderKey(k)] = v
|
||||
}
|
||||
|
||||
return filterMetadata(metadata), nil
|
||||
@@ -397,6 +406,7 @@ func getAllMetadata(sourceAlias, sourceURLStr string, srcSSE encrypt.ServerSide,
|
||||
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,25 @@ 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 {
|
||||
metadata, err = getAllMetadata(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
|
||||
for k, v := range urls.TargetContent.Metadata {
|
||||
metadata[http.CanonicalHeaderKey(k)] = v
|
||||
}
|
||||
|
||||
// Get userMetadata from target content as well
|
||||
for k, v := range urls.TargetContent.UserMetadata {
|
||||
metadata[http.CanonicalHeaderKey(k)] = v
|
||||
}
|
||||
|
||||
sourcePath := filepath.ToSlash(sourceURL.Path)
|
||||
@@ -468,34 +490,38 @@ func uploadSourceToTargetURL(ctx context.Context, urls URLs, progress io.Reader,
|
||||
return urls.WithError(err.Trace(sourceURL.String()))
|
||||
}
|
||||
|
||||
// Get metadata from target content as well
|
||||
for k, v := range urls.TargetContent.Metadata {
|
||||
metadata[k] = v
|
||||
}
|
||||
// Get userMetadata from target content as well
|
||||
for k, v := range urls.TargetContent.UserMetadata {
|
||||
metadata[k] = v
|
||||
}
|
||||
|
||||
err = copySourceToTargetURL(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 {
|
||||
metadata, err = getAllMetadata(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
|
||||
for k, v := range urls.TargetContent.Metadata {
|
||||
metadata[http.CanonicalHeaderKey(k)] = v
|
||||
}
|
||||
|
||||
// Get userMetadata from target content as well
|
||||
for k, v := range urls.TargetContent.UserMetadata {
|
||||
metadata[http.CanonicalHeaderKey(k)] = v
|
||||
}
|
||||
|
||||
err = putTargetRetention(ctx, targetAlias, targetURL.String(), metadata)
|
||||
return urls.WithError(err.Trace(sourceURL.String()))
|
||||
}
|
||||
|
||||
var reader io.ReadCloser
|
||||
// Proceed with regular stream copy.
|
||||
reader, metadata, err = getSourceStream(sourceAlias, sourceURL.String(), true, srcSSE, preserve)
|
||||
reader, metadata, err = getSourceStream(ctx, sourceAlias, sourceURL.String(), sourceVersion, true, srcSSE, preserve)
|
||||
if err != nil {
|
||||
return urls.WithError(err.Trace(sourceURL.String()))
|
||||
}
|
||||
@@ -503,22 +529,23 @@ func uploadSourceToTargetURL(ctx context.Context, urls URLs, progress io.Reader,
|
||||
|
||||
// Get metadata from target content as well
|
||||
for k, v := range urls.TargetContent.Metadata {
|
||||
metadata[k] = v
|
||||
metadata[http.CanonicalHeaderKey(k)] = v
|
||||
}
|
||||
|
||||
// Get userMetadata from target content as well
|
||||
for k, v := range urls.TargetContent.UserMetadata {
|
||||
metadata[k] = v
|
||||
metadata[http.CanonicalHeaderKey(k)] = v
|
||||
}
|
||||
|
||||
if isReadAt(reader) {
|
||||
_, err = putTargetStream(ctx, targetAlias, targetURL.String(), mode, until,
|
||||
legalHold, reader, length, filterMetadata(metadata),
|
||||
progress, tgtSSE, urls.MD5, urls.DisableMultipart)
|
||||
progress, tgtSSE, urls.MD5, urls.DisableMultipart, preserve)
|
||||
} else {
|
||||
_, err = putTargetStream(ctx, targetAlias, targetURL.String(), mode, until,
|
||||
legalHold, io.LimitReader(reader, length),
|
||||
length, filterMetadata(metadata), progress, tgtSSE, urls.MD5,
|
||||
urls.DisableMultipart)
|
||||
urls.DisableMultipart, preserve)
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
|
||||
@@ -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
@@ -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)
|
||||
|
||||
@@ -1,53 +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,
|
||||
Before: setGlobalsFromContext,
|
||||
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
@@ -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())
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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 {
|
||||
@@ -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
@@ -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
|
||||
}
|
||||
|
||||
+160
-53
@@ -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",
|
||||
@@ -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
|
||||
|
||||
`,
|
||||
}
|
||||
|
||||
@@ -244,28 +252,28 @@ func doCopy(ctx context.Context, cpURLs URLs, pg ProgressReader, encKeyDB map[st
|
||||
|
||||
urls := uploadSourceToTargetURL(ctx, cpURLs, pg, encKeyDB, preserve)
|
||||
if isMvCmd && urls.Error == nil {
|
||||
bgRemove(sourcePath)
|
||||
bgRemove(ctx, sourcePath)
|
||||
}
|
||||
|
||||
return urls
|
||||
}
|
||||
|
||||
// doCopyFake - Perform a fake copy to update the progress bar appropriately.
|
||||
func doCopyFake(cpURLs URLs, pg Progress, isMvCmd bool) URLs {
|
||||
func doCopyFake(ctx context.Context, cpURLs URLs, pg Progress, isMvCmd bool) URLs {
|
||||
if progressReader, ok := pg.(*progressBar); ok {
|
||||
progressReader.ProgressBar.Add64(cpURLs.SourceContent.Size)
|
||||
}
|
||||
|
||||
if isMvCmd {
|
||||
sourcePath := filepath.ToSlash(filepath.Join(cpURLs.SourceAlias, cpURLs.SourceContent.URL.Path))
|
||||
bgRemove(sourcePath)
|
||||
bgRemove(ctx, sourcePath)
|
||||
}
|
||||
|
||||
return cpURLs
|
||||
}
|
||||
|
||||
// doPrepareCopyURLs scans the source URL and prepares a list of objects for copying.
|
||||
func doPrepareCopyURLs(session *sessionV8, cancelCopy context.CancelFunc) (totalBytes, totalObjects int64) {
|
||||
func doPrepareCopyURLs(ctx context.Context, session *sessionV8, cancelCopy context.CancelFunc) (totalBytes, totalObjects int64) {
|
||||
// Separate source and target. 'cp' can take only one target,
|
||||
// but any number of sources.
|
||||
sourceURLs := session.Header.CommandArgs[:len(session.Header.CommandArgs)-1]
|
||||
@@ -273,7 +281,7 @@ func doPrepareCopyURLs(session *sessionV8, cancelCopy context.CancelFunc) (total
|
||||
|
||||
// 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(session *sessionV8, cancelCopy context.CancelFunc) (total
|
||||
scanBar = scanBarFactory()
|
||||
}
|
||||
|
||||
URLsCh := prepareCopyURLs(sourceURLs, targetURL, isRecursive, encKeyDB, olderThan, newerThan)
|
||||
URLsCh := prepareCopyURLs(ctx, sourceURLs, targetURL, isRecursive, encKeyDB, olderThan, newerThan, parseRewindFlag(rewind))
|
||||
done := false
|
||||
for !done {
|
||||
select {
|
||||
@@ -341,10 +349,7 @@ func doPrepareCopyURLs(session *sessionV8, cancelCopy context.CancelFunc) (total
|
||||
return
|
||||
}
|
||||
|
||||
func doCopySession(cli *cli.Context, session *sessionV8, encKeyDB map[string][]prefixSSEPair, isMvCmd bool) error {
|
||||
ctx, cancelCopy := context.WithCancel(globalContext)
|
||||
defer cancelCopy()
|
||||
|
||||
func doCopySession(ctx context.Context, cancelCopy context.CancelFunc, cli *cli.Context, session *sessionV8, encKeyDB map[string][]prefixSSEPair, isMvCmd bool) error {
|
||||
var isCopied func(string) bool
|
||||
var totalObjects, totalBytes int64
|
||||
|
||||
@@ -366,7 +371,7 @@ func doCopySession(cli *cli.Context, session *sessionV8, encKeyDB map[string][]p
|
||||
isCopied = isLastFactory(session.Header.LastCopied)
|
||||
|
||||
if !session.HasData() {
|
||||
totalBytes, totalObjects = doPrepareCopyURLs(session, cancelCopy)
|
||||
totalBytes, totalObjects = doPrepareCopyURLs(ctx, session, cancelCopy)
|
||||
} else {
|
||||
totalBytes, totalObjects = session.Header.TotalBytes, session.Header.TotalObjects
|
||||
}
|
||||
@@ -400,11 +405,12 @@ func doCopySession(cli *cli.Context, session *sessionV8, encKeyDB map[string][]p
|
||||
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(sourceURLs, targetURL, isRecursive,
|
||||
encKeyDB, olderThan, newerThan) {
|
||||
for cpURLs := range prepareCopyURLs(ctx, sourceURLs, targetURL, isRecursive,
|
||||
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
|
||||
@@ -478,7 +484,7 @@ func doCopySession(cli *cli.Context, session *sessionV8, encKeyDB map[string][]p
|
||||
cpURLs.TargetContent.RetentionEnabled = true
|
||||
}
|
||||
cpURLs.TargetContent.RetentionDuration = session.Header.CommandStringFlags[rdFlag]
|
||||
cpURLs.TargetContent.LegalHold = session.Header.CommandStringFlags[lhFlag]
|
||||
cpURLs.TargetContent.LegalHold = strings.ToUpper(session.Header.CommandStringFlags[lhFlag])
|
||||
if cpURLs.TargetContent.LegalHold != "" {
|
||||
cpURLs.TargetContent.LegalHoldEnabled = true
|
||||
}
|
||||
@@ -491,25 +497,27 @@ func doCopySession(cli *cli.Context, session *sessionV8, encKeyDB map[string][]p
|
||||
cpURLs.TargetContent.RetentionDuration = rd
|
||||
}
|
||||
if lh := cli.String(lhFlag); lh != "" {
|
||||
cpURLs.TargetContent.LegalHold = lh
|
||||
cpURLs.TargetContent.LegalHold = strings.ToUpper(lh)
|
||||
cpURLs.TargetContent.LegalHoldEnabled = true
|
||||
}
|
||||
}
|
||||
if cli.String("attr") != "" {
|
||||
userMetaMap, _ := getMetaDataEntry(cli.String("attr"))
|
||||
for metaDataKey, metaDataVal := range userMetaMap {
|
||||
cpURLs.TargetContent.UserMetadata[metaDataKey] = metaDataVal
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
cpURLs.MD5 = cli.Bool("md5")
|
||||
cpURLs.DisableMultipart = cli.Bool("disable-multipart")
|
||||
|
||||
// Verify if previously copied, notify progress bar.
|
||||
if isCopied != nil && isCopied(cpURLs.SourceContent.URL.String()) {
|
||||
queueCh <- func() URLs {
|
||||
return doCopyFake(cpURLs, pg, isMvCmd)
|
||||
return doCopyFake(ctx, cpURLs, pg, isMvCmd)
|
||||
}
|
||||
} else {
|
||||
queueCh <- func() URLs {
|
||||
@@ -607,44 +615,142 @@ 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.
|
||||
func mainCopy(ctx *cli.Context) error {
|
||||
func mainCopy(cliCtx *cli.Context) error {
|
||||
ctx, cancelCopy := context.WithCancel(globalContext)
|
||||
defer cancelCopy()
|
||||
|
||||
// Parse encryption keys per command.
|
||||
encKeyDB, err := getEncKeys(ctx)
|
||||
encKeyDB, err := getEncKeys(cliCtx)
|
||||
fatalIf(err, "Unable to parse encryption keys.")
|
||||
|
||||
// Parse metadata.
|
||||
userMetaMap := make(map[string]string)
|
||||
if ctx.String("attr") != "" {
|
||||
userMetaMap, err = getMetaDataEntry(ctx.String("attr"))
|
||||
fatalIf(err, "Unable to parse attribute %v", ctx.String("attr"))
|
||||
if cliCtx.String("attr") != "" {
|
||||
userMetaMap, err = getMetaDataEntry(cliCtx.String("attr"))
|
||||
fatalIf(err, "Unable to parse attribute %v", cliCtx.String("attr"))
|
||||
}
|
||||
|
||||
// check 'copy' cli arguments.
|
||||
checkCopySyntax(ctx, encKeyDB, false)
|
||||
checkCopySyntax(ctx, cliCtx, encKeyDB, false)
|
||||
|
||||
// Additional command specific theme customization.
|
||||
console.SetColor("Copy", color.New(color.FgGreen, color.Bold))
|
||||
|
||||
recursive := ctx.Bool("recursive")
|
||||
olderThan := ctx.String("older-than")
|
||||
newerThan := ctx.String("newer-than")
|
||||
storageClass := ctx.String("storage-class")
|
||||
retentionMode := ctx.String(rmFlag)
|
||||
retentionDuration := ctx.String(rdFlag)
|
||||
legalHold := ctx.String(lhFlag)
|
||||
recursive := cliCtx.Bool("recursive")
|
||||
rewind := cliCtx.String("rewind")
|
||||
olderThan := cliCtx.String("older-than")
|
||||
newerThan := cliCtx.String("newer-than")
|
||||
storageClass := cliCtx.String("storage-class")
|
||||
retentionMode := cliCtx.String(rmFlag)
|
||||
retentionDuration := cliCtx.String(rdFlag)
|
||||
legalHold := strings.ToUpper(cliCtx.String(lhFlag))
|
||||
sseKeys := os.Getenv("MC_ENCRYPT_KEY")
|
||||
if key := ctx.String("encrypt-key"); key != "" {
|
||||
if key := cliCtx.String("encrypt-key"); key != "" {
|
||||
sseKeys = key
|
||||
}
|
||||
|
||||
@@ -652,12 +758,12 @@ func mainCopy(ctx *cli.Context) error {
|
||||
sseKeys, err = getDecodedKey(sseKeys)
|
||||
fatalIf(err, "Unable to parse encryption keys.")
|
||||
}
|
||||
sse := ctx.String("encrypt")
|
||||
sse := cliCtx.String("encrypt")
|
||||
|
||||
var session *sessionV8
|
||||
|
||||
if ctx.Bool("continue") {
|
||||
sessionID := getHash("cp", ctx.Args())
|
||||
if cliCtx.Bool("continue") {
|
||||
sessionID := getHash("cp", cliCtx.Args())
|
||||
if isSessionExists(sessionID) {
|
||||
session, err = loadSessionV8(sessionID)
|
||||
fatalIf(err.Trace(sessionID), "Unable to load session.")
|
||||
@@ -665,6 +771,7 @@ func mainCopy(ctx *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
|
||||
@@ -673,14 +780,14 @@ func mainCopy(ctx *cli.Context) error {
|
||||
session.Header.CommandStringFlags[lhFlag] = legalHold
|
||||
session.Header.CommandStringFlags["encrypt-key"] = sseKeys
|
||||
session.Header.CommandStringFlags["encrypt"] = sse
|
||||
session.Header.CommandBoolFlags["session"] = ctx.Bool("continue")
|
||||
session.Header.CommandBoolFlags["session"] = cliCtx.Bool("continue")
|
||||
|
||||
if ctx.Bool("preserve") {
|
||||
session.Header.CommandBoolFlags["preserve"] = ctx.Bool("preserve")
|
||||
if cliCtx.Bool("preserve") {
|
||||
session.Header.CommandBoolFlags["preserve"] = cliCtx.Bool("preserve")
|
||||
}
|
||||
session.Header.UserMetaData = userMetaMap
|
||||
session.Header.CommandBoolFlags["md5"] = ctx.Bool("md5")
|
||||
session.Header.CommandBoolFlags["disable-multipart"] = ctx.Bool("disable-multipart")
|
||||
session.Header.CommandBoolFlags["md5"] = cliCtx.Bool("md5")
|
||||
session.Header.CommandBoolFlags["disable-multipart"] = cliCtx.Bool("disable-multipart")
|
||||
|
||||
var e error
|
||||
if session.Header.RootPath, e = os.Getwd(); e != nil {
|
||||
@@ -689,11 +796,11 @@ func mainCopy(ctx *cli.Context) error {
|
||||
}
|
||||
|
||||
// extract URLs.
|
||||
session.Header.CommandArgs = ctx.Args()
|
||||
session.Header.CommandArgs = cliCtx.Args()
|
||||
}
|
||||
}
|
||||
|
||||
e := doCopySession(ctx, session, encKeyDB, false)
|
||||
e := doCopySession(ctx, cancelCopy, cliCtx, session, encKeyDB, false)
|
||||
if session != nil {
|
||||
session.Delete()
|
||||
}
|
||||
|
||||
@@ -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 {
|
||||
|
||||
+30
-26
@@ -17,34 +17,38 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"runtime"
|
||||
"time"
|
||||
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/minio/pkg/console"
|
||||
)
|
||||
|
||||
func checkCopySyntax(ctx *cli.Context, encKeyDB map[string][]prefixSSEPair, isMvCmd bool) {
|
||||
if len(ctx.Args()) < 2 {
|
||||
func checkCopySyntax(ctx context.Context, cliCtx *cli.Context, encKeyDB map[string][]prefixSSEPair, isMvCmd bool) {
|
||||
if len(cliCtx.Args()) < 2 {
|
||||
if isMvCmd {
|
||||
cli.ShowCommandHelpAndExit(ctx, "mv", 1) // last argument is exit code.
|
||||
cli.ShowCommandHelpAndExit(cliCtx, "mv", 1) // last argument is exit code.
|
||||
}
|
||||
cli.ShowCommandHelpAndExit(ctx, "cp", 1) // last argument is exit code.
|
||||
cli.ShowCommandHelpAndExit(cliCtx, "cp", 1) // last argument is exit code.
|
||||
}
|
||||
|
||||
// extract URLs.
|
||||
URLs := ctx.Args()
|
||||
URLs := cliCtx.Args()
|
||||
if len(URLs) < 2 {
|
||||
fatalIf(errDummy().Trace(ctx.Args()...), "Unable to parse source and target arguments.")
|
||||
fatalIf(errDummy().Trace(cliCtx.Args()...), "Unable to parse source and target arguments.")
|
||||
}
|
||||
|
||||
srcURLs := URLs[:len(URLs)-1]
|
||||
tgtURL := URLs[len(URLs)-1]
|
||||
isRecursive := ctx.Bool("recursive")
|
||||
isRecursive := cliCtx.Bool("recursive")
|
||||
rewind := cliCtx.String("rewind")
|
||||
timeRef := parseRewindFlag(rewind)
|
||||
|
||||
// Verify if source(s) exists.
|
||||
for _, srcURL := range srcURLs {
|
||||
_, _, err := url2Stat(srcURL, false, encKeyDB)
|
||||
_, _, err := url2Stat(ctx, srcURL, "", false, encKeyDB, timeRef)
|
||||
if err != nil {
|
||||
console.Fatalf("Unable to validate source %s\n", srcURL)
|
||||
}
|
||||
@@ -58,11 +62,11 @@ func checkCopySyntax(ctx *cli.Context, encKeyDB map[string][]prefixSSEPair, isMv
|
||||
}
|
||||
}
|
||||
|
||||
if ctx.String(rdFlag) != "" && ctx.String(rmFlag) == "" {
|
||||
if cliCtx.String(rdFlag) != "" && cliCtx.String(rmFlag) == "" {
|
||||
fatalIf(errInvalidArgument().Trace(), fmt.Sprintf("Both object retention flags `--%s` and `--%s` are required.\n", rdFlag, rmFlag))
|
||||
}
|
||||
|
||||
if ctx.String(rdFlag) == "" && ctx.String(rmFlag) != "" {
|
||||
if cliCtx.String(rdFlag) == "" && cliCtx.String(rmFlag) != "" {
|
||||
fatalIf(errInvalidArgument().Trace(), fmt.Sprintf("Both object retention flags `--%s` and `--%s` are required.\n", rdFlag, rmFlag))
|
||||
}
|
||||
|
||||
@@ -72,38 +76,38 @@ func checkCopySyntax(ctx *cli.Context, encKeyDB map[string][]prefixSSEPair, isMv
|
||||
}
|
||||
|
||||
// Guess CopyURLsType based on source and target URLs.
|
||||
copyURLsType, err := guessCopyURLType(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(srcURLs, tgtURL, encKeyDB, isMvCmd)
|
||||
checkCopySyntaxTypeA(ctx, srcURLs, tgtURL, encKeyDB, isMvCmd, timeRef)
|
||||
case copyURLsTypeB: // File -> Folder.
|
||||
checkCopySyntaxTypeB(srcURLs, tgtURL, encKeyDB, isMvCmd)
|
||||
checkCopySyntaxTypeB(ctx, srcURLs, tgtURL, encKeyDB, isMvCmd, timeRef)
|
||||
case copyURLsTypeC: // Folder... -> Folder.
|
||||
checkCopySyntaxTypeC(srcURLs, tgtURL, isRecursive, encKeyDB, isMvCmd)
|
||||
checkCopySyntaxTypeC(ctx, srcURLs, tgtURL, isRecursive, encKeyDB, isMvCmd, timeRef)
|
||||
case copyURLsTypeD: // File1...FileN -> Folder.
|
||||
checkCopySyntaxTypeD(srcURLs, tgtURL, encKeyDB, isMvCmd)
|
||||
checkCopySyntaxTypeD(ctx, srcURLs, tgtURL, encKeyDB, isMvCmd, timeRef)
|
||||
default:
|
||||
fatalIf(errInvalidArgument().Trace(), "Unable to guess the type of "+operation+" operation.")
|
||||
}
|
||||
|
||||
// Preserve functionality not supported for windows
|
||||
if ctx.Bool("preserve") && runtime.GOOS == "windows" {
|
||||
if cliCtx.Bool("preserve") && runtime.GOOS == "windows" {
|
||||
fatalIf(errInvalidArgument().Trace(), "Permissions are not preserved on windows platform.")
|
||||
}
|
||||
}
|
||||
|
||||
// checkCopySyntaxTypeA verifies if the source and target are valid file arguments.
|
||||
func checkCopySyntaxTypeA(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(srcURL, false, keys)
|
||||
_, srcContent, err := url2Stat(ctx, srcURL, "", false, keys, timeRef)
|
||||
fatalIf(err.Trace(srcURL), "Unable to stat source `"+srcURL+"`.")
|
||||
|
||||
if !srcContent.Type.IsRegular() {
|
||||
@@ -112,13 +116,13 @@ func checkCopySyntaxTypeA(srcURLs []string, tgtURL string, keys map[string][]pre
|
||||
}
|
||||
|
||||
// checkCopySyntaxTypeB verifies if the source is a valid file and target is a valid folder.
|
||||
func checkCopySyntaxTypeB(srcURLs []string, tgtURL string, keys map[string][]prefixSSEPair, 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(srcURL, false, keys)
|
||||
_, srcContent, err := url2Stat(ctx, srcURL, "", false, keys, timeRef)
|
||||
fatalIf(err.Trace(srcURL), "Unable to stat source `"+srcURL+"`.")
|
||||
|
||||
if !srcContent.Type.IsRegular() {
|
||||
@@ -126,7 +130,7 @@ func checkCopySyntaxTypeB(srcURLs []string, tgtURL string, keys map[string][]pre
|
||||
}
|
||||
|
||||
// Check target.
|
||||
if _, tgtContent, err := url2Stat(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.")
|
||||
}
|
||||
@@ -134,21 +138,21 @@ func checkCopySyntaxTypeB(srcURLs []string, tgtURL string, keys map[string][]pre
|
||||
}
|
||||
|
||||
// checkCopySyntaxTypeC verifies if the source is a valid recursive dir and target is a valid folder.
|
||||
func checkCopySyntaxTypeC(srcURLs []string, tgtURL string, isRecursive bool, keys map[string][]prefixSSEPair, 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(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(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 {
|
||||
@@ -183,10 +187,10 @@ func checkCopySyntaxTypeC(srcURLs []string, tgtURL string, isRecursive bool, key
|
||||
}
|
||||
|
||||
// checkCopySyntaxTypeD verifies if the source is a valid list of files and target is a valid folder.
|
||||
func checkCopySyntaxTypeD(srcURLs []string, tgtURL string, keys map[string][]prefixSSEPair, 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(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.")
|
||||
}
|
||||
|
||||
+28
-40
@@ -17,9 +17,10 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"os"
|
||||
"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(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(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(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(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(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(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(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(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(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(sourceURL, targetURL string, isRecursive bool, encKeyD
|
||||
return
|
||||
}
|
||||
|
||||
isIncomplete := false
|
||||
for sourceContent := range sourceClient.List(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())}
|
||||
@@ -192,18 +192,6 @@ func makeCopyContentTypeC(sourceAlias string, sourceURL ClientURL, sourceContent
|
||||
newSourceSuffix := filepath.ToSlash(newSourceURL.Path)
|
||||
if pathSeparatorIndex > 1 {
|
||||
sourcePrefix := filepath.ToSlash(sourceURL.Path[:pathSeparatorIndex])
|
||||
// do not preserve unix cp behavior when copying a filesytem dir to
|
||||
// objectstore.
|
||||
if sourceAlias == "" && targetAlias != "" {
|
||||
// Check if sourceURL.Path is a directory or not
|
||||
fileInfo, err := os.Stat(sourceURL.Path)
|
||||
if err != nil {
|
||||
return URLs{Error: probe.NewError(err)}
|
||||
}
|
||||
if fileInfo.IsDir() {
|
||||
sourcePrefix = filepath.ToSlash(sourceURL.Path)
|
||||
}
|
||||
}
|
||||
newSourceSuffix = strings.TrimPrefix(newSourceSuffix, sourcePrefix)
|
||||
}
|
||||
newTargetURL := urlJoinPath(targetURL, newSourceSuffix)
|
||||
@@ -212,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(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(sourceURL, targetURL, isRecursive, encKeyDB) {
|
||||
for cpURLs := range prepareCopyURLsTypeC(ctx, sourceURL, targetURL, isRecursive, timeRef, encKeyDB) {
|
||||
copyURLsCh <- cpURLs
|
||||
}
|
||||
}
|
||||
@@ -226,30 +214,30 @@ func prepareCopyURLsTypeD(sourceURLs []string, targetURL string, isRecursive boo
|
||||
}
|
||||
|
||||
// prepareCopyURLs - prepares target and source clientURLs for copying.
|
||||
func prepareCopyURLs(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(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(sourceURLs[0], targetURL, encKeyDB)
|
||||
copyURLsCh <- prepareCopyURLsTypeA(ctx, sourceURLs[0], cpVersion, targetURL, encKeyDB)
|
||||
case copyURLsTypeB:
|
||||
copyURLsCh <- prepareCopyURLsTypeB(sourceURLs[0], targetURL, encKeyDB)
|
||||
copyURLsCh <- prepareCopyURLsTypeB(ctx, sourceURLs[0], cpVersion, targetURL, encKeyDB)
|
||||
case copyURLsTypeC:
|
||||
for cURLs := range prepareCopyURLsTypeC(sourceURLs[0], targetURL, isRecursive, encKeyDB) {
|
||||
for cURLs := range prepareCopyURLsTypeC(ctx, sourceURLs[0], targetURL, isRecursive, timeRef, encKeyDB) {
|
||||
copyURLsCh <- cURLs
|
||||
}
|
||||
case copyURLsTypeD:
|
||||
for cURLs := range prepareCopyURLsTypeD(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() {
|
||||
|
||||
+21
-16
@@ -17,8 +17,10 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/cli"
|
||||
@@ -90,7 +92,7 @@ func (d diffMessage) String() string {
|
||||
msg = console.Colorize("DiffSize", "! "+d.SecondURL)
|
||||
case differInMetadata:
|
||||
msg = console.Colorize("DiffMetadata", "! "+d.SecondURL)
|
||||
case differInMMSourceMTime:
|
||||
case differInAASourceMTime:
|
||||
msg = console.Colorize("DiffMMSourceMTime", "! "+d.SecondURL)
|
||||
default:
|
||||
fatalIf(errDummy().Trace(d.FirstURL, d.SecondURL),
|
||||
@@ -109,23 +111,23 @@ func (d diffMessage) JSON() string {
|
||||
return string(diffJSONBytes)
|
||||
}
|
||||
|
||||
func checkDiffSyntax(ctx *cli.Context, encKeyDB map[string][]prefixSSEPair) {
|
||||
if len(ctx.Args()) != 2 {
|
||||
cli.ShowCommandHelpAndExit(ctx, "diff", 1) // last argument is exit code
|
||||
func checkDiffSyntax(ctx context.Context, cliCtx *cli.Context, encKeyDB map[string][]prefixSSEPair) {
|
||||
if len(cliCtx.Args()) != 2 {
|
||||
cli.ShowCommandHelpAndExit(cliCtx, "diff", 1) // last argument is exit code
|
||||
}
|
||||
for _, arg := range ctx.Args() {
|
||||
for _, arg := range cliCtx.Args() {
|
||||
if strings.TrimSpace(arg) == "" {
|
||||
fatalIf(errInvalidArgument().Trace(ctx.Args()...), "Unable to validate empty argument.")
|
||||
fatalIf(errInvalidArgument().Trace(cliCtx.Args()...), "Unable to validate empty argument.")
|
||||
}
|
||||
}
|
||||
URLs := ctx.Args()
|
||||
URLs := cliCtx.Args()
|
||||
firstURL := URLs[0]
|
||||
secondURL := URLs[1]
|
||||
|
||||
// Diff only works between two directories, verify them below.
|
||||
|
||||
// Verify if firstURL is accessible.
|
||||
_, firstContent, err := url2Stat(firstURL, false, encKeyDB)
|
||||
_, firstContent, err := url2Stat(ctx, firstURL, "", false, encKeyDB, time.Time{})
|
||||
if err != nil {
|
||||
fatalIf(err.Trace(firstURL), fmt.Sprintf("Unable to stat '%s'.", firstURL))
|
||||
}
|
||||
@@ -136,7 +138,7 @@ func checkDiffSyntax(ctx *cli.Context, encKeyDB map[string][]prefixSSEPair) {
|
||||
}
|
||||
|
||||
// Verify if secondURL is accessible.
|
||||
_, secondContent, err := url2Stat(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))
|
||||
}
|
||||
@@ -148,7 +150,7 @@ func checkDiffSyntax(ctx *cli.Context, encKeyDB map[string][]prefixSSEPair) {
|
||||
}
|
||||
|
||||
// doDiffMain runs the diff.
|
||||
func doDiffMain(firstURL, secondURL string) error {
|
||||
func doDiffMain(ctx context.Context, firstURL, secondURL string) error {
|
||||
// Source and targets are always directories
|
||||
sourceSeparator := string(newClientURL(firstURL).Separator)
|
||||
if !strings.HasSuffix(firstURL, sourceSeparator) {
|
||||
@@ -176,7 +178,7 @@ func doDiffMain(firstURL, secondURL string) error {
|
||||
}
|
||||
|
||||
// Diff first and second urls.
|
||||
for diffMsg := range objectDifference(firstClient, secondClient, firstURL, secondURL, false) {
|
||||
for diffMsg := range objectDifference(ctx, firstClient, secondClient, firstURL, secondURL, true) {
|
||||
if diffMsg.Error != nil {
|
||||
errorIf(diffMsg.Error, "Unable to calculate objects difference.")
|
||||
// Ignore error and proceed to next object.
|
||||
@@ -189,13 +191,16 @@ func doDiffMain(firstURL, secondURL string) error {
|
||||
}
|
||||
|
||||
// mainDiff main for 'diff'.
|
||||
func mainDiff(ctx *cli.Context) error {
|
||||
func mainDiff(cliCtx *cli.Context) error {
|
||||
ctx, cancelDiff := context.WithCancel(globalContext)
|
||||
defer cancelDiff()
|
||||
|
||||
// Parse encryption keys per command.
|
||||
encKeyDB, err := getEncKeys(ctx)
|
||||
encKeyDB, err := getEncKeys(cliCtx)
|
||||
fatalIf(err, "Unable to parse encryption keys.")
|
||||
|
||||
// check 'diff' cli arguments.
|
||||
checkDiffSyntax(ctx, encKeyDB)
|
||||
checkDiffSyntax(ctx, cliCtx, encKeyDB)
|
||||
|
||||
// Additional command specific theme customization.
|
||||
console.SetColor("DiffMessage", color.New(color.FgGreen, color.Bold))
|
||||
@@ -206,9 +211,9 @@ func mainDiff(ctx *cli.Context) error {
|
||||
console.SetColor("DiffMetadata", color.New(color.FgYellow, color.Bold))
|
||||
console.SetColor("DiffMMSourceMTime", color.New(color.FgYellow, color.Bold))
|
||||
|
||||
URLs := ctx.Args()
|
||||
URLs := cliCtx.Args()
|
||||
firstURL := URLs.Get(0)
|
||||
secondURL := URLs.Get(1)
|
||||
|
||||
return doDiffMain(firstURL, secondURL)
|
||||
return doDiffMain(ctx, firstURL, secondURL)
|
||||
}
|
||||
|
||||
+69
-40
@@ -17,6 +17,7 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
@@ -24,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"
|
||||
)
|
||||
|
||||
@@ -38,7 +39,7 @@ const (
|
||||
differInType // differs in type, exfile/directory
|
||||
differInFirst // only in source (FIRST)
|
||||
differInSecond // only in target (SECOND)
|
||||
differInMMSourceMTime // differs in multi-master source modtime
|
||||
differInAASourceMTime // differs in active-active source modtime
|
||||
)
|
||||
|
||||
func (d differType) String() string {
|
||||
@@ -49,7 +50,7 @@ func (d differType) String() string {
|
||||
return "size"
|
||||
case differInMetadata:
|
||||
return "metadata"
|
||||
case differInMMSourceMTime:
|
||||
case differInAASourceMTime:
|
||||
return "mm-source-mtime"
|
||||
case differInType:
|
||||
return "type"
|
||||
@@ -61,25 +62,27 @@ func (d differType) String() string {
|
||||
return "unknown"
|
||||
}
|
||||
|
||||
const multiMasterSourceModTimeKey = "X-Amz-Meta-Mm-Source-Mtime"
|
||||
const activeActiveSourceModTimeKey = "X-Amz-Meta-Mm-Source-Mtime"
|
||||
|
||||
func oldestNonNullTime(t1, t2 time.Time) time.Time {
|
||||
if t1.IsZero() {
|
||||
return t2
|
||||
func getSourceModTimeKey(metadata map[string]string) string {
|
||||
if metadata[activeActiveSourceModTimeKey] != "" {
|
||||
return metadata[activeActiveSourceModTimeKey]
|
||||
}
|
||||
if t2.IsZero() {
|
||||
return t1
|
||||
if metadata[strings.ToLower(activeActiveSourceModTimeKey)] != "" {
|
||||
return metadata[strings.ToLower(activeActiveSourceModTimeKey)]
|
||||
}
|
||||
if t1.Before(t2) {
|
||||
return t1
|
||||
if metadata[strings.ToLower("Mm-Source-Mtime")] != "" {
|
||||
return metadata[strings.ToLower("Mm-Source-Mtime")]
|
||||
}
|
||||
|
||||
return t2
|
||||
if metadata["Mm-Source-Mtime"] != "" {
|
||||
return metadata["Mm-Source-Mtime"]
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// multiMasterModTimeUpdated tries to calculate if the object copy in the target
|
||||
// activeActiveModTimeUpdated tries to calculate if the object copy in the target
|
||||
// is older than the one in the source by comparing the modtime of the data.
|
||||
func multiMasterModTimeUpdated(src, dst *ClientContent) bool {
|
||||
func activeActiveModTimeUpdated(src, dst *ClientContent) bool {
|
||||
if src == nil || dst == nil {
|
||||
return false
|
||||
}
|
||||
@@ -91,25 +94,49 @@ func multiMasterModTimeUpdated(src, dst *ClientContent) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
_, ok1 := src.UserMetadata[multiMasterSourceModTimeKey]
|
||||
_, ok2 := dst.UserMetadata[multiMasterSourceModTimeKey]
|
||||
if !ok1 && !ok2 {
|
||||
// No multimaster context found, consider src & dst as similar
|
||||
srcModTime := getSourceModTimeKey(src.UserMetadata)
|
||||
dstModTime := getSourceModTimeKey(dst.UserMetadata)
|
||||
if srcModTime == "" && dstModTime == "" {
|
||||
// No active-active mirror context found, consider src & dst as similar
|
||||
return false
|
||||
}
|
||||
|
||||
srcOriginLastModified, _ := time.Parse(time.RFC3339Nano, src.UserMetadata[multiMasterSourceModTimeKey])
|
||||
dstOriginLastModified, _ := time.Parse(time.RFC3339Nano, dst.UserMetadata[multiMasterSourceModTimeKey])
|
||||
var srcOriginLastModified, dstOriginLastModified time.Time
|
||||
var err error
|
||||
if srcModTime != "" {
|
||||
srcOriginLastModified, err = time.Parse(time.RFC3339Nano, srcModTime)
|
||||
if err != nil {
|
||||
// failure to parse source modTime, modTime tampered ignore the file
|
||||
return false
|
||||
}
|
||||
}
|
||||
if dstModTime != "" {
|
||||
dstOriginLastModified, err = time.Parse(time.RFC3339Nano, dstModTime)
|
||||
if err != nil {
|
||||
// failure to parse source modTime, modTime tampered ignore the file
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
srcActualModTime := oldestNonNullTime(src.Time, srcOriginLastModified)
|
||||
dstActualModTime := oldestNonNullTime(dst.Time, dstOriginLastModified)
|
||||
srcActualModTime := src.Time
|
||||
if !srcOriginLastModified.IsZero() && srcOriginLastModified.After(src.Time) {
|
||||
srcActualModTime = srcOriginLastModified
|
||||
}
|
||||
|
||||
dstActualModTime := dst.Time
|
||||
if !dstOriginLastModified.IsZero() && dstOriginLastModified.After(dst.Time) {
|
||||
dstActualModTime = dstOriginLastModified
|
||||
}
|
||||
|
||||
return srcActualModTime.After(dstActualModTime)
|
||||
}
|
||||
|
||||
func metadataEqual(m1, m2 map[string]string) bool {
|
||||
for k, v := range m1 {
|
||||
if k == multiMasterSourceModTimeKey {
|
||||
if k == activeActiveSourceModTimeKey {
|
||||
continue
|
||||
}
|
||||
if k == strings.ToLower(activeActiveSourceModTimeKey) {
|
||||
continue
|
||||
}
|
||||
if m2[k] != v {
|
||||
@@ -117,7 +144,10 @@ func metadataEqual(m1, m2 map[string]string) bool {
|
||||
}
|
||||
}
|
||||
for k, v := range m2 {
|
||||
if k == multiMasterSourceModTimeKey {
|
||||
if k == activeActiveSourceModTimeKey {
|
||||
continue
|
||||
}
|
||||
if k == strings.ToLower(activeActiveSourceModTimeKey) {
|
||||
continue
|
||||
}
|
||||
if m1[k] != v {
|
||||
@@ -127,19 +157,18 @@ func metadataEqual(m1, m2 map[string]string) bool {
|
||||
return true
|
||||
}
|
||||
|
||||
func objectDifference(sourceClnt, targetClnt Client, sourceURL, targetURL string, isMetadata bool) (diffCh chan diffMessage) {
|
||||
return difference(sourceClnt, targetClnt, sourceURL, targetURL, isMetadata, true, false, DirNone)
|
||||
func objectDifference(ctx context.Context, sourceClnt, targetClnt Client, sourceURL, targetURL string, isMetadata bool) (diffCh chan diffMessage) {
|
||||
return difference(ctx, sourceClnt, targetClnt, sourceURL, targetURL, isMetadata, true, false, DirNone)
|
||||
}
|
||||
|
||||
func dirDifference(sourceClnt, targetClnt Client, sourceURL, targetURL string) (diffCh chan diffMessage) {
|
||||
return difference(sourceClnt, targetClnt, sourceURL, targetURL, false, false, true, DirFirst)
|
||||
func dirDifference(ctx context.Context, sourceClnt, targetClnt Client, sourceURL, targetURL string) (diffCh chan diffMessage) {
|
||||
return difference(ctx, sourceClnt, targetClnt, sourceURL, targetURL, false, false, true, DirFirst)
|
||||
}
|
||||
|
||||
func differenceInternal(sourceClnt, targetClnt Client, sourceURL, targetURL string, isMetadata bool, isRecursive, returnSimilar bool, dirOpt DirOpt, diffCh chan<- diffMessage) *probe.Error {
|
||||
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(isRecursive, isIncomplete, isMetadata, dirOpt)
|
||||
tgtCh := targetClnt.List(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
|
||||
@@ -245,11 +274,11 @@ func differenceInternal(sourceClnt, targetClnt Client, sourceURL, targetURL stri
|
||||
firstContent: srcCtnt,
|
||||
secondContent: tgtCtnt,
|
||||
}
|
||||
} else if multiMasterModTimeUpdated(srcCtnt, tgtCtnt) {
|
||||
} else if activeActiveModTimeUpdated(srcCtnt, tgtCtnt) {
|
||||
diffCh <- diffMessage{
|
||||
FirstURL: srcCtnt.URL.String(),
|
||||
SecondURL: tgtCtnt.URL.String(),
|
||||
Diff: differInMMSourceMTime,
|
||||
Diff: differInAASourceMTime,
|
||||
firstContent: srcCtnt,
|
||||
secondContent: tgtCtnt,
|
||||
}
|
||||
@@ -296,17 +325,17 @@ func differenceInternal(sourceClnt, targetClnt Client, sourceURL, targetURL stri
|
||||
|
||||
// objectDifference function finds the difference between all objects
|
||||
// recursively in sorted order from source and target.
|
||||
func difference(sourceClnt, targetClnt Client, sourceURL, targetURL string, isMetadata bool, isRecursive, returnSimilar bool, dirOpt DirOpt) (diffCh chan diffMessage) {
|
||||
func difference(ctx context.Context, sourceClnt, targetClnt Client, sourceURL, targetURL string, isMetadata bool, isRecursive, returnSimilar bool, dirOpt DirOpt) (diffCh chan diffMessage) {
|
||||
diffCh = make(chan diffMessage, 10000)
|
||||
|
||||
go func() {
|
||||
defer close(diffCh)
|
||||
|
||||
doneCh := make(chan struct{}, 1)
|
||||
defer close(doneCh)
|
||||
retryCtx, cancel := context.WithCancel(ctx)
|
||||
defer cancel()
|
||||
|
||||
for range newRetryTimerContinous(time.Second, time.Second*30, minio.MaxJitter, doneCh) {
|
||||
err := differenceInternal(sourceClnt, targetClnt, sourceURL, targetURL,
|
||||
for range newRetryTimerContinous(retryCtx, time.Second, time.Second*30, minio.MaxJitter) {
|
||||
err := differenceInternal(retryCtx, sourceClnt, targetClnt, sourceURL, targetURL,
|
||||
isMetadata, isRecursive, returnSimilar, dirOpt, diffCh)
|
||||
if err != nil {
|
||||
// handle this specifically for filesystem related errors.
|
||||
|
||||
+1
-3
@@ -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(isRecursive, isIncomplete, false, DirFirst)
|
||||
contentCh := clnt.List(globalContext, ListOptions{isRecursive: false, showDir: DirFirst})
|
||||
size := int64(0)
|
||||
for content := range contentCh {
|
||||
if content.Err != nil {
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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.
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
+12
-8
@@ -17,6 +17,7 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
|
||||
"github.com/fatih/color"
|
||||
@@ -104,19 +105,22 @@ func (u eventAddMessage) String() string {
|
||||
return msg
|
||||
}
|
||||
|
||||
func mainEventAdd(ctx *cli.Context) error {
|
||||
func mainEventAdd(cliCtx *cli.Context) error {
|
||||
ctx, cancelEventAdd := context.WithCancel(globalContext)
|
||||
defer cancelEventAdd()
|
||||
|
||||
console.SetColor("Event", color.New(color.FgGreen, color.Bold))
|
||||
|
||||
checkEventAddSyntax(ctx)
|
||||
checkEventAddSyntax(cliCtx)
|
||||
|
||||
args := ctx.Args()
|
||||
args := cliCtx.Args()
|
||||
path := args[0]
|
||||
arn := args[1]
|
||||
ignoreExisting := ctx.Bool("p")
|
||||
ignoreExisting := cliCtx.Bool("p")
|
||||
|
||||
event := strings.Split(ctx.String("event"), ",")
|
||||
prefix := ctx.String("prefix")
|
||||
suffix := ctx.String("suffix")
|
||||
event := strings.Split(cliCtx.String("event"), ",")
|
||||
prefix := cliCtx.String("prefix")
|
||||
suffix := cliCtx.String("suffix")
|
||||
|
||||
client, err := newClient(path)
|
||||
if err != nil {
|
||||
@@ -128,7 +132,7 @@ func mainEventAdd(ctx *cli.Context) error {
|
||||
fatalIf(errDummy().Trace(), "The provided url doesn't point to a S3 server.")
|
||||
}
|
||||
|
||||
err = s3Client.AddNotificationConfig(arn, event, prefix, suffix, ignoreExisting)
|
||||
err = s3Client.AddNotificationConfig(ctx, arn, event, prefix, suffix, ignoreExisting)
|
||||
fatalIf(err, "Cannot enable notification on the specified bucket.")
|
||||
printMsg(eventAddMessage{
|
||||
ARN: arn,
|
||||
|
||||
+8
-4
@@ -17,6 +17,7 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/fatih/color"
|
||||
@@ -96,14 +97,17 @@ func (u eventListMessage) String() string {
|
||||
return msg
|
||||
}
|
||||
|
||||
func mainEventList(ctx *cli.Context) error {
|
||||
func mainEventList(cliCtx *cli.Context) error {
|
||||
ctx, cancelEventList := context.WithCancel(globalContext)
|
||||
defer cancelEventList()
|
||||
|
||||
console.SetColor("ARN", color.New(color.FgGreen, color.Bold))
|
||||
console.SetColor("Event", color.New(color.FgCyan, color.Bold))
|
||||
console.SetColor("Filter", color.New(color.Bold))
|
||||
|
||||
checkEventListSyntax(ctx)
|
||||
checkEventListSyntax(cliCtx)
|
||||
|
||||
args := ctx.Args()
|
||||
args := cliCtx.Args()
|
||||
path := args[0]
|
||||
arn := ""
|
||||
if len(args) > 1 {
|
||||
@@ -120,7 +124,7 @@ func mainEventList(ctx *cli.Context) error {
|
||||
fatalIf(errDummy().Trace(), "The provided url doesn't point to a S3 server.")
|
||||
}
|
||||
|
||||
configs, err := s3Client.ListNotificationConfigs(arn)
|
||||
configs, err := s3Client.ListNotificationConfigs(ctx, arn)
|
||||
fatalIf(err, "Cannot list notifications on the specified bucket.")
|
||||
|
||||
for _, config := range configs {
|
||||
|
||||
+1
-1
@@ -24,7 +24,7 @@ var (
|
||||
|
||||
var eventCmd = cli.Command{
|
||||
Name: "event",
|
||||
Usage: "configure object notifications",
|
||||
Usage: "manage object notifications",
|
||||
HideHelpCommand: true,
|
||||
Action: mainEvent,
|
||||
Before: setGlobalsFromContext,
|
||||
|
||||
+11
-12
@@ -17,10 +17,9 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"github.com/minio/minio-go/v6"
|
||||
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/cli"
|
||||
json "github.com/minio/mc/pkg/colorjson"
|
||||
@@ -102,12 +101,15 @@ func (u eventRemoveMessage) String() string {
|
||||
return msg
|
||||
}
|
||||
|
||||
func mainEventRemove(ctx *cli.Context) error {
|
||||
func mainEventRemove(cliCtx *cli.Context) error {
|
||||
ctx, cancelEventRemove := context.WithCancel(globalContext)
|
||||
defer cancelEventRemove()
|
||||
|
||||
console.SetColor("Event", color.New(color.FgGreen, color.Bold))
|
||||
|
||||
checkEventRemoveSyntax(ctx)
|
||||
checkEventRemoveSyntax(cliCtx)
|
||||
|
||||
args := ctx.Args()
|
||||
args := cliCtx.Args()
|
||||
path := args.Get(0)
|
||||
|
||||
arn := ""
|
||||
@@ -126,15 +128,12 @@ func mainEventRemove(ctx *cli.Context) error {
|
||||
}
|
||||
|
||||
// flags for the attributes of the even
|
||||
event := ctx.String("event")
|
||||
prefix := ctx.String("prefix")
|
||||
suffix := ctx.String("suffix")
|
||||
event := cliCtx.String("event")
|
||||
prefix := cliCtx.String("prefix")
|
||||
suffix := cliCtx.String("suffix")
|
||||
|
||||
err = s3Client.RemoveNotificationConfig(arn, event, prefix, suffix)
|
||||
err = s3Client.RemoveNotificationConfig(ctx, arn, event, prefix, suffix)
|
||||
if err != nil {
|
||||
if err.Cause == minio.ErrNoNotificationConfigMatch {
|
||||
fatalIf(err, "Remove event failed.")
|
||||
}
|
||||
fatalIf(err, "Cannot disable notification on the specified bucket.")
|
||||
}
|
||||
|
||||
|
||||
+33
-28
@@ -17,7 +17,9 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
humanize "github.com/dustin/go-humanize"
|
||||
"github.com/fatih/color"
|
||||
@@ -154,8 +156,8 @@ EXAMPLES:
|
||||
}
|
||||
|
||||
// checkFindSyntax - validate the passed arguments
|
||||
func checkFindSyntax(ctx *cli.Context, encKeyDB map[string][]prefixSSEPair) {
|
||||
args := ctx.Args()
|
||||
func checkFindSyntax(ctx context.Context, cliCtx *cli.Context, encKeyDB map[string][]prefixSSEPair) {
|
||||
args := cliCtx.Args()
|
||||
if !args.Present() {
|
||||
args = []string{"./"} // No args just default to present directory.
|
||||
} else if args.Get(0) == "." {
|
||||
@@ -170,10 +172,10 @@ func checkFindSyntax(ctx *cli.Context, encKeyDB map[string][]prefixSSEPair) {
|
||||
|
||||
// Extract input URLs and validate.
|
||||
for _, url := range args {
|
||||
_, _, err := url2Stat(url, false, encKeyDB)
|
||||
_, _, err := url2Stat(ctx, url, "", false, encKeyDB, time.Time{})
|
||||
if err != nil && !isURLPrefixExists(url, false) {
|
||||
// Bucket name empty is a valid error for 'find myminio' unless we are using watch, treat it as such.
|
||||
if _, ok := err.ToGoError().(BucketNameEmpty); ok && !ctx.Bool("watch") {
|
||||
if _, ok := err.ToGoError().(BucketNameEmpty); ok && !cliCtx.Bool("watch") {
|
||||
continue
|
||||
}
|
||||
fatalIf(err.Trace(url), "Unable to stat `"+url+"`.")
|
||||
@@ -207,18 +209,21 @@ type findContext struct {
|
||||
}
|
||||
|
||||
// mainFind - handler for mc find commands
|
||||
func mainFind(ctx *cli.Context) error {
|
||||
func mainFind(cliCtx *cli.Context) error {
|
||||
ctx, cancelFind := context.WithCancel(globalContext)
|
||||
defer cancelFind()
|
||||
|
||||
// Additional command specific theme customization.
|
||||
console.SetColor("Find", color.New(color.FgGreen, color.Bold))
|
||||
console.SetColor("FindExecErr", color.New(color.FgRed, color.Italic, color.Bold))
|
||||
|
||||
// Parse encryption keys per command.
|
||||
encKeyDB, err := getEncKeys(ctx)
|
||||
encKeyDB, err := getEncKeys(cliCtx)
|
||||
fatalIf(err, "Unable to parse encryption keys.")
|
||||
|
||||
checkFindSyntax(ctx, encKeyDB)
|
||||
checkFindSyntax(ctx, cliCtx, encKeyDB)
|
||||
|
||||
args := ctx.Args()
|
||||
args := cliCtx.Args()
|
||||
if !args.Present() {
|
||||
args = []string{"./"} // Not args present default to present directory.
|
||||
} else if args.Get(0) == "." {
|
||||
@@ -230,11 +235,11 @@ func mainFind(ctx *cli.Context) error {
|
||||
|
||||
var olderThan, newerThan string
|
||||
|
||||
if ctx.String("older-than") != "" {
|
||||
olderThan = ctx.String("older-than")
|
||||
if cliCtx.String("older-than") != "" {
|
||||
olderThan = cliCtx.String("older-than")
|
||||
}
|
||||
if ctx.String("newer-than") != "" {
|
||||
newerThan = ctx.String("newer-than")
|
||||
if cliCtx.String("newer-than") != "" {
|
||||
newerThan = cliCtx.String("newer-than")
|
||||
}
|
||||
|
||||
// Use 'e' to indicate Go error, this is a convention followed in `mc`. For probe.Error we call it
|
||||
@@ -242,14 +247,14 @@ func mainFind(ctx *cli.Context) error {
|
||||
var e error
|
||||
var largerSize, smallerSize uint64
|
||||
|
||||
if ctx.String("larger") != "" {
|
||||
largerSize, e = humanize.ParseBytes(ctx.String("larger"))
|
||||
fatalIf(probe.NewError(e).Trace(ctx.String("larger")), "Unable to parse input bytes.")
|
||||
if cliCtx.String("larger") != "" {
|
||||
largerSize, e = humanize.ParseBytes(cliCtx.String("larger"))
|
||||
fatalIf(probe.NewError(e).Trace(cliCtx.String("larger")), "Unable to parse input bytes.")
|
||||
}
|
||||
|
||||
if ctx.String("smaller") != "" {
|
||||
smallerSize, e = humanize.ParseBytes(ctx.String("smaller"))
|
||||
fatalIf(probe.NewError(e).Trace(ctx.String("smaller")), "Unable to parse input bytes.")
|
||||
if cliCtx.String("smaller") != "" {
|
||||
smallerSize, e = humanize.ParseBytes(cliCtx.String("smaller"))
|
||||
fatalIf(probe.NewError(e).Trace(cliCtx.String("smaller")), "Unable to parse input bytes.")
|
||||
}
|
||||
|
||||
targetAlias, _, hostCfg, err := expandAlias(args[0])
|
||||
@@ -260,20 +265,20 @@ func mainFind(ctx *cli.Context) error {
|
||||
targetFullURL = hostCfg.URL
|
||||
}
|
||||
|
||||
return doFind(&findContext{
|
||||
Context: ctx,
|
||||
maxDepth: ctx.Uint("maxdepth"),
|
||||
execCmd: ctx.String("exec"),
|
||||
printFmt: ctx.String("print"),
|
||||
namePattern: ctx.String("name"),
|
||||
pathPattern: ctx.String("path"),
|
||||
regexPattern: ctx.String("regex"),
|
||||
ignorePattern: ctx.String("ignore"),
|
||||
return doFind(ctx, &findContext{
|
||||
Context: cliCtx,
|
||||
maxDepth: cliCtx.Uint("maxdepth"),
|
||||
execCmd: cliCtx.String("exec"),
|
||||
printFmt: cliCtx.String("print"),
|
||||
namePattern: cliCtx.String("name"),
|
||||
pathPattern: cliCtx.String("path"),
|
||||
regexPattern: cliCtx.String("regex"),
|
||||
ignorePattern: cliCtx.String("ignore"),
|
||||
olderThan: olderThan,
|
||||
newerThan: newerThan,
|
||||
largerSize: largerSize,
|
||||
smallerSize: smallerSize,
|
||||
watch: ctx.Bool("watch"),
|
||||
watch: cliCtx.Bool("watch"),
|
||||
targetAlias: targetAlias,
|
||||
targetURL: args[0],
|
||||
targetFullURL: targetFullURL,
|
||||
|
||||
+18
-17
@@ -18,6 +18,7 @@ package cmd
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
@@ -131,7 +132,7 @@ func execFind(command string) {
|
||||
// watchFind - enables listening on the input path, listens for all file/object
|
||||
// created actions. Asynchronously executes the input command line, also allows
|
||||
// formatting for the command line in accordance with subsititution arguments.
|
||||
func watchFind(ctx *findContext) {
|
||||
func watchFind(ctxCtx context.Context, ctx *findContext) {
|
||||
// Watch is not enabled, return quickly.
|
||||
if !ctx.watch {
|
||||
return
|
||||
@@ -140,7 +141,7 @@ func watchFind(ctx *findContext) {
|
||||
Recursive: true,
|
||||
Events: []string{"put"},
|
||||
}
|
||||
watchObj, err := ctx.clnt.Watch(options)
|
||||
watchObj, err := ctx.clnt.Watch(ctxCtx, options)
|
||||
fatalIf(err.Trace(ctx.targetAlias), "Cannot watch with given options.")
|
||||
|
||||
// Loop until user CTRL-C the command line.
|
||||
@@ -162,7 +163,7 @@ func watchFind(ctx *findContext) {
|
||||
continue
|
||||
}
|
||||
|
||||
find(ctx, contentMessage{
|
||||
find(ctxCtx, ctx, contentMessage{
|
||||
Key: getAliasedPath(ctx, event.Path),
|
||||
Time: time,
|
||||
Size: event.Size,
|
||||
@@ -220,7 +221,7 @@ func getAliasedPath(ctx *findContext, path string) string {
|
||||
return trimSuffixAtMaxDepth(ctx.targetURL, aliasedPath, separator, ctx.maxDepth)
|
||||
}
|
||||
|
||||
func find(ctx *findContext, fileContent contentMessage) {
|
||||
func find(ctxCtx context.Context, ctx *findContext, fileContent contentMessage) {
|
||||
// Match the incoming content, didn't match return.
|
||||
if !matchFind(ctx, fileContent) {
|
||||
return
|
||||
@@ -228,27 +229,27 @@ func find(ctx *findContext, fileContent contentMessage) {
|
||||
|
||||
// proceed to either exec, format the output string.
|
||||
if ctx.execCmd != "" {
|
||||
execFind(stringsReplace(ctx.execCmd, fileContent))
|
||||
execFind(stringsReplace(ctxCtx, ctx.execCmd, fileContent))
|
||||
return
|
||||
}
|
||||
if ctx.printFmt != "" {
|
||||
fileContent.Key = stringsReplace(ctx.printFmt, fileContent)
|
||||
fileContent.Key = stringsReplace(ctxCtx, ctx.printFmt, fileContent)
|
||||
}
|
||||
printMsg(findMessage{fileContent})
|
||||
}
|
||||
|
||||
// doFind - find is main function body which interprets and executes
|
||||
// all the input parameters.
|
||||
func doFind(ctx *findContext) error {
|
||||
func doFind(ctxCtx context.Context, ctx *findContext) error {
|
||||
// If watch is enabled we will wait on the prefix perpetually
|
||||
// for all I/O events until canceled by user, if watch is not enabled
|
||||
// following defer is a no-op.
|
||||
defer watchFind(ctx)
|
||||
defer watchFind(ctxCtx, ctx)
|
||||
|
||||
var prevKeyName string
|
||||
|
||||
// iterate over all content which is within the given directory
|
||||
for content := range ctx.clnt.List(true, false, false, DirNone) {
|
||||
for content := range ctx.clnt.List(globalContext, ListOptions{isRecursive: true, showDir: DirNone}) {
|
||||
if content.Err != nil {
|
||||
switch content.Err.ToGoError().(type) {
|
||||
// handle this specifically for filesystem related errors.
|
||||
@@ -288,11 +289,11 @@ func doFind(ctx *findContext) error {
|
||||
|
||||
// proceed to either exec, format the output string.
|
||||
if ctx.execCmd != "" {
|
||||
execFind(stringsReplace(ctx.execCmd, fileContent))
|
||||
execFind(stringsReplace(ctxCtx, ctx.execCmd, fileContent))
|
||||
continue
|
||||
}
|
||||
if ctx.printFmt != "" {
|
||||
fileContent.Key = stringsReplace(ctx.printFmt, fileContent)
|
||||
fileContent.Key = stringsReplace(ctxCtx, ctx.printFmt, fileContent)
|
||||
}
|
||||
|
||||
printMsg(findMessage{fileContent})
|
||||
@@ -305,7 +306,7 @@ func doFind(ctx *findContext) error {
|
||||
|
||||
// stringsReplace - formats the string to remove {} and replace each
|
||||
// with the appropriate argument
|
||||
func stringsReplace(args string, fileContent contentMessage) string {
|
||||
func stringsReplace(ctx context.Context, args string, fileContent contentMessage) string {
|
||||
// replace all instances of {}
|
||||
str := args
|
||||
if strings.Contains(str, "{}") {
|
||||
@@ -359,12 +360,12 @@ func stringsReplace(args string, fileContent contentMessage) string {
|
||||
|
||||
// replace all instances of {url}
|
||||
if strings.Contains(str, "{url}") {
|
||||
str = strings.Replace(str, "{url}", getShareURL(fileContent.Key), -1)
|
||||
str = strings.Replace(str, "{url}", getShareURL(ctx, fileContent.Key), -1)
|
||||
}
|
||||
|
||||
// replace all instances of {"url"}
|
||||
if strings.Contains(str, `{"url"}`) {
|
||||
str = strings.Replace(str, `{"url"}`, strconv.Quote(getShareURL(fileContent.Key)), -1)
|
||||
str = strings.Replace(str, `{"url"}`, strconv.Quote(getShareURL(ctx, fileContent.Key)), -1)
|
||||
}
|
||||
|
||||
return str
|
||||
@@ -414,14 +415,14 @@ var defaultSevenDays = time.Duration(604800) * time.Second
|
||||
|
||||
// getShareURL is used in conjunction with the {url} substitution
|
||||
// argument to generate and return presigned URLs, returns error if any.
|
||||
func getShareURL(path string) string {
|
||||
func getShareURL(ctx context.Context, path string) string {
|
||||
targetAlias, targetURLFull, _, err := expandAlias(path)
|
||||
fatalIf(err.Trace(path), "Unable to expand alias.")
|
||||
|
||||
clnt, err := newClientFromAlias(targetAlias, targetURLFull)
|
||||
fatalIf(err.Trace(targetAlias, targetURLFull), "Unable to initialize client instance from alias.")
|
||||
|
||||
content, err := clnt.Stat(false, false, nil)
|
||||
content, err := clnt.Stat(ctx, StatOptions{})
|
||||
fatalIf(err.Trace(targetURLFull, targetAlias), "Unable to lookup file/object.")
|
||||
|
||||
// Skip if its a directory.
|
||||
@@ -434,7 +435,7 @@ func getShareURL(path string) string {
|
||||
fatalIf(err.Trace(targetAlias, objectURL), "Unable to initialize new client from alias.")
|
||||
|
||||
// Set default expiry for each url (point of no longer valid), to be 7 days
|
||||
shareURL, err := newClnt.ShareDownload(defaultSevenDays)
|
||||
shareURL, err := newClnt.ShareDownload(ctx, defaultSevenDays)
|
||||
fatalIf(err.Trace(targetAlias, objectURL), "Unable to generate share url.")
|
||||
|
||||
return shareURL
|
||||
|
||||
+2
-1
@@ -17,6 +17,7 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os/exec"
|
||||
"strings"
|
||||
"testing"
|
||||
@@ -410,7 +411,7 @@ func TestStringReplace(t *testing.T) {
|
||||
},
|
||||
}
|
||||
for i, testCase := range testCases {
|
||||
gotStr := stringsReplace(testCase.str, testCase.content)
|
||||
gotStr := stringsReplace(context.Background(), testCase.str, testCase.content)
|
||||
if gotStr != testCase.expectedStr {
|
||||
t.Errorf("Test %d: Expected %s, got %s", i+1, testCase.expectedStr, gotStr)
|
||||
}
|
||||
|
||||
+6
-6
@@ -26,7 +26,7 @@ import (
|
||||
)
|
||||
|
||||
const (
|
||||
globalMCConfigVersion = "9"
|
||||
globalMCConfigVersion = "10"
|
||||
|
||||
globalMCConfigFile = "config.json"
|
||||
globalMCCertsDir = "certs"
|
||||
@@ -83,11 +83,11 @@ func setGlobals(quiet, debug, json, noColor, insecure bool) {
|
||||
|
||||
// Set global states. NOTE: It is deliberately kept monolithic to ensure we dont miss out any flags.
|
||||
func setGlobalsFromContext(ctx *cli.Context) error {
|
||||
quiet := ctx.IsSet("quiet")
|
||||
debug := ctx.IsSet("debug")
|
||||
json := ctx.IsSet("json")
|
||||
noColor := ctx.IsSet("no-color")
|
||||
insecure := ctx.IsSet("insecure")
|
||||
quiet := ctx.IsSet("quiet") || ctx.GlobalIsSet("quiet")
|
||||
debug := ctx.IsSet("debug") || ctx.GlobalIsSet("debug")
|
||||
json := ctx.IsSet("json") || ctx.GlobalIsSet("json")
|
||||
noColor := ctx.IsSet("no-color") || ctx.GlobalIsSet("no-color")
|
||||
insecure := ctx.IsSet("insecure") || ctx.GlobalIsSet("insecure")
|
||||
setGlobals(quiet, debug, json, noColor, insecure)
|
||||
return nil
|
||||
}
|
||||
|
||||
+2
-1
@@ -20,6 +20,7 @@ import (
|
||||
"bufio"
|
||||
"compress/bzip2"
|
||||
"compress/gzip"
|
||||
"context"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
@@ -84,7 +85,7 @@ func headURL(sourceURL string, encKeyDB map[string][]prefixSSEPair, nlines int64
|
||||
default:
|
||||
var err *probe.Error
|
||||
var metadata map[string]string
|
||||
if reader, metadata, err = getSourceStreamMetadataFromURL(sourceURL, encKeyDB); err != nil {
|
||||
if reader, metadata, err = getSourceStreamMetadataFromURL(context.Background(), sourceURL, encKeyDB); err != nil {
|
||||
return err.Trace(sourceURL)
|
||||
}
|
||||
ctype := metadata["Content-Type"]
|
||||
|
||||
+22
-9
@@ -17,10 +17,14 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/mc/cmd/ilm"
|
||||
json "github.com/minio/mc/pkg/colorjson"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
minio "github.com/minio/minio-go/v7"
|
||||
"github.com/minio/minio-go/v7/pkg/lifecycle"
|
||||
"github.com/minio/minio/pkg/console"
|
||||
)
|
||||
|
||||
@@ -51,7 +55,7 @@ EXAMPLES:
|
||||
|
||||
2. Add rule for testbucket on s3. Both expiry and transition are number of days.
|
||||
{{.Prompt}} {{.HelpName}} --id "Docs" --prefix "doc/" \
|
||||
--expiry-days "200" --transition-days "300 days" \
|
||||
--expiry-days "300" --transition-days "200" \
|
||||
--storage-class "GLACIER" s3/testbucket
|
||||
|
||||
3. Add rule for testbucket on s3. Only expiry is given as number of days and transition is not set.
|
||||
@@ -129,30 +133,39 @@ func checkILMAddSyntax(ctx *cli.Context) {
|
||||
}
|
||||
|
||||
// Calls SetBucketLifecycle with the XML representation of lifecycleConfiguration type.
|
||||
func mainILMAdd(ctx *cli.Context) error {
|
||||
checkILMAddSyntax(ctx)
|
||||
func mainILMAdd(cliCtx *cli.Context) error {
|
||||
ctx, cancelILMAdd := context.WithCancel(globalContext)
|
||||
defer cancelILMAdd()
|
||||
|
||||
checkILMAddSyntax(cliCtx)
|
||||
setILMDisplayColorScheme()
|
||||
args := ctx.Args()
|
||||
args := cliCtx.Args()
|
||||
urlStr := args.Get(0)
|
||||
|
||||
client, err := newClient(urlStr)
|
||||
fatalIf(err.Trace(urlStr), "Unable to initialize client for "+urlStr)
|
||||
|
||||
// Configuration that is already set.
|
||||
lfcCfg, err := client.GetLifecycle()
|
||||
fatalIf(err.Trace(args...), "Unable to fetch lifecycle rules for "+urlStr)
|
||||
lfcCfg, err := client.GetLifecycle(ctx)
|
||||
if err != nil {
|
||||
if e := err.ToGoError(); minio.ToErrorResponse(e).Code == "NoSuchLifecycleConfiguration" {
|
||||
lfcCfg = lifecycle.NewConfiguration()
|
||||
} else {
|
||||
fatalIf(err.Trace(args...), "Unable to fetch lifecycle rules for "+urlStr)
|
||||
}
|
||||
}
|
||||
|
||||
// Configuration that needs to be set is returned by ilm.GetILMConfigToSet.
|
||||
// A new rule is added or the rule (if existing) is replaced
|
||||
lfcCfg, err = ilm.ApplyNewILMConfig(ctx, lfcCfg)
|
||||
lfcCfg, err = ilm.ApplyNewILMConfig(cliCtx, lfcCfg)
|
||||
fatalIf(err.Trace(args...), "Unable to generate new lifecyle rules for the input")
|
||||
|
||||
fatalIf(client.SetLifecycle(lfcCfg).Trace(urlStr), "Unable to set new lifecycle rules")
|
||||
fatalIf(client.SetLifecycle(ctx, lfcCfg).Trace(urlStr), "Unable to set new lifecycle rules")
|
||||
|
||||
printMsg(ilmAddMessage{
|
||||
Status: "success",
|
||||
Target: urlStr,
|
||||
ID: ctx.String("id"),
|
||||
ID: cliCtx.String("id"),
|
||||
})
|
||||
|
||||
return nil
|
||||
|
||||
+16
-12
@@ -17,12 +17,13 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/mc/cmd/ilm"
|
||||
json "github.com/minio/mc/pkg/colorjson"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/minio-go/v7/pkg/lifecycle"
|
||||
)
|
||||
|
||||
var ilmExportCmd = cli.Command{
|
||||
@@ -50,13 +51,13 @@ EXAMPLES:
|
||||
}
|
||||
|
||||
type ilmExportMessage struct {
|
||||
Status string `json:"status"`
|
||||
Target string `json:"target"`
|
||||
ILMConfig ilm.LifecycleConfiguration `json:"ilmConfig"`
|
||||
Status string `json:"status"`
|
||||
Target string `json:"target"`
|
||||
Config *lifecycle.Configuration `json:"config"`
|
||||
}
|
||||
|
||||
func (i ilmExportMessage) String() string {
|
||||
msgBytes, e := json.MarshalIndent(i.ILMConfig, "", " ")
|
||||
msgBytes, e := json.MarshalIndent(i.Config, "", " ")
|
||||
fatalIf(probe.NewError(e), "Unable to export ILM configuration")
|
||||
|
||||
return string(msgBytes)
|
||||
@@ -76,17 +77,20 @@ func checkILMExportSyntax(ctx *cli.Context) {
|
||||
}
|
||||
}
|
||||
|
||||
func mainILMExport(ctx *cli.Context) error {
|
||||
checkILMExportSyntax(ctx)
|
||||
func mainILMExport(cliCtx *cli.Context) error {
|
||||
ctx, cancelILMExport := context.WithCancel(globalContext)
|
||||
defer cancelILMExport()
|
||||
|
||||
checkILMExportSyntax(cliCtx)
|
||||
setILMDisplayColorScheme()
|
||||
|
||||
args := ctx.Args()
|
||||
args := cliCtx.Args()
|
||||
urlStr := args.Get(0)
|
||||
|
||||
client, err := newClient(urlStr)
|
||||
fatalIf(err.Trace(args...), "Unable to initialize client for "+urlStr+".")
|
||||
|
||||
ilmCfg, err := client.GetLifecycle()
|
||||
ilmCfg, err := client.GetLifecycle(ctx)
|
||||
fatalIf(err.Trace(args...), "Unable to get lifecycle configuration")
|
||||
if len(ilmCfg.Rules) == 0 {
|
||||
fatalIf(probe.NewError(errors.New("lifecycle configuration not set")).Trace(urlStr),
|
||||
@@ -94,9 +98,9 @@ func mainILMExport(ctx *cli.Context) error {
|
||||
}
|
||||
|
||||
printMsg(ilmExportMessage{
|
||||
Status: "success",
|
||||
Target: urlStr,
|
||||
ILMConfig: ilmCfg,
|
||||
Status: "success",
|
||||
Target: urlStr,
|
||||
Config: ilmCfg,
|
||||
})
|
||||
|
||||
return nil
|
||||
|
||||
+16
-10
@@ -17,12 +17,13 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/mc/cmd/ilm"
|
||||
json "github.com/minio/mc/pkg/colorjson"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/minio-go/v7/pkg/lifecycle"
|
||||
"github.com/minio/minio/pkg/console"
|
||||
)
|
||||
|
||||
@@ -66,15 +67,17 @@ func (i ilmImportMessage) JSON() string {
|
||||
}
|
||||
|
||||
// readILMConfig read from stdin, returns XML.
|
||||
func readILMConfig() (ilm.LifecycleConfiguration, *probe.Error) {
|
||||
func readILMConfig() (*lifecycle.Configuration, *probe.Error) {
|
||||
// User is expected to enter the lifecycleConfiguration instance contents in JSON format
|
||||
var ilmCfg ilm.LifecycleConfiguration
|
||||
var cfg = lifecycle.NewConfiguration()
|
||||
|
||||
// Consume json from STDIN
|
||||
dec := json.NewDecoder(os.Stdin)
|
||||
if e := dec.Decode(&ilmCfg); e != nil {
|
||||
return ilmCfg, probe.NewError(e)
|
||||
if e := dec.Decode(cfg); e != nil {
|
||||
return cfg, probe.NewError(e)
|
||||
}
|
||||
return ilmCfg, nil
|
||||
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
// checkILMImportSyntax - validate arguments passed by user
|
||||
@@ -84,11 +87,14 @@ func checkILMImportSyntax(ctx *cli.Context) {
|
||||
}
|
||||
}
|
||||
|
||||
func mainILMImport(ctx *cli.Context) error {
|
||||
checkILMImportSyntax(ctx)
|
||||
func mainILMImport(cliCtx *cli.Context) error {
|
||||
ctx, cancelILMImport := context.WithCancel(globalContext)
|
||||
defer cancelILMImport()
|
||||
|
||||
checkILMImportSyntax(cliCtx)
|
||||
setILMDisplayColorScheme()
|
||||
|
||||
args := ctx.Args()
|
||||
args := cliCtx.Args()
|
||||
urlStr := args.Get(0)
|
||||
|
||||
client, err := newClient(urlStr)
|
||||
@@ -97,7 +103,7 @@ func mainILMImport(ctx *cli.Context) error {
|
||||
ilmCfg, err := readILMConfig()
|
||||
fatalIf(err.Trace(args...), "Unable to read ILM configuration")
|
||||
|
||||
fatalIf(client.SetLifecycle(ilmCfg).Trace(urlStr), "Unable to set new lifecycle rules")
|
||||
fatalIf(client.SetLifecycle(ctx, ilmCfg).Trace(urlStr), "Unable to set new lifecycle rules")
|
||||
|
||||
printMsg(ilmImportMessage{
|
||||
Status: "success",
|
||||
|
||||
+18
-13
@@ -18,6 +18,7 @@ package cmd
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"strconv"
|
||||
"strings"
|
||||
@@ -26,6 +27,7 @@ import (
|
||||
"github.com/minio/mc/cmd/ilm"
|
||||
json "github.com/minio/mc/pkg/colorjson"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/minio-go/v7/pkg/lifecycle"
|
||||
"github.com/minio/minio/pkg/console"
|
||||
)
|
||||
|
||||
@@ -81,10 +83,10 @@ EXAMPLES:
|
||||
}
|
||||
|
||||
type ilmListMessage struct {
|
||||
Status string `json:"status"`
|
||||
Target string `json:"target"`
|
||||
Context *cli.Context `json:"-"`
|
||||
ILMConfig ilm.LifecycleConfiguration `json:"ilmConfig"`
|
||||
Status string `json:"status"`
|
||||
Target string `json:"target"`
|
||||
Context *cli.Context `json:"-"`
|
||||
Config *lifecycle.Configuration `json:"config"`
|
||||
}
|
||||
|
||||
func (i ilmListMessage) String() string {
|
||||
@@ -101,7 +103,7 @@ func (i ilmListMessage) String() string {
|
||||
var tagRows map[string][]string
|
||||
var tbl PrettyTable
|
||||
|
||||
ilm.PopulateILMDataForDisplay(i.ILMConfig, &hdrLabelIndexMap, &alignedHdrLabels,
|
||||
ilm.PopulateILMDataForDisplay(i.Config, &hdrLabelIndexMap, &alignedHdrLabels,
|
||||
&cellDataNoTags, &cellDataWithTags, &tagRows,
|
||||
showAll, showMinimum, showExpiry, showTransition)
|
||||
|
||||
@@ -253,17 +255,20 @@ func getILMRowsWithTags(tbl *PrettyTable, cellDataWithTags *[][]string, newRows
|
||||
return rows
|
||||
}
|
||||
|
||||
func mainILMList(ctx *cli.Context) error {
|
||||
checkILMListSyntax(ctx)
|
||||
func mainILMList(cliCtx *cli.Context) error {
|
||||
ctx, cancelILMList := context.WithCancel(globalContext)
|
||||
defer cancelILMList()
|
||||
|
||||
checkILMListSyntax(cliCtx)
|
||||
setILMDisplayColorScheme()
|
||||
|
||||
args := ctx.Args()
|
||||
args := cliCtx.Args()
|
||||
urlStr := args.Get(0)
|
||||
|
||||
client, err := newClient(urlStr)
|
||||
fatalIf(err.Trace(urlStr), "Unable to initialize client for "+urlStr)
|
||||
|
||||
ilmCfg, err := client.GetLifecycle()
|
||||
ilmCfg, err := client.GetLifecycle(ctx)
|
||||
fatalIf(err.Trace(args...), "Unable to get lifecycle")
|
||||
|
||||
if len(ilmCfg.Rules) == 0 {
|
||||
@@ -272,10 +277,10 @@ func mainILMList(ctx *cli.Context) error {
|
||||
}
|
||||
|
||||
printMsg(ilmListMessage{
|
||||
Status: "success",
|
||||
Target: urlStr,
|
||||
Context: ctx,
|
||||
ILMConfig: ilmCfg,
|
||||
Status: "success",
|
||||
Target: urlStr,
|
||||
Context: cliCtx,
|
||||
Config: ilmCfg,
|
||||
})
|
||||
|
||||
return nil
|
||||
|
||||
+2
-2
@@ -22,9 +22,9 @@ import (
|
||||
"github.com/minio/minio/pkg/console"
|
||||
)
|
||||
|
||||
var ilmCmd = cli.Command{
|
||||
var bucketILMCmd = cli.Command{
|
||||
Name: "ilm",
|
||||
Usage: "configure bucket lifecycle",
|
||||
Usage: "manage bucket lifecycle",
|
||||
Action: mainILM,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
|
||||
+16
-12
@@ -17,6 +17,8 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/mc/cmd/ilm"
|
||||
json "github.com/minio/mc/pkg/colorjson"
|
||||
@@ -54,7 +56,6 @@ USAGE:
|
||||
FLAGS:
|
||||
{{range .VisibleFlags}}{{.}}
|
||||
{{end}}
|
||||
|
||||
DESCRIPTION:
|
||||
Remove a lifecycle configuration rule for the bucket by ID, optionally you can remove
|
||||
all the lifecycle rules on a bucket with '--all --force' option.
|
||||
@@ -63,7 +64,7 @@ EXAMPLES:
|
||||
1. Remove the lifecycle management configuration rule given by ID "Documents" for testbucket on alias 'myminio'. ID is case sensitive.
|
||||
{{.Prompt}} {{.HelpName}} --id "Documents" myminio/testbucket
|
||||
|
||||
2. Remove ALL the lifecycle management configuration rules for testbucket on alias 'myminio'.
|
||||
2. Remove ALL the lifecycle management configuration rules for testbucket on alias 'myminio'.
|
||||
Because the result is complete removal, the use of --force flag is enforced.
|
||||
{{.Prompt}} {{.HelpName}} --all --force myminio/testbucket
|
||||
`,
|
||||
@@ -112,33 +113,36 @@ func checkILMRemoveSyntax(ctx *cli.Context) {
|
||||
}
|
||||
}
|
||||
|
||||
func mainILMRemove(ctx *cli.Context) error {
|
||||
checkILMRemoveSyntax(ctx)
|
||||
func mainILMRemove(cliCtx *cli.Context) error {
|
||||
ctx, cancelILMImport := context.WithCancel(globalContext)
|
||||
defer cancelILMImport()
|
||||
|
||||
checkILMRemoveSyntax(cliCtx)
|
||||
setILMDisplayColorScheme()
|
||||
args := ctx.Args()
|
||||
args := cliCtx.Args()
|
||||
urlStr := args.Get(0)
|
||||
|
||||
client, err := newClient(urlStr)
|
||||
fatalIf(err.Trace(args...), "Unable to initialize client for "+urlStr+".")
|
||||
|
||||
ilmCfg, err := client.GetLifecycle()
|
||||
ilmCfg, err := client.GetLifecycle(ctx)
|
||||
fatalIf(err.Trace(urlStr), "Unable to fetch lifecycle rules")
|
||||
|
||||
ilmAll := ctx.Bool("all")
|
||||
ilmForce := ctx.Bool("force")
|
||||
ilmAll := cliCtx.Bool("all")
|
||||
ilmForce := cliCtx.Bool("force")
|
||||
|
||||
if ilmAll && ilmForce {
|
||||
ilmCfg.Rules = nil // Remove all rules
|
||||
} else {
|
||||
ilmCfg, err = ilm.RemoveILMRule(ilmCfg, ctx.String("id"))
|
||||
fatalIf(err.Trace(urlStr, ctx.String("id")), "Unable to remove rule by id")
|
||||
ilmCfg, err = ilm.RemoveILMRule(ilmCfg, cliCtx.String("id"))
|
||||
fatalIf(err.Trace(urlStr, cliCtx.String("id")), "Unable to remove rule by id")
|
||||
}
|
||||
|
||||
fatalIf(client.SetLifecycle(ilmCfg).Trace(urlStr), "Unable to set lifecycle rules")
|
||||
fatalIf(client.SetLifecycle(ctx, ilmCfg).Trace(urlStr), "Unable to set lifecycle rules")
|
||||
|
||||
printMsg(ilmRmMessage{
|
||||
Status: "success",
|
||||
ID: ctx.String("id"),
|
||||
ID: cliCtx.String("id"),
|
||||
All: ilmAll,
|
||||
Target: urlStr,
|
||||
})
|
||||
|
||||
@@ -1,105 +0,0 @@
|
||||
/*
|
||||
* MinIO Client (C) 2020 MinIO, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
// Package ilm contains all the ilm related functionality. TO BE ACCESSED VIA GET FUNCTIONS or Operation-related Global functions.
|
||||
package ilm
|
||||
|
||||
import (
|
||||
"encoding/xml"
|
||||
"time"
|
||||
)
|
||||
|
||||
// AbortIncompleteMultipartUpload structure
|
||||
type AbortIncompleteMultipartUpload struct {
|
||||
XMLName xml.Name `xml:"AbortIncompleteMultipartUpload,omitempty" json:"-"`
|
||||
DaysAfterInitiation int64 `xml:"DaysAfterInitiation,omitempty" json:"DaysAfterInitiation,omitempty"`
|
||||
}
|
||||
|
||||
// NoncurrentVersionTransition structure
|
||||
type NoncurrentVersionTransition struct {
|
||||
XMLName xml.Name `xml:"NoncurrentVersionTransition,omitempty" json:"-"`
|
||||
StorageClass string `xml:"StorageClass,omitempty" json:"StorageClass,omitempty"`
|
||||
TransitionInDays int `xml:"TransitionInDays,omitempty" json:"TransitionInDays,omitempty"`
|
||||
}
|
||||
|
||||
// LifecycleTag structure key/value pair representing an object tag to apply lifecycle configuration
|
||||
type LifecycleTag struct {
|
||||
XMLName xml.Name `xml:"Tag,omitempty" json:"-"`
|
||||
Key string `xml:"Key,omitempty" json:"Key,omitempty"`
|
||||
Value string `xml:"Value,omitempty" json:"Value,omitempty"`
|
||||
}
|
||||
|
||||
// LifecycleTransition structure - transition details of lifecycle configuration
|
||||
type LifecycleTransition struct {
|
||||
XMLName xml.Name `xml:"Transition" json:"-"`
|
||||
TransitionDate *time.Time `xml:"Date,omitempty" json:"Date,omitempty"`
|
||||
StorageClass string `xml:"StorageClass,omitempty" json:"StorageClass,omitempty"`
|
||||
TransitionInDays int `xml:"Days,omitempty" json:"Days,omitempty"`
|
||||
}
|
||||
|
||||
// IsSet is transition set
|
||||
func (t LifecycleTransition) IsSet() bool {
|
||||
return t.TransitionDate != nil && !t.TransitionDate.IsZero() || t.TransitionInDays > 0
|
||||
}
|
||||
|
||||
// LifecycleAndOperator And Rule for LifecycleTag, to be used in LifecycleRuleFilter
|
||||
type LifecycleAndOperator struct {
|
||||
XMLName xml.Name `xml:"And,omitempty" json:"-"`
|
||||
Prefix string `xml:"Prefix,omitempty" json:"Prefix,omitempty"`
|
||||
Tags []LifecycleTag `xml:"Tag,omitempty" json:"Tags,omitempty"`
|
||||
}
|
||||
|
||||
// LifecycleRuleFilter will be used in selecting rule(s) for lifecycle configuration
|
||||
type LifecycleRuleFilter struct {
|
||||
XMLName xml.Name `xml:"Filter" json:"-"`
|
||||
And *LifecycleAndOperator `xml:"And,omitempty" json:"And,omitempty"`
|
||||
Prefix string `xml:"Prefix,omitempty" json:"Prefix,omitempty"`
|
||||
Tag *LifecycleTag `xml:"Tag,omitempty" json:"-"`
|
||||
}
|
||||
|
||||
// LifecycleExpiration structure - expiration details of lifecycle configuration
|
||||
type LifecycleExpiration struct {
|
||||
XMLName xml.Name `xml:"Expiration,omitempty" json:"-"`
|
||||
ExpirationDate *time.Time `xml:"Date,omitempty" json:"Date,omitempty"`
|
||||
ExpirationInDays int `xml:"Days,omitempty" json:"Days,omitempty"`
|
||||
}
|
||||
|
||||
// IsSet - is LifecycleExpiration set?
|
||||
func (e LifecycleExpiration) IsSet() bool {
|
||||
return e.ExpirationDate != nil && !e.ExpirationDate.IsZero() || e.ExpirationInDays > 0
|
||||
}
|
||||
|
||||
// LifecycleRule represents a single rule in lifecycle configuration
|
||||
type LifecycleRule struct {
|
||||
XMLName xml.Name `xml:"Rule,omitempty" json:"-"`
|
||||
AbortIncompleteMultipartUpload *AbortIncompleteMultipartUpload `xml:"AbortIncompleteMultipartUpload,omitempty" json:"AbortIncompleteMultipartUpload,omitempty"`
|
||||
Expiration *LifecycleExpiration `xml:"Expiration,omitempty" json:"Expiration,omitempty"`
|
||||
ID string `xml:"ID" json:"ID"`
|
||||
RuleFilter *LifecycleRuleFilter `xml:"Filter,omitempty" json:"Filter,omitempty"`
|
||||
NoncurrentVersionTransition *NoncurrentVersionTransition `xml:"NoncurrentVersionTransition,omitempty" json:"NoncurrentVersionTransition,omitempty"`
|
||||
NoncurrentVersionTransitions []NoncurrentVersionTransition `xml:"NoncurrentVersionTransitions,omitempty" json:"NoncurrentVersionTransitions,omitempty"`
|
||||
Prefix string `xml:"Prefix,omitempty" json:"Prefix,omitempty"`
|
||||
Status string `xml:"Status" json:"Status"`
|
||||
Transition *LifecycleTransition `xml:"Transition,omitempty" json:"Transition,omitempty"`
|
||||
Transitions []LifecycleTransition `xml:"Transitions,omitempty" json:"Transitions,omitempty"`
|
||||
TagFilters []LifecycleTag `xml:"Tag,omitempty" json:"Tags,omitempty"`
|
||||
}
|
||||
|
||||
// LifecycleConfiguration is a collection of LifecycleRule objects.
|
||||
type LifecycleConfiguration struct {
|
||||
XMLName xml.Name `xml:"LifecycleConfiguration,omitempty" json:"-"`
|
||||
Rules []LifecycleRule `xml:"Rule"`
|
||||
}
|
||||
+24
-29
@@ -23,6 +23,7 @@ import (
|
||||
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/minio-go/v7/pkg/lifecycle"
|
||||
)
|
||||
|
||||
const defaultILMDateFormat string = "2006-01-02"
|
||||
@@ -73,7 +74,10 @@ func getRightAligned(label string, maxLen int) string {
|
||||
}
|
||||
|
||||
// RemoveILMRule - Remove the ILM rule (with ilmID) from the configuration in XML that is provided.
|
||||
func RemoveILMRule(lfcCfg LifecycleConfiguration, ilmID string) (LifecycleConfiguration, *probe.Error) {
|
||||
func RemoveILMRule(lfcCfg *lifecycle.Configuration, ilmID string) (*lifecycle.Configuration, *probe.Error) {
|
||||
if lfcCfg == nil {
|
||||
return lfcCfg, probe.NewError(fmt.Errorf("lifecycle configuration not set"))
|
||||
}
|
||||
if len(lfcCfg.Rules) == 0 {
|
||||
return lfcCfg, probe.NewError(fmt.Errorf("lifecycle configuration not set"))
|
||||
}
|
||||
@@ -105,69 +109,60 @@ type lifecycleOptions struct {
|
||||
StorageClass string
|
||||
}
|
||||
|
||||
func (opts lifecycleOptions) ToConfig(lfcCfg LifecycleConfiguration) (LifecycleConfiguration, *probe.Error) {
|
||||
ilmExpiry, err := parseExpiry(opts.ExpiryDate, opts.ExpiryDays)
|
||||
func (opts lifecycleOptions) ToConfig(config *lifecycle.Configuration) (*lifecycle.Configuration, *probe.Error) {
|
||||
expiry, err := parseExpiry(opts.ExpiryDate, opts.ExpiryDays)
|
||||
if err != nil {
|
||||
return lfcCfg, err.Trace(opts.ExpiryDate, opts.ExpiryDays)
|
||||
return nil, err.Trace(opts.ExpiryDate, opts.ExpiryDays)
|
||||
}
|
||||
|
||||
ilmTransition, err := parseTransition(opts.StorageClass, opts.TransitionDate, opts.TransitionDays)
|
||||
transition, err := parseTransition(opts.StorageClass, opts.TransitionDate, opts.TransitionDays)
|
||||
if err != nil {
|
||||
return lfcCfg, err.Trace(opts.StorageClass, opts.TransitionDate, opts.TransitionDays)
|
||||
return nil, err.Trace(opts.StorageClass, opts.TransitionDate, opts.TransitionDays)
|
||||
}
|
||||
|
||||
andVal := LifecycleAndOperator{
|
||||
andVal := lifecycle.And{
|
||||
Tags: extractILMTags(opts.Tags),
|
||||
}
|
||||
|
||||
filter := LifecycleRuleFilter{Prefix: opts.Prefix}
|
||||
filter := lifecycle.Filter{Prefix: opts.Prefix}
|
||||
if len(andVal.Tags) > 0 {
|
||||
filter.And = &andVal
|
||||
filter.And = andVal
|
||||
filter.And.Prefix = opts.Prefix
|
||||
filter.Prefix = ""
|
||||
}
|
||||
|
||||
var expP *LifecycleExpiration
|
||||
var transP *LifecycleTransition
|
||||
if ilmTransition.IsSet() {
|
||||
transP = &ilmTransition
|
||||
}
|
||||
if ilmExpiry.IsSet() {
|
||||
expP = &ilmExpiry
|
||||
}
|
||||
|
||||
newRule := LifecycleRule{
|
||||
newRule := lifecycle.Rule{
|
||||
ID: opts.ID,
|
||||
RuleFilter: &filter,
|
||||
RuleFilter: filter,
|
||||
Status: func() string {
|
||||
if opts.Status {
|
||||
return "Enabled"
|
||||
}
|
||||
return "Disabled"
|
||||
}(),
|
||||
Expiration: expP,
|
||||
Transition: transP,
|
||||
Expiration: expiry,
|
||||
Transition: transition,
|
||||
}
|
||||
|
||||
if err := validateILMRule(newRule); err != nil {
|
||||
return lfcCfg, err.Trace(opts.ID)
|
||||
return nil, err.Trace(opts.ID)
|
||||
}
|
||||
|
||||
ruleFound := false
|
||||
for i, rule := range lfcCfg.Rules {
|
||||
for i, rule := range config.Rules {
|
||||
if rule.ID != newRule.ID {
|
||||
continue
|
||||
}
|
||||
lfcCfg.Rules[i] = newRule
|
||||
config.Rules[i] = newRule
|
||||
ruleFound = true
|
||||
break
|
||||
}
|
||||
|
||||
if !ruleFound {
|
||||
lfcCfg.Rules = append(lfcCfg.Rules, newRule)
|
||||
config.Rules = append(config.Rules, newRule)
|
||||
}
|
||||
|
||||
return lfcCfg, nil
|
||||
return config, nil
|
||||
}
|
||||
|
||||
func getLifecycleOptions(ctx *cli.Context) lifecycleOptions {
|
||||
@@ -186,7 +181,7 @@ func getLifecycleOptions(ctx *cli.Context) lifecycleOptions {
|
||||
|
||||
// ApplyNewILMConfig apply new lifecycle rules to existing lifecycle configuration, this
|
||||
// function returns modified/overwritten rules if any.
|
||||
func ApplyNewILMConfig(ctx *cli.Context, lfcCfg LifecycleConfiguration) (LifecycleConfiguration, *probe.Error) {
|
||||
func ApplyNewILMConfig(ctx *cli.Context, config *lifecycle.Configuration) (*lifecycle.Configuration, *probe.Error) {
|
||||
opts := getLifecycleOptions(ctx)
|
||||
return opts.ToConfig(lfcCfg)
|
||||
return opts.ToConfig(config)
|
||||
}
|
||||
|
||||
+46
-46
@@ -23,17 +23,18 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/minio-go/v7/pkg/lifecycle"
|
||||
)
|
||||
|
||||
// Extracts the tags provided by user. The tagfilter array will be put in lifecycleRule structure.
|
||||
func extractILMTags(tagLabelVal string) []LifecycleTag {
|
||||
var ilmTagKVList []LifecycleTag
|
||||
func extractILMTags(tagLabelVal string) []lifecycle.Tag {
|
||||
var ilmTagKVList []lifecycle.Tag
|
||||
for _, tag := range strings.Split(tagLabelVal, tagSeperator) {
|
||||
if tag == "" {
|
||||
// split returns empty for empty tagLabelVal, skip it.
|
||||
continue
|
||||
}
|
||||
lfcTag := LifecycleTag{}
|
||||
lfcTag := lifecycle.Tag{}
|
||||
kvs := strings.SplitN(tag, keyValSeperator, 2)
|
||||
if len(kvs) == 2 {
|
||||
lfcTag.Key = kvs[0]
|
||||
@@ -49,41 +50,40 @@ func extractILMTags(tagLabelVal string) []LifecycleTag {
|
||||
// Some of these rules are enforced by Amazon S3 standards.
|
||||
// For example: Transition has to happen before Expiry.
|
||||
// Storage class must be specified if transition date/days is provided.
|
||||
func validateTranExpDate(rule LifecycleRule) error {
|
||||
expirySet := (rule.Expiration != nil)
|
||||
expiryDateSet := expirySet && rule.Expiration.ExpirationDate != nil && !rule.Expiration.ExpirationDate.IsZero()
|
||||
expiryDaySet := expirySet && rule.Expiration.ExpirationInDays > 0
|
||||
func validateTranExpDate(rule lifecycle.Rule) error {
|
||||
expiryDateSet := rule.Expiration.IsDateNull()
|
||||
expiryDaySet := rule.Expiration.IsDaysNull()
|
||||
|
||||
transitionSet := (rule.Transition != nil)
|
||||
transitionDateSet := transitionSet && (rule.Transition.TransitionDate != nil && !rule.Transition.TransitionDate.IsZero())
|
||||
transitionDaySet := transitionSet && (rule.Transition.TransitionInDays > 0)
|
||||
transitionSet := !rule.Transition.IsNull()
|
||||
transitionDateSet := transitionSet && !rule.Transition.IsDateNull()
|
||||
transitionDaySet := transitionSet && !rule.Transition.IsDaysNull()
|
||||
errMsg := "Error in Transition/Expiration Date/days compatibility. Transition should happen before Expiration"
|
||||
if transitionDateSet && expiryDateSet {
|
||||
if rule.Expiration.ExpirationDate.Before(*(rule.Transition.TransitionDate)) {
|
||||
if rule.Expiration.Date.Before(rule.Transition.Date.Time) {
|
||||
return errors.New(errMsg)
|
||||
}
|
||||
}
|
||||
if transitionDaySet && expiryDaySet {
|
||||
if rule.Transition.TransitionInDays >= rule.Expiration.ExpirationInDays {
|
||||
if rule.Transition.Days >= rule.Expiration.Days {
|
||||
return errors.New(errMsg)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateTranDays(rule LifecycleRule) error {
|
||||
transitionSet := (rule.Transition != nil)
|
||||
transitionDaySet := transitionSet && (rule.Transition.TransitionInDays > 0)
|
||||
if transitionDaySet && rule.Transition.TransitionInDays < 30 && strings.ToLower(rule.Transition.StorageClass) == "standard_ia" {
|
||||
func validateTranDays(rule lifecycle.Rule) error {
|
||||
transitionSet := !rule.Transition.IsNull()
|
||||
transitionDaySet := transitionSet && !rule.Transition.IsDaysNull()
|
||||
if transitionDaySet && rule.Transition.Days < 30 && strings.ToLower(rule.Transition.StorageClass) == "standard_ia" {
|
||||
return errors.New("Transition Date/Days are less than or equal to 30 when Storage class is STANDARD_IA")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Amazon S3 requires a minimum of one action for a rule to be added.
|
||||
func validateRuleAction(rule LifecycleRule) error {
|
||||
expirySet := (rule.Expiration != nil)
|
||||
transitionSet := (rule.Transition != nil)
|
||||
func validateRuleAction(rule lifecycle.Rule) error {
|
||||
expirySet := !rule.Expiration.IsNull()
|
||||
transitionSet := !rule.Transition.IsNull()
|
||||
if !expirySet && !transitionSet {
|
||||
errMsg := "At least one action (Expiry or Transition) needs to be specified in a rule."
|
||||
return errors.New(errMsg)
|
||||
@@ -92,28 +92,28 @@ func validateRuleAction(rule LifecycleRule) error {
|
||||
}
|
||||
|
||||
// Check if any date is before than cur date
|
||||
func validateTranExpCurdate(rule LifecycleRule) error {
|
||||
var err error
|
||||
expirySet := (rule.Expiration != nil)
|
||||
transitionSet := (rule.Transition != nil)
|
||||
transitionDateSet := transitionSet && (rule.Transition.TransitionDate != nil && !rule.Transition.TransitionDate.IsZero())
|
||||
expiryDateSet := expirySet && rule.Expiration.ExpirationDate != nil && !rule.Expiration.ExpirationDate.IsZero()
|
||||
func validateTranExpCurdate(rule lifecycle.Rule) error {
|
||||
var e error
|
||||
expirySet := !rule.Expiration.IsNull()
|
||||
transitionSet := !rule.Transition.IsNull()
|
||||
transitionDateSet := transitionSet && !rule.Transition.IsDateNull()
|
||||
expiryDateSet := expirySet && !rule.Expiration.IsDateNull()
|
||||
currentTime := time.Now()
|
||||
curTimeStr := currentTime.Format(defaultILMDateFormat)
|
||||
currentTime, err = time.Parse(defaultILMDateFormat, curTimeStr)
|
||||
if err != nil {
|
||||
return err
|
||||
currentTime, e = time.Parse(defaultILMDateFormat, curTimeStr)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
if expirySet && expiryDateSet && rule.Expiration.ExpirationDate.Before(currentTime) {
|
||||
err = errors.New("Expiry date falls before or on today's date")
|
||||
} else if transitionSet && transitionDateSet && rule.Transition.TransitionDate.Before(currentTime) {
|
||||
err = errors.New("Transition date falls before or on today's date")
|
||||
if expirySet && expiryDateSet && rule.Expiration.Date.Before(currentTime) {
|
||||
e = errors.New("Expiry date falls before or on today's date")
|
||||
} else if transitionSet && transitionDateSet && rule.Transition.Date.Before(currentTime) {
|
||||
e = errors.New("Transition date falls before or on today's date")
|
||||
}
|
||||
return err
|
||||
return e
|
||||
}
|
||||
|
||||
// Check S3 compatibility for the new rule and some other basic checks.
|
||||
func validateILMRule(rule LifecycleRule) *probe.Error {
|
||||
func validateILMRule(rule lifecycle.Rule) *probe.Error {
|
||||
if e := validateRuleAction(rule); e != nil {
|
||||
return probe.NewError(e)
|
||||
}
|
||||
@@ -130,23 +130,23 @@ func validateILMRule(rule LifecycleRule) *probe.Error {
|
||||
}
|
||||
|
||||
// Returns valid lifecycleTransition to be included in lifecycleRule
|
||||
func parseTransition(storageClass, transitionDateStr, transitionDayStr string) (transition LifecycleTransition, err *probe.Error) {
|
||||
func parseTransition(storageClass, transitionDateStr, transitionDayStr string) (transition lifecycle.Transition, err *probe.Error) {
|
||||
storageClass = strings.ToUpper(storageClass) // Just-in-case the user has entered lower case characters.
|
||||
if storageClass != "" {
|
||||
if transitionDateStr != "" {
|
||||
transitionDate, e := time.Parse(defaultILMDateFormat, transitionDateStr)
|
||||
if e != nil {
|
||||
return LifecycleTransition{}, probe.NewError(e)
|
||||
return lifecycle.Transition{}, probe.NewError(e)
|
||||
}
|
||||
transition.TransitionDate = &transitionDate
|
||||
transition.Date = lifecycle.ExpirationDate{Time: transitionDate}
|
||||
} else if transitionDayStr != "" {
|
||||
transitionDay, e := strconv.Atoi(transitionDayStr)
|
||||
if e != nil {
|
||||
return LifecycleTransition{}, probe.NewError(e)
|
||||
return lifecycle.Transition{}, probe.NewError(e)
|
||||
}
|
||||
transition.TransitionInDays = transitionDay
|
||||
transition.Days = lifecycle.ExpirationDays(transitionDay)
|
||||
} else {
|
||||
return LifecycleTransition{}, probe.NewError(errors.New("if storage class is set a valid transitionDate or transitionDay must be set"))
|
||||
return lifecycle.Transition{}, probe.NewError(errors.New("if storage class is set a valid transitionDate or transitionDay must be set"))
|
||||
}
|
||||
transition.StorageClass = storageClass
|
||||
}
|
||||
@@ -155,16 +155,16 @@ func parseTransition(storageClass, transitionDateStr, transitionDayStr string) (
|
||||
}
|
||||
|
||||
// Returns lifecycleExpiration to be included in lifecycleRule
|
||||
func parseExpiry(expiryDateStr, expiryDayStr string) (lfcExp LifecycleExpiration, err *probe.Error) {
|
||||
func parseExpiry(expiryDateStr, expiryDayStr string) (lfcExp lifecycle.Expiration, err *probe.Error) {
|
||||
if expiryDateStr != "" {
|
||||
date, e := time.Parse(defaultILMDateFormat, expiryDateStr)
|
||||
if e != nil {
|
||||
return LifecycleExpiration{}, probe.NewError(e)
|
||||
return lifecycle.Expiration{}, probe.NewError(e)
|
||||
}
|
||||
if date.IsZero() {
|
||||
return LifecycleExpiration{}, probe.NewError(errors.New("expiration date cannot be set to zero"))
|
||||
return lifecycle.Expiration{}, probe.NewError(errors.New("expiration date cannot be set to zero"))
|
||||
}
|
||||
lfcExp.ExpirationDate = &date
|
||||
lfcExp.Date = lifecycle.ExpirationDate{Time: date}
|
||||
}
|
||||
|
||||
if expiryDayStr != "" {
|
||||
@@ -173,9 +173,9 @@ func parseExpiry(expiryDateStr, expiryDayStr string) (lfcExp LifecycleExpiration
|
||||
return lfcExp, probe.NewError(e)
|
||||
}
|
||||
if days == 0 {
|
||||
return LifecycleExpiration{}, probe.NewError(errors.New("expiration days cannot be set to zero"))
|
||||
return lifecycle.Expiration{}, probe.NewError(errors.New("expiration days cannot be set to zero"))
|
||||
}
|
||||
lfcExp.ExpirationInDays = days
|
||||
lfcExp.Days = lifecycle.ExpirationDays(days)
|
||||
}
|
||||
|
||||
return lfcExp, nil
|
||||
|
||||
+54
-66
@@ -18,13 +18,15 @@ package ilm
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
|
||||
"github.com/minio/minio-go/v7/pkg/lifecycle"
|
||||
)
|
||||
|
||||
const (
|
||||
// rule ID field column width in table output
|
||||
idColumnWidth int = 12
|
||||
idColumnWidth int = 16
|
||||
// rule prefix field column width in table output
|
||||
prefixColumnWidth int = 10
|
||||
prefixColumnWidth int = 16
|
||||
// StatusColumnWidth column width in table output
|
||||
statusColumnWidth int = 12
|
||||
// ExpiryColumnWidth column width in table output
|
||||
@@ -100,7 +102,7 @@ type showDetails struct {
|
||||
|
||||
// PopulateILMDataForDisplay based on showDetails determined by user input, populate the ILM display
|
||||
// table with information. Table is constructed row-by-row. Headers are first, then the rest of the rows.
|
||||
func PopulateILMDataForDisplay(ilmCfg LifecycleConfiguration, rowCheck *map[string]int, alignedHdrLabels *[]string,
|
||||
func PopulateILMDataForDisplay(ilmCfg *lifecycle.Configuration, rowCheck *map[string]int, alignedHdrLabels *[]string,
|
||||
cellDataNoTags *[][]string, cellDataWithTags *[][]string, tagRows *map[string][]string,
|
||||
showAll, showMin, showExpiry, showTransition bool) {
|
||||
|
||||
@@ -201,18 +203,16 @@ func checkAddTableCellRows(rowArr *[]string, rowCheck map[string]int, showOpts s
|
||||
}
|
||||
|
||||
// The right kind of tick is returned. Cross-tick if expiry is not set.
|
||||
func getExpiryTick(rule LifecycleRule) string {
|
||||
func getExpiryTick(rule lifecycle.Rule) string {
|
||||
expiryTick := crossTickCell
|
||||
expiryDateSet := rule.Expiration != nil && rule.Expiration.ExpirationDate != nil && !rule.Expiration.ExpirationDate.IsZero()
|
||||
expirySet := rule.Expiration != nil && (expiryDateSet || rule.Expiration.ExpirationInDays > 0)
|
||||
if expirySet {
|
||||
if !rule.Expiration.IsNull() {
|
||||
expiryTick = tickCell
|
||||
}
|
||||
return expiryTick
|
||||
}
|
||||
|
||||
// The right kind of tick is returned. Cross-tick if status is 'Disabled' & tick if status is 'Enabled'.
|
||||
func getStatusTick(rule LifecycleRule) string {
|
||||
func getStatusTick(rule lifecycle.Rule) string {
|
||||
statusTick := crossTickCell
|
||||
if rule.Status == statusLabelKey {
|
||||
statusTick = tickCell
|
||||
@@ -221,26 +221,22 @@ func getStatusTick(rule LifecycleRule) string {
|
||||
}
|
||||
|
||||
// Expiry date. 'YYYY-MM-DD'. Set for 00:00:00 GMT as per the standard.
|
||||
func getExpiryDateVal(rule LifecycleRule) string {
|
||||
func getExpiryDateVal(rule lifecycle.Rule) string {
|
||||
expiryDate := blankCell
|
||||
expirySet := (rule.Expiration != nil)
|
||||
expiryDateSet := expirySet && rule.Expiration.ExpirationDate != nil && !rule.Expiration.ExpirationDate.IsZero()
|
||||
if expiryDateSet {
|
||||
expiryDate = strconv.Itoa(rule.Expiration.ExpirationDate.Day()) + " " +
|
||||
rule.Expiration.ExpirationDate.Month().String()[0:3] + " " +
|
||||
strconv.Itoa(rule.Expiration.ExpirationDate.Year())
|
||||
} else if expirySet && rule.Expiration.ExpirationInDays > 0 {
|
||||
expiryDate = strconv.Itoa(rule.Expiration.ExpirationInDays) + " day(s)"
|
||||
if !rule.Expiration.IsDateNull() {
|
||||
expiryDate = strconv.Itoa(rule.Expiration.Date.Day()) + " " +
|
||||
rule.Expiration.Date.Month().String()[0:3] + " " +
|
||||
strconv.Itoa(rule.Expiration.Date.Year())
|
||||
} else if !rule.Expiration.IsDaysNull() {
|
||||
expiryDate = strconv.Itoa(int(rule.Expiration.Days)) + " day(s)"
|
||||
}
|
||||
return expiryDate
|
||||
}
|
||||
|
||||
// Cross-tick if Transition is not set.
|
||||
func getTransitionTick(rule LifecycleRule) string {
|
||||
transitionSet := rule.Transition != nil
|
||||
transitionDateSet := transitionSet && ((rule.Transition.TransitionDate != nil &&
|
||||
!rule.Transition.TransitionDate.IsZero()) ||
|
||||
rule.Transition.TransitionInDays > 0)
|
||||
func getTransitionTick(rule lifecycle.Rule) string {
|
||||
transitionSet := !rule.Transition.IsNull()
|
||||
transitionDateSet := transitionSet && !rule.Transition.IsDateNull()
|
||||
if !transitionSet || !transitionDateSet {
|
||||
return crossTickCell
|
||||
}
|
||||
@@ -248,26 +244,25 @@ func getTransitionTick(rule LifecycleRule) string {
|
||||
}
|
||||
|
||||
// Transition date. 'YYYY-MM-DD'. Set for 00:00:00 GMT as per the standard.
|
||||
func getTransitionDate(rule LifecycleRule) string {
|
||||
func getTransitionDate(rule lifecycle.Rule) string {
|
||||
transitionDate := blankCell
|
||||
transitionSet := (rule.Transition != nil)
|
||||
transitionDateSet := transitionSet && (rule.Transition.TransitionDate != nil &&
|
||||
!rule.Transition.TransitionDate.IsZero())
|
||||
transitionDaySet := transitionSet && (rule.Transition.TransitionInDays > 0)
|
||||
transitionSet := !rule.Transition.IsNull()
|
||||
transitionDateSet := transitionSet && !rule.Transition.IsDateNull()
|
||||
transitionDaySet := transitionSet && !rule.Transition.IsDaysNull()
|
||||
if transitionDateSet {
|
||||
transitionDate = strconv.Itoa(rule.Transition.TransitionDate.Day()) + " " +
|
||||
rule.Transition.TransitionDate.Month().String()[0:3] + " " +
|
||||
strconv.Itoa(rule.Transition.TransitionDate.Year())
|
||||
transitionDate = strconv.Itoa(rule.Transition.Date.Day()) + " " +
|
||||
rule.Transition.Date.Month().String()[0:3] + " " +
|
||||
strconv.Itoa(rule.Transition.Date.Year())
|
||||
} else if transitionDaySet {
|
||||
transitionDate = strconv.Itoa(rule.Transition.TransitionInDays) + " day(s)"
|
||||
transitionDate = strconv.Itoa(int(rule.Transition.Days)) + " day(s)"
|
||||
}
|
||||
return transitionDate
|
||||
}
|
||||
|
||||
// Storage class name for transition.
|
||||
func getStorageClassName(rule LifecycleRule) string {
|
||||
func getStorageClassName(rule lifecycle.Rule) string {
|
||||
storageClass := blankCell
|
||||
transitionSet := (rule.Transition != nil)
|
||||
transitionSet := !rule.Transition.IsNull()
|
||||
storageClassAvail := transitionSet && (rule.Transition.StorageClass != "")
|
||||
if storageClassAvail {
|
||||
storageClass = rule.Transition.StorageClass
|
||||
@@ -276,13 +271,12 @@ func getStorageClassName(rule LifecycleRule) string {
|
||||
}
|
||||
|
||||
// Array of Tag strings, each in key:value format
|
||||
func getTagArr(rule LifecycleRule) []string {
|
||||
tagArr := rule.TagFilters
|
||||
tagLth := len(rule.TagFilters)
|
||||
if len(rule.TagFilters) == 0 && rule.RuleFilter != nil && rule.RuleFilter.And != nil {
|
||||
tagLth = len(rule.RuleFilter.And.Tags)
|
||||
tagArr = rule.RuleFilter.And.Tags
|
||||
func getTagArr(rule lifecycle.Rule) []string {
|
||||
if rule.RuleFilter.And.IsEmpty() {
|
||||
return []string{}
|
||||
}
|
||||
tagArr := rule.RuleFilter.And.Tags
|
||||
tagLth := len(tagArr)
|
||||
tagCellArr := make([]string, len(tagArr))
|
||||
for tagIdx := 0; tagIdx < tagLth; tagIdx++ {
|
||||
tagCellArr[tagIdx] = (tagArr[tagIdx].Key + ":" + tagArr[tagIdx].Value)
|
||||
@@ -302,28 +296,29 @@ func checkAddTableCell(rowArr *[]string, rowCheck map[string]int, cellInfo table
|
||||
if colIdx, ok := rowCheck[cellInfo.labelKey]; ok {
|
||||
if len(cellInfo.label)%2 != 0 && len(cellInfo.label) < cellInfo.columnWidth {
|
||||
cellInfo.label += " "
|
||||
} else if len(cellInfo.label) > (cellInfo.columnWidth - 2) { // 2 dots to indicate text longer than column width
|
||||
cellInfo.label = cellInfo.label[:(cellInfo.columnWidth-6)] + ".."
|
||||
}
|
||||
|
||||
(*rowArr)[colIdx] = getAlignedText(cellInfo.label, cellInfo.align, cellInfo.columnWidth)
|
||||
}
|
||||
}
|
||||
|
||||
// GetILMShowDataWithoutTags - Without tags
|
||||
func getILMShowDataWithoutTags(cellInfo *[][]string, rowCheck map[string]int, info LifecycleConfiguration, showOpts showDetails) {
|
||||
func getILMShowDataWithoutTags(cellInfo *[][]string, rowCheck map[string]int, info *lifecycle.Configuration, showOpts showDetails) {
|
||||
*cellInfo = make([][]string, 0)
|
||||
count := 0
|
||||
for index := 0; index < len(info.Rules); index++ {
|
||||
rule := info.Rules[index]
|
||||
|
||||
showExpiry := (rule.Expiration != nil) && ((rule.Expiration.ExpirationDate != nil && !rule.Expiration.ExpirationDate.IsZero()) ||
|
||||
rule.Expiration.ExpirationInDays > 0)
|
||||
transitionSet := (rule.Transition != nil) && ((rule.Transition.TransitionDate != nil && !rule.Transition.TransitionDate.IsZero()) ||
|
||||
rule.Transition.TransitionInDays > 0)
|
||||
showExpiry := !rule.Expiration.IsNull()
|
||||
transitionSet := !rule.Transition.IsNull()
|
||||
skipExpTran := (showOpts.expiry && !showExpiry) || (showOpts.transition && !transitionSet)
|
||||
if skipExpTran {
|
||||
continue
|
||||
}
|
||||
tagPresent := (rule.RuleFilter != nil) && (rule.RuleFilter.And != nil)
|
||||
if len(rule.TagFilters) > 0 || (tagPresent && len(rule.RuleFilter.And.Tags) > 0) {
|
||||
tagPresent := !rule.RuleFilter.And.IsEmpty()
|
||||
if tagPresent {
|
||||
continue
|
||||
}
|
||||
*cellInfo = append(*cellInfo, make([]string, 0))
|
||||
@@ -350,16 +345,14 @@ func getILMShowDataWithoutTags(cellInfo *[][]string, rowCheck map[string]int, in
|
||||
}
|
||||
|
||||
// GetILMShowDataWithTags Just the data with extra rows for extra tags
|
||||
func getILMShowDataWithTags(cellInfo *[][]string, newRows map[string][]string, rowCheck map[string]int, info LifecycleConfiguration, showOpts showDetails) {
|
||||
func getILMShowDataWithTags(cellInfo *[][]string, newRows map[string][]string, rowCheck map[string]int, info *lifecycle.Configuration, showOpts showDetails) {
|
||||
*cellInfo = make([][]string, 0)
|
||||
count := 0
|
||||
for index := 0; index < len(info.Rules); index++ {
|
||||
rule := info.Rules[index]
|
||||
|
||||
showExpiry := (rule.Expiration != nil) && ((rule.Expiration.ExpirationDate != nil && !rule.Expiration.ExpirationDate.IsZero()) ||
|
||||
rule.Expiration.ExpirationInDays > 0)
|
||||
transitionSet := (rule.Transition != nil) && ((rule.Transition.TransitionDate != nil && !rule.Transition.TransitionDate.IsZero()) ||
|
||||
rule.Transition.TransitionInDays > 0)
|
||||
showExpiry := !rule.Expiration.IsNull()
|
||||
transitionSet := !rule.Transition.IsNull()
|
||||
skipExpTran := (showOpts.expiry && !showExpiry) || (showOpts.transition && !transitionSet)
|
||||
if skipExpTran {
|
||||
continue
|
||||
@@ -391,26 +384,24 @@ func getILMShowDataWithTags(cellInfo *[][]string, newRows map[string][]string, r
|
||||
}
|
||||
}
|
||||
|
||||
func getPrefixVal(rule LifecycleRule) string {
|
||||
func getPrefixVal(rule lifecycle.Rule) string {
|
||||
prefixVal := ""
|
||||
switch {
|
||||
case rule.Prefix != "":
|
||||
prefixVal = rule.Prefix
|
||||
case rule.RuleFilter != nil && rule.RuleFilter.And != nil && rule.RuleFilter.And.Prefix != "":
|
||||
case !rule.RuleFilter.And.IsEmpty():
|
||||
prefixVal = rule.RuleFilter.And.Prefix
|
||||
case rule.RuleFilter != nil && rule.RuleFilter.Prefix != "":
|
||||
case rule.RuleFilter.Prefix != "":
|
||||
prefixVal = rule.RuleFilter.Prefix
|
||||
}
|
||||
return prefixVal
|
||||
}
|
||||
|
||||
func showExpiryDetails(rule LifecycleRule, showOpts showDetails) bool {
|
||||
func showExpiryDetails(rule lifecycle.Rule, showOpts showDetails) bool {
|
||||
if showOpts.allAvailable {
|
||||
return true
|
||||
}
|
||||
expirySet := (rule.Expiration != nil) &&
|
||||
((rule.Expiration.ExpirationDate != nil && !rule.Expiration.ExpirationDate.IsZero()) ||
|
||||
rule.Expiration.ExpirationInDays > 0)
|
||||
expirySet := !rule.Expiration.IsNull()
|
||||
|
||||
return (expirySet && (showOpts.allAvailable || showOpts.expiry))
|
||||
|
||||
@@ -424,27 +415,24 @@ func showTransitionTick(showOpts showDetails) bool {
|
||||
return (showOpts.allAvailable || showOpts.minimum)
|
||||
}
|
||||
|
||||
func showTransitionDetails(rule LifecycleRule, showOpts showDetails) bool {
|
||||
func showTransitionDetails(rule lifecycle.Rule, showOpts showDetails) bool {
|
||||
if showOpts.allAvailable {
|
||||
return true
|
||||
}
|
||||
transitionSet := (rule.Transition != nil) &&
|
||||
((rule.Transition.TransitionDate != nil && !rule.Transition.TransitionDate.IsZero()) ||
|
||||
rule.Transition.TransitionInDays > 0)
|
||||
transitionSet := !rule.Transition.IsNull()
|
||||
transitionDetailsShow := (showOpts.allAvailable || showOpts.transition)
|
||||
return transitionSet && transitionDetailsShow
|
||||
}
|
||||
|
||||
func showTags(rule LifecycleRule, showOpts showDetails) bool {
|
||||
func showTags(rule lifecycle.Rule, showOpts showDetails) bool {
|
||||
if showOpts.minimum {
|
||||
return false
|
||||
}
|
||||
tagSet := showOpts.allAvailable ||
|
||||
(len(rule.TagFilters) > 0 || (rule.RuleFilter != nil && rule.RuleFilter.And != nil && (len(rule.RuleFilter.And.Tags) > 0)))
|
||||
tagSet := showOpts.allAvailable || !rule.RuleFilter.And.IsEmpty()
|
||||
return tagSet
|
||||
}
|
||||
|
||||
func getColumns(info LifecycleConfiguration, rowCheck map[string]int, alignedHdrLabels *[]string, showOpts showDetails) {
|
||||
func getColumns(info *lifecycle.Configuration, rowCheck map[string]int, alignedHdrLabels *[]string, showOpts showDetails) {
|
||||
tagIn := false // Keep tag in the end
|
||||
colIdx := 0
|
||||
colWidthTbl := getILMColumnWidthTable()
|
||||
|
||||
@@ -17,6 +17,7 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
@@ -24,7 +25,7 @@ import (
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/cli"
|
||||
"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"
|
||||
)
|
||||
|
||||
@@ -86,12 +87,15 @@ func (l legalHoldCmdMessage) JSON() string {
|
||||
|
||||
// setRetention - Set Retention for all objects within a given prefix.
|
||||
func setLegalHold(urlStr string, lhold minio.LegalHoldStatus, isRecursive bool) error {
|
||||
ctx, cancelLegalHold := context.WithCancel(globalContext)
|
||||
defer cancelLegalHold()
|
||||
|
||||
clnt, err := newClient(urlStr)
|
||||
if err != nil {
|
||||
fatalIf(err.Trace(), "Cannot parse the provided url.")
|
||||
}
|
||||
if !isRecursive {
|
||||
err = clnt.PutObjectLegalHold(lhold)
|
||||
err = clnt.PutObjectLegalHold(ctx, lhold)
|
||||
if err != nil {
|
||||
errorIf(err.Trace(urlStr), "Failed to set legal hold on `"+urlStr+"` successfully")
|
||||
} else {
|
||||
@@ -107,7 +111,7 @@ func setLegalHold(urlStr string, lhold minio.LegalHoldStatus, isRecursive bool)
|
||||
alias, _, _ := mustExpandAlias(urlStr)
|
||||
var cErr error
|
||||
errorsFound := false
|
||||
for content := range clnt.List(isRecursive, false, false, DirNone) {
|
||||
for content := range clnt.List(ctx, ListOptions{isRecursive: isRecursive, showDir: DirNone}) {
|
||||
if content.Err != nil {
|
||||
errorIf(content.Err.Trace(clnt.GetURL().String()), "Unable to list folder.")
|
||||
cErr = exitStatus(globalErrorExitStatus) // Set the exit status.
|
||||
@@ -119,7 +123,7 @@ func setLegalHold(urlStr string, lhold minio.LegalHoldStatus, isRecursive bool)
|
||||
errorIf(content.Err.Trace(clnt.GetURL().String()), "Invalid URL")
|
||||
continue
|
||||
}
|
||||
probeErr := newClnt.PutObjectLegalHold(lhold)
|
||||
probeErr := newClnt.PutObjectLegalHold(ctx, lhold)
|
||||
if probeErr != nil {
|
||||
errorsFound = true
|
||||
errorIf(probeErr.Trace(content.URL.Path), "Failed to set legal hold on `"+content.URL.Path+"` successfully")
|
||||
|
||||
+89
-25
@@ -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.
|
||||
@@ -17,16 +17,29 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/mc/pkg/ioutils"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/minio/pkg/console"
|
||||
)
|
||||
|
||||
// ls specific flags.
|
||||
var (
|
||||
lsFlags = []cli.Flag{
|
||||
cli.StringFlag{
|
||||
Name: "rewind",
|
||||
Usage: "back in time",
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "versions",
|
||||
Usage: "List all versions",
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "recursive, r",
|
||||
Usage: "list recursively",
|
||||
@@ -72,13 +85,63 @@ EXAMPLES:
|
||||
|
||||
6. List incomplete (previously failed) uploads of objects on Amazon S3.
|
||||
{{.Prompt}} {{.HelpName}} --incomplete s3/mybucket
|
||||
|
||||
7. List contents at a specific time in the past if the bucket versioning is enabled.
|
||||
{{.Prompt}} {{.HelpName}} --rewind 2020.01.01 s3/mybucket
|
||||
{{.Prompt}} {{.HelpName}} --rewind 2020.01.01T11:30 s3/mybucket
|
||||
{{.Prompt}} {{.HelpName}} --rewind 7d s3/mybucket
|
||||
|
||||
8. List all contents versions if the bucket versioning is enabled.
|
||||
{{.Prompt}} {{.HelpName}} --versions s3/mybucket
|
||||
|
||||
`,
|
||||
}
|
||||
|
||||
var rewindSupportedFormat = []string{
|
||||
"2006.01.02",
|
||||
"2006.01.02T15:04",
|
||||
"2006.01.02T15:04:05",
|
||||
time.RFC3339,
|
||||
}
|
||||
|
||||
// Parse rewind flag while considering the system local time zone
|
||||
func parseRewindFlag(rewind string) (timeRef time.Time) {
|
||||
if rewind != "" {
|
||||
location, e := time.LoadLocation("Local")
|
||||
if e != nil {
|
||||
return
|
||||
}
|
||||
|
||||
for _, format := range rewindSupportedFormat {
|
||||
if t, e := time.ParseInLocation(format, rewind, location); e == nil {
|
||||
timeRef = t
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if timeRef.IsZero() {
|
||||
// rewind is not parsed, check if it is a duration instead
|
||||
if duration, e := ioutils.ParseDurationTime(rewind); e == nil {
|
||||
if duration < 0 {
|
||||
fatalIf(probe.NewError(errors.New("negative duration is not supported")),
|
||||
"Unable to parse --rewind argument")
|
||||
}
|
||||
timeRef = time.Now().Add(-duration)
|
||||
}
|
||||
}
|
||||
|
||||
if timeRef.IsZero() {
|
||||
// rewind argument still not parsed, error out
|
||||
fatalIf(probe.NewError(errors.New("unknown format")), "Unable to parse --rewind argument")
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// checkListSyntax - validate all the passed arguments
|
||||
func checkListSyntax(ctx *cli.Context) {
|
||||
args := ctx.Args()
|
||||
if !ctx.Args().Present() {
|
||||
func checkListSyntax(ctx context.Context, cliCtx *cli.Context) ([]string, bool, bool, time.Time, bool) {
|
||||
args := cliCtx.Args()
|
||||
if !cliCtx.Args().Present() {
|
||||
args = []string{"."}
|
||||
}
|
||||
for _, arg := range args {
|
||||
@@ -86,12 +149,18 @@ func checkListSyntax(ctx *cli.Context) {
|
||||
fatalIf(errInvalidArgument().Trace(args...), "Unable to validate empty argument.")
|
||||
}
|
||||
}
|
||||
// extract URLs.
|
||||
URLs := ctx.Args()
|
||||
isIncomplete := ctx.Bool("incomplete")
|
||||
|
||||
for _, url := range URLs {
|
||||
_, _, err := url2Stat(url, false, nil)
|
||||
isRecursive := cliCtx.Bool("recursive")
|
||||
isIncomplete := cliCtx.Bool("incomplete")
|
||||
withOlderVersions := cliCtx.Bool("versions")
|
||||
|
||||
timeRef := parseRewindFlag(cliCtx.String("rewind"))
|
||||
if timeRef.IsZero() && withOlderVersions {
|
||||
timeRef = time.Now().UTC()
|
||||
}
|
||||
|
||||
for _, url := range cliCtx.Args() {
|
||||
_, _, err := url2Stat(ctx, url, "", false, nil, timeRef)
|
||||
if err != nil && !isURLPrefixExists(url, isIncomplete) {
|
||||
// Bucket name empty is a valid error for 'ls myminio',
|
||||
// treat it as such.
|
||||
@@ -103,37 +172,32 @@ func checkListSyntax(ctx *cli.Context) {
|
||||
fatalIf(err.Trace(url), "Unable to stat `"+url+"`.")
|
||||
}
|
||||
}
|
||||
|
||||
return args, isRecursive, isIncomplete, timeRef, withOlderVersions
|
||||
}
|
||||
|
||||
// mainList - is a handler for mc ls command
|
||||
func mainList(ctx *cli.Context) error {
|
||||
func mainList(cliCtx *cli.Context) error {
|
||||
ctx, cancelList := context.WithCancel(globalContext)
|
||||
defer cancelList()
|
||||
|
||||
// Additional command specific theme customization.
|
||||
console.SetColor("File", color.New(color.Bold))
|
||||
console.SetColor("DeletedFile", color.New(color.Bold, color.FgRed))
|
||||
console.SetColor("Dir", color.New(color.FgCyan, color.Bold))
|
||||
console.SetColor("Size", color.New(color.FgYellow))
|
||||
console.SetColor("Time", color.New(color.FgGreen))
|
||||
|
||||
// check 'ls' cli arguments.
|
||||
checkListSyntax(ctx)
|
||||
|
||||
// Set command flags from context.
|
||||
isRecursive := ctx.Bool("recursive")
|
||||
isIncomplete := ctx.Bool("incomplete")
|
||||
|
||||
args := ctx.Args()
|
||||
// mimic operating system tool behavior.
|
||||
if !ctx.Args().Present() {
|
||||
args = []string{"."}
|
||||
}
|
||||
// check 'ls' cliCtx arguments.
|
||||
args, isRecursive, isIncomplete, timeRef, withOlderVersions := checkListSyntax(ctx, cliCtx)
|
||||
|
||||
var cErr error
|
||||
for _, targetURL := range args {
|
||||
clnt, err := newClient(targetURL)
|
||||
fatalIf(err.Trace(targetURL), "Unable to initialize target `"+targetURL+"`.")
|
||||
|
||||
if !strings.HasSuffix(targetURL, string(clnt.GetURL().Separator)) {
|
||||
var st *ClientContent
|
||||
st, err = clnt.Stat(isIncomplete, false, nil)
|
||||
st, err = clnt.Stat(ctx, StatOptions{incomplete: isIncomplete})
|
||||
if st != nil && err == nil && st.Type.IsDir() {
|
||||
targetURL = targetURL + string(clnt.GetURL().Separator)
|
||||
clnt, err = newClient(targetURL)
|
||||
@@ -141,7 +205,7 @@ func mainList(ctx *cli.Context) error {
|
||||
}
|
||||
}
|
||||
|
||||
if e := doList(clnt, isRecursive, isIncomplete); e != nil {
|
||||
if e := doList(ctx, clnt, isRecursive, isIncomplete, timeRef, withOlderVersions); e != nil {
|
||||
cErr = e
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,9 +17,11 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -43,18 +45,30 @@ type contentMessage struct {
|
||||
Key string `json:"key"`
|
||||
ETag string `json:"etag"`
|
||||
URL string `json:"url,omitempty"`
|
||||
|
||||
VersionID string `json:"versionId,omitempty"`
|
||||
VersionIndex int `json:"versionIndex,omitempty"`
|
||||
IsDeleteMarker bool `json:"isDeleteMarker,omitempty"`
|
||||
}
|
||||
|
||||
// String colorized string message.
|
||||
func (c contentMessage) String() string {
|
||||
message := console.Colorize("Time", fmt.Sprintf("[%s] ", c.Time.Format(printDate)))
|
||||
message = message + console.Colorize("Size", fmt.Sprintf("%7s ", strings.Join(strings.Fields(humanize.IBytes(uint64(c.Size))), "")))
|
||||
message = func() string {
|
||||
if c.Filetype == "folder" {
|
||||
return message + console.Colorize("Dir", c.Key)
|
||||
message += console.Colorize("Size", fmt.Sprintf("%7s ", strings.Join(strings.Fields(humanize.IBytes(uint64(c.Size))), "")))
|
||||
if c.Filetype == "folder" {
|
||||
return message + console.Colorize("Dir", c.Key)
|
||||
}
|
||||
|
||||
fileDesc := c.Key
|
||||
if c.VersionID != "" {
|
||||
fileDesc += fmt.Sprintf(" (v%d, %s", c.VersionIndex, c.VersionID)
|
||||
if c.IsDeleteMarker {
|
||||
fileDesc += ", delete-marker"
|
||||
}
|
||||
return message + console.Colorize("File", c.Key)
|
||||
}()
|
||||
fileDesc += ")"
|
||||
}
|
||||
|
||||
message += console.Colorize("file", fileDesc)
|
||||
return message
|
||||
}
|
||||
|
||||
@@ -67,28 +81,6 @@ func (c contentMessage) JSON() string {
|
||||
return string(jsonMessageBytes)
|
||||
}
|
||||
|
||||
// parseContent parse client Content container into printer struct.
|
||||
func parseContent(c *ClientContent) contentMessage {
|
||||
content := contentMessage{}
|
||||
content.Time = c.Time.Local()
|
||||
|
||||
// guess file type.
|
||||
content.Filetype = func() string {
|
||||
if c.Type.IsDir() {
|
||||
return "folder"
|
||||
}
|
||||
return "file"
|
||||
}()
|
||||
|
||||
content.Size = c.Size
|
||||
md5sum := strings.TrimPrefix(c.ETag, "\"")
|
||||
md5sum = strings.TrimSuffix(md5sum, "\"")
|
||||
content.ETag = md5sum
|
||||
// Convert OS Type to match console file printing style.
|
||||
content.Key = getKey(c)
|
||||
return content
|
||||
}
|
||||
|
||||
// get content key
|
||||
func getKey(c *ClientContent) string {
|
||||
sep := "/"
|
||||
@@ -105,15 +97,88 @@ func getKey(c *ClientContent) string {
|
||||
return c.URL.Path
|
||||
}
|
||||
|
||||
// doList - list all entities inside a folder.
|
||||
func doList(clnt Client, isRecursive, isIncomplete bool) error {
|
||||
// Generate printable listing from a list of client contents
|
||||
func generateContentMessages(clnt Client, ctnts []*ClientContent) (msgs []contentMessage) {
|
||||
prefixPath := clnt.GetURL().Path
|
||||
separator := string(clnt.GetURL().Separator)
|
||||
if !strings.HasSuffix(prefixPath, separator) {
|
||||
prefixPath = prefixPath[:strings.LastIndex(prefixPath, separator)+1]
|
||||
prefixPath = filepath.ToSlash(prefixPath)
|
||||
if !strings.HasSuffix(prefixPath, "/") {
|
||||
prefixPath = prefixPath[:strings.LastIndex(prefixPath, "/")+1]
|
||||
}
|
||||
var cErr error
|
||||
for content := range clnt.List(isRecursive, isIncomplete, false, DirNone) {
|
||||
prefixPath = strings.TrimPrefix(prefixPath, "./")
|
||||
|
||||
nrVersions := len(ctnts)
|
||||
|
||||
for i, c := range ctnts {
|
||||
// Convert any os specific delimiters to "/".
|
||||
contentURL := filepath.ToSlash(c.URL.Path)
|
||||
// Trim prefix path from the content path.
|
||||
c.URL.Path = strings.TrimPrefix(contentURL, prefixPath)
|
||||
|
||||
contentMsg := contentMessage{}
|
||||
contentMsg.Time = c.Time.Local()
|
||||
|
||||
// guess file type.
|
||||
contentMsg.Filetype = func() string {
|
||||
if c.Type.IsDir() {
|
||||
return "folder"
|
||||
}
|
||||
return "file"
|
||||
}()
|
||||
|
||||
contentMsg.Size = c.Size
|
||||
md5sum := strings.TrimPrefix(c.ETag, "\"")
|
||||
md5sum = strings.TrimSuffix(md5sum, "\"")
|
||||
contentMsg.ETag = md5sum
|
||||
// Convert OS Type to match console file printing style.
|
||||
contentMsg.Key = getKey(c)
|
||||
contentMsg.VersionID = c.VersionID
|
||||
contentMsg.IsDeleteMarker = c.IsDeleteMarker
|
||||
contentMsg.VersionIndex = nrVersions - i
|
||||
// URL is empty by default
|
||||
// Set it to either relative dir (host) or public url (remote)
|
||||
contentMsg.URL = clnt.GetURL().String()
|
||||
|
||||
msgs = append(msgs, contentMsg)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// Pretty print the list of versions belonging to one object
|
||||
func printObjectVersions(clnt Client, ctntVersions []*ClientContent) {
|
||||
// Sort versions
|
||||
sort.Slice(ctntVersions, func(i, j int) bool {
|
||||
if ctntVersions[i].IsLatest {
|
||||
return true
|
||||
}
|
||||
if ctntVersions[j].IsLatest {
|
||||
return false
|
||||
}
|
||||
return ctntVersions[i].Time.After(ctntVersions[j].Time)
|
||||
})
|
||||
|
||||
msgs := generateContentMessages(clnt, ctntVersions)
|
||||
for _, msg := range msgs {
|
||||
printMsg(msg)
|
||||
}
|
||||
}
|
||||
|
||||
// doList - list all entities inside a folder.
|
||||
func doList(ctx context.Context, clnt Client, isRecursive, isIncomplete bool, timeRef time.Time, withOlderVersions bool) error {
|
||||
|
||||
var (
|
||||
lastPath string
|
||||
perObjectVersions []*ClientContent
|
||||
cErr error
|
||||
)
|
||||
|
||||
for content := range clnt.List(ctx, ListOptions{
|
||||
isRecursive: isRecursive,
|
||||
isIncomplete: isIncomplete,
|
||||
timeRef: timeRef,
|
||||
withOlderVersions: withOlderVersions,
|
||||
withDeleteMarkers: true,
|
||||
showDir: DirNone,
|
||||
}) {
|
||||
if content.Err != nil {
|
||||
switch content.Err.ToGoError().(type) {
|
||||
// handle this specifically for filesystem related errors.
|
||||
@@ -139,21 +204,16 @@ func doList(clnt Client, isRecursive, isIncomplete bool) error {
|
||||
continue
|
||||
}
|
||||
|
||||
// Convert any os specific delimiters to "/".
|
||||
contentURL := filepath.ToSlash(content.URL.Path)
|
||||
prefixPath = filepath.ToSlash(prefixPath)
|
||||
if lastPath != content.URL.Path {
|
||||
// Print any object in the current list before reinitializing it
|
||||
printObjectVersions(clnt, perObjectVersions)
|
||||
lastPath = content.URL.Path
|
||||
perObjectVersions = []*ClientContent{}
|
||||
}
|
||||
|
||||
// Trim prefix of current working dir
|
||||
prefixPath = strings.TrimPrefix(prefixPath, "."+separator)
|
||||
// Trim prefix path from the content path.
|
||||
contentURL = strings.TrimPrefix(contentURL, prefixPath)
|
||||
content.URL.Path = contentURL
|
||||
parsedContent := parseContent(content)
|
||||
// URL is empty by default
|
||||
// Set it to either relative dir (host) or public url (remote)
|
||||
parsedContent.URL = clnt.GetURL().String()
|
||||
// Print colorized or jsonized content info.
|
||||
printMsg(parsedContent)
|
||||
perObjectVersions = append(perObjectVersions, content)
|
||||
}
|
||||
|
||||
printObjectVersions(clnt, perObjectVersions)
|
||||
return cErr
|
||||
}
|
||||
|
||||
+17
-7
@@ -73,6 +73,7 @@ VERSION:
|
||||
|
||||
// Main starts mc application
|
||||
func Main(args []string) {
|
||||
|
||||
if len(args) > 1 {
|
||||
switch args[1] {
|
||||
case "mc", filepath.Base(args[0]):
|
||||
@@ -255,15 +256,20 @@ func installAutoCompletion() {
|
||||
}
|
||||
|
||||
func registerBefore(ctx *cli.Context) error {
|
||||
// Set the config directory.
|
||||
setMcConfigDir(ctx.GlobalString("config-dir"))
|
||||
|
||||
// Migrate any old version of config / state files to newer format.
|
||||
migrate()
|
||||
if ctx.IsSet("config-dir") {
|
||||
// Set the config directory.
|
||||
setMcConfigDir(ctx.String("config-dir"))
|
||||
} else if ctx.GlobalIsSet("config-dir") {
|
||||
// Set the config directory.
|
||||
setMcConfigDir(ctx.GlobalString("config-dir"))
|
||||
}
|
||||
|
||||
// Set global flags.
|
||||
setGlobalsFromContext(ctx)
|
||||
|
||||
// Migrate any old version of config / state files to newer format.
|
||||
migrate()
|
||||
|
||||
// Initialize default config files.
|
||||
initMC()
|
||||
|
||||
@@ -313,6 +319,7 @@ func checkUpdate(ctx *cli.Context) {
|
||||
}
|
||||
|
||||
var appCmds = []cli.Command{
|
||||
aliasCmd,
|
||||
lsCmd,
|
||||
mbCmd,
|
||||
rbCmd,
|
||||
@@ -328,16 +335,19 @@ var appCmds = []cli.Command{
|
||||
mvCmd,
|
||||
treeCmd,
|
||||
duCmd,
|
||||
lockCmd,
|
||||
retentionCmd,
|
||||
legalHoldCmd,
|
||||
diffCmd,
|
||||
rmCmd,
|
||||
versionCmd,
|
||||
bucketLockCmd,
|
||||
bucketILMCmd,
|
||||
encryptCmd,
|
||||
eventCmd,
|
||||
ilmCmd,
|
||||
watchCmd,
|
||||
policyCmd,
|
||||
tagCmd,
|
||||
replicateCmd,
|
||||
adminCmd,
|
||||
configCmd,
|
||||
updateCmd,
|
||||
|
||||
+15
-10
@@ -17,6 +17,8 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/cli"
|
||||
json "github.com/minio/mc/pkg/colorjson"
|
||||
@@ -103,28 +105,28 @@ func (s makeBucketMessage) JSON() string {
|
||||
}
|
||||
|
||||
// Validate command line arguments.
|
||||
func checkMakeBucketSyntax(ctx *cli.Context) {
|
||||
if !ctx.Args().Present() {
|
||||
cli.ShowCommandHelpAndExit(ctx, "mb", 1) // last argument is exit code
|
||||
func checkMakeBucketSyntax(cliCtx *cli.Context) {
|
||||
if !cliCtx.Args().Present() {
|
||||
cli.ShowCommandHelpAndExit(cliCtx, "mb", 1) // last argument is exit code
|
||||
}
|
||||
}
|
||||
|
||||
// mainMakeBucket is entry point for mb command.
|
||||
func mainMakeBucket(ctx *cli.Context) error {
|
||||
func mainMakeBucket(cli *cli.Context) error {
|
||||
|
||||
// check 'mb' cli arguments.
|
||||
checkMakeBucketSyntax(ctx)
|
||||
checkMakeBucketSyntax(cli)
|
||||
|
||||
// Additional command speific theme customization.
|
||||
console.SetColor("MakeBucket", color.New(color.FgGreen, color.Bold))
|
||||
|
||||
// Save region.
|
||||
region := ctx.String("region")
|
||||
ignoreExisting := ctx.Bool("p")
|
||||
withLock := ctx.Bool("l")
|
||||
region := cli.String("region")
|
||||
ignoreExisting := cli.Bool("p")
|
||||
withLock := cli.Bool("l")
|
||||
|
||||
var cErr error
|
||||
for _, targetURL := range ctx.Args() {
|
||||
for _, targetURL := range cli.Args() {
|
||||
// Instantiate client for URL.
|
||||
clnt, err := newClient(targetURL)
|
||||
if err != nil {
|
||||
@@ -133,8 +135,11 @@ func mainMakeBucket(ctx *cli.Context) error {
|
||||
continue
|
||||
}
|
||||
|
||||
ctx, cancelMakeBucket := context.WithCancel(globalContext)
|
||||
defer cancelMakeBucket()
|
||||
|
||||
// Make bucket.
|
||||
err = clnt.MakeBucket(region, ignoreExisting, withLock)
|
||||
err = clnt.MakeBucket(ctx, region, ignoreExisting, withLock)
|
||||
if err != nil {
|
||||
switch err.ToGoError().(type) {
|
||||
case BucketNameEmpty:
|
||||
|
||||
+132
-156
@@ -31,7 +31,7 @@ import (
|
||||
"github.com/minio/cli"
|
||||
json "github.com/minio/mc/pkg/colorjson"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/minio-go/v6/pkg/encrypt"
|
||||
"github.com/minio/minio-go/v7/pkg/encrypt"
|
||||
"github.com/minio/minio/pkg/console"
|
||||
)
|
||||
|
||||
@@ -72,9 +72,14 @@ var (
|
||||
Name: "md5",
|
||||
Usage: "force all upload(s) to calculate md5sum checksum",
|
||||
},
|
||||
cli.StringFlag{
|
||||
Name: "multi-master",
|
||||
Usage: "enable multi-master multi-site setup",
|
||||
cli.BoolFlag{
|
||||
Name: "multi-master",
|
||||
Usage: "enable multi-master multi-site setup",
|
||||
Hidden: true,
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "active-active",
|
||||
Usage: "enable active-active multi-site setup",
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "disable-multipart",
|
||||
@@ -174,9 +179,9 @@ EXAMPLES:
|
||||
14. Mirror a local folder recursively to Amazon S3 cloud storage and preserve all local file attributes.
|
||||
{{.Prompt}} {{.HelpName}} -a backup/ s3/archive
|
||||
|
||||
15. Cross mirror between sites in a multi-master deployment.
|
||||
Site-A: {{.Prompt}} {{.HelpName}} --watch --multi-master siteA siteB
|
||||
Site-B: {{.Prompt}} {{.HelpName}} --watch --multi-master siteB siteA
|
||||
15. Cross mirror between sites in a active-active deployment.
|
||||
Site-A: {{.Prompt}} {{.HelpName}} --watch --active-active siteA siteB
|
||||
Site-B: {{.Prompt}} {{.HelpName}} --watch --active-active siteB siteA
|
||||
`,
|
||||
}
|
||||
|
||||
@@ -208,17 +213,7 @@ type mirrorJob struct {
|
||||
sourceURL string
|
||||
targetURL string
|
||||
|
||||
isFake, isRemove, isOverwrite bool
|
||||
isWatch, isPreserve bool
|
||||
md5, disableMultipart bool
|
||||
olderThan, newerThan string
|
||||
storageClass string
|
||||
userMetadata map[string]string
|
||||
|
||||
excludeOptions []string
|
||||
encKeyDB map[string][]prefixSSEPair
|
||||
|
||||
multiMasterEnable bool
|
||||
opts mirrorOptions
|
||||
}
|
||||
|
||||
// mirrorMessage container for file mirror messages
|
||||
@@ -246,8 +241,8 @@ func (m mirrorMessage) JSON() string {
|
||||
}
|
||||
|
||||
// doRemove - removes files on target.
|
||||
func (mj *mirrorJob) doRemove(sURLs URLs) URLs {
|
||||
if mj.isFake {
|
||||
func (mj *mirrorJob) doRemove(ctx context.Context, sURLs URLs) URLs {
|
||||
if mj.opts.isFake {
|
||||
return sURLs.WithError(nil)
|
||||
}
|
||||
|
||||
@@ -262,7 +257,7 @@ func (mj *mirrorJob) doRemove(sURLs URLs) URLs {
|
||||
contentCh <- &ClientContent{URL: *newClientURL(sURLs.TargetContent.URL.Path)}
|
||||
close(contentCh)
|
||||
isRemoveBucket := false
|
||||
errorCh := clnt.Remove(false, isRemoveBucket, false, contentCh)
|
||||
errorCh := clnt.Remove(ctx, false, isRemoveBucket, false, contentCh)
|
||||
for pErr := range errorCh {
|
||||
if pErr != nil {
|
||||
switch pErr.ToGoError().(type) {
|
||||
@@ -280,13 +275,13 @@ func (mj *mirrorJob) doRemove(sURLs URLs) URLs {
|
||||
// doMirror - Mirror an object to multiple destination. URLs status contains a copy of sURLs and error if any.
|
||||
func (mj *mirrorJob) doMirrorWatch(ctx context.Context, targetPath string, tgtSSE encrypt.ServerSide, sURLs URLs) URLs {
|
||||
shouldQueue := false
|
||||
if !mj.isOverwrite && !mj.multiMasterEnable {
|
||||
if !mj.opts.isOverwrite && !mj.opts.activeActive {
|
||||
targetClient, err := newClient(targetPath)
|
||||
if err != nil {
|
||||
// cannot create targetclient
|
||||
return sURLs.WithError(err)
|
||||
}
|
||||
_, err = targetClient.Stat(false, false, tgtSSE)
|
||||
_, err = targetClient.Stat(ctx, StatOptions{sse: tgtSSE})
|
||||
if err == nil {
|
||||
if !sURLs.SourceContent.RetentionEnabled && !sURLs.SourceContent.LegalHoldEnabled {
|
||||
return sURLs.WithError(probe.NewError(ObjectAlreadyExists{}))
|
||||
@@ -294,7 +289,7 @@ func (mj *mirrorJob) doMirrorWatch(ctx context.Context, targetPath string, tgtSS
|
||||
} // doesn't exist
|
||||
shouldQueue = true
|
||||
}
|
||||
if shouldQueue || mj.isOverwrite || mj.multiMasterEnable {
|
||||
if shouldQueue || mj.opts.isOverwrite || mj.opts.activeActive {
|
||||
// adjust total, because we want to show progress of
|
||||
// the item still queued to be copied.
|
||||
mj.status.Add(sURLs.SourceContent.Size)
|
||||
@@ -316,7 +311,7 @@ func (mj *mirrorJob) doMirror(ctx context.Context, sURLs URLs) URLs {
|
||||
|
||||
// For a fake mirror make sure we update respective progress bars
|
||||
// and accounting readers under relevant conditions.
|
||||
if mj.isFake {
|
||||
if mj.opts.isFake {
|
||||
if sURLs.SourceContent != nil {
|
||||
mj.status.Add(sURLs.SourceContent.Size)
|
||||
}
|
||||
@@ -335,22 +330,23 @@ func (mj *mirrorJob) doMirror(ctx context.Context, sURLs URLs) URLs {
|
||||
// Initialize target metadata.
|
||||
sURLs.TargetContent.Metadata = make(map[string]string)
|
||||
|
||||
if mj.storageClass != "" {
|
||||
sURLs.TargetContent.Metadata["X-Amz-Storage-Class"] = mj.storageClass
|
||||
if mj.opts.storageClass != "" {
|
||||
sURLs.TargetContent.Metadata["X-Amz-Storage-Class"] = mj.opts.storageClass
|
||||
}
|
||||
|
||||
if mj.multiMasterEnable {
|
||||
if mj.opts.activeActive {
|
||||
srcModTime := getSourceModTimeKey(sURLs.SourceContent.Metadata)
|
||||
// If the source object already has source modtime attribute set, then
|
||||
// use it in target. Otherwise use the S3 modtime instead.
|
||||
if sURLs.SourceContent.Metadata[multiMasterSourceModTimeKey] != "" {
|
||||
sURLs.TargetContent.Metadata[multiMasterSourceModTimeKey] = sURLs.SourceContent.Metadata[multiMasterSourceModTimeKey]
|
||||
if srcModTime != "" {
|
||||
sURLs.TargetContent.Metadata[activeActiveSourceModTimeKey] = srcModTime
|
||||
} else {
|
||||
sURLs.TargetContent.Metadata[multiMasterSourceModTimeKey] = sURLs.SourceContent.Time.Format(time.RFC3339Nano)
|
||||
sURLs.TargetContent.Metadata[activeActiveSourceModTimeKey] = sURLs.SourceContent.Time.Format(time.RFC3339Nano)
|
||||
}
|
||||
}
|
||||
|
||||
// Initialize additional target user metadata.
|
||||
sURLs.TargetContent.UserMetadata = mj.userMetadata
|
||||
sURLs.TargetContent.UserMetadata = mj.opts.userMetadata
|
||||
|
||||
sourcePath := filepath.ToSlash(filepath.Join(sourceAlias, sourceURL.Path))
|
||||
targetPath := filepath.ToSlash(filepath.Join(targetAlias, targetURL.Path))
|
||||
@@ -361,9 +357,9 @@ func (mj *mirrorJob) doMirror(ctx context.Context, sURLs URLs) URLs {
|
||||
TotalCount: sURLs.TotalCount,
|
||||
TotalSize: sURLs.TotalSize,
|
||||
})
|
||||
sURLs.MD5 = mj.md5
|
||||
sURLs.DisableMultipart = mj.disableMultipart
|
||||
return uploadSourceToTargetURL(ctx, sURLs, mj.status, mj.encKeyDB, mj.isPreserve)
|
||||
sURLs.MD5 = mj.opts.md5
|
||||
sURLs.DisableMultipart = mj.opts.disableMultipart
|
||||
return uploadSourceToTargetURL(ctx, sURLs, mj.status, mj.opts.encKeyDB, mj.opts.isMetadata)
|
||||
}
|
||||
|
||||
// Update progress status
|
||||
@@ -390,7 +386,7 @@ func (mj *mirrorJob) monitorMirrorStatus() (errDuringMirror bool) {
|
||||
errorIf(sURLs.Error.Trace(), "Failed to perform mirroring.")
|
||||
errDuringMirror = true
|
||||
}
|
||||
if mj.multiMasterEnable {
|
||||
if mj.opts.activeActive {
|
||||
close(mj.stopCh)
|
||||
break
|
||||
}
|
||||
@@ -438,7 +434,7 @@ func (mj *mirrorJob) watchMirrorEvents(ctx context.Context, events []EventInfo)
|
||||
// joined to the targetURL.
|
||||
sourceSuffix := strings.TrimPrefix(eventPath, sourceURLFull)
|
||||
//Skip the object, if it matches the Exclude options provided
|
||||
if matchExcludeOptions(mj.excludeOptions, sourceSuffix) {
|
||||
if matchExcludeOptions(mj.opts.excludeOptions, sourceSuffix) {
|
||||
continue
|
||||
}
|
||||
|
||||
@@ -447,7 +443,7 @@ func (mj *mirrorJob) watchMirrorEvents(ctx context.Context, events []EventInfo)
|
||||
// newClient needs the unexpanded path, newCLientURL needs the expanded path
|
||||
targetAlias, expandedTargetPath, _ := mustExpandAlias(targetPath)
|
||||
targetURL := newClientURL(expandedTargetPath)
|
||||
tgtSSE := getSSE(targetPath, mj.encKeyDB[targetAlias])
|
||||
tgtSSE := getSSE(targetPath, mj.opts.encKeyDB[targetAlias])
|
||||
|
||||
if (event.Type == EventCreate) ||
|
||||
(event.Type == EventCreateCopy) ||
|
||||
@@ -465,13 +461,14 @@ func (mj *mirrorJob) watchMirrorEvents(ctx context.Context, events []EventInfo)
|
||||
},
|
||||
TargetAlias: targetAlias,
|
||||
TargetContent: &ClientContent{URL: *targetURL},
|
||||
MD5: mj.md5,
|
||||
DisableMultipart: mj.disableMultipart,
|
||||
encKeyDB: mj.encKeyDB,
|
||||
MD5: mj.opts.md5,
|
||||
DisableMultipart: mj.opts.disableMultipart,
|
||||
encKeyDB: mj.opts.encKeyDB,
|
||||
}
|
||||
if mj.multiMasterEnable &&
|
||||
mirrorURL.SourceContent.Metadata[multiMasterSourceModTimeKey] != "" {
|
||||
// If source has multi-master attributes, it means that the
|
||||
if mj.opts.activeActive &&
|
||||
(getSourceModTimeKey(mirrorURL.SourceContent.Metadata) != "" ||
|
||||
getSourceModTimeKey(mirrorURL.SourceContent.UserMetadata) != "") {
|
||||
// If source has active-active attributes, it means that the
|
||||
// object was uploaded by "mc mirror", hence ignore the event
|
||||
// to avoid copying it.
|
||||
continue
|
||||
@@ -488,15 +485,15 @@ func (mj *mirrorJob) watchMirrorEvents(ctx context.Context, events []EventInfo)
|
||||
SourceContent: nil,
|
||||
TargetAlias: targetAlias,
|
||||
TargetContent: &ClientContent{URL: *targetURL},
|
||||
MD5: mj.md5,
|
||||
DisableMultipart: mj.disableMultipart,
|
||||
encKeyDB: mj.encKeyDB,
|
||||
MD5: mj.opts.md5,
|
||||
DisableMultipart: mj.opts.disableMultipart,
|
||||
encKeyDB: mj.opts.encKeyDB,
|
||||
}
|
||||
mirrorURL.TotalCount = mj.status.GetCounts()
|
||||
mirrorURL.TotalSize = mj.status.Get()
|
||||
if mirrorURL.TargetContent != nil && (mj.isRemove || mj.multiMasterEnable) {
|
||||
if mirrorURL.TargetContent != nil && (mj.opts.isRemove || mj.opts.activeActive) {
|
||||
mj.queueCh <- func() URLs {
|
||||
return mj.doRemove(mirrorURL)
|
||||
return mj.doRemove(ctx, mirrorURL)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -536,8 +533,8 @@ func (mj *mirrorJob) watchMirror(ctx context.Context, stopParallel func()) {
|
||||
}
|
||||
}
|
||||
|
||||
func (mj *mirrorJob) watchURL(sourceClient Client) *probe.Error {
|
||||
return mj.watcher.Join(sourceClient, true)
|
||||
func (mj *mirrorJob) watchURL(ctx context.Context, sourceClient Client) *probe.Error {
|
||||
return mj.watcher.Join(ctx, sourceClient, true)
|
||||
}
|
||||
|
||||
// Fetch urls that need to be mirrored
|
||||
@@ -546,8 +543,7 @@ func (mj *mirrorJob) startMirror(ctx context.Context, cancelMirror context.Cance
|
||||
mj.m.Lock()
|
||||
defer mj.m.Unlock()
|
||||
|
||||
isMetadata := len(mj.userMetadata) > 0 || mj.isPreserve
|
||||
URLsCh := prepareMirrorURLs(mj.sourceURL, mj.targetURL, mj.isFake, mj.isOverwrite, mj.isRemove, isMetadata, mj.excludeOptions, mj.encKeyDB)
|
||||
URLsCh := prepareMirrorURLs(ctx, mj.sourceURL, mj.targetURL, mj.opts)
|
||||
|
||||
for {
|
||||
select {
|
||||
@@ -562,10 +558,10 @@ func (mj *mirrorJob) startMirror(ctx context.Context, cancelMirror context.Cance
|
||||
}
|
||||
|
||||
if sURLs.SourceContent != nil {
|
||||
if mj.olderThan != "" && isOlder(sURLs.SourceContent.Time, mj.olderThan) {
|
||||
if isOlder(sURLs.SourceContent.Time, mj.opts.olderThan) {
|
||||
continue
|
||||
}
|
||||
if mj.newerThan != "" && isNewer(sURLs.SourceContent.Time, mj.newerThan) {
|
||||
if isNewer(sURLs.SourceContent.Time, mj.opts.newerThan) {
|
||||
continue
|
||||
}
|
||||
}
|
||||
@@ -573,6 +569,7 @@ func (mj *mirrorJob) startMirror(ctx context.Context, cancelMirror context.Cance
|
||||
if sURLs.SourceContent != nil {
|
||||
mj.status.Add(sURLs.SourceContent.Size)
|
||||
}
|
||||
|
||||
mj.status.SetTotal(mj.status.Get()).Update()
|
||||
mj.status.AddCounts(1)
|
||||
|
||||
@@ -585,9 +582,9 @@ func (mj *mirrorJob) startMirror(ctx context.Context, cancelMirror context.Cance
|
||||
mj.queueCh <- func() URLs {
|
||||
return mj.doMirror(ctx, sURLs)
|
||||
}
|
||||
} else if sURLs.TargetContent != nil && mj.isRemove {
|
||||
} else if sURLs.TargetContent != nil && mj.opts.isRemove {
|
||||
mj.queueCh <- func() URLs {
|
||||
return mj.doRemove(sURLs)
|
||||
return mj.doRemove(ctx, sURLs)
|
||||
}
|
||||
}
|
||||
case <-globalContext.Done():
|
||||
@@ -606,7 +603,7 @@ func (mj *mirrorJob) mirror(ctx context.Context, cancelMirror context.CancelFunc
|
||||
var wg sync.WaitGroup
|
||||
|
||||
// Starts watcher loop for watching for new events.
|
||||
if mj.isWatch {
|
||||
if mj.opts.isWatch {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
@@ -624,7 +621,7 @@ func (mj *mirrorJob) mirror(ctx context.Context, cancelMirror context.CancelFunc
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
stopParallel := func() {
|
||||
if !mj.isWatch {
|
||||
if !mj.opts.isWatch {
|
||||
close(mj.queueCh)
|
||||
mj.parallel.wait()
|
||||
cancelMirror()
|
||||
@@ -643,32 +640,15 @@ func (mj *mirrorJob) mirror(ctx context.Context, cancelMirror context.CancelFunc
|
||||
return mj.monitorMirrorStatus()
|
||||
}
|
||||
|
||||
func newMirrorJob(srcURL, dstURL string, isFake, isRemove, isOverwrite, isWatch, isPreserve, multiMasterEnable bool, excludeOptions []string, olderThan, newerThan string, storageClass string, userMetadata map[string]string, encKeyDB map[string][]prefixSSEPair, md5, disableMultipart bool) *mirrorJob {
|
||||
if multiMasterEnable {
|
||||
isPreserve = true
|
||||
}
|
||||
func newMirrorJob(srcURL, dstURL string, opts mirrorOptions) *mirrorJob {
|
||||
mj := mirrorJob{
|
||||
stopCh: make(chan struct{}),
|
||||
|
||||
sourceURL: srcURL,
|
||||
targetURL: dstURL,
|
||||
|
||||
isFake: isFake,
|
||||
isRemove: isRemove,
|
||||
isOverwrite: isOverwrite,
|
||||
isWatch: isWatch,
|
||||
isPreserve: isPreserve || multiMasterEnable,
|
||||
md5: md5,
|
||||
disableMultipart: disableMultipart,
|
||||
excludeOptions: excludeOptions,
|
||||
olderThan: olderThan,
|
||||
newerThan: newerThan,
|
||||
storageClass: storageClass,
|
||||
userMetadata: userMetadata,
|
||||
encKeyDB: encKeyDB,
|
||||
statusCh: make(chan URLs),
|
||||
watcher: NewWatcher(UTCNow()),
|
||||
multiMasterEnable: multiMasterEnable,
|
||||
opts: opts,
|
||||
statusCh: make(chan URLs),
|
||||
watcher: NewWatcher(UTCNow()),
|
||||
}
|
||||
|
||||
mj.parallel, mj.queueCh = newParallelManager(mj.statusCh)
|
||||
@@ -687,8 +667,8 @@ func newMirrorJob(srcURL, dstURL string, isFake, isRemove, isOverwrite, isWatch,
|
||||
}
|
||||
|
||||
// copyBucketPolicies - copy policies from source to dest
|
||||
func copyBucketPolicies(srcClt, dstClt Client, isOverwrite bool) *probe.Error {
|
||||
rules, err := srcClt.GetAccessRules()
|
||||
func copyBucketPolicies(ctx context.Context, srcClt, dstClt Client, isOverwrite bool) *probe.Error {
|
||||
rules, err := srcClt.GetAccessRules(ctx)
|
||||
if err != nil {
|
||||
switch err.ToGoError().(type) {
|
||||
case APINotImplemented:
|
||||
@@ -698,14 +678,14 @@ func copyBucketPolicies(srcClt, dstClt Client, isOverwrite bool) *probe.Error {
|
||||
}
|
||||
// Set found rules to target bucket if permitted
|
||||
for _, r := range rules {
|
||||
originalRule, _, err := dstClt.GetAccess()
|
||||
originalRule, _, err := dstClt.GetAccess(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// Set rule only if it doesn't exist in the target bucket
|
||||
// or force flag is activated
|
||||
if originalRule == "none" || isOverwrite {
|
||||
err = dstClt.SetAccess(r, false)
|
||||
err = dstClt.SetAccess(ctx, r, false)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -738,20 +718,20 @@ func getEventPathURLWin(srcURL, eventPath string) string {
|
||||
}
|
||||
|
||||
// runMirror - mirrors all buckets to another S3 server
|
||||
func runMirror(srcURL, dstURL string, ctx *cli.Context, encKeyDB map[string][]prefixSSEPair) bool {
|
||||
func runMirror(ctx context.Context, cancelMirror context.CancelFunc, srcURL, dstURL string, cli *cli.Context, encKeyDB map[string][]prefixSSEPair) bool {
|
||||
// This is kept for backward compatibility, `--force` means
|
||||
// --overwrite.
|
||||
isOverwrite := ctx.Bool("force")
|
||||
isOverwrite := cli.Bool("force")
|
||||
if !isOverwrite {
|
||||
isOverwrite = ctx.Bool("overwrite")
|
||||
isOverwrite = cli.Bool("overwrite")
|
||||
}
|
||||
|
||||
// Parse metadata.
|
||||
userMetaMap := make(map[string]string)
|
||||
if ctx.String("attr") != "" {
|
||||
userMetadata := make(map[string]string)
|
||||
if cli.String("attr") != "" {
|
||||
var err *probe.Error
|
||||
userMetaMap, err = getMetaDataEntry(ctx.String("attr"))
|
||||
fatalIf(err, "Unable to parse attribute %v", ctx.String("attr"))
|
||||
userMetadata, err = getMetaDataEntry(cli.String("attr"))
|
||||
fatalIf(err, "Unable to parse attribute %v", cli.String("attr"))
|
||||
}
|
||||
|
||||
srcClt, err := newClient(srcURL)
|
||||
@@ -775,34 +755,29 @@ func runMirror(srcURL, dstURL string, ctx *cli.Context, encKeyDB map[string][]pr
|
||||
}
|
||||
|
||||
// Create a new mirror job and execute it
|
||||
mj := newMirrorJob(srcURL, dstURL,
|
||||
ctx.Bool("fake"),
|
||||
ctx.Bool("remove"),
|
||||
isOverwrite,
|
||||
ctx.Bool("watch"),
|
||||
ctx.Bool("a"),
|
||||
ctx.Bool("multi-master"),
|
||||
ctx.StringSlice("exclude"),
|
||||
ctx.String("older-than"),
|
||||
ctx.String("newer-than"),
|
||||
ctx.String("storage-class"),
|
||||
userMetaMap,
|
||||
encKeyDB,
|
||||
ctx.Bool("md5"),
|
||||
ctx.Bool("disable-multipart"),
|
||||
)
|
||||
|
||||
go func() {
|
||||
<-globalContext.Done()
|
||||
os.Exit(globalErrorExitStatus)
|
||||
}()
|
||||
mj := newMirrorJob(srcURL, dstURL, mirrorOptions{
|
||||
isFake: cli.Bool("fake"),
|
||||
isRemove: cli.Bool("remove"),
|
||||
isOverwrite: isOverwrite,
|
||||
isWatch: cli.Bool("watch") || cli.Bool("multi-master") || cli.Bool("active-active"),
|
||||
isMetadata: cli.Bool("a") || cli.Bool("multi-master") || cli.Bool("active-active") || len(userMetadata) > 0,
|
||||
md5: cli.Bool("md5"),
|
||||
disableMultipart: cli.Bool("disable-multipart"),
|
||||
excludeOptions: cli.StringSlice("exclude"),
|
||||
olderThan: cli.String("older-than"),
|
||||
newerThan: cli.String("newer-than"),
|
||||
storageClass: cli.String("storage-class"),
|
||||
userMetadata: userMetadata,
|
||||
encKeyDB: encKeyDB,
|
||||
activeActive: cli.Bool("multi-master") || cli.Bool("active-active"),
|
||||
})
|
||||
|
||||
if mirrorAllBuckets {
|
||||
// Synchronize buckets using dirDifference function
|
||||
for d := range dirDifference(srcClt, dstClt, srcURL, dstURL) {
|
||||
for d := range dirDifference(ctx, srcClt, dstClt, srcURL, dstURL) {
|
||||
if d.Error != nil {
|
||||
if mj.multiMasterEnable {
|
||||
errorIf(d.Error, "Failed to start mirroring.")
|
||||
if mj.opts.activeActive {
|
||||
errorIf(d.Error, "Failed to start mirroring.. retrying")
|
||||
return true
|
||||
}
|
||||
mj.status.fatalIf(d.Error, "Failed to start mirroring.")
|
||||
@@ -821,104 +796,102 @@ func runMirror(srcURL, dstURL string, ctx *cli.Context, encKeyDB map[string][]pr
|
||||
|
||||
if d.Diff == differInFirst {
|
||||
withLock := false
|
||||
mode, validity, unit, err := newSrcClt.GetObjectLockConfig()
|
||||
mode, validity, unit, err := newSrcClt.GetObjectLockConfig(ctx)
|
||||
if err == nil {
|
||||
withLock = true
|
||||
}
|
||||
// Bucket only exists in the source, create the same bucket in the destination
|
||||
if err := newDstClt.MakeBucket(ctx.String("region"), false, withLock); err != nil {
|
||||
if err := newDstClt.MakeBucket(ctx, cli.String("region"), false, withLock); err != nil {
|
||||
errorIf(err, "Unable to create bucket at `"+newTgtURL+"`.")
|
||||
continue
|
||||
}
|
||||
// object lock configuration set on bucket
|
||||
if mode != "" {
|
||||
errorIf(newDstClt.SetObjectLockConfig(mode, validity, unit),
|
||||
errorIf(newDstClt.SetObjectLockConfig(ctx, mode, validity, unit),
|
||||
"Unable to set object lock config in `"+newTgtURL+"`.")
|
||||
}
|
||||
errorIf(copyBucketPolicies(newSrcClt, newDstClt, isOverwrite),
|
||||
errorIf(copyBucketPolicies(ctx, newSrcClt, newDstClt, isOverwrite),
|
||||
"Unable to copy bucket policies to `"+newDstClt.GetURL().String()+"`.")
|
||||
}
|
||||
|
||||
if mj.isWatch {
|
||||
if mj.opts.isWatch {
|
||||
// monitor mode will watch the source folders for changes,
|
||||
// and queue them for copying.
|
||||
if err := mj.watchURL(newSrcClt); err != nil {
|
||||
if mj.multiMasterEnable {
|
||||
errorIf(err, "Failed to start monitoring.")
|
||||
if err := mj.watchURL(ctx, newSrcClt); err != nil {
|
||||
if mj.opts.activeActive {
|
||||
errorIf(err, "Failed to start monitoring.. retrying")
|
||||
return true
|
||||
}
|
||||
mj.status.fatalIf(err, "Failed to start monitoring.")
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if _, err := dstClt.Stat(false, false, nil); err != nil {
|
||||
} else if _, err := dstClt.Stat(ctx, StatOptions{}); err != nil {
|
||||
withLock := false
|
||||
mode, validity, unit, err := srcClt.GetObjectLockConfig()
|
||||
mode, validity, unit, err := srcClt.GetObjectLockConfig(ctx)
|
||||
if err == nil {
|
||||
withLock = true
|
||||
}
|
||||
|
||||
// Create bucket if it doesn't exist at destination.
|
||||
// ignore if already exists.
|
||||
if mj.multiMasterEnable {
|
||||
err = dstClt.MakeBucket(ctx.String("region"), true, withLock)
|
||||
if mj.opts.activeActive {
|
||||
err = dstClt.MakeBucket(ctx, cli.String("region"), true, withLock)
|
||||
errorIf(err, "Unable to create bucket at `"+dstURL+"`.")
|
||||
if err != nil {
|
||||
return true
|
||||
}
|
||||
} else {
|
||||
mj.status.fatalIf(dstClt.MakeBucket(ctx.String("region"), true, withLock),
|
||||
mj.status.fatalIf(dstClt.MakeBucket(ctx, cli.String("region"), true, withLock),
|
||||
"Unable to create bucket at `"+dstURL+"`.")
|
||||
}
|
||||
|
||||
// object lock configuration set on bucket
|
||||
if mode != "" {
|
||||
err = dstClt.SetObjectLockConfig(mode, validity, unit)
|
||||
err = dstClt.SetObjectLockConfig(ctx, mode, validity, unit)
|
||||
errorIf(err, "Unable to set object lock config in `"+dstURL+"`.")
|
||||
if err != nil && mj.multiMasterEnable {
|
||||
if err != nil && mj.opts.activeActive {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
err = copyBucketPolicies(srcClt, dstClt, isOverwrite)
|
||||
err = copyBucketPolicies(ctx, srcClt, dstClt, isOverwrite)
|
||||
errorIf(err, "Unable to copy bucket policies to `"+dstClt.GetURL().String()+"`.")
|
||||
if err != nil && mj.multiMasterEnable {
|
||||
if err != nil && mj.opts.activeActive {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
if !mirrorAllBuckets && mj.isWatch {
|
||||
if !mirrorAllBuckets && mj.opts.isWatch {
|
||||
// monitor mode will watch the source folders for changes,
|
||||
// and queue them for copying.
|
||||
if err := mj.watchURL(srcClt); err != nil {
|
||||
if mj.multiMasterEnable {
|
||||
errorIf(err, "Failed to start monitoring.")
|
||||
if err := mj.watchURL(ctx, srcClt); err != nil {
|
||||
if mj.opts.activeActive {
|
||||
errorIf(err, "Failed to start monitoring.. retrying")
|
||||
return true
|
||||
}
|
||||
mj.status.fatalIf(err, "Failed to start monitoring.")
|
||||
}
|
||||
}
|
||||
|
||||
ctxt, cancelMirror := context.WithCancel(context.Background())
|
||||
defer cancelMirror()
|
||||
|
||||
// Start mirroring job
|
||||
return mj.mirror(ctxt, cancelMirror)
|
||||
return mj.mirror(ctx, cancelMirror)
|
||||
}
|
||||
|
||||
// Main entry point for mirror command.
|
||||
func mainMirror(ctx *cli.Context) error {
|
||||
func mainMirror(cliCtx *cli.Context) error {
|
||||
ctx, cancelMirror := context.WithCancel(globalContext)
|
||||
defer cancelMirror()
|
||||
|
||||
// Parse encryption keys per command.
|
||||
encKeyDB, err := getEncKeys(ctx)
|
||||
encKeyDB, err := getEncKeys(cliCtx)
|
||||
fatalIf(err, "Unable to parse encryption keys.")
|
||||
|
||||
// check 'mirror' cli arguments.
|
||||
checkMirrorSyntax(ctx, encKeyDB)
|
||||
checkMirrorSyntax(ctx, cliCtx, encKeyDB)
|
||||
|
||||
// Additional command specific theme customization.
|
||||
console.SetColor("Mirror", color.New(color.FgGreen, color.Bold))
|
||||
|
||||
args := ctx.Args()
|
||||
args := cliCtx.Args()
|
||||
|
||||
srcURL := args[0]
|
||||
tgtURL := args[1]
|
||||
@@ -932,16 +905,19 @@ func mainMirror(ctx *cli.Context) error {
|
||||
}
|
||||
}
|
||||
|
||||
if ctx.Bool("multi-master") {
|
||||
for {
|
||||
runMirror(srcURL, tgtURL, ctx, encKeyDB)
|
||||
time.Sleep(time.Second * 2)
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return exitStatus(globalErrorExitStatus)
|
||||
default:
|
||||
if errorDetected := runMirror(ctx, cancelMirror, srcURL, tgtURL, cliCtx, encKeyDB); errorDetected {
|
||||
if cliCtx.Bool("multi-master") || cliCtx.Bool("active-active") {
|
||||
time.Sleep(2 * time.Second)
|
||||
continue
|
||||
}
|
||||
return exitStatus(globalErrorExitStatus)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
if errorDetected := runMirror(srcURL, tgtURL, ctx, encKeyDB); errorDetected {
|
||||
return exitStatus(globalErrorExitStatus)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
+35
-22
@@ -17,9 +17,11 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"runtime"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/minio/pkg/wildcard"
|
||||
@@ -31,20 +33,20 @@ import (
|
||||
// mirror(d1..., d2) -> []mirror(d1/f, d2/d1/f)
|
||||
|
||||
// checkMirrorSyntax(URLs []string)
|
||||
func checkMirrorSyntax(ctx *cli.Context, encKeyDB map[string][]prefixSSEPair) {
|
||||
if len(ctx.Args()) != 2 {
|
||||
cli.ShowCommandHelpAndExit(ctx, "mirror", 1) // last argument is exit code.
|
||||
func checkMirrorSyntax(ctx context.Context, cliCtx *cli.Context, encKeyDB map[string][]prefixSSEPair) {
|
||||
if len(cliCtx.Args()) != 2 {
|
||||
cli.ShowCommandHelpAndExit(cliCtx, "mirror", 1) // last argument is exit code.
|
||||
}
|
||||
|
||||
// extract URLs.
|
||||
URLs := ctx.Args()
|
||||
URLs := cliCtx.Args()
|
||||
srcURL := URLs[0]
|
||||
tgtURL := URLs[1]
|
||||
|
||||
if ctx.Bool("force") && ctx.Bool("remove") {
|
||||
errorIf(errInvalidArgument().Trace(URLs...), "`--force` is deprecated please use `--overwrite` instead with `--remove` for the same functionality.")
|
||||
} else if ctx.Bool("force") {
|
||||
errorIf(errInvalidArgument().Trace(URLs...), "`--force` is deprecated please use `--overwrite` instead for the same functionality.")
|
||||
if cliCtx.Bool("force") && cliCtx.Bool("remove") {
|
||||
errorIf(errInvalidArgument().Trace(URLs...), "`--force` is deprecated, please use `--overwrite` instead with `--remove` for the same functionality.")
|
||||
} else if cliCtx.Bool("force") {
|
||||
errorIf(errInvalidArgument().Trace(URLs...), "`--force` is deprecated, please use `--overwrite` instead for the same functionality.")
|
||||
}
|
||||
|
||||
tgtClientURL := newClientURL(tgtURL)
|
||||
@@ -62,19 +64,19 @@ func checkMirrorSyntax(ctx *cli.Context, encKeyDB map[string][]prefixSSEPair) {
|
||||
|
||||
// Mirror with preserve option on windows
|
||||
// only works for object storage to object storage
|
||||
if runtime.GOOS == "windows" && ctx.Bool("a") {
|
||||
if runtime.GOOS == "windows" && cliCtx.Bool("a") {
|
||||
if srcClient.Type == fileSystem || destClient.Type == fileSystem {
|
||||
errorIf(errInvalidArgument(), "Preserve functionality on windows support object storage to object storage transfer only.")
|
||||
}
|
||||
}
|
||||
|
||||
/****** Generic rules *******/
|
||||
if !ctx.Bool("watch") {
|
||||
_, srcContent, err := url2Stat(srcURL, false, encKeyDB)
|
||||
// incomplete uploads are not necessary for copy operation, no need to verify for them.
|
||||
if !cliCtx.Bool("watch") && !cliCtx.Bool("active-active") && !cliCtx.Bool("multi-master") {
|
||||
_, srcContent, err := url2Stat(ctx, srcURL, "", false, encKeyDB, time.Time{})
|
||||
// incomplete uploads are not necessary for mirror operation, no need to verify for them.
|
||||
isIncomplete := false
|
||||
if err != nil && !isURLPrefixExists(srcURL, isIncomplete) {
|
||||
errorIf(err.Trace(srcURL), "Unable to stat source `"+srcURL+"`.")
|
||||
fatalIf(err.Trace(srcURL), "Unable to stat source `"+srcURL+"`.")
|
||||
}
|
||||
|
||||
if err == nil {
|
||||
@@ -95,7 +97,7 @@ func matchExcludeOptions(excludeOptions []string, srcSuffix string) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
func deltaSourceTarget(sourceURL, targetURL string, isFake, isOverwrite, isRemove, isMetadata bool, excludeOptions []string, URLsCh chan<- URLs, encKeyDB map[string][]prefixSSEPair) {
|
||||
func deltaSourceTarget(ctx context.Context, sourceURL, targetURL string, opts mirrorOptions, URLsCh chan<- URLs) {
|
||||
// source and targets are always directories
|
||||
sourceSeparator := string(newClientURL(sourceURL).Separator)
|
||||
if !strings.HasSuffix(sourceURL, sourceSeparator) {
|
||||
@@ -125,7 +127,7 @@ func deltaSourceTarget(sourceURL, targetURL string, isFake, isOverwrite, isRemov
|
||||
}
|
||||
|
||||
// List both source and target, compare and return values through channel.
|
||||
for diffMsg := range objectDifference(sourceClnt, targetClnt, sourceURL, targetURL, isMetadata) {
|
||||
for diffMsg := range objectDifference(ctx, sourceClnt, targetClnt, sourceURL, targetURL, opts.isMetadata) {
|
||||
if diffMsg.Error != nil {
|
||||
// Send all errors through the channel
|
||||
URLsCh <- URLs{Error: diffMsg.Error}
|
||||
@@ -134,13 +136,13 @@ func deltaSourceTarget(sourceURL, targetURL string, isFake, isOverwrite, isRemov
|
||||
|
||||
srcSuffix := strings.TrimPrefix(diffMsg.FirstURL, sourceURL)
|
||||
//Skip the source object if it matches the Exclude options provided
|
||||
if matchExcludeOptions(excludeOptions, srcSuffix) {
|
||||
if matchExcludeOptions(opts.excludeOptions, srcSuffix) {
|
||||
continue
|
||||
}
|
||||
|
||||
tgtSuffix := strings.TrimPrefix(diffMsg.SecondURL, targetURL)
|
||||
//Skip the target object if it matches the Exclude options provided
|
||||
if matchExcludeOptions(excludeOptions, tgtSuffix) {
|
||||
if matchExcludeOptions(opts.excludeOptions, tgtSuffix) {
|
||||
continue
|
||||
}
|
||||
|
||||
@@ -149,8 +151,8 @@ func deltaSourceTarget(sourceURL, targetURL string, isFake, isOverwrite, isRemov
|
||||
// No difference, continue.
|
||||
case differInType:
|
||||
URLsCh <- URLs{Error: errInvalidTarget(diffMsg.SecondURL)}
|
||||
case differInSize, differInMetadata, differInMMSourceMTime:
|
||||
if !isOverwrite && !isFake {
|
||||
case differInSize, differInMetadata, differInAASourceMTime:
|
||||
if !opts.isOverwrite && !opts.isFake && !opts.activeActive {
|
||||
// Size or time or etag differs but --overwrite not set.
|
||||
URLsCh <- URLs{Error: errOverWriteNotAllowed(diffMsg.SecondURL)}
|
||||
continue
|
||||
@@ -180,7 +182,7 @@ func deltaSourceTarget(sourceURL, targetURL string, isFake, isOverwrite, isRemov
|
||||
TargetContent: targetContent,
|
||||
}
|
||||
case differInSecond:
|
||||
if !isRemove && !isFake {
|
||||
if !opts.isRemove && !opts.isFake {
|
||||
continue
|
||||
}
|
||||
URLsCh <- URLs{
|
||||
@@ -195,9 +197,20 @@ func deltaSourceTarget(sourceURL, targetURL string, isFake, isOverwrite, isRemov
|
||||
}
|
||||
}
|
||||
|
||||
type mirrorOptions struct {
|
||||
isFake, isOverwrite, activeActive bool
|
||||
isWatch, isRemove, isMetadata bool
|
||||
excludeOptions []string
|
||||
encKeyDB map[string][]prefixSSEPair
|
||||
md5, disableMultipart bool
|
||||
olderThan, newerThan string
|
||||
storageClass string
|
||||
userMetadata map[string]string
|
||||
}
|
||||
|
||||
// Prepares urls that need to be copied or removed based on requested options.
|
||||
func prepareMirrorURLs(sourceURL string, targetURL string, isFake, isOverwrite, isRemove, isMetadata bool, excludeOptions []string, encKeyDB map[string][]prefixSSEPair) <-chan URLs {
|
||||
func prepareMirrorURLs(ctx context.Context, sourceURL string, targetURL string, opts mirrorOptions) <-chan URLs {
|
||||
URLsCh := make(chan URLs)
|
||||
go deltaSourceTarget(sourceURL, targetURL, isFake, isOverwrite, isRemove, isMetadata, excludeOptions, URLsCh, encKeyDB)
|
||||
go deltaSourceTarget(ctx, sourceURL, targetURL, opts, URLsCh)
|
||||
return URLsCh
|
||||
}
|
||||
|
||||
+33
-29
@@ -17,6 +17,7 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
@@ -181,7 +182,7 @@ func (rm *removeManager) readErrors(errorCh <-chan *probe.Error, targetURL strin
|
||||
}()
|
||||
}
|
||||
|
||||
func (rm *removeManager) add(targetAlias, targetURL string) {
|
||||
func (rm *removeManager) add(ctx context.Context, targetAlias, targetURL string) {
|
||||
if atomic.LoadInt32(&rm.isClosed) != 0 {
|
||||
return
|
||||
}
|
||||
@@ -198,7 +199,7 @@ func (rm *removeManager) add(targetAlias, targetURL string) {
|
||||
}
|
||||
|
||||
contentCh := make(chan *ClientContent)
|
||||
errorCh := client.Remove(false, false, false, contentCh)
|
||||
errorCh := client.Remove(ctx, false, false, false, contentCh)
|
||||
rm.readErrors(errorCh, targetURL)
|
||||
|
||||
clientInfo = &removeClientInfo{
|
||||
@@ -236,7 +237,7 @@ var rmManager = &removeManager{
|
||||
doneCh: make(chan struct{}),
|
||||
}
|
||||
|
||||
func bgRemove(url string) {
|
||||
func bgRemove(ctx context.Context, url string) {
|
||||
remove := func(targetAlias, targetURL string) {
|
||||
clnt, pErr := newClientFromAlias(targetAlias, targetURL)
|
||||
if pErr != nil {
|
||||
@@ -246,7 +247,7 @@ func bgRemove(url string) {
|
||||
contentCh := make(chan *ClientContent, 1)
|
||||
contentCh <- &ClientContent{URL: *newClientURL(targetURL)}
|
||||
close(contentCh)
|
||||
errorCh := clnt.Remove(false, false, false, contentCh)
|
||||
errorCh := clnt.Remove(ctx, false, false, false, contentCh)
|
||||
for pErr := range errorCh {
|
||||
if pErr != nil {
|
||||
errorIf(pErr.Trace(url), "Failed to remove `"+url+"`.")
|
||||
@@ -266,27 +267,30 @@ func bgRemove(url string) {
|
||||
return
|
||||
}
|
||||
|
||||
rmManager.add(targetAlias, targetURL)
|
||||
rmManager.add(ctx, targetAlias, targetURL)
|
||||
}
|
||||
|
||||
// mainMove is the entry point for mv command.
|
||||
func mainMove(ctx *cli.Context) error {
|
||||
func mainMove(cliCtx *cli.Context) error {
|
||||
ctx, cancelMove := context.WithCancel(globalContext)
|
||||
defer cancelMove()
|
||||
|
||||
// Parse encryption keys per command.
|
||||
encKeyDB, err := getEncKeys(ctx)
|
||||
encKeyDB, err := getEncKeys(cliCtx)
|
||||
fatalIf(err, "Unable to parse encryption keys.")
|
||||
|
||||
// Parse metadata.
|
||||
userMetaMap := make(map[string]string)
|
||||
if ctx.String("attr") != "" {
|
||||
userMetaMap, err = getMetaDataEntry(ctx.String("attr"))
|
||||
fatalIf(err, "Unable to parse attribute %v", ctx.String("attr"))
|
||||
if cliCtx.String("attr") != "" {
|
||||
userMetaMap, err = getMetaDataEntry(cliCtx.String("attr"))
|
||||
fatalIf(err, "Unable to parse attribute %v", cliCtx.String("attr"))
|
||||
}
|
||||
|
||||
// check 'copy' cli arguments.
|
||||
checkCopySyntax(ctx, encKeyDB, true)
|
||||
checkCopySyntax(ctx, cliCtx, encKeyDB, true)
|
||||
|
||||
if ctx.NArg() == 2 {
|
||||
args := ctx.Args()
|
||||
if cliCtx.NArg() == 2 {
|
||||
args := cliCtx.Args()
|
||||
srcURL := args.Get(0)
|
||||
dstURL := args.Get(1)
|
||||
if srcURL == dstURL {
|
||||
@@ -294,14 +298,14 @@ func mainMove(ctx *cli.Context) error {
|
||||
}
|
||||
}
|
||||
|
||||
for _, urlStr := range ctx.Args() {
|
||||
for _, urlStr := range cliCtx.Args() {
|
||||
client, err := newClient(urlStr)
|
||||
if err != nil {
|
||||
fatalIf(err.Trace(), "Cannot parse the provided url.")
|
||||
}
|
||||
|
||||
if s3Client, ok := client.(*S3Client); ok {
|
||||
if _, _, _, err = s3Client.GetObjectLockConfig(); err == nil {
|
||||
if _, _, _, err = s3Client.GetObjectLockConfig(ctx); err == nil {
|
||||
fatalIf(probe.NewError(errors.New("")), fmt.Sprintf("Object lock configuration is enabled on the specified bucket in alias %v.", urlStr))
|
||||
}
|
||||
}
|
||||
@@ -310,12 +314,12 @@ func mainMove(ctx *cli.Context) error {
|
||||
// Additional command speific theme customization.
|
||||
console.SetColor("Copy", color.New(color.FgGreen, color.Bold))
|
||||
|
||||
recursive := ctx.Bool("recursive")
|
||||
olderThan := ctx.String("older-than")
|
||||
newerThan := ctx.String("newer-than")
|
||||
storageClass := ctx.String("storage-class")
|
||||
recursive := cliCtx.Bool("recursive")
|
||||
olderThan := cliCtx.String("older-than")
|
||||
newerThan := cliCtx.String("newer-than")
|
||||
storageClass := cliCtx.String("storage-class")
|
||||
sseKeys := os.Getenv("MC_ENCRYPT_KEY")
|
||||
if key := ctx.String("encrypt-key"); key != "" {
|
||||
if key := cliCtx.String("encrypt-key"); key != "" {
|
||||
sseKeys = key
|
||||
}
|
||||
|
||||
@@ -323,12 +327,12 @@ func mainMove(ctx *cli.Context) error {
|
||||
sseKeys, err = getDecodedKey(sseKeys)
|
||||
fatalIf(err, "Unable to parse encryption keys.")
|
||||
}
|
||||
sse := ctx.String("encrypt")
|
||||
sse := cliCtx.String("encrypt")
|
||||
|
||||
var session *sessionV8
|
||||
|
||||
if ctx.Bool("continue") {
|
||||
sessionID := getHash("mv", ctx.Args())
|
||||
if cliCtx.Bool("continue") {
|
||||
sessionID := getHash("mv", cliCtx.Args())
|
||||
if isSessionExists(sessionID) {
|
||||
session, err = loadSessionV8(sessionID)
|
||||
fatalIf(err.Trace(sessionID), "Unable to load session.")
|
||||
@@ -341,13 +345,13 @@ func mainMove(ctx *cli.Context) error {
|
||||
session.Header.CommandStringFlags["storage-class"] = storageClass
|
||||
session.Header.CommandStringFlags["encrypt-key"] = sseKeys
|
||||
session.Header.CommandStringFlags["encrypt"] = sse
|
||||
session.Header.CommandBoolFlags["session"] = ctx.Bool("continue")
|
||||
session.Header.CommandBoolFlags["session"] = cliCtx.Bool("continue")
|
||||
|
||||
if ctx.Bool("preserve") {
|
||||
session.Header.CommandBoolFlags["preserve"] = ctx.Bool("preserve")
|
||||
if cliCtx.Bool("preserve") {
|
||||
session.Header.CommandBoolFlags["preserve"] = cliCtx.Bool("preserve")
|
||||
}
|
||||
session.Header.UserMetaData = userMetaMap
|
||||
session.Header.CommandBoolFlags["disable-multipart"] = ctx.Bool("disable-multipart")
|
||||
session.Header.CommandBoolFlags["disable-multipart"] = cliCtx.Bool("disable-multipart")
|
||||
|
||||
var e error
|
||||
if session.Header.RootPath, e = os.Getwd(); e != nil {
|
||||
@@ -356,11 +360,11 @@ func mainMove(ctx *cli.Context) error {
|
||||
}
|
||||
|
||||
// extract URLs.
|
||||
session.Header.CommandArgs = ctx.Args()
|
||||
session.Header.CommandArgs = cliCtx.Args()
|
||||
}
|
||||
}
|
||||
|
||||
e := doCopySession(ctx, session, encKeyDB, true)
|
||||
e := doCopySession(ctx, cancelMove, cliCtx, session, encKeyDB, true)
|
||||
if session != nil {
|
||||
session.Delete()
|
||||
}
|
||||
|
||||
+1
-1
@@ -90,7 +90,7 @@ func pipe(targetURL string, encKeyDB map[string][]prefixSSEPair, storageClass st
|
||||
if storageClass != "" {
|
||||
metadata = map[string]string{"X-Amz-Storage-Class": storageClass}
|
||||
}
|
||||
_, err := putTargetStreamWithURL(targetURL, os.Stdin, -1, sseKey, false, false, metadata)
|
||||
_, err := putTargetStreamWithURL(targetURL, os.Stdin, -1, sseKey, false, false, false, metadata)
|
||||
// TODO: See if this check is necessary.
|
||||
switch e := err.ToGoError().(type) {
|
||||
case *os.PathError:
|
||||
|
||||
+28
-18
@@ -18,6 +18,7 @@ package cmd
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"io"
|
||||
"net/url"
|
||||
"os"
|
||||
@@ -253,20 +254,20 @@ func accessPermToString(perm accessPerms) string {
|
||||
}
|
||||
|
||||
// doSetAccess do set access.
|
||||
func doSetAccess(targetURL string, targetPERMS accessPerms) *probe.Error {
|
||||
func doSetAccess(ctx context.Context, targetURL string, targetPERMS accessPerms) *probe.Error {
|
||||
clnt, err := newClient(targetURL)
|
||||
if err != nil {
|
||||
return err.Trace(targetURL)
|
||||
}
|
||||
policy := accessPermToString(targetPERMS)
|
||||
if err = clnt.SetAccess(policy, false); err != nil {
|
||||
if err = clnt.SetAccess(ctx, policy, false); err != nil {
|
||||
return err.Trace(targetURL, string(targetPERMS))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// doSetAccessJSON do set access JSON.
|
||||
func doSetAccessJSON(targetURL string, targetPERMS accessPerms) *probe.Error {
|
||||
func doSetAccessJSON(ctx context.Context, targetURL string, targetPERMS accessPerms) *probe.Error {
|
||||
clnt, err := newClient(targetURL)
|
||||
if err != nil {
|
||||
return err.Trace(targetURL)
|
||||
@@ -289,7 +290,7 @@ func doSetAccessJSON(targetURL string, targetPERMS accessPerms) *probe.Error {
|
||||
}
|
||||
|
||||
configBytes := configBuf[:n]
|
||||
if err = clnt.SetAccess(string(configBytes), true); err != nil {
|
||||
if err = clnt.SetAccess(ctx, string(configBytes), true); err != nil {
|
||||
return err.Trace(targetURL, string(targetPERMS))
|
||||
}
|
||||
return nil
|
||||
@@ -314,12 +315,12 @@ func stringToAccessPerm(perm string) accessPerms {
|
||||
}
|
||||
|
||||
// doGetAccess do get access.
|
||||
func doGetAccess(targetURL string) (perms accessPerms, policyStr string, err *probe.Error) {
|
||||
func doGetAccess(ctx context.Context, targetURL string) (perms accessPerms, policyStr string, err *probe.Error) {
|
||||
clnt, err := newClient(targetURL)
|
||||
if err != nil {
|
||||
return "", "", err.Trace(targetURL)
|
||||
}
|
||||
perm, policyJSON, err := clnt.GetAccess()
|
||||
perm, policyJSON, err := clnt.GetAccess(ctx)
|
||||
if err != nil {
|
||||
return "", "", err.Trace(targetURL)
|
||||
}
|
||||
@@ -327,18 +328,21 @@ func doGetAccess(targetURL string) (perms accessPerms, policyStr string, err *pr
|
||||
}
|
||||
|
||||
// doGetAccessRules do get access rules.
|
||||
func doGetAccessRules(targetURL string) (r map[string]string, err *probe.Error) {
|
||||
func doGetAccessRules(ctx context.Context, targetURL string) (r map[string]string, err *probe.Error) {
|
||||
clnt, err := newClient(targetURL)
|
||||
if err != nil {
|
||||
return map[string]string{}, err.Trace(targetURL)
|
||||
}
|
||||
return clnt.GetAccessRules()
|
||||
return clnt.GetAccessRules(ctx)
|
||||
}
|
||||
|
||||
// Run policy list command
|
||||
func runPolicyListCmd(args cli.Args) {
|
||||
ctx, cancelPolicyList := context.WithCancel(globalContext)
|
||||
defer cancelPolicyList()
|
||||
|
||||
targetURL := args.First()
|
||||
policies, err := doGetAccessRules(targetURL)
|
||||
policies, err := doGetAccessRules(ctx, targetURL)
|
||||
if err != nil {
|
||||
switch err.ToGoError().(type) {
|
||||
case APINotImplemented:
|
||||
@@ -354,11 +358,14 @@ func runPolicyListCmd(args cli.Args) {
|
||||
|
||||
// Run policy links command
|
||||
func runPolicyLinksCmd(args cli.Args, recursive bool) {
|
||||
ctx, cancelPolicyLinks := context.WithCancel(globalContext)
|
||||
defer cancelPolicyLinks()
|
||||
|
||||
// Get alias/bucket/prefix argument
|
||||
targetURL := args.First()
|
||||
|
||||
// Fetch all policies associated to the passed url
|
||||
policies, err := doGetAccessRules(targetURL)
|
||||
policies, err := doGetAccessRules(ctx, targetURL)
|
||||
if err != nil {
|
||||
switch err.ToGoError().(type) {
|
||||
case APINotImplemented:
|
||||
@@ -372,9 +379,6 @@ func runPolicyLinksCmd(args cli.Args, recursive bool) {
|
||||
// construct new pathes to list public objects
|
||||
alias, path := url2Alias(targetURL)
|
||||
|
||||
isRecursive := recursive
|
||||
isIncomplete := false
|
||||
|
||||
// Iterate over policy rules to fetch public urls, then search
|
||||
// for objects under those urls
|
||||
for k, v := range policies {
|
||||
@@ -394,13 +398,13 @@ func runPolicyLinksCmd(args cli.Args, recursive bool) {
|
||||
clnt, err := newClient(newURL)
|
||||
fatalIf(err.Trace(newURL), "Unable to initialize target `"+targetURL+"`.")
|
||||
// Search for public objects
|
||||
for content := range clnt.List(isRecursive, isIncomplete, false, DirFirst) {
|
||||
for content := range clnt.List(globalContext, ListOptions{isRecursive: recursive, showDir: DirFirst}) {
|
||||
if content.Err != nil {
|
||||
errorIf(content.Err.Trace(clnt.GetURL().String()), "Unable to list folder.")
|
||||
continue
|
||||
}
|
||||
|
||||
if content.Type.IsDir() && isRecursive {
|
||||
if content.Type.IsDir() && recursive {
|
||||
continue
|
||||
}
|
||||
|
||||
@@ -422,15 +426,21 @@ func runPolicyLinksCmd(args cli.Args, recursive bool) {
|
||||
|
||||
// Run policy cmd to fetch set permission
|
||||
func runPolicyCmd(args cli.Args) {
|
||||
ctx, cancelPolicy := context.WithCancel(globalContext)
|
||||
defer cancelPolicy()
|
||||
|
||||
var operation, policyStr string
|
||||
var probeErr *probe.Error
|
||||
perms := accessPerms(args.Get(1))
|
||||
targetURL := args.Get(2)
|
||||
if perms.isValidAccessPERM() {
|
||||
probeErr = doSetAccess(targetURL, perms)
|
||||
operation = "set"
|
||||
probeErr = doSetAccess(ctx, targetURL, perms)
|
||||
if probeErr == nil {
|
||||
perms, _, probeErr = doGetAccess(ctx, targetURL)
|
||||
}
|
||||
} else if perms.isValidAccessFile() {
|
||||
probeErr = doSetAccessJSON(targetURL, perms)
|
||||
probeErr = doSetAccessJSON(ctx, targetURL, perms)
|
||||
operation = "set-json"
|
||||
} else {
|
||||
targetURL = args.Get(1)
|
||||
@@ -438,7 +448,7 @@ func runPolicyCmd(args cli.Args) {
|
||||
if args.First() == "get-json" {
|
||||
operation = "get-json"
|
||||
}
|
||||
perms, policyStr, probeErr = doGetAccess(targetURL)
|
||||
perms, policyStr, probeErr = doGetAccess(ctx, targetURL)
|
||||
|
||||
}
|
||||
// Upon error exit.
|
||||
|
||||
+50
-28
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* MinIO Client (C) 2019 MinIO, Inc.
|
||||
* MinIO Client (C) 2019-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.
|
||||
@@ -21,6 +21,7 @@ import (
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/cli"
|
||||
@@ -33,7 +34,7 @@ var (
|
||||
rbFlags = []cli.Flag{
|
||||
cli.BoolFlag{
|
||||
Name: "force",
|
||||
Usage: "allow a recursive remove operation",
|
||||
Usage: "force a recursive remove operation on all object versions",
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "dangerous",
|
||||
@@ -61,10 +62,10 @@ FLAGS:
|
||||
EXAMPLES:
|
||||
1. Remove an empty bucket on Amazon S3 cloud storage
|
||||
{{.Prompt}} {{.HelpName}} s3/mybucket
|
||||
|
||||
|
||||
2. Remove a directory hierarchy.
|
||||
{{.Prompt}} {{.HelpName}} /tmp/this/new/dir1
|
||||
|
||||
|
||||
3. Remove bucket 'jazz-songs' and all its contents
|
||||
{{.Prompt}} {{.HelpName}} --force s3/jazz-songs
|
||||
|
||||
@@ -93,17 +94,17 @@ func (s removeBucketMessage) JSON() string {
|
||||
}
|
||||
|
||||
// Validate command line arguments.
|
||||
func checkRbSyntax(ctx *cli.Context) {
|
||||
if !ctx.Args().Present() {
|
||||
func checkRbSyntax(ctx context.Context, cliCtx *cli.Context) {
|
||||
if !cliCtx.Args().Present() {
|
||||
exitCode := 1
|
||||
cli.ShowCommandHelpAndExit(ctx, "rb", exitCode)
|
||||
cli.ShowCommandHelpAndExit(cliCtx, "rb", exitCode)
|
||||
}
|
||||
// Set command flags from context.
|
||||
isForce := ctx.Bool("force")
|
||||
isDangerous := ctx.Bool("dangerous")
|
||||
isForce := cliCtx.Bool("force")
|
||||
isDangerous := cliCtx.Bool("dangerous")
|
||||
|
||||
for _, url := range ctx.Args() {
|
||||
if isNamespaceRemoval(url) {
|
||||
for _, url := range cliCtx.Args() {
|
||||
if isNamespaceRemoval(ctx, url) {
|
||||
if isForce && isDangerous {
|
||||
continue
|
||||
}
|
||||
@@ -113,11 +114,8 @@ func checkRbSyntax(ctx *cli.Context) {
|
||||
}
|
||||
}
|
||||
|
||||
// deletes a bucket and all its contents
|
||||
func deleteBucket(url string) *probe.Error {
|
||||
ctx, cancelCopy := context.WithCancel(globalContext)
|
||||
defer cancelCopy()
|
||||
|
||||
// Delete a bucket and all its objects and versions will be removed as well.
|
||||
func deleteBucket(ctx context.Context, url string) *probe.Error {
|
||||
targetAlias, targetURL, _ := mustExpandAlias(url)
|
||||
clnt, pErr := newClientFromAlias(targetAlias, targetURL)
|
||||
if pErr != nil {
|
||||
@@ -126,11 +124,18 @@ func deleteBucket(url string) *probe.Error {
|
||||
var isIncomplete bool
|
||||
isRemoveBucket := true
|
||||
contentCh := make(chan *ClientContent)
|
||||
errorCh := clnt.Remove(isIncomplete, isRemoveBucket, false, contentCh)
|
||||
errorCh := clnt.Remove(ctx, isIncomplete, isRemoveBucket, false, contentCh)
|
||||
|
||||
go func() {
|
||||
defer close(contentCh)
|
||||
for content := range clnt.List(true, false, false, DirLast) {
|
||||
opts := ListOptions{
|
||||
isRecursive: true,
|
||||
withOlderVersions: true,
|
||||
withDeleteMarkers: true,
|
||||
showDir: DirLast,
|
||||
}
|
||||
|
||||
for content := range clnt.List(ctx, opts) {
|
||||
if content.Err != nil {
|
||||
contentCh <- content
|
||||
continue
|
||||
@@ -175,12 +180,12 @@ func deleteBucket(url string) *probe.Error {
|
||||
|
||||
// isNamespaceRemoval returns true if alias
|
||||
// is not qualified by bucket
|
||||
func isNamespaceRemoval(url string) bool {
|
||||
func isNamespaceRemoval(ctx context.Context, url string) bool {
|
||||
// clean path for aliases like s3/.
|
||||
//Note: UNC path using / works properly in go 1.9.2 even though it breaks the UNC specification.
|
||||
url = filepath.ToSlash(filepath.Clean(url))
|
||||
// namespace removal applies only for non FS. So filter out if passed url represents a directory
|
||||
if !isAliasURLDir(url, nil) {
|
||||
if !isAliasURLDir(ctx, url, nil, time.Time{}) {
|
||||
_, path := url2Alias(url)
|
||||
return (path == "")
|
||||
}
|
||||
@@ -188,16 +193,19 @@ func isNamespaceRemoval(url string) bool {
|
||||
}
|
||||
|
||||
// mainRemoveBucket is entry point for rb command.
|
||||
func mainRemoveBucket(ctx *cli.Context) error {
|
||||
func mainRemoveBucket(cliCtx *cli.Context) error {
|
||||
ctx, cancelRemoveBucket := context.WithCancel(globalContext)
|
||||
defer cancelRemoveBucket()
|
||||
|
||||
// check 'rb' cli arguments.
|
||||
checkRbSyntax(ctx)
|
||||
isForce := ctx.Bool("force")
|
||||
checkRbSyntax(ctx, cliCtx)
|
||||
isForce := cliCtx.Bool("force")
|
||||
|
||||
// Additional command specific theme customization.
|
||||
console.SetColor("RemoveBucket", color.New(color.FgGreen, color.Bold))
|
||||
|
||||
var cErr error
|
||||
for _, targetURL := range ctx.Args() {
|
||||
for _, targetURL := range cliCtx.Args() {
|
||||
// Instantiate client for URL.
|
||||
clnt, err := newClient(targetURL)
|
||||
if err != nil {
|
||||
@@ -205,7 +213,7 @@ func mainRemoveBucket(ctx *cli.Context) error {
|
||||
cErr = exitStatus(globalErrorExitStatus)
|
||||
continue
|
||||
}
|
||||
_, err = clnt.Stat(false, false, nil)
|
||||
_, err = clnt.Stat(ctx, StatOptions{})
|
||||
if err != nil {
|
||||
switch err.ToGoError().(type) {
|
||||
case BucketNameEmpty:
|
||||
@@ -217,20 +225,34 @@ func mainRemoveBucket(ctx *cli.Context) error {
|
||||
}
|
||||
}
|
||||
|
||||
// Check if the bucket contains any object, version or delete marker.
|
||||
isEmpty := true
|
||||
for range clnt.List(true, false, false, DirNone) {
|
||||
opts := ListOptions{
|
||||
isRecursive: true,
|
||||
showDir: DirNone,
|
||||
withOlderVersions: true,
|
||||
withDeleteMarkers: true,
|
||||
}
|
||||
|
||||
listCtx, listCancel := context.WithCancel(ctx)
|
||||
for obj := range clnt.List(listCtx, opts) {
|
||||
if obj.Err != nil {
|
||||
continue
|
||||
}
|
||||
isEmpty = false
|
||||
break
|
||||
}
|
||||
listCancel()
|
||||
|
||||
// For all recursive operations make sure to check for 'force' flag.
|
||||
if !isForce && !isEmpty {
|
||||
fatalIf(errDummy().Trace(), "`"+targetURL+"` is not empty. Retry this command with ‘--force’ flag if you want to remove `"+targetURL+"` and all its contents")
|
||||
}
|
||||
|
||||
e := deleteBucket(targetURL)
|
||||
e := deleteBucket(ctx, targetURL)
|
||||
fatalIf(e.Trace(targetURL), "Failed to remove `"+targetURL+"`.")
|
||||
|
||||
if !isNamespaceRemoval(targetURL) {
|
||||
if !isNamespaceRemoval(ctx, targetURL) {
|
||||
printMsg(removeBucketMessage{
|
||||
Bucket: targetURL, Status: "success",
|
||||
})
|
||||
|
||||
@@ -0,0 +1,150 @@
|
||||
/*
|
||||
* 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"
|
||||
"strconv"
|
||||
|
||||
"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-go/v7/pkg/replication"
|
||||
"github.com/minio/minio/pkg/console"
|
||||
)
|
||||
|
||||
var replicateAddFlags = []cli.Flag{
|
||||
cli.StringFlag{
|
||||
Name: "arn",
|
||||
Usage: "Role Arn",
|
||||
},
|
||||
cli.StringFlag{
|
||||
Name: "id",
|
||||
Usage: "id for the rule, should be a unique value",
|
||||
},
|
||||
cli.StringFlag{
|
||||
Name: "tags",
|
||||
Usage: "format '<key1>=<value1>&<key2>=<value2>&<key3>=<value3>', multiple values allowed for multiple key/value pairs",
|
||||
},
|
||||
cli.StringFlag{
|
||||
Name: "storage-class",
|
||||
Usage: "storage class for destination (STANDARD_IA,REDUCED_REDUNDANCY etc)",
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "disable",
|
||||
Usage: "disable the rule",
|
||||
},
|
||||
cli.IntFlag{
|
||||
Name: "priority",
|
||||
Usage: "priority of the rule, should be unique and is a required field",
|
||||
},
|
||||
}
|
||||
|
||||
var replicateAddCmd = cli.Command{
|
||||
Name: "add",
|
||||
Usage: "add a server side replication configuration rule",
|
||||
Action: mainReplicateAdd,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: append(globalFlags, replicateAddFlags...),
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
{{.HelpName}} TARGET
|
||||
|
||||
FLAGS:
|
||||
{{range .VisibleFlags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
1. Add replication configuration rule on bucket "mybucket" for alias "myminio".
|
||||
{{.Prompt}} {{.HelpName}} myminio/mybucket/prefix --tags "key1=value1&key2=value2" \
|
||||
--storage-class "STANDARD" \
|
||||
--arn 'arn:minio:replica::c5be6b16-769d-432a-9ef1-4567081f3566:destbucket' --priority 1
|
||||
|
||||
2. Add replication configuration rule with Disabled status on bucket "mybucket" for alias "myminio".
|
||||
{{.Prompt}} {{.HelpName}} myminio/mybucket/prefix --tags "key1=value1&key2=value2" \
|
||||
--storage-class "STANDARD" --disable
|
||||
--arn 'arn:minio:replica::c5be6b16-769d-432a-9ef1-4567081f3566:destbucket' --priority 1
|
||||
`,
|
||||
}
|
||||
|
||||
// checkReplicateAddSyntax - validate all the passed arguments
|
||||
func checkReplicateAddSyntax(ctx *cli.Context) {
|
||||
if len(ctx.Args()) != 1 {
|
||||
cli.ShowCommandHelpAndExit(ctx, "add", 1) // last argument is exit code
|
||||
}
|
||||
}
|
||||
|
||||
type replicateAddMessage struct {
|
||||
Op string `json:"op"`
|
||||
Status string `json:"status"`
|
||||
URL string `json:"url"`
|
||||
ID string `json:"id"`
|
||||
}
|
||||
|
||||
func (l replicateAddMessage) JSON() string {
|
||||
l.Status = "success"
|
||||
jsonMessageBytes, e := json.MarshalIndent(l, "", " ")
|
||||
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
|
||||
return string(jsonMessageBytes)
|
||||
}
|
||||
|
||||
func (l replicateAddMessage) String() string {
|
||||
if l.ID != "" {
|
||||
return console.Colorize("replicateAddMessage", "Replication configuration rule with ID `"+l.ID+"` applied to "+l.URL+".")
|
||||
}
|
||||
return console.Colorize("replicateAddMessage", "Replication configuration rule applied to "+l.URL+" successfully.")
|
||||
}
|
||||
|
||||
func mainReplicateAdd(cliCtx *cli.Context) error {
|
||||
ctx, cancelReplicateAdd := context.WithCancel(globalContext)
|
||||
defer cancelReplicateAdd()
|
||||
|
||||
console.SetColor("replicateAddMessage", color.New(color.FgGreen))
|
||||
|
||||
checkReplicateAddSyntax(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.")
|
||||
rcfg, err := client.GetReplication(ctx)
|
||||
fatalIf(err.Trace(args...), "Unable to get replication configuration")
|
||||
ruleStatus := "enable"
|
||||
if cliCtx.Bool("disable") {
|
||||
ruleStatus = "disable"
|
||||
}
|
||||
opts := replication.Options{
|
||||
TagString: cliCtx.String("tags"),
|
||||
Arn: cliCtx.String("arn"),
|
||||
StorageClass: cliCtx.String("storage-class"),
|
||||
Priority: strconv.Itoa(cliCtx.Int("priority")),
|
||||
RuleStatus: ruleStatus,
|
||||
ID: cliCtx.String("id"),
|
||||
Op: replication.AddOption,
|
||||
}
|
||||
fatalIf(client.SetReplication(ctx, &rcfg, opts), "Could not add replication rule")
|
||||
printMsg(replicateAddMessage{
|
||||
Op: "add",
|
||||
URL: aliasedURL,
|
||||
ID: opts.ID,
|
||||
})
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
/*
|
||||
* 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"
|
||||
|
||||
"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-go/v7/pkg/replication"
|
||||
"github.com/minio/minio/pkg/console"
|
||||
)
|
||||
|
||||
var replicateExportCmd = cli.Command{
|
||||
Name: "export",
|
||||
Usage: "export server side replication configuration",
|
||||
Action: mainReplicateExport,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
{{.HelpName}} TARGET
|
||||
|
||||
FLAGS:
|
||||
{{range .VisibleFlags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
1. Print replication configuration on bucket "mybucket" for alias "myminio" to STDOUT.
|
||||
{{.Prompt}} {{.HelpName}} myminio/mybucket
|
||||
|
||||
2. Export replication configuration on bucket "mybucket" for alias "myminio" to '/data/replicate/config'.
|
||||
{{.Prompt}} {{.HelpName}} myminio/mybucket > /data/replicate/config
|
||||
`,
|
||||
}
|
||||
|
||||
// checkReplicateExportSyntax - validate all the passed arguments
|
||||
func checkReplicateExportSyntax(ctx *cli.Context) {
|
||||
if len(ctx.Args()) != 1 {
|
||||
cli.ShowCommandHelpAndExit(ctx, "export", 1) // last argument is exit code
|
||||
}
|
||||
}
|
||||
|
||||
type replicateExportMessage struct {
|
||||
Op string `json:"op"`
|
||||
Status string `json:"status"`
|
||||
URL string `json:"url"`
|
||||
ReplicationConfig replication.Config `json:"config"`
|
||||
}
|
||||
|
||||
func (r replicateExportMessage) JSON() string {
|
||||
r.Status = "success"
|
||||
jsonMessageBytes, e := json.MarshalIndent(r, "", " ")
|
||||
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
|
||||
return string(jsonMessageBytes)
|
||||
}
|
||||
|
||||
func (r replicateExportMessage) String() string {
|
||||
if r.ReplicationConfig.Empty() {
|
||||
return console.Colorize("ReplicateNMessage", "No replication configuration found for "+r.URL+".")
|
||||
}
|
||||
msgBytes, e := json.MarshalIndent(r.ReplicationConfig, "", " ")
|
||||
fatalIf(probe.NewError(e), "Unable to marshal replication configuration")
|
||||
return string(msgBytes)
|
||||
}
|
||||
|
||||
func mainReplicateExport(cliCtx *cli.Context) error {
|
||||
ctx, cancelReplicateExport := context.WithCancel(globalContext)
|
||||
defer cancelReplicateExport()
|
||||
|
||||
console.SetColor("replicateExportMessage", color.New(color.FgGreen))
|
||||
console.SetColor("replicateExportFailure", color.New(color.FgRed))
|
||||
|
||||
checkReplicateExportSyntax(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.")
|
||||
rCfg, err := client.GetReplication(ctx)
|
||||
fatalIf(err.Trace(args...), "Unable to get replication configuration")
|
||||
printMsg(replicateExportMessage{
|
||||
Op: "export",
|
||||
Status: "success",
|
||||
URL: aliasedURL,
|
||||
ReplicationConfig: rCfg,
|
||||
})
|
||||
return nil
|
||||
}
|
||||
@@ -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"
|
||||
"os"
|
||||
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/cli"
|
||||
json "github.com/minio/mc/pkg/colorjson"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/minio-go/v7/pkg/replication"
|
||||
"github.com/minio/minio/pkg/console"
|
||||
)
|
||||
|
||||
var replicateImportCmd = cli.Command{
|
||||
Name: "import",
|
||||
Usage: "import server side replication configuration in JSON format",
|
||||
Action: mainReplicateImport,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
{{.HelpName}} TARGET
|
||||
|
||||
FLAGS:
|
||||
{{range .VisibleFlags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
1. Set replication configuration from '/data/replication/config' on bucket "mybucket" for alias "myminio".
|
||||
{{.Prompt}} {{.HelpName}} myminio/mybucket < '/data/replication/config'
|
||||
|
||||
2. Import replication configuration for bucket "mybucket" on alias "myminio" from STDIN.
|
||||
{{.Prompt}} {{.HelpName}} myminio/mybucket
|
||||
`,
|
||||
}
|
||||
|
||||
// checkReplicateImportSyntax - validate all the passed arguments
|
||||
func checkReplicateImportSyntax(ctx *cli.Context) {
|
||||
if len(ctx.Args()) != 1 {
|
||||
cli.ShowCommandHelpAndExit(ctx, "import", 1) // last argument is exit code
|
||||
}
|
||||
}
|
||||
|
||||
type replicateImportMessage struct {
|
||||
Op string `json:"op"`
|
||||
Status string `json:"status"`
|
||||
URL string `json:"url"`
|
||||
ReplicationConfig replication.Config `json:"config"`
|
||||
}
|
||||
|
||||
func (r replicateImportMessage) JSON() string {
|
||||
r.Status = "success"
|
||||
jsonMessageBytes, e := json.MarshalIndent(r, "", " ")
|
||||
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
|
||||
return string(jsonMessageBytes)
|
||||
}
|
||||
|
||||
func (r replicateImportMessage) String() string {
|
||||
return console.Colorize("replicateImportMessage", "Replication configuration successfully set on `"+r.URL+"`.")
|
||||
}
|
||||
|
||||
// readReplicationConfig read from stdin, returns XML.
|
||||
func readReplicationConfig() (*replication.Config, *probe.Error) {
|
||||
// User is expected to enter the replication configuration in JSON format
|
||||
var cfg = replication.Config{}
|
||||
|
||||
// Consume json from STDIN
|
||||
dec := json.NewDecoder(os.Stdin)
|
||||
if e := dec.Decode(&cfg); e != nil {
|
||||
return &cfg, probe.NewError(e)
|
||||
}
|
||||
|
||||
return &cfg, nil
|
||||
}
|
||||
|
||||
func mainReplicateImport(cliCtx *cli.Context) error {
|
||||
ctx, cancelReplicateImport := context.WithCancel(globalContext)
|
||||
defer cancelReplicateImport()
|
||||
|
||||
console.SetColor("replicateImportMessage", color.New(color.FgGreen))
|
||||
checkReplicateImportSyntax(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.")
|
||||
rCfg, err := readReplicationConfig()
|
||||
fatalIf(err.Trace(args...), "Unable to read replication configuration")
|
||||
|
||||
fatalIf(client.SetReplication(ctx, rCfg, replication.Options{Op: replication.ImportOption}).Trace(aliasedURL), "Unable to set replication configuration")
|
||||
printMsg(replicateImportMessage{
|
||||
Op: "import",
|
||||
Status: "success",
|
||||
URL: aliasedURL,
|
||||
})
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
/*
|
||||
* 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"
|
||||
"errors"
|
||||
"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-go/v7/pkg/replication"
|
||||
"github.com/minio/minio/pkg/console"
|
||||
)
|
||||
|
||||
var replicateListFlags = []cli.Flag{
|
||||
cli.StringFlag{
|
||||
Name: "status",
|
||||
Usage: "show rules by status. Valid options are [enabled,disabled]",
|
||||
},
|
||||
}
|
||||
|
||||
var replicateListCmd = cli.Command{
|
||||
Name: "ls",
|
||||
Usage: "list server side replication configuration rules",
|
||||
Action: mainReplicateList,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: append(globalFlags, replicateListFlags...),
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
{{.HelpName}} TARGET
|
||||
|
||||
FLAGS:
|
||||
{{range .VisibleFlags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
1. List server side replication configuration rules on bucket "mybucket" for alias "myminio".
|
||||
{{.Prompt}} {{.HelpName}} myminio/mybucket
|
||||
`,
|
||||
}
|
||||
|
||||
// checkReplicateListSyntax - validate all the passed arguments
|
||||
func checkReplicateListSyntax(ctx *cli.Context) {
|
||||
if len(ctx.Args()) != 1 {
|
||||
cli.ShowCommandHelpAndExit(ctx, "ls", 1) // last argument is exit code
|
||||
}
|
||||
}
|
||||
func printReplicateListHeader() {
|
||||
if globalJSON {
|
||||
return
|
||||
}
|
||||
idFieldMaxLen := 20
|
||||
priorityFieldMaxLen := 8
|
||||
statusFieldMaxLen := 8
|
||||
prefixFieldMaxLen := 25
|
||||
tagsFieldMaxLen := 25
|
||||
scFieldMaxLen := 15
|
||||
destBucketFieldMaxLen := 20
|
||||
console.Println(console.Colorize("Headers", newPrettyTable(" | ",
|
||||
Field{"ID", idFieldMaxLen},
|
||||
Field{"Priority", priorityFieldMaxLen},
|
||||
Field{"Status", statusFieldMaxLen},
|
||||
Field{"Prefix", prefixFieldMaxLen},
|
||||
Field{"Tags", tagsFieldMaxLen},
|
||||
Field{"DestBucket", destBucketFieldMaxLen},
|
||||
Field{"StorageClass", scFieldMaxLen},
|
||||
).buildRow("ID", "Priority", "Status", "Prefix", "Tags", "DestBucket", "StorageClass")))
|
||||
}
|
||||
|
||||
type replicateListMessage struct {
|
||||
Op string `json:"op"`
|
||||
Status string `json:"status"`
|
||||
URL string `json:"url"`
|
||||
Rule replication.Rule `json:"rule"`
|
||||
}
|
||||
|
||||
func (l replicateListMessage) JSON() string {
|
||||
l.Status = "success"
|
||||
jsonMessageBytes, e := json.MarshalIndent(l, "", " ")
|
||||
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
|
||||
return string(jsonMessageBytes)
|
||||
}
|
||||
|
||||
func (l replicateListMessage) String() string {
|
||||
idFieldMaxLen := 20
|
||||
priorityFieldMaxLen := 8
|
||||
statusFieldMaxLen := 8
|
||||
prefixFieldMaxLen := 25
|
||||
tagsFieldMaxLen := 25
|
||||
scFieldMaxLen := 15
|
||||
destBucketFieldMaxLen := 20
|
||||
r := l.Rule
|
||||
return console.Colorize("replicateListMessage", newPrettyTable(" | ",
|
||||
Field{"ID", idFieldMaxLen},
|
||||
Field{"Priority", priorityFieldMaxLen},
|
||||
Field{"Status", statusFieldMaxLen},
|
||||
Field{"Prefix", prefixFieldMaxLen},
|
||||
Field{"Tags", tagsFieldMaxLen},
|
||||
Field{"DestBucket", destBucketFieldMaxLen},
|
||||
Field{"StorageClass", scFieldMaxLen},
|
||||
).buildRow(r.ID, strconv.Itoa(r.Priority), string(r.Status), r.Filter.And.Prefix, r.Tags(), r.Destination.Bucket, r.Destination.StorageClass))
|
||||
}
|
||||
|
||||
func mainReplicateList(cliCtx *cli.Context) error {
|
||||
ctx, cancelReplicateList := context.WithCancel(globalContext)
|
||||
defer cancelReplicateList()
|
||||
|
||||
console.SetColor("Headers", color.New(color.Bold, color.FgHiGreen))
|
||||
|
||||
checkReplicateListSyntax(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.")
|
||||
rCfg, err := client.GetReplication(ctx)
|
||||
fatalIf(err.Trace(args...), "Unable to get replication configuration")
|
||||
|
||||
if rCfg.Empty() {
|
||||
fatalIf(probe.NewError(errors.New("replication configuration not set")).Trace(aliasedURL),
|
||||
"Unable to list replication configuration")
|
||||
}
|
||||
printReplicateListHeader()
|
||||
statusFlag := cliCtx.String("status")
|
||||
for _, rule := range rCfg.Rules {
|
||||
if statusFlag == "" || strings.EqualFold(statusFlag, string(rule.Status)) {
|
||||
printMsg(replicateListMessage{
|
||||
Rule: rule,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
/*
|
||||
* 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 replicateCmd = cli.Command{
|
||||
Name: "replicate",
|
||||
Usage: "configure server side bucket replication",
|
||||
HideHelpCommand: true,
|
||||
Action: mainReplicate,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
Subcommands: []cli.Command{
|
||||
replicateAddCmd,
|
||||
replicateSetCmd,
|
||||
replicateListCmd,
|
||||
replicateExportCmd,
|
||||
replicateImportCmd,
|
||||
replicateRemoveCmd,
|
||||
},
|
||||
}
|
||||
|
||||
// mainReplicate is the handle for "mc replicate" command.
|
||||
func mainReplicate(ctx *cli.Context) error {
|
||||
cli.ShowCommandHelp(ctx, ctx.Args().First())
|
||||
return nil
|
||||
// Sub-commands like "list", "clear", "add" have their own main.
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
/*
|
||||
* 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"
|
||||
"errors"
|
||||
|
||||
"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-go/v7/pkg/replication"
|
||||
"github.com/minio/minio/pkg/console"
|
||||
)
|
||||
|
||||
var replicateRemoveFlags = []cli.Flag{
|
||||
cli.StringFlag{
|
||||
Name: "id",
|
||||
Usage: "id for the rule, should be a unique value",
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "force",
|
||||
Usage: "force remove all the replication configuration rules on the bucket",
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "all",
|
||||
Usage: "remove all replication configuration rules of the bucket, force flag enforced",
|
||||
},
|
||||
}
|
||||
|
||||
var replicateRemoveCmd = cli.Command{
|
||||
Name: "rm",
|
||||
Usage: "remove a server side replication configuration rule",
|
||||
Action: mainReplicateRemove,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: append(globalFlags, replicateRemoveFlags...),
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
{{.HelpName}} TARGET
|
||||
|
||||
FLAGS:
|
||||
{{range .VisibleFlags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
1. Remove replication configuration rule on bucket "mybucket" for alias "myminio" with rule id "bsib5mgt874bi56l0fmg".
|
||||
{{.Prompt}} {{.HelpName}} --id "bsib5mgt874bi56l0fmg" myminio/mybucket
|
||||
|
||||
2. Remove all the replication configuration rules on bucket "mybucket" for alias "myminio". --force flag is required.
|
||||
{{.Prompt}} {{.HelpName}} --all --force myminio/mybucket
|
||||
`,
|
||||
}
|
||||
|
||||
// checkReplicateRemoveSyntax - validate all the passed arguments
|
||||
func checkReplicateRemoveSyntax(ctx *cli.Context) {
|
||||
if len(ctx.Args()) != 1 {
|
||||
cli.ShowCommandHelpAndExit(ctx, "rm", 1) // last argument is exit code
|
||||
}
|
||||
rmAll := ctx.Bool("all")
|
||||
rmForce := ctx.Bool("force")
|
||||
rID := ctx.String("id")
|
||||
|
||||
rmChk := (rmAll && rmForce) || (!rmAll && !rmForce)
|
||||
if !rmChk {
|
||||
fatalIf(errInvalidArgument(),
|
||||
"It is mandatory to specify --all and --force flag together for mc "+ctx.Command.FullName()+".")
|
||||
}
|
||||
if rmAll && rmForce {
|
||||
return
|
||||
}
|
||||
|
||||
if rID == "" {
|
||||
fatalIf(errInvalidArgument().Trace(rID), "rule ID cannot be empty")
|
||||
}
|
||||
}
|
||||
|
||||
type replicateRemoveMessage struct {
|
||||
Op string `json:"op"`
|
||||
Status string `json:"status"`
|
||||
URL string `json:"url"`
|
||||
ID string `json:"id"`
|
||||
}
|
||||
|
||||
func (l replicateRemoveMessage) JSON() string {
|
||||
l.Status = "success"
|
||||
jsonMessageBytes, e := json.MarshalIndent(l, "", " ")
|
||||
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
|
||||
return string(jsonMessageBytes)
|
||||
}
|
||||
|
||||
func (l replicateRemoveMessage) String() string {
|
||||
if l.ID != "" {
|
||||
return console.Colorize("replicateRemoveMessage", "Replication configuration rule with ID `"+l.ID+"`removed from "+l.URL+".")
|
||||
}
|
||||
return console.Colorize("replicateRemoveMessage", "Replication configuration removed from "+l.URL+" successfully.")
|
||||
}
|
||||
|
||||
func mainReplicateRemove(cliCtx *cli.Context) error {
|
||||
ctx, cancelReplicateRemove := context.WithCancel(globalContext)
|
||||
defer cancelReplicateRemove()
|
||||
|
||||
console.SetColor("replicateRemoveMessage", color.New(color.FgGreen))
|
||||
|
||||
checkReplicateRemoveSyntax(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.")
|
||||
rcfg, err := client.GetReplication(ctx)
|
||||
fatalIf(err.Trace(args...), "Unable to get replication configuration")
|
||||
|
||||
if rcfg.Empty() {
|
||||
fatalIf(probe.NewError(errors.New("replication configuration not set")).Trace(aliasedURL),
|
||||
"Unable to remove replication configuration")
|
||||
}
|
||||
rmAll := cliCtx.Bool("all")
|
||||
rmForce := cliCtx.Bool("force")
|
||||
ruleID := cliCtx.String("id")
|
||||
if rmAll && rmForce {
|
||||
fatalIf(client.RemoveReplication(ctx), "Cannot remove replication configuration")
|
||||
} else {
|
||||
opts := replication.Options{
|
||||
ID: ruleID,
|
||||
Op: replication.RemoveOption,
|
||||
}
|
||||
fatalIf(client.SetReplication(ctx, &rcfg, opts), "Could not remove replication rule")
|
||||
}
|
||||
printMsg(replicateRemoveMessage{
|
||||
Op: "rm",
|
||||
Status: "success",
|
||||
URL: aliasedURL,
|
||||
ID: ruleID,
|
||||
})
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
/*
|
||||
* 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"
|
||||
"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-go/v7/pkg/replication"
|
||||
"github.com/minio/minio/pkg/console"
|
||||
)
|
||||
|
||||
var replicateSetFlags = []cli.Flag{
|
||||
cli.StringFlag{
|
||||
Name: "id",
|
||||
Usage: "id for the rule, should be a unique value",
|
||||
},
|
||||
cli.StringFlag{
|
||||
Name: "tags",
|
||||
Usage: "format '<key1>=<value1>&<key2>=<value2>&<key3>=<value3>', multiple values allowed for multiple key/value pairs",
|
||||
},
|
||||
cli.StringFlag{
|
||||
Name: "storage-class",
|
||||
Usage: "storage class for destination (STANDARD_IA,REDUCED_REDUNDANCY etc)",
|
||||
},
|
||||
cli.StringFlag{
|
||||
Name: "state",
|
||||
Usage: "change rule status. Valid values are [enable|disable]",
|
||||
},
|
||||
cli.IntFlag{
|
||||
Name: "priority",
|
||||
Usage: "priority of the rule, should be unique and is a required field",
|
||||
},
|
||||
}
|
||||
|
||||
var replicateSetCmd = cli.Command{
|
||||
Name: "set",
|
||||
Usage: "modify an existing server side replication configuration rule",
|
||||
Action: mainReplicateSet,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: append(globalFlags, replicateSetFlags...),
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
{{.HelpName}} TARGET
|
||||
|
||||
FLAGS:
|
||||
{{range .VisibleFlags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
1. Change priority of rule with rule ID "bsibgh8t874dnjst8hkg" on bucket "mybucket" for alias "myminio".
|
||||
{{.Prompt}} {{.HelpName}} myminio/mybucket --id "bsibgh8t874dnjst8hkg" --priority 3
|
||||
|
||||
2. Disable a replication configuration rule with rule ID "bsibgh8t874dnjst8hkg" on target myminio/bucket
|
||||
{{.Prompt}} {{.HelpName}} myminio/mybucket --id "bsibgh8t874dnjst8hkg" --state disable
|
||||
|
||||
3. Set tags and storage class on a replication configuration with rule ID "kMYD.491" on target myminio/bucket/prefix.
|
||||
{{.Prompt}} {{.HelpName}} myminio/mybucket --id "kMYD.491" --tags "key1=value1&key2=value2" \
|
||||
--storage-class "STANDARD" --priority 2
|
||||
|
||||
4. Clear tags for replication configuration rule with ID "kMYD.491" on a target myminio/bucket.
|
||||
{{.Prompt}} {{.HelpName}} myminio/mybucket --id "kMYD.491" --tags ""
|
||||
`,
|
||||
}
|
||||
|
||||
// checkReplicateSetSyntax - validate all the passed arguments
|
||||
func checkReplicateSetSyntax(ctx *cli.Context) {
|
||||
if len(ctx.Args()) != 1 {
|
||||
cli.ShowCommandHelpAndExit(ctx, "set", 1) // last argument is exit code
|
||||
}
|
||||
}
|
||||
|
||||
type replicateSetMessage struct {
|
||||
Op string `json:"op"`
|
||||
Status string `json:"status"`
|
||||
URL string `json:"url"`
|
||||
ID string `json:"id"`
|
||||
}
|
||||
|
||||
func (l replicateSetMessage) JSON() string {
|
||||
l.Status = "success"
|
||||
jsonMessageBytes, e := json.MarshalIndent(l, "", " ")
|
||||
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
|
||||
return string(jsonMessageBytes)
|
||||
}
|
||||
|
||||
func (l replicateSetMessage) String() string {
|
||||
if l.ID != "" {
|
||||
return console.Colorize("replicateSetMessage", "Replication configuration rule with ID `"+l.ID+"` applied to "+l.URL+".")
|
||||
}
|
||||
return console.Colorize("replicateSetMessage", "Replication configuration rule applied to "+l.URL+" successfully.")
|
||||
}
|
||||
|
||||
func mainReplicateSet(cliCtx *cli.Context) error {
|
||||
ctx, cancelReplicateSet := context.WithCancel(globalContext)
|
||||
defer cancelReplicateSet()
|
||||
|
||||
console.SetColor("replicateSetMessage", color.New(color.FgGreen))
|
||||
|
||||
checkReplicateSetSyntax(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.")
|
||||
rcfg, err := client.GetReplication(ctx)
|
||||
fatalIf(err.Trace(args...), "Unable to get replication configuration")
|
||||
|
||||
if !cliCtx.IsSet("id") {
|
||||
fatalIf(errInvalidArgument(), "--id is a required flag")
|
||||
}
|
||||
var state string
|
||||
if cliCtx.IsSet("state") {
|
||||
state = strings.ToLower(cliCtx.String("state"))
|
||||
if state != "enable" && state != "disable" {
|
||||
fatalIf(err.Trace(args...), "--state can be either `enable` or `disable`")
|
||||
}
|
||||
}
|
||||
opts := replication.Options{
|
||||
TagString: cliCtx.String("tags"),
|
||||
Arn: cliCtx.String("arn"),
|
||||
StorageClass: cliCtx.String("storage-class"),
|
||||
RuleStatus: state,
|
||||
ID: cliCtx.String("id"),
|
||||
Op: replication.SetOption,
|
||||
}
|
||||
if cliCtx.IsSet("priority") {
|
||||
opts.Priority = strconv.Itoa(cliCtx.Int("priority"))
|
||||
}
|
||||
|
||||
fatalIf(client.SetReplication(ctx, &rcfg, opts), "Could not modify replication rule")
|
||||
printMsg(replicateSetMessage{
|
||||
Op: "set",
|
||||
URL: aliasedURL,
|
||||
ID: opts.ID,
|
||||
})
|
||||
return nil
|
||||
}
|
||||
@@ -17,6 +17,7 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
@@ -26,7 +27,7 @@ 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"
|
||||
)
|
||||
|
||||
@@ -116,6 +117,9 @@ func getRetainUntilDate(validity uint64, unit minio.ValidityUnit) (string, *prob
|
||||
|
||||
// setRetention - Set Retention for all objects within a given prefix.
|
||||
func setRetention(urlStr string, mode minio.RetentionMode, validity uint64, unit minio.ValidityUnit, bypassGovernance, isRecursive bool) error {
|
||||
ctx, cancelSetRetention := context.WithCancel(globalContext)
|
||||
defer cancelSetRetention()
|
||||
|
||||
clnt, err := newClient(urlStr)
|
||||
if err != nil {
|
||||
fatalIf(err.Trace(), "Cannot parse the provided url.")
|
||||
@@ -130,7 +134,7 @@ func setRetention(urlStr string, mode minio.RetentionMode, validity uint64, unit
|
||||
alias, _, _ := mustExpandAlias(urlStr)
|
||||
|
||||
var cErr error
|
||||
for content := range clnt.List(isRecursive, false, false, DirNone) {
|
||||
for content := range clnt.List(ctx, ListOptions{isRecursive: isRecursive, showDir: DirNone}) {
|
||||
if content.Err != nil {
|
||||
errorIf(content.Err.Trace(clnt.GetURL().String()), "Unable to list folder.")
|
||||
cErr = exitStatus(globalErrorExitStatus) // Set the exit status.
|
||||
@@ -152,7 +156,7 @@ func setRetention(urlStr string, mode minio.RetentionMode, validity uint64, unit
|
||||
errorIf(err.Trace(clnt.GetURL().String()), "Invalid URL")
|
||||
continue
|
||||
}
|
||||
err = newClnt.PutObjectRetention(mode, retainUntil, bypassGovernance)
|
||||
err = newClnt.PutObjectRetention(ctx, mode, retainUntil, bypassGovernance)
|
||||
if err != nil {
|
||||
printMsg(retentionCmdMessage{
|
||||
Mode: mode,
|
||||
|
||||
+10
-6
@@ -18,11 +18,12 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"context"
|
||||
"math/rand"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/minio/minio-go/v6"
|
||||
"github.com/minio/minio-go/v7"
|
||||
)
|
||||
|
||||
// lockedRandSource provides protected rand source, implements rand.Source interface.
|
||||
@@ -51,7 +52,7 @@ func (r *lockedRandSource) Seed(seed int64) {
|
||||
var random = rand.New(&lockedRandSource{src: rand.NewSource(time.Now().UTC().UnixNano())})
|
||||
|
||||
// newRetryTimerContinous creates a timer with exponentially increasing delays forever.
|
||||
func newRetryTimerContinous(unit time.Duration, cap time.Duration, jitter float64, doneCh chan struct{}) <-chan int {
|
||||
func newRetryTimerContinous(ctx context.Context, unit time.Duration, cap time.Duration, jitter float64) <-chan int {
|
||||
attemptCh := make(chan int)
|
||||
|
||||
// normalize jitter to the range [0, 1.0]
|
||||
@@ -86,14 +87,17 @@ func newRetryTimerContinous(unit time.Duration, cap time.Duration, jitter float6
|
||||
var nextBackoff int
|
||||
for {
|
||||
select {
|
||||
// Attempts starts.
|
||||
case attemptCh <- nextBackoff:
|
||||
nextBackoff++
|
||||
case <-doneCh:
|
||||
// Stop the routine.
|
||||
case <-ctx.Done():
|
||||
return
|
||||
}
|
||||
|
||||
select {
|
||||
case <-time.After(exponentialBackoffWait(nextBackoff)):
|
||||
case <-ctx.Done():
|
||||
return
|
||||
}
|
||||
time.Sleep(exponentialBackoffWait(nextBackoff))
|
||||
}
|
||||
}()
|
||||
return attemptCh
|
||||
|
||||
+36
-26
@@ -18,10 +18,12 @@ package cmd
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/cli"
|
||||
@@ -148,20 +150,20 @@ func (r rmMessage) JSON() string {
|
||||
}
|
||||
|
||||
// Validate command line arguments.
|
||||
func checkRmSyntax(ctx *cli.Context, encKeyDB map[string][]prefixSSEPair) {
|
||||
func checkRmSyntax(ctx context.Context, cliCtx *cli.Context, encKeyDB map[string][]prefixSSEPair) {
|
||||
// Set command flags from context.
|
||||
isForce := ctx.Bool("force")
|
||||
isRecursive := ctx.Bool("recursive")
|
||||
isStdin := ctx.Bool("stdin")
|
||||
isDangerous := ctx.Bool("dangerous")
|
||||
isForce := cliCtx.Bool("force")
|
||||
isRecursive := cliCtx.Bool("recursive")
|
||||
isStdin := cliCtx.Bool("stdin")
|
||||
isDangerous := cliCtx.Bool("dangerous")
|
||||
isNamespaceRemoval := false
|
||||
|
||||
for _, url := range ctx.Args() {
|
||||
for _, url := range cliCtx.Args() {
|
||||
// clean path for aliases like s3/.
|
||||
// Note: UNC path using / works properly in go 1.9.2 even though it breaks the UNC specification.
|
||||
url = filepath.ToSlash(filepath.Clean(url))
|
||||
// namespace removal applies only for non FS. So filter out if passed url represents a directory
|
||||
dir := isAliasURLDir(url, encKeyDB)
|
||||
dir := isAliasURLDir(ctx, url, encKeyDB, time.Time{})
|
||||
if !dir {
|
||||
_, path := url2Alias(url)
|
||||
isNamespaceRemoval = (path == "")
|
||||
@@ -176,9 +178,9 @@ func checkRmSyntax(ctx *cli.Context, encKeyDB map[string][]prefixSSEPair) {
|
||||
"Removal requires --recursive flag. This operation is *IRREVERSIBLE*. Please review carefully before performing this *DANGEROUS* operation.")
|
||||
}
|
||||
}
|
||||
if !ctx.Args().Present() && !isStdin {
|
||||
if !cliCtx.Args().Present() && !isStdin {
|
||||
exitCode := 1
|
||||
cli.ShowCommandHelpAndExit(ctx, "rm", exitCode)
|
||||
cli.ShowCommandHelpAndExit(cliCtx, "rm", exitCode)
|
||||
}
|
||||
|
||||
// For all recursive operations make sure to check for 'force' flag.
|
||||
@@ -197,8 +199,11 @@ func checkRmSyntax(ctx *cli.Context, encKeyDB map[string][]prefixSSEPair) {
|
||||
}
|
||||
|
||||
func removeSingle(url string, isIncomplete, isFake, isForce, isBypass bool, olderThan, newerThan string, encKeyDB map[string][]prefixSSEPair) error {
|
||||
ctx, cancelRemoveSingle := context.WithCancel(globalContext)
|
||||
defer cancelRemoveSingle()
|
||||
|
||||
isRecursive := false
|
||||
contents, pErr := statURL(url, isIncomplete, isRecursive, encKeyDB)
|
||||
contents, pErr := statURL(ctx, url, isIncomplete, isRecursive, encKeyDB)
|
||||
if pErr != nil {
|
||||
errorIf(pErr.Trace(url), "Failed to remove `"+url+"`.")
|
||||
return exitStatus(globalErrorExitStatus)
|
||||
@@ -243,7 +248,7 @@ func removeSingle(url string, isIncomplete, isFake, isForce, isBypass bool, olde
|
||||
contentCh <- &ClientContent{URL: *newClientURL(targetURL)}
|
||||
close(contentCh)
|
||||
isRemoveBucket := false
|
||||
errorCh := clnt.Remove(isIncomplete, isRemoveBucket, isBypass, contentCh)
|
||||
errorCh := clnt.Remove(ctx, isIncomplete, isRemoveBucket, isBypass, contentCh)
|
||||
for pErr := range errorCh {
|
||||
if pErr != nil {
|
||||
errorIf(pErr.Trace(url), "Failed to remove `"+url+"`.")
|
||||
@@ -260,6 +265,9 @@ func removeSingle(url string, isIncomplete, isFake, isForce, isBypass bool, olde
|
||||
}
|
||||
|
||||
func removeRecursive(url string, isIncomplete, isFake, isBypass bool, olderThan, newerThan string, encKeyDB map[string][]prefixSSEPair) error {
|
||||
ctx, cancelRemoveRecursive := context.WithCancel(globalContext)
|
||||
defer cancelRemoveRecursive()
|
||||
|
||||
targetAlias, targetURL, _ := mustExpandAlias(url)
|
||||
clnt, pErr := newClientFromAlias(targetAlias, targetURL)
|
||||
if pErr != nil {
|
||||
@@ -269,10 +277,9 @@ func removeRecursive(url string, isIncomplete, isFake, isBypass bool, olderThan,
|
||||
contentCh := make(chan *ClientContent)
|
||||
isRemoveBucket := false
|
||||
|
||||
errorCh := clnt.Remove(isIncomplete, isRemoveBucket, isBypass, contentCh)
|
||||
errorCh := clnt.Remove(ctx, isIncomplete, isRemoveBucket, isBypass, contentCh)
|
||||
|
||||
isRecursive := true
|
||||
for content := range clnt.List(isRecursive, isIncomplete, false, DirNone) {
|
||||
for content := range clnt.List(ctx, ListOptions{isRecursive: true, isIncomplete: isIncomplete, showDir: DirNone}) {
|
||||
if content.Err != nil {
|
||||
errorIf(content.Err.Trace(url), "Failed to remove `"+url+"` recursively.")
|
||||
switch content.Err.ToGoError().(type) {
|
||||
@@ -340,23 +347,26 @@ func removeRecursive(url string, isIncomplete, isFake, isBypass bool, olderThan,
|
||||
}
|
||||
|
||||
// main for rm command.
|
||||
func mainRm(ctx *cli.Context) error {
|
||||
func mainRm(cliCtx *cli.Context) error {
|
||||
ctx, cancelRm := context.WithCancel(globalContext)
|
||||
defer cancelRm()
|
||||
|
||||
// Parse encryption keys per command.
|
||||
encKeyDB, err := getEncKeys(ctx)
|
||||
encKeyDB, err := getEncKeys(cliCtx)
|
||||
fatalIf(err, "Unable to parse encryption keys.")
|
||||
|
||||
// check 'rm' cli arguments.
|
||||
checkRmSyntax(ctx, encKeyDB)
|
||||
checkRmSyntax(ctx, cliCtx, encKeyDB)
|
||||
|
||||
// rm specific flags.
|
||||
isIncomplete := ctx.Bool("incomplete")
|
||||
isRecursive := ctx.Bool("recursive")
|
||||
isFake := ctx.Bool("fake")
|
||||
isStdin := ctx.Bool("stdin")
|
||||
isBypass := ctx.Bool(bypass)
|
||||
olderThan := ctx.String("older-than")
|
||||
newerThan := ctx.String("newer-than")
|
||||
isForce := ctx.Bool("force")
|
||||
isIncomplete := cliCtx.Bool("incomplete")
|
||||
isRecursive := cliCtx.Bool("recursive")
|
||||
isFake := cliCtx.Bool("fake")
|
||||
isStdin := cliCtx.Bool("stdin")
|
||||
isBypass := cliCtx.Bool(bypass)
|
||||
olderThan := cliCtx.String("older-than")
|
||||
newerThan := cliCtx.String("newer-than")
|
||||
isForce := cliCtx.Bool("force")
|
||||
|
||||
// Set color.
|
||||
console.SetColor("Remove", color.New(color.FgGreen, color.Bold))
|
||||
@@ -364,7 +374,7 @@ func mainRm(ctx *cli.Context) error {
|
||||
var rerr error
|
||||
var e error
|
||||
// Support multiple targets.
|
||||
for _, url := range ctx.Args() {
|
||||
for _, url := range cliCtx.Args() {
|
||||
if isRecursive {
|
||||
e = removeRecursive(url, isIncomplete, isFake, isBypass, olderThan, newerThan, encKeyDB)
|
||||
} else {
|
||||
|
||||
+24
-22
@@ -17,6 +17,7 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -66,15 +67,15 @@ EXAMPLES:
|
||||
}
|
||||
|
||||
// checkShareDownloadSyntax - validate command-line args.
|
||||
func checkShareDownloadSyntax(ctx *cli.Context, encKeyDB map[string][]prefixSSEPair) {
|
||||
args := ctx.Args()
|
||||
func checkShareDownloadSyntax(ctx context.Context, cliCtx *cli.Context, encKeyDB map[string][]prefixSSEPair) {
|
||||
args := cliCtx.Args()
|
||||
if !args.Present() {
|
||||
cli.ShowCommandHelpAndExit(ctx, "download", 1) // last argument is exit code.
|
||||
cli.ShowCommandHelpAndExit(cliCtx, "download", 1) // last argument is exit code.
|
||||
}
|
||||
|
||||
// Parse expiry.
|
||||
expiry := shareDefaultExpiry
|
||||
expireArg := ctx.String("expire")
|
||||
expireArg := cliCtx.String("expire")
|
||||
if expireArg != "" {
|
||||
var e error
|
||||
expiry, e = time.ParseDuration(expireArg)
|
||||
@@ -90,10 +91,10 @@ func checkShareDownloadSyntax(ctx *cli.Context, encKeyDB map[string][]prefixSSEP
|
||||
}
|
||||
|
||||
// Validate if object exists only if the `--recursive` flag was NOT specified
|
||||
isRecursive := ctx.Bool("recursive")
|
||||
isRecursive := cliCtx.Bool("recursive")
|
||||
if !isRecursive {
|
||||
for _, url := range ctx.Args() {
|
||||
_, _, err := url2Stat(url, false, encKeyDB)
|
||||
for _, url := range cliCtx.Args() {
|
||||
_, _, err := url2Stat(ctx, url, "", false, encKeyDB, time.Time{})
|
||||
if err != nil {
|
||||
fatalIf(err.Trace(url), "Unable to stat `"+url+"`.")
|
||||
}
|
||||
@@ -102,7 +103,7 @@ func checkShareDownloadSyntax(ctx *cli.Context, encKeyDB map[string][]prefixSSEP
|
||||
}
|
||||
|
||||
// doShareURL share files from target.
|
||||
func doShareDownloadURL(targetURL string, isRecursive bool, expiry time.Duration) *probe.Error {
|
||||
func doShareDownloadURL(ctx context.Context, targetURL string, isRecursive bool, expiry time.Duration) *probe.Error {
|
||||
targetAlias, targetURLFull, _, err := expandAlias(targetURL)
|
||||
if err != nil {
|
||||
return err.Trace(targetURL)
|
||||
@@ -120,12 +121,10 @@ func doShareDownloadURL(targetURL string, isRecursive bool, expiry time.Duration
|
||||
return err.Trace(shareDownloadsFile)
|
||||
}
|
||||
|
||||
// Generate share URL for each target.
|
||||
isIncomplete := false
|
||||
// Channel which will receive objects whose URLs need to be shared
|
||||
objectsCh := make(chan *ClientContent)
|
||||
|
||||
content, err := clnt.Stat(isIncomplete, false, nil)
|
||||
content, err := clnt.Stat(ctx, StatOptions{})
|
||||
if err != nil {
|
||||
return err.Trace(clnt.GetURL().String())
|
||||
}
|
||||
@@ -146,7 +145,7 @@ func doShareDownloadURL(targetURL string, isRecursive bool, expiry time.Duration
|
||||
// Recursive mode: Share list of objects
|
||||
go func() {
|
||||
defer close(objectsCh)
|
||||
for content := range clnt.List(isRecursive, isIncomplete, false, DirNone) {
|
||||
for content := range clnt.List(ctx, ListOptions{isRecursive: isRecursive, showDir: DirNone}) {
|
||||
objectsCh <- content
|
||||
}
|
||||
}()
|
||||
@@ -168,7 +167,7 @@ func doShareDownloadURL(targetURL string, isRecursive bool, expiry time.Duration
|
||||
}
|
||||
|
||||
// Generate share URL.
|
||||
shareURL, err := newClnt.ShareDownload(expiry)
|
||||
shareURL, err := newClnt.ShareDownload(ctx, expiry)
|
||||
if err != nil {
|
||||
// add objectURL and expiry as part of the trace arguments.
|
||||
return err.Trace(objectURL, "expiry="+expiry.String())
|
||||
@@ -190,13 +189,16 @@ func doShareDownloadURL(targetURL string, isRecursive bool, expiry time.Duration
|
||||
}
|
||||
|
||||
// main for share download.
|
||||
func mainShareDownload(ctx *cli.Context) error {
|
||||
func mainShareDownload(cliCtx *cli.Context) error {
|
||||
ctx, cancelShareDownload := context.WithCancel(globalContext)
|
||||
defer cancelShareDownload()
|
||||
|
||||
// Parse encryption keys per command.
|
||||
encKeyDB, err := getEncKeys(ctx)
|
||||
encKeyDB, err := getEncKeys(cliCtx)
|
||||
fatalIf(err, "Unable to parse encryption keys.")
|
||||
|
||||
// check input arguments.
|
||||
checkShareDownloadSyntax(ctx, encKeyDB)
|
||||
checkShareDownloadSyntax(ctx, cliCtx, encKeyDB)
|
||||
|
||||
// Initialize share config folder.
|
||||
initShareConfig()
|
||||
@@ -205,16 +207,16 @@ func mainShareDownload(ctx *cli.Context) error {
|
||||
shareSetColor()
|
||||
|
||||
// Set command flags from context.
|
||||
isRecursive := ctx.Bool("recursive")
|
||||
isRecursive := cliCtx.Bool("recursive")
|
||||
expiry := shareDefaultExpiry
|
||||
if ctx.String("expire") != "" {
|
||||
if cliCtx.String("expire") != "" {
|
||||
var e error
|
||||
expiry, e = time.ParseDuration(ctx.String("expire"))
|
||||
fatalIf(probe.NewError(e), "Unable to parse expire=`"+ctx.String("expire")+"`.")
|
||||
expiry, e = time.ParseDuration(cliCtx.String("expire"))
|
||||
fatalIf(probe.NewError(e), "Unable to parse expire=`"+cliCtx.String("expire")+"`.")
|
||||
}
|
||||
|
||||
for _, targetURL := range ctx.Args() {
|
||||
err := doShareDownloadURL(targetURL, isRecursive, expiry)
|
||||
for _, targetURL := range cliCtx.Args() {
|
||||
err := doShareDownloadURL(ctx, targetURL, isRecursive, expiry)
|
||||
if err != nil {
|
||||
switch err.ToGoError().(type) {
|
||||
case APINotImplemented:
|
||||
|
||||
@@ -17,6 +17,7 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
@@ -142,14 +143,14 @@ func saveSharedURL(objectURL string, shareURL string, expiry time.Duration, cont
|
||||
}
|
||||
|
||||
// doShareUploadURL uploads files to the target.
|
||||
func doShareUploadURL(objectURL string, isRecursive bool, expiry time.Duration, contentType string) *probe.Error {
|
||||
func doShareUploadURL(ctx context.Context, objectURL string, isRecursive bool, expiry time.Duration, contentType string) *probe.Error {
|
||||
clnt, err := newClient(objectURL)
|
||||
if err != nil {
|
||||
return err.Trace(objectURL)
|
||||
}
|
||||
|
||||
// Generate pre-signed access info.
|
||||
shareURL, uploadInfo, err := clnt.ShareUpload(isRecursive, expiry, contentType)
|
||||
shareURL, uploadInfo, err := clnt.ShareUpload(context.Background(), isRecursive, expiry, contentType)
|
||||
if err != nil {
|
||||
return err.Trace(objectURL, "expiry="+expiry.String(), "contentType="+contentType)
|
||||
}
|
||||
@@ -175,10 +176,12 @@ func doShareUploadURL(objectURL string, isRecursive bool, expiry time.Duration,
|
||||
}
|
||||
|
||||
// main for share upload command.
|
||||
func mainShareUpload(ctx *cli.Context) error {
|
||||
func mainShareUpload(cliCtx *cli.Context) error {
|
||||
ctx, cancelShareDownload := context.WithCancel(globalContext)
|
||||
defer cancelShareDownload()
|
||||
|
||||
// check input arguments.
|
||||
checkShareUploadSyntax(ctx)
|
||||
checkShareUploadSyntax(cliCtx)
|
||||
|
||||
// Initialize share config folder.
|
||||
initShareConfig()
|
||||
@@ -187,18 +190,18 @@ func mainShareUpload(ctx *cli.Context) error {
|
||||
shareSetColor()
|
||||
|
||||
// Set command flags from context.
|
||||
isRecursive := ctx.Bool("recursive")
|
||||
expireArg := ctx.String("expire")
|
||||
isRecursive := cliCtx.Bool("recursive")
|
||||
expireArg := cliCtx.String("expire")
|
||||
expiry := shareDefaultExpiry
|
||||
contentType := ctx.String("content-type")
|
||||
contentType := cliCtx.String("content-type")
|
||||
if expireArg != "" {
|
||||
var e error
|
||||
expiry, e = time.ParseDuration(expireArg)
|
||||
fatalIf(probe.NewError(e), "Unable to parse expire=`"+expireArg+"`.")
|
||||
}
|
||||
|
||||
for _, targetURL := range ctx.Args() {
|
||||
err := doShareUploadURL(targetURL, isRecursive, expiry, contentType)
|
||||
for _, targetURL := range cliCtx.Args() {
|
||||
err := doShareUploadURL(ctx, targetURL, isRecursive, expiry, contentType)
|
||||
if err != nil {
|
||||
switch err.ToGoError().(type) {
|
||||
case APINotImplemented:
|
||||
|
||||
@@ -35,8 +35,10 @@ func trapSignals(sig ...os.Signal) {
|
||||
<-sigCh
|
||||
|
||||
// Once signal has been received stop signal Notify handler.
|
||||
|
||||
signal.Stop(sigCh)
|
||||
|
||||
// Cancel the global context
|
||||
globalCancel()
|
||||
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user