Compare commits
190
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f1f3003e5e | ||
|
|
5fcb069e8a | ||
|
|
c1fe60f7ad | ||
|
|
e7df97d1e0 | ||
|
|
95ee8f0714 | ||
|
|
c041d86f03 | ||
|
|
e13737383f | ||
|
|
c00afbc516 | ||
|
|
766b69802c | ||
|
|
864e4589ac | ||
|
|
41c804b179 | ||
|
|
fca6cb2815 | ||
|
|
d0e1456be3 | ||
|
|
2b99236a22 | ||
|
|
5023905a3a | ||
|
|
5ed74df9ed | ||
|
|
4e8e67fb04 | ||
|
|
1967d38dd4 | ||
|
|
74fc02e5eb | ||
|
|
52fc5e8c15 | ||
|
|
7ef637884c | ||
|
|
24101f18aa | ||
|
|
b6969bc501 | ||
|
|
4dc0a44ebf | ||
|
|
c691cc5488 | ||
|
|
d4fbfb5975 | ||
|
|
00873e4b93 | ||
|
|
b1f5e78980 | ||
|
|
bd7442fbc6 | ||
|
|
c7989d06bc | ||
|
|
681cbb06de | ||
|
|
3dffa04f66 | ||
|
|
060b0762fb | ||
|
|
df5f03a109 | ||
|
|
465e6cf63c | ||
|
|
25fd302af6 | ||
|
|
bf2f7f0292 | ||
|
|
138587816a | ||
|
|
d4f9ea859d | ||
|
|
adafa0024f | ||
|
|
9ac1bf4a29 | ||
|
|
f3dd24f578 | ||
|
|
3792e9f906 | ||
|
|
f1c04ad4b8 | ||
|
|
e216394765 | ||
|
|
6ab70467cc | ||
|
|
b2ab462551 | ||
|
|
786a53672b | ||
|
|
63ce578c46 | ||
|
|
965747e45d | ||
|
|
0289d32164 | ||
|
|
40e328eac2 | ||
|
|
470ae1ee5f | ||
|
|
50bfa26724 | ||
|
|
ab396ae957 | ||
|
|
7838365102 | ||
|
|
6c2325129f | ||
|
|
fa4da03a4f | ||
|
|
d1232dc089 | ||
|
|
91c9364f3c | ||
|
|
440f6dccbc | ||
|
|
6bae0eb218 | ||
|
|
b47b2e19a8 | ||
|
|
00f655ac41 | ||
|
|
b7a3dff287 | ||
|
|
8a8611cf74 | ||
|
|
bb2bfdc918 | ||
|
|
0324fdcc6e | ||
|
|
2b36376bbc | ||
|
|
f11c3a9733 | ||
|
|
3b65e9cba6 | ||
|
|
f11ae85566 | ||
|
|
7f2df96e48 | ||
|
|
4b34df590a | ||
|
|
177f15db2e | ||
|
|
2568f9e7bf | ||
|
|
217f5fcbae | ||
|
|
1ca2182203 | ||
|
|
150d2494e9 | ||
|
|
db1b508d8b | ||
|
|
d24de97cde | ||
|
|
3776dff20f | ||
|
|
9ff6c146b4 | ||
|
|
ce0c109ae3 | ||
|
|
0449df8887 | ||
|
|
a5d03c51e2 | ||
|
|
0c1f1e29f1 | ||
|
|
1dde65d9c0 | ||
|
|
f7b1b4a139 | ||
|
|
fede0756d4 | ||
|
|
64fb8f0a8f | ||
|
|
93209e842c | ||
|
|
8f2ffbfa86 | ||
|
|
af6cff00a5 | ||
|
|
7f550f9482 | ||
|
|
19c49468b7 | ||
|
|
f992322606 | ||
|
|
b7e4a633d8 | ||
|
|
5649deee40 | ||
|
|
b55e3e2d29 | ||
|
|
05d63c9aba | ||
|
|
d5b4a04592 | ||
|
|
d584adda01 | ||
|
|
25a043b508 | ||
|
|
85cce08a85 | ||
|
|
8f1ce3c59f | ||
|
|
41d337e95c | ||
|
|
e10c597425 | ||
|
|
6fc39cdf8e | ||
|
|
35632bc1af | ||
|
|
a104aa1cb2 | ||
|
|
2a6bdd8164 | ||
|
|
c58148a421 | ||
|
|
b1ca6482d5 | ||
|
|
54fab0ad8f | ||
|
|
ebb05ce469 | ||
|
|
ce7ffc38df | ||
|
|
ff9731a0d2 | ||
|
|
b604a89a9c | ||
|
|
fe5e714593 | ||
|
|
cd41dbc0a2 | ||
|
|
24e58fce38 | ||
|
|
6f2dc37ad8 | ||
|
|
eafc9ee7b4 | ||
|
|
a80eca5af8 | ||
|
|
091a109e5a | ||
|
|
cdb458c987 | ||
|
|
f9dc22561c | ||
|
|
5ad2d36f5c | ||
|
|
6313ee7dab | ||
|
|
73d8b35425 | ||
|
|
4d70066990 | ||
|
|
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 |
@@ -4,9 +4,6 @@ on:
|
||||
pull_request:
|
||||
branches:
|
||||
- master
|
||||
push:
|
||||
branches:
|
||||
- master
|
||||
|
||||
jobs:
|
||||
build:
|
||||
@@ -14,7 +11,7 @@ jobs:
|
||||
runs-on: ${{ matrix.os }}
|
||||
strategy:
|
||||
matrix:
|
||||
go-version: [1.13.x]
|
||||
go-version: [1.14.x, 1.15.x]
|
||||
os: [ubuntu-latest, windows-latest]
|
||||
steps:
|
||||
- name: Set up Go ${{ matrix.go-version }} on ${{ matrix.os }}
|
||||
|
||||
+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
|
||||
+10
-5
@@ -1,4 +1,4 @@
|
||||
FROM golang:1.13-alpine
|
||||
FROM golang:1.15-alpine as builder
|
||||
|
||||
LABEL maintainer="MinIO Inc <dev@min.io>"
|
||||
|
||||
@@ -11,12 +11,17 @@ RUN \
|
||||
git clone https://github.com/minio/mc && cd mc && \
|
||||
go install -v -ldflags "$(go run buildscripts/gen-ldflags.go)"
|
||||
|
||||
FROM alpine:3.10
|
||||
FROM registry.access.redhat.com/ubi8/ubi-minimal:8.3
|
||||
|
||||
COPY --from=0 /go/bin/mc /usr/bin/mc
|
||||
ARG TARGETARCH
|
||||
|
||||
COPY --from=builder /go/bin/mc /usr/bin/mc
|
||||
COPY --from=builder /go/mc/CREDITS /licenses/CREDITS
|
||||
COPY --from=builder /go/mc/LICENSE /licenses/LICENSE
|
||||
|
||||
RUN \
|
||||
apk add --no-cache ca-certificates && \
|
||||
echo 'hosts: files mdns4_minimal [NOTFOUND=return] dns mdns4' >> /etc/nsswitch.conf
|
||||
microdnf update --nodocs && \
|
||||
microdnf install ca-certificates --nodocs && \
|
||||
microdnf clean all
|
||||
|
||||
ENTRYPOINT ["mc"]
|
||||
|
||||
+9
-5
@@ -1,10 +1,14 @@
|
||||
FROM alpine:3.10
|
||||
FROM registry.access.redhat.com/ubi8/ubi-minimal:8.3
|
||||
|
||||
LABEL maintainer="MinIO Inc <dev@min.io>"
|
||||
|
||||
COPY mc /usr/bin/
|
||||
COPY CREDITS /licenses/CREDITS
|
||||
COPY LICENSE /licenses/LICENSE
|
||||
|
||||
RUN \
|
||||
apk add --no-cache ca-certificates && \
|
||||
echo 'hosts: files mdns4_minimal [NOTFOUND=return] dns mdns4' >> /etc/nsswitch.conf \
|
||||
chmod +x /usr/bin/mc
|
||||
RUN \
|
||||
microdnf update --nodocs && \
|
||||
microdnf install ca-certificates --nodocs && \
|
||||
microdnf clean all
|
||||
|
||||
ENTRYPOINT ["mc"]
|
||||
|
||||
+12
-6
@@ -1,11 +1,17 @@
|
||||
FROM alpine:3.10
|
||||
FROM registry.access.redhat.com/ubi8/ubi-minimal:8.3
|
||||
|
||||
MAINTAINER MinIO Inc <dev@min.io>
|
||||
ARG TARGETARCH
|
||||
|
||||
LABEL maintainer="MinIO Inc <dev@min.io>"
|
||||
|
||||
COPY CREDITS /licenses/CREDITS
|
||||
COPY LICENSE /licenses/LICENSE
|
||||
|
||||
RUN \
|
||||
apk add --no-cache ca-certificates && \
|
||||
apk add --no-cache --virtual .build-deps curl && \
|
||||
curl https://dl.min.io/client/mc/release/linux-amd64/mc > /usr/bin/mc && \
|
||||
chmod +x /usr/bin/mc && apk del .build-deps
|
||||
microdnf update --nodocs && \
|
||||
microdnf install curl ca-certificates shadow-utils --nodocs && \
|
||||
microdnf clean all && \
|
||||
curl -s -q https://dl.minio.io/client/mc/release/linux-${TARGETARCH}/mc -o /usr/bin/mc && \
|
||||
chmod +x /usr/bin/mc
|
||||
|
||||
ENTRYPOINT ["mc"]
|
||||
|
||||
@@ -19,6 +19,7 @@ checks:
|
||||
getdeps:
|
||||
@mkdir -p ${GOPATH}/bin
|
||||
@which golangci-lint 1>/dev/null || (echo "Installing golangci-lint" && curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(GOPATH)/bin v1.27.0)
|
||||
@which stringer 1>/dev/null || (echo "Installing stringer" && go get golang.org/x/tools/cmd/stringer)
|
||||
|
||||
crosscompile:
|
||||
@(env bash $(PWD)/buildscripts/cross-compile.sh)
|
||||
|
||||
@@ -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,37 @@
|
||||
MinIO Client (mc) provides a modern alternative to UNIX commands like ls, cat, cp, mirror, diff, find etc. It supports filesystems and Amazon S3 compatible cloud storage service (AWS Signature v2 and v4).
|
||||
|
||||
```
|
||||
ls list buckets and objects
|
||||
mb make a bucket
|
||||
rb remove a bucket
|
||||
cat display object contents
|
||||
head display first 'n' lines of an object
|
||||
pipe stream STDIN to an object
|
||||
share generate URL for temporary access to an object
|
||||
cp copy objects
|
||||
mirror synchronize objects to a remote site
|
||||
find search for objects
|
||||
sql run sql queries on objects
|
||||
stat stat contents of objects
|
||||
lock set and get object lock configuration
|
||||
retention set object retention for objects with a given prefix
|
||||
legalhold set object legal hold for objects
|
||||
diff list differences in object name, size, and date between buckets
|
||||
rm remove objects
|
||||
event manage object notifications
|
||||
watch watch for object events
|
||||
policy manage anonymous access to objects
|
||||
admin manage MinIO servers
|
||||
session manage saved sessions for cp command
|
||||
config manage mc configuration file
|
||||
update check for a new software update
|
||||
version print version info
|
||||
alias set, remove and list aliases in configuration file
|
||||
ls list buckets and objects
|
||||
mb make a bucket
|
||||
rb remove a bucket
|
||||
cp copy objects
|
||||
mirror synchronize object(s) to a remote site
|
||||
cat display object contents
|
||||
head display first 'n' lines of an object
|
||||
pipe stream STDIN to an object
|
||||
share generate URL for temporary access to an object
|
||||
find search for objects
|
||||
sql run sql queries on objects
|
||||
stat show object metadata
|
||||
mv move objects
|
||||
tree list buckets and objects in a tree format
|
||||
du summarize disk usage recursively
|
||||
retention set retention for object(s)
|
||||
legalhold set legal hold for object(s)
|
||||
diff list differences in object name, size, and date between two buckets
|
||||
rm remove objects
|
||||
encrypt manage bucket encryption config
|
||||
event manage object notifications
|
||||
watch listen for object notification events
|
||||
undo undo PUT/DELETE operations
|
||||
policy manage anonymous access to buckets and objects
|
||||
tag manage tags for bucket(s) and object(s)
|
||||
ilm manage bucket lifecycle
|
||||
version manage bucket versioning
|
||||
replicate configure server side bucket replication
|
||||
admin manage MinIO servers
|
||||
update update mc to latest release
|
||||
```
|
||||
|
||||
## Docker Container
|
||||
@@ -97,25 +103,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 +155,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 +227,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](https://github.com/minio/mc/blob/master/LICENSE).
|
||||
|
||||
+4
-4
@@ -92,7 +92,7 @@ make
|
||||
添加一个或多个S3兼容的服务,请参考下面说明。`mc`将所有的配置信息都存储在``~/.mc/config.json``文件中。
|
||||
|
||||
```
|
||||
mc config host add <ALIAS> <YOUR-S3-ENDPOINT> <YOUR-ACCESS-KEY> <YOUR-SECRET-KEY> [--api API-SIGNATURE]
|
||||
mc alias set <ALIAS> <YOUR-S3-ENDPOINT> <YOUR-ACCESS-KEY> <YOUR-SECRET-KEY> [--api API-SIGNATURE]
|
||||
```
|
||||
|
||||
别名就是给你的云存储服务起了一个短点的外号。S3 endpoint,access key和secret key是你的云存储服务提供的。API签名是可选参数,默认情况下,它被设置为"S3v4"。
|
||||
@@ -101,21 +101,21 @@ mc config host add <ALIAS> <YOUR-S3-ENDPOINT> <YOUR-ACCESS-KEY> <YOUR-SECRET-KEY
|
||||
从MinIO服务获得URL、access key和secret key。
|
||||
|
||||
```
|
||||
mc config host add minio http://192.168.1.51 BKIKJAA5BMMU2RHO6IBB V7f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12 --api s3v4
|
||||
mc alias set minio http://192.168.1.51 BKIKJAA5BMMU2RHO6IBB V7f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12 --api s3v4
|
||||
```
|
||||
|
||||
### 示例-Amazon S3云存储
|
||||
参考[AWS Credentials指南](http://docs.aws.amazon.com/general/latest/gr/aws-security-credentials.html)获取你的AccessKeyID和SecretAccessKey。
|
||||
|
||||
```
|
||||
mc config host add s3 https://s3.amazonaws.com BKIKJAA5BMMU2RHO6IBB V7f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12 --api s3v4
|
||||
mc alias set s3 https://s3.amazonaws.com BKIKJAA5BMMU2RHO6IBB V7f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12 --api s3v4
|
||||
```
|
||||
|
||||
### 示例-Google云存储
|
||||
参考[Google Credentials Guide](https://cloud.google.com/storage/docs/migrating?hl=en#keys)获取你的AccessKeyID和SecretAccessKey。
|
||||
|
||||
```
|
||||
mc config host add gcs https://storage.googleapis.com BKIKJAA5BMMU2RHO6IBB V8f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12 --api s3v2
|
||||
mc alias set gcs https://storage.googleapis.com BKIKJAA5BMMU2RHO6IBB V8f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12 --api s3v2
|
||||
```
|
||||
|
||||
注意:Google云存储只支持旧版签名版本V2,所以你需要选择S3v2。
|
||||
|
||||
@@ -1,14 +1,16 @@
|
||||
#!/bin/bash
|
||||
|
||||
set -e
|
||||
|
||||
# Enable tracing if set.
|
||||
[ -n "$BASH_XTRACEFD" ] && set -ex
|
||||
[ -n "$BASH_XTRACEFD" ] && set -x
|
||||
|
||||
function _init() {
|
||||
## All binaries are static make sure to disable CGO.
|
||||
export CGO_ENABLED=0
|
||||
|
||||
## List of architectures and OS to test coss compilation.
|
||||
SUPPORTED_OSARCH="linux/ppc64le linux/arm64 linux/s390x darwin/amd64 freebsd/amd64 linux/arm linux/386"
|
||||
SUPPORTED_OSARCH="linux/ppc64le linux/arm64 linux/s390x darwin/amd64 freebsd/amd64 linux/arm linux/386 windows/amd64"
|
||||
}
|
||||
|
||||
function _build() {
|
||||
|
||||
+28
-27
@@ -74,46 +74,47 @@ func (q quotaMessage) JSON() string {
|
||||
}
|
||||
|
||||
var adminBucketQuotaCmd = cli.Command{
|
||||
Name: "quota",
|
||||
Usage: "Manage bucket quota",
|
||||
Action: mainAdminBucketQuota,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: append(adminQuotaFlags, globalFlags...),
|
||||
Name: "quota",
|
||||
Usage: "manage bucket quota",
|
||||
Action: mainAdminBucketQuota,
|
||||
OnUsageError: onUsageError,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: append(adminQuotaFlags, globalFlags...),
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
{{.HelpName}} TARGET [--fifo QUOTA | --hard QUOTA | --clear]
|
||||
|
||||
{{.HelpName}} TARGET [--fifo QUOTA | --hard QUOTA | --clear]
|
||||
|
||||
QUOTA
|
||||
quota accepts human-readable case-insensitive number
|
||||
suffixes such as "k", "m", "g" and "t" referring to the metric units KB,
|
||||
MB, GB and TB respectively. Adding an "i" to these prefixes, uses the IEC
|
||||
units, so that "gi" refers to "gibibyte" or "GiB". A "b" at the end is
|
||||
also accepted. Without suffixes the unit is bytes.
|
||||
|
||||
quota accepts human-readable case-insensitive number
|
||||
suffixes such as "k", "m", "g" and "t" referring to the metric units KB,
|
||||
MB, GB and TB respectively. Adding an "i" to these prefixes, uses the IEC
|
||||
units, so that "gi" refers to "gibibyte" or "GiB". A "b" at the end is
|
||||
also accepted. Without suffixes the unit is bytes.
|
||||
|
||||
FLAGS:
|
||||
{{range .VisibleFlags}}{{.}}
|
||||
{{end}}
|
||||
{{range .VisibleFlags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
1. Display bucket quota configured for "mybucket" on MinIO.
|
||||
{{.Prompt}} {{.HelpName}} myminio/mybucket
|
||||
|
||||
2. Set FIFO quota for a bucket "mybucket" on MinIO.
|
||||
{{.Prompt}} {{.HelpName}} myminio/mybucket --fifo 64kB
|
||||
1. Display bucket quota configured for "mybucket" on MinIO.
|
||||
{{.Prompt}} {{.HelpName}} myminio/mybucket
|
||||
|
||||
3. Set hard quota of 1gb for a bucket "mybucket" on MinIO.
|
||||
{{.Prompt}} {{.HelpName}} myminio/mybucket --hard 1gb
|
||||
2. Set FIFO quota for a bucket "mybucket" on MinIO.
|
||||
{{.Prompt}} {{.HelpName}} myminio/mybucket --fifo 10GB
|
||||
|
||||
4. Clear bucket quota configured for bucket "mybucket" on MinIO.
|
||||
{{.Prompt}} {{.HelpName}} myminio/mybucket --clear
|
||||
3. Set hard quota of 1gb for a bucket "mybucket" on MinIO.
|
||||
{{.Prompt}} {{.HelpName}} myminio/mybucket --hard 1GB
|
||||
|
||||
4. Clear bucket quota configured for bucket "mybucket" on MinIO.
|
||||
{{.Prompt}} {{.HelpName}} myminio/mybucket --clear
|
||||
`,
|
||||
}
|
||||
|
||||
// checkAdminBucketQuotaSyntax - validate all the passed arguments
|
||||
func checkAdminBucketQuotaSyntax(ctx *cli.Context) {
|
||||
if len(ctx.Args()) == 0 || len(ctx.Args()) > 1 {
|
||||
cli.ShowCommandHelpAndExit(ctx, "quota", 1) // last argument is exit code
|
||||
cli.ShowCommandHelpAndExit(ctx, ctx.Command.Name, 1) // last argument is exit code
|
||||
}
|
||||
|
||||
if ctx.IsSet("hard") && ctx.IsSet("fifo") {
|
||||
|
||||
@@ -0,0 +1,254 @@
|
||||
/*
|
||||
* 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"
|
||||
"strings"
|
||||
|
||||
humanize "github.com/dustin/go-humanize"
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/cli"
|
||||
json "github.com/minio/mc/pkg/colorjson"
|
||||
"github.com/minio/mc/pkg/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)",
|
||||
},
|
||||
cli.StringFlag{
|
||||
Name: "bandwidth",
|
||||
Usage: "Set bandwidth limit in bits per second (K,B,G,T for metric and Ki,Bi,Gi,Ti for IEC units)",
|
||||
},
|
||||
}
|
||||
var adminBucketRemoteAddCmd = cli.Command{
|
||||
Name: "add",
|
||||
Usage: "add a new remote target",
|
||||
Action: mainAdminBucketRemoteAdd,
|
||||
OnUsageError: onUsageError,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: append(globalFlags, adminBucketRemoteAddFlags...),
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
{{.HelpName}} TARGET http(s)://ACCESSKEY:SECRETKEY@DEST_URL/DEST_BUCKET [--path | --region | --label| --bandwidth] --service
|
||||
|
||||
TARGET:
|
||||
Also called as alias/sourcebucketname
|
||||
|
||||
DEST_BUCKET:
|
||||
Also called as remote target bucket.
|
||||
|
||||
DEST_URL:
|
||||
Also called as remote endpoint.
|
||||
|
||||
ACCESSKEY:
|
||||
Also called as username.
|
||||
|
||||
SECRETKEY:
|
||||
Also called as password.
|
||||
|
||||
FLAGS:
|
||||
{{range .VisibleFlags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
1. Set a new remote replication target "targetbucket" in region "us-west-1" on https://minio.siteb.example.com for bucket 'sourcebucket'.
|
||||
{{.Prompt}} {{.HelpName}} sitea/sourcebucket https://foobar:foo12345@minio.siteb.example.com/targetbucket \
|
||||
--service "replication" --region "us-west-1"
|
||||
|
||||
2. Set a new remote replication target 'targetbucket' in region "us-west-1" on https://minio.siteb.example.com for
|
||||
bucket 'sourcebucket' with bandwidth set to 2 gigabits per second.
|
||||
{{.Prompt}} {{.HelpName}} sitea/sourcebucket https://foobar:foo12345@minio.siteb.example.com/targetbucket \
|
||||
--service "replication" --region "us-west-1 --bandwidth "2G"
|
||||
`,
|
||||
}
|
||||
|
||||
// checkAdminBucketRemoteAddSyntax - validate all the passed arguments
|
||||
func checkAdminBucketRemoteAddSyntax(ctx *cli.Context) {
|
||||
argsNr := len(ctx.Args())
|
||||
if argsNr < 2 {
|
||||
cli.ShowCommandHelpAndExit(ctx, ctx.Command.Name, 1) // last argument is exit code
|
||||
}
|
||||
if argsNr > 2 {
|
||||
fatalIf(errInvalidArgument().Trace(ctx.Args().Tail()...),
|
||||
"Incorrect number of arguments for remote add command.")
|
||||
}
|
||||
}
|
||||
|
||||
// RemoteMessage container for content message structure
|
||||
type RemoteMessage struct {
|
||||
op string
|
||||
Status string `json:"status"`
|
||||
AccessKey string `json:"accessKey,omitempty"`
|
||||
SecretKey string `json:"secretKey,omitempty"`
|
||||
SourceBucket string `json:"sourceBucket"`
|
||||
TargetURL string `json:"TargetURL,omitempty"`
|
||||
TargetBucket string `json:"TargetBucket,omitempty"`
|
||||
RemoteARN string `json:"RemoteARN,omitempty"`
|
||||
Path string `json:"path,omitempty"`
|
||||
Region string `json:"region,omitempty"`
|
||||
ServiceType string `json:"service"`
|
||||
TargetLabel string `json:"TargetLabel"`
|
||||
Bandwidth int64 `json:"bandwidth"`
|
||||
}
|
||||
|
||||
func (r RemoteMessage) String() string {
|
||||
switch r.op {
|
||||
case "ls":
|
||||
message := console.Colorize("TargetURL", fmt.Sprintf("%s ", r.TargetURL))
|
||||
if r.TargetLabel != "" {
|
||||
message += console.Colorize("TargetLabel", fmt.Sprintf("%s ", r.TargetLabel))
|
||||
}
|
||||
|
||||
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+"`.")
|
||||
case "edit":
|
||||
return console.Colorize("RemoteMessage", "Credentials updated successfully for target with ARN:`"+r.RemoteARN+"`.")
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// JSON returns jsonified message
|
||||
func (r RemoteMessage) JSON() string {
|
||||
r.Status = "success"
|
||||
jsonMessageBytes, e := json.MarshalIndent(r, "", " ")
|
||||
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
|
||||
|
||||
return string(jsonMessageBytes)
|
||||
}
|
||||
|
||||
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")
|
||||
}
|
||||
|
||||
serviceType := cli.String("service")
|
||||
if !madmin.ServiceType(serviceType).IsValid() {
|
||||
fatalIf(errInvalidArgument().Trace(serviceType), "Invalid service type. Valid option is `[replication]`.")
|
||||
}
|
||||
bandwidthStr := cli.String("bandwidth")
|
||||
bandwidth, err := getBandwidthInBytes(bandwidthStr)
|
||||
if err != nil {
|
||||
fatalIf(errInvalidArgument().Trace(bandwidthStr), "Invalid bandwidth number")
|
||||
}
|
||||
console.SetColor(cred, color.New(color.FgYellow, color.Italic))
|
||||
creds := &auth.Credentials{AccessKey: accessKey, SecretKey: secretKey}
|
||||
bktTarget = &madmin.BucketTarget{
|
||||
TargetBucket: TargetBucket,
|
||||
Secure: u.Scheme == "https",
|
||||
Credentials: creds,
|
||||
Endpoint: u.Host,
|
||||
Path: path,
|
||||
API: "s3v4",
|
||||
Type: madmin.ServiceType(serviceType),
|
||||
Region: cli.String("region"),
|
||||
BandwidthLimit: int64(bandwidth),
|
||||
}
|
||||
return sourceBucket, bktTarget
|
||||
}
|
||||
|
||||
func getBandwidthInBytes(bandwidthStr string) (bandwidth uint64, err error) {
|
||||
if bandwidthStr != "" {
|
||||
bandwidth, err = humanize.ParseBytes(bandwidthStr)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
bandwidth = bandwidth / 8
|
||||
return
|
||||
}
|
||||
|
||||
// mainAdminBucketRemoteAdd is the handle for "mc admin bucket remote set" command.
|
||||
func mainAdminBucketRemoteAdd(ctx *cli.Context) error {
|
||||
checkAdminBucketRemoteAddSyntax(ctx)
|
||||
|
||||
console.SetColor("RemoteMessage", color.New(color.FgGreen))
|
||||
|
||||
// Get the alias parameter from cli
|
||||
args := ctx.Args()
|
||||
aliasedURL := args.Get(0)
|
||||
// Create a new MinIO Admin Client
|
||||
client, cerr := newAdminClient(aliasedURL)
|
||||
fatalIf(cerr, "Unable to initialize admin connection.")
|
||||
|
||||
sourceBucket, bktTarget := fetchRemoteTarget(ctx)
|
||||
arn, e := client.SetRemoteTarget(globalContext, sourceBucket, bktTarget)
|
||||
if e != nil {
|
||||
fatalIf(probe.NewError(e).Trace(args...), "Unable to configure remote target")
|
||||
}
|
||||
|
||||
printMsg(RemoteMessage{
|
||||
op: ctx.Command.Name,
|
||||
TargetURL: bktTarget.URL().String(),
|
||||
TargetBucket: bktTarget.TargetBucket,
|
||||
AccessKey: bktTarget.Credentials.AccessKey,
|
||||
SourceBucket: sourceBucket,
|
||||
RemoteARN: arn,
|
||||
})
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestGetBandwidthInBytes(t *testing.T) {
|
||||
type args struct {
|
||||
bandwidthStr string
|
||||
}
|
||||
f1 := 999.123457 * 1024 * 1024 / 8
|
||||
f2 := 10.123456790 * 1024 * 1024 * 1024 / 8
|
||||
f3 := 10000.123456790 * 1024 * 1024 * 1024 / 8
|
||||
f4 := (0.001*1024*1024*1024 + 1) / 8 // round up
|
||||
tests := []struct {
|
||||
name string
|
||||
args args
|
||||
want uint64
|
||||
}{
|
||||
{
|
||||
name: "1MegaByte",
|
||||
args: args{
|
||||
bandwidthStr: "1Mi",
|
||||
},
|
||||
want: 1024 * 1024 / 8,
|
||||
},
|
||||
{
|
||||
name: "1MegaBit",
|
||||
args: args{
|
||||
bandwidthStr: "1M",
|
||||
},
|
||||
want: 1000000 / 8,
|
||||
},
|
||||
{
|
||||
name: "1GigaBit",
|
||||
args: args{
|
||||
bandwidthStr: "1G",
|
||||
},
|
||||
want: 1000000000 / 8,
|
||||
},
|
||||
{
|
||||
name: "1GigaByte",
|
||||
args: args{
|
||||
bandwidthStr: "1Gi",
|
||||
},
|
||||
want: 1024 * 1024 * 1024 / 8,
|
||||
},
|
||||
{
|
||||
name: "FractionalMegaBits",
|
||||
args: args{
|
||||
bandwidthStr: "999.123456789123456789M",
|
||||
},
|
||||
want: 999123457 / 8,
|
||||
},
|
||||
{
|
||||
name: "FractionalGigaBits",
|
||||
args: args{
|
||||
bandwidthStr: "10.123456789123456789123456G",
|
||||
},
|
||||
want: 10123456789 / 8,
|
||||
},
|
||||
{
|
||||
name: "FractionalBigGigaBits",
|
||||
args: args{
|
||||
bandwidthStr: "10000.123456789123456789123456G",
|
||||
},
|
||||
want: 10000123456789 / 8,
|
||||
},
|
||||
{
|
||||
name: "FractionalMegaBytes",
|
||||
args: args{
|
||||
bandwidthStr: "999.123456789123456789Mi",
|
||||
},
|
||||
want: uint64(f1),
|
||||
},
|
||||
{
|
||||
name: "FractionalGigaBytes",
|
||||
args: args{
|
||||
bandwidthStr: "10.123456789123456789123456Gi",
|
||||
},
|
||||
want: uint64(f2),
|
||||
},
|
||||
{
|
||||
name: "FractionalBigGigaBytes",
|
||||
args: args{
|
||||
bandwidthStr: "10000.123456789123456789123456Gi",
|
||||
},
|
||||
want: uint64(f3),
|
||||
},
|
||||
{
|
||||
name: "SmallGiga",
|
||||
args: args{
|
||||
bandwidthStr: "0.001Gi",
|
||||
},
|
||||
want: uint64(f4),
|
||||
},
|
||||
{
|
||||
name: "LargeK",
|
||||
args: args{
|
||||
bandwidthStr: "1024Ki",
|
||||
},
|
||||
want: 1024 * 1024 / 8,
|
||||
},
|
||||
}
|
||||
t.Parallel()
|
||||
for _, tt := range tests {
|
||||
tt := tt
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if got, err := getBandwidthInBytes(tt.args.bandwidthStr); err != nil || got != tt.want {
|
||||
t.Errorf("getBandwidthInBytes() = %v, want %v", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,181 @@
|
||||
/*
|
||||
* 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"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/cli"
|
||||
"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 adminBucketRemoteEditFlags = []cli.Flag{
|
||||
cli.StringFlag{
|
||||
Name: "arn",
|
||||
Usage: "ARN of target",
|
||||
}}
|
||||
var adminBucketRemoteEditCmd = cli.Command{
|
||||
Name: "edit",
|
||||
Usage: "edit credentials for existing remote target",
|
||||
Action: mainAdminBucketRemoteEdit,
|
||||
Before: setGlobalsFromContext,
|
||||
OnUsageError: onUsageError,
|
||||
Flags: append(globalFlags, adminBucketRemoteEditFlags...),
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
{{.HelpName}} TARGET http(s)://ACCESSKEY:SECRETKEY@DEST_URL/DEST_BUCKET --arn arn
|
||||
|
||||
TARGET:
|
||||
Also called as alias/sourcebucketname
|
||||
|
||||
DEST_BUCKET:
|
||||
Also called as remote target bucket.
|
||||
|
||||
DEST_URL:
|
||||
Also called as remote endpoint.
|
||||
|
||||
ACCESSKEY:
|
||||
Also called as username.
|
||||
|
||||
SECRETKEY:
|
||||
Also called as password.
|
||||
|
||||
FLAGS:
|
||||
{{range .VisibleFlags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
1. Edit credentials for existing remote target with arn where a remote target has been configured between sourcebucket on sitea to targetbucket on siteb.
|
||||
{{.DisableHistory}}
|
||||
{{.Prompt}} {{.HelpName}} sitea/sourcebucket \
|
||||
https://foobar:newpassword@minio.siteb.example.com/targetbucket \
|
||||
--arn "arn:minio:replication:us-west-1:993bc6b6-accd-45e3-884f-5f3e652aed2a:dest1"
|
||||
{{.EnableHistory}}
|
||||
`,
|
||||
}
|
||||
|
||||
// checkAdminBucketRemoteEditSyntax - validate all the passed arguments
|
||||
func checkAdminBucketRemoteEditSyntax(ctx *cli.Context) {
|
||||
argsNr := len(ctx.Args())
|
||||
if argsNr != 2 {
|
||||
cli.ShowCommandHelpAndExit(ctx, ctx.Command.Name, 1) // last argument is exit code
|
||||
}
|
||||
}
|
||||
|
||||
// fetchRemoteEditTarget - returns the dest bucket, dest endpoint, access and secret key
|
||||
func fetchRemoteEditTarget(cli *cli.Context) (bktTarget *madmin.BucketTarget) {
|
||||
args := cli.Args()
|
||||
_, sourceBucket := url2Alias(args[0])
|
||||
TargetURL := args[1]
|
||||
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)
|
||||
}
|
||||
console.SetColor(cred, color.New(color.FgYellow, color.Italic))
|
||||
creds := &auth.Credentials{AccessKey: accessKey, SecretKey: secretKey}
|
||||
bktTarget = &madmin.BucketTarget{
|
||||
SourceBucket: sourceBucket,
|
||||
TargetBucket: TargetBucket,
|
||||
Secure: secure,
|
||||
Credentials: creds,
|
||||
Endpoint: host,
|
||||
API: "s3v4",
|
||||
Region: cli.String("region"),
|
||||
Label: strings.ToUpper(cli.String("label")),
|
||||
Arn: cli.String("arn"),
|
||||
}
|
||||
return bktTarget
|
||||
}
|
||||
|
||||
// mainAdminBucketRemoteEdit is the handle for "mc admin bucket remote edit" command.
|
||||
func mainAdminBucketRemoteEdit(ctx *cli.Context) error {
|
||||
checkAdminBucketRemoteEditSyntax(ctx)
|
||||
|
||||
console.SetColor("RemoteMessage", color.New(color.FgGreen))
|
||||
|
||||
// Get the alias parameter from cli
|
||||
args := ctx.Args()
|
||||
aliasedURL := args.Get(0)
|
||||
// Create a new MinIO Admin Client
|
||||
client, cerr := newAdminClient(aliasedURL)
|
||||
fatalIf(cerr, "Unable to initialize admin connection.")
|
||||
bktTarget := fetchRemoteEditTarget(ctx)
|
||||
|
||||
targets, e := client.ListRemoteTargets(globalContext, bktTarget.SourceBucket, "")
|
||||
fatalIf(probe.NewError(e).Trace(args...), "Unable to fetch remote target.")
|
||||
|
||||
var found bool
|
||||
for _, t := range targets {
|
||||
if t.Arn == bktTarget.Arn {
|
||||
if t.Endpoint != bktTarget.Endpoint {
|
||||
fatalIf(errInvalidArgument().Trace(args...), "configured Endpoint `"+t.Endpoint+"` does not match "+bktTarget.Endpoint+"` for this ARN `"+bktTarget.Arn+"`")
|
||||
}
|
||||
if t.TargetBucket != bktTarget.TargetBucket {
|
||||
fatalIf(errInvalidArgument().Trace(args...), "configured remote target bucket `"+t.TargetBucket+"` does not match "+bktTarget.TargetBucket+"` for this ARN `"+bktTarget.Arn+"`")
|
||||
}
|
||||
if t.SourceBucket != bktTarget.SourceBucket {
|
||||
fatalIf(errInvalidArgument().Trace(args...), "configured source bucket `"+t.SourceBucket+"` does not match "+bktTarget.SourceBucket+"` for this ARN `"+bktTarget.Arn+"`")
|
||||
}
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
fatalIf(errInvalidArgument().Trace(args...), "Unable to edit remote target - `"+bktTarget.Arn+"` is not a valid Arn")
|
||||
}
|
||||
arn, e := client.UpdateRemoteTarget(globalContext, bktTarget)
|
||||
if e != nil {
|
||||
fatalIf(probe.NewError(e).Trace(args...), "Unable to update credentials for remote target `"+bktTarget.Endpoint+"` from `"+bktTarget.SourceBucket+"` -> `"+bktTarget.TargetBucket+"`")
|
||||
}
|
||||
|
||||
printMsg(RemoteMessage{
|
||||
op: ctx.Command.Name,
|
||||
TargetURL: bktTarget.URL().String(),
|
||||
TargetBucket: bktTarget.TargetBucket,
|
||||
AccessKey: bktTarget.Credentials.AccessKey,
|
||||
SourceBucket: bktTarget.SourceBucket,
|
||||
RemoteARN: arn,
|
||||
})
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
/*
|
||||
* 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"
|
||||
"path/filepath"
|
||||
|
||||
"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,
|
||||
OnUsageError: onUsageError,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: append(globalFlags, adminBucketRemoteListFlags...),
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
{{.HelpName}} TARGET
|
||||
|
||||
FLAGS:
|
||||
{{range .VisibleFlags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
1. Get remote bucket target for replication on MinIO server for bucket 'srcbucket'.
|
||||
{{.Prompt}} {{.HelpName}} myminio/srcbucket --service "replication"
|
||||
|
||||
2. List all remote bucket target(s) on MinIO server for bucket 'srcbucket'.
|
||||
{{.Prompt}} {{.HelpName}} myminio/srcbucket
|
||||
|
||||
3. List all remote bucket target(s) on MinIO tenant.
|
||||
{{.Prompt}} {{.HelpName}} myminio
|
||||
`,
|
||||
}
|
||||
|
||||
// checkAdminBucketRemoteListSyntax - validate all the passed arguments
|
||||
func checkAdminBucketRemoteListSyntax(ctx *cli.Context) {
|
||||
if len(ctx.Args()) != 1 {
|
||||
cli.ShowCommandHelpAndExit(ctx, ctx.Command.Name, 1) // last argument is exit code
|
||||
}
|
||||
}
|
||||
|
||||
// mainAdminBucketRemoteList is the handle for "mc admin bucket remote list" command.
|
||||
func mainAdminBucketRemoteList(ctx *cli.Context) error {
|
||||
checkAdminBucketRemoteListSyntax(ctx)
|
||||
|
||||
// Additional command specific theme customization.
|
||||
console.SetColor("RemoteListMessage", color.New(color.Bold, color.FgHiGreen))
|
||||
console.SetColor("RemoteListEmpty", color.New(color.FgYellow))
|
||||
console.SetColor("SourceBucket", color.New(color.FgYellow))
|
||||
console.SetColor("TargetBucket", color.New(color.FgYellow))
|
||||
console.SetColor("TargetURL", color.New(color.FgHiWhite))
|
||||
console.SetColor("TargetLabel", color.New(color.FgHiCyan))
|
||||
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)
|
||||
aliasedURL = filepath.Clean(aliasedURL)
|
||||
_, sourceBucket := url2Alias(aliasedURL)
|
||||
// Create a new MinIO Admin Client
|
||||
client, err := newAdminClient(aliasedURL)
|
||||
fatalIf(err, "Unable to initialize admin connection.")
|
||||
targets, e := client.ListRemoteTargets(globalContext, sourceBucket, ctx.String("service"))
|
||||
fatalIf(probe.NewError(e).Trace(args...), "Unable to list remote target")
|
||||
printRemotes(ctx, aliasedURL, targets)
|
||||
return nil
|
||||
}
|
||||
|
||||
func printRemotes(ctx *cli.Context, urlStr string, targets []madmin.BucketTarget) {
|
||||
|
||||
maxURLLen := 10
|
||||
maxTgtLen := 6
|
||||
maxSrcLen := 6
|
||||
maxLabelLen := 5
|
||||
if !globalJSON {
|
||||
if len(targets) == 0 {
|
||||
console.Print(console.Colorize("RemoteListEmpty", fmt.Sprintf("No remote targets found for `%s`. \n", urlStr)))
|
||||
return
|
||||
}
|
||||
for _, t := range targets {
|
||||
l := len(t.Endpoint)
|
||||
if l > maxURLLen {
|
||||
maxURLLen = l
|
||||
}
|
||||
if len(t.TargetBucket) > maxTgtLen {
|
||||
maxTgtLen = len(t.TargetBucket)
|
||||
}
|
||||
if len(t.SourceBucket) > maxSrcLen {
|
||||
maxSrcLen = len(t.SourceBucket)
|
||||
}
|
||||
if len(t.Label) > maxLabelLen {
|
||||
maxLabelLen = len(t.Label)
|
||||
}
|
||||
}
|
||||
if maxURLLen > 0 {
|
||||
console.Println(console.Colorize("RemoteListMessage", fmt.Sprintf("%-*.*s %-*.*s %-*.*s->%-*.*s %s", maxURLLen+8, maxURLLen+8, "Remote URL", maxLabelLen, maxLabelLen, "Label", maxSrcLen, maxSrcLen, "Source", maxTgtLen, maxTgtLen, "Target", "ARN")))
|
||||
}
|
||||
}
|
||||
for _, target := range targets {
|
||||
targetURL := target.URL().String()
|
||||
if !globalJSON {
|
||||
if maxURLLen > 0 {
|
||||
targetURL = fmt.Sprintf("%-*.*s", maxURLLen+8, maxURLLen+8, target.URL().String())
|
||||
}
|
||||
if maxTgtLen > 0 {
|
||||
target.TargetBucket = fmt.Sprintf("%-*.*s", maxTgtLen, maxTgtLen, target.TargetBucket)
|
||||
}
|
||||
|
||||
if maxSrcLen > 0 {
|
||||
target.SourceBucket = fmt.Sprintf("%-*.*s", maxSrcLen, maxSrcLen, target.SourceBucket)
|
||||
}
|
||||
if maxLabelLen > 0 {
|
||||
target.Label = fmt.Sprintf("%-*.*s", maxLabelLen, maxLabelLen, target.Label)
|
||||
}
|
||||
}
|
||||
printMsg(RemoteMessage{
|
||||
op: ctx.Command.Name,
|
||||
AccessKey: target.Credentials.AccessKey,
|
||||
TargetBucket: target.TargetBucket,
|
||||
TargetURL: targetURL,
|
||||
SourceBucket: target.SourceBucket,
|
||||
RemoteARN: target.Arn,
|
||||
ServiceType: string(target.Type),
|
||||
TargetLabel: target.Label,
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -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 adminBucketRemoteSubcommands = []cli.Command{
|
||||
adminBucketRemoteAddCmd,
|
||||
adminBucketRemoteEditCmd,
|
||||
adminBucketRemoteListCmd,
|
||||
adminBucketRemoteRmCmd,
|
||||
}
|
||||
|
||||
var adminBucketRemoteCmd = cli.Command{
|
||||
Name: "remote",
|
||||
Usage: "configure remote target buckets",
|
||||
Action: mainadminBucketRemote,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
Subcommands: adminBucketRemoteSubcommands,
|
||||
HideHelpCommand: true,
|
||||
}
|
||||
|
||||
// mainadminBucketRemote is the handle for "mc admin bucket remote" command.
|
||||
func mainadminBucketRemote(ctx *cli.Context) error {
|
||||
commandNotFound(ctx, adminBucketRemoteSubcommands)
|
||||
return nil
|
||||
// Sub-commands like "add", "ls", "rm" have their own main.
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
/*
|
||||
* 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,
|
||||
OnUsageError: onUsageError,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: append(globalFlags, adminBucketRemoteRmFlags...),
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
{{.HelpName}} TARGET
|
||||
|
||||
FLAGS:
|
||||
{{range .VisibleFlags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
1. Remove existing remote target with arn "arn:minio:replication:us-west-1:993bc6b6-accd-45e3-884f-5f3e652aed2a:dest1"
|
||||
for bucket srcbucket on MinIO server.
|
||||
{{.Prompt}} {{.HelpName}} myminio/srcbucket --arn "arn:minio:replication:us-west-1:993bc6b6-accd-45e3-884f-5f3e652aed2a:dest1"
|
||||
`,
|
||||
}
|
||||
|
||||
// checkAdminBucketRemoteRemoveSyntax - validate all the passed arguments
|
||||
func checkAdminBucketRemoteRemoveSyntax(ctx *cli.Context) {
|
||||
|
||||
if len(ctx.Args()) != 1 {
|
||||
cli.ShowCommandHelpAndExit(ctx, ctx.Command.Name, 1) // last argument is exit code
|
||||
}
|
||||
}
|
||||
|
||||
// mainAdminBucketRemoteRemove is the handle for "mc admin bucket remote rm" command.
|
||||
func mainAdminBucketRemoteRemove(ctx *cli.Context) error {
|
||||
checkAdminBucketRemoteRemoveSyntax(ctx)
|
||||
|
||||
console.SetColor("RemoteMessage", color.New(color.FgGreen))
|
||||
|
||||
// Get the alias parameter from cli
|
||||
args := ctx.Args()
|
||||
aliasedURL := args.Get(0)
|
||||
// Create a new MinIO Admin Client
|
||||
client, cerr := newAdminClient(aliasedURL)
|
||||
fatalIf(cerr.Trace(aliasedURL), "Unable to initialize admin connection.")
|
||||
_, sourceBucket := url2Alias(args[0])
|
||||
if sourceBucket == "" {
|
||||
fatalIf(errInvalidArgument(), "Source bucket not specified in `"+args[0]+"`.")
|
||||
}
|
||||
arn := ctx.String("arn")
|
||||
if arn == "" {
|
||||
fatalIf(errInvalidArgument(), "ARN needs to be specified.")
|
||||
}
|
||||
fatalIf(probe.NewError(client.RemoveRemoteTarget(globalContext, sourceBucket, arn)).Trace(args...), "Unable to remove remote target")
|
||||
|
||||
printMsg(RemoteMessage{
|
||||
op: ctx.Command.Name,
|
||||
SourceBucket: sourceBucket,
|
||||
RemoteARN: arn,
|
||||
})
|
||||
|
||||
return nil
|
||||
}
|
||||
+13
-10
@@ -18,21 +18,24 @@ package cmd
|
||||
|
||||
import "github.com/minio/cli"
|
||||
|
||||
var adminBucketSubcommands = []cli.Command{
|
||||
adminBucketRemoteCmd,
|
||||
adminBucketQuotaCmd,
|
||||
}
|
||||
|
||||
var adminBucketCmd = cli.Command{
|
||||
Name: "bucket",
|
||||
Usage: "manage buckets defined in the MinIO server",
|
||||
Action: mainAdminBucket,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
Subcommands: []cli.Command{
|
||||
adminBucketQuotaCmd,
|
||||
},
|
||||
Name: "bucket",
|
||||
Usage: "manage buckets defined in the MinIO server",
|
||||
Action: mainAdminBucket,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
Subcommands: adminBucketSubcommands,
|
||||
HideHelpCommand: true,
|
||||
}
|
||||
|
||||
// mainAdminBucket is the handle for "mc admin bucket" command.
|
||||
func mainAdminBucket(ctx *cli.Context) error {
|
||||
cli.ShowCommandHelp(ctx, ctx.Args().First())
|
||||
commandNotFound(ctx, adminBucketSubcommands)
|
||||
return nil
|
||||
// Sub-commands like "quota", "usage" have their own main.
|
||||
// Sub-commands like "quota", "remote" have their own main.
|
||||
}
|
||||
|
||||
@@ -23,11 +23,12 @@ import (
|
||||
)
|
||||
|
||||
var adminConfigExportCmd = cli.Command{
|
||||
Name: "export",
|
||||
Usage: "export all config keys to STDOUT",
|
||||
Before: setGlobalsFromContext,
|
||||
Action: mainAdminConfigExport,
|
||||
Flags: globalFlags,
|
||||
Name: "export",
|
||||
Usage: "export all config keys to STDOUT",
|
||||
Before: setGlobalsFromContext,
|
||||
Action: mainAdminConfigExport,
|
||||
OnUsageError: onUsageError,
|
||||
Flags: globalFlags,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
@@ -84,7 +85,7 @@ func mainAdminConfigExport(ctx *cli.Context) error {
|
||||
|
||||
// Call get config API
|
||||
buf, e := client.GetConfig(globalContext)
|
||||
fatalIf(probe.NewError(e), "Cannot get server config")
|
||||
fatalIf(probe.NewError(e), "Unable to get server config")
|
||||
|
||||
// Print
|
||||
printMsg(configExportMessage{
|
||||
|
||||
@@ -25,11 +25,12 @@ import (
|
||||
)
|
||||
|
||||
var adminConfigGetCmd = cli.Command{
|
||||
Name: "get",
|
||||
Usage: "interactively retrieve a config key parameters",
|
||||
Before: setGlobalsFromContext,
|
||||
Action: mainAdminConfigGet,
|
||||
Flags: globalFlags,
|
||||
Name: "get",
|
||||
Usage: "interactively retrieve a config key parameters",
|
||||
Before: setGlobalsFromContext,
|
||||
Action: mainAdminConfigGet,
|
||||
OnUsageError: onUsageError,
|
||||
Flags: globalFlags,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
@@ -96,7 +97,7 @@ func mainAdminConfigGet(ctx *cli.Context) error {
|
||||
if len(ctx.Args()) == 1 {
|
||||
// Call get config API
|
||||
hr, e := client.HelpConfigKV(globalContext, "", "", false)
|
||||
fatalIf(probe.NewError(e), "Cannot get help for the sub-system")
|
||||
fatalIf(probe.NewError(e), "Unable to get help for the sub-system")
|
||||
|
||||
// Print
|
||||
printMsg(configHelpMessage{
|
||||
@@ -109,7 +110,7 @@ func mainAdminConfigGet(ctx *cli.Context) error {
|
||||
|
||||
// Call get config API
|
||||
buf, e := client.GetConfigKV(globalContext, strings.Join(args.Tail(), " "))
|
||||
fatalIf(probe.NewError(e), "Cannot get server '%s' config", args.Tail())
|
||||
fatalIf(probe.NewError(e), "Unable to get server '%s' config", args.Tail())
|
||||
|
||||
// Print
|
||||
printMsg(configGetMessage{
|
||||
|
||||
@@ -66,7 +66,7 @@ func (u configHelpMessage) String() string {
|
||||
} else {
|
||||
e = HelpEnvTemplate.Execute(w, u.Value)
|
||||
}
|
||||
fatalIf(probe.NewError(e), "Cannot initialize template writer")
|
||||
fatalIf(probe.NewError(e), "Unable to initialize template writer")
|
||||
|
||||
w.Flush()
|
||||
|
||||
|
||||
@@ -41,11 +41,12 @@ var historyListFlags = []cli.Flag{
|
||||
}
|
||||
|
||||
var adminConfigHistoryCmd = cli.Command{
|
||||
Name: "history",
|
||||
Usage: "show all historic configuration changes",
|
||||
Before: setGlobalsFromContext,
|
||||
Action: mainAdminConfigHistory,
|
||||
Flags: append(append([]cli.Flag{}, globalFlags...), historyListFlags...),
|
||||
Name: "history",
|
||||
Usage: "show all historic configuration changes",
|
||||
Before: setGlobalsFromContext,
|
||||
Action: mainAdminConfigHistory,
|
||||
OnUsageError: onUsageError,
|
||||
Flags: append(append([]cli.Flag{}, globalFlags...), historyListFlags...),
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
@@ -89,7 +90,7 @@ func (u configHistoryMessage) String() string {
|
||||
var s strings.Builder
|
||||
w := tabwriter.NewWriter(&s, 1, 8, 2, ' ', 0)
|
||||
e := HistoryTemplate.Execute(w, u.Entries)
|
||||
fatalIf(probe.NewError(e), "Cannot initialize template writer")
|
||||
fatalIf(probe.NewError(e), "Unable to initialize template writer")
|
||||
|
||||
w.Flush()
|
||||
return s.String()
|
||||
@@ -127,7 +128,7 @@ func mainAdminConfigHistory(ctx *cli.Context) error {
|
||||
fatalIf(err, "Unable to initialize admin connection.")
|
||||
|
||||
if ctx.IsSet("clear") {
|
||||
fatalIf(probe.NewError(client.ClearConfigHistoryKV(globalContext, "all")), "Cannot clear server configuration.")
|
||||
fatalIf(probe.NewError(client.ClearConfigHistoryKV(globalContext, "all")), "Unable to clear server configuration.")
|
||||
|
||||
// Print
|
||||
printMsg(configHistoryMessage{})
|
||||
@@ -135,7 +136,7 @@ func mainAdminConfigHistory(ctx *cli.Context) error {
|
||||
}
|
||||
|
||||
chEntries, e := client.ListConfigHistoryKV(globalContext, ctx.Int("count"))
|
||||
fatalIf(probe.NewError(e), "Cannot list server history configuration.")
|
||||
fatalIf(probe.NewError(e), "Unable to list server history configuration.")
|
||||
|
||||
hentries := make([]historyEntry, len(chEntries))
|
||||
for i, chEntry := range chEntries {
|
||||
|
||||
@@ -28,11 +28,12 @@ import (
|
||||
)
|
||||
|
||||
var adminConfigImportCmd = cli.Command{
|
||||
Name: "import",
|
||||
Usage: "import multiple config keys from STDIN",
|
||||
Before: setGlobalsFromContext,
|
||||
Action: mainAdminConfigImport,
|
||||
Flags: globalFlags,
|
||||
Name: "import",
|
||||
Usage: "import multiple config keys from STDIN",
|
||||
Before: setGlobalsFromContext,
|
||||
Action: mainAdminConfigImport,
|
||||
OnUsageError: onUsageError,
|
||||
Flags: globalFlags,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
@@ -96,7 +97,7 @@ func mainAdminConfigImport(ctx *cli.Context) error {
|
||||
fatalIf(err, "Unable to initialize admin connection.")
|
||||
|
||||
// Call set config API
|
||||
fatalIf(probe.NewError(client.SetConfig(globalContext, os.Stdin)), "Cannot set server config")
|
||||
fatalIf(probe.NewError(client.SetConfig(globalContext, os.Stdin)), "Unable to set server config")
|
||||
|
||||
// Print
|
||||
printMsg(configImportMessage{
|
||||
|
||||
@@ -35,11 +35,12 @@ var adminConfigEnvFlags = []cli.Flag{
|
||||
}
|
||||
|
||||
var adminConfigResetCmd = cli.Command{
|
||||
Name: "reset",
|
||||
Usage: "interactively reset a config key parameters",
|
||||
Before: setGlobalsFromContext,
|
||||
Action: mainAdminConfigReset,
|
||||
Flags: append(adminConfigEnvFlags, globalFlags...),
|
||||
Name: "reset",
|
||||
Usage: "interactively reset a config key parameters",
|
||||
Before: setGlobalsFromContext,
|
||||
Action: mainAdminConfigReset,
|
||||
OnUsageError: onUsageError,
|
||||
Flags: append(adminConfigEnvFlags, globalFlags...),
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
@@ -108,7 +109,7 @@ func mainAdminConfigReset(ctx *cli.Context) error {
|
||||
if len(ctx.Args()) == 1 {
|
||||
// Call get config API
|
||||
hr, e := client.HelpConfigKV(globalContext, "", "", ctx.IsSet("env"))
|
||||
fatalIf(probe.NewError(e), "Cannot get help for the sub-system")
|
||||
fatalIf(probe.NewError(e), "Unable to get help for the sub-system")
|
||||
|
||||
// Print
|
||||
printMsg(configHelpMessage{
|
||||
@@ -122,7 +123,7 @@ func mainAdminConfigReset(ctx *cli.Context) error {
|
||||
// Call reset config API
|
||||
input := strings.Join(args.Tail(), " ")
|
||||
fatalIf(probe.NewError(client.DelConfigKV(globalContext, input)),
|
||||
"Cannot reset '%s' on the server", input)
|
||||
"Unable to reset '%s' on the server", input)
|
||||
|
||||
// Print set config result
|
||||
printMsg(configResetMessage{
|
||||
|
||||
@@ -27,11 +27,12 @@ import (
|
||||
)
|
||||
|
||||
var adminConfigRestoreCmd = cli.Command{
|
||||
Name: "restore",
|
||||
Usage: "rollback back changes to a specific config history",
|
||||
Before: setGlobalsFromContext,
|
||||
Action: mainAdminConfigRestore,
|
||||
Flags: globalFlags,
|
||||
Name: "restore",
|
||||
Usage: "rollback back changes to a specific config history",
|
||||
Before: setGlobalsFromContext,
|
||||
Action: mainAdminConfigRestore,
|
||||
OnUsageError: onUsageError,
|
||||
Flags: globalFlags,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
@@ -94,7 +95,7 @@ func mainAdminConfigRestore(ctx *cli.Context) error {
|
||||
fatalIf(err, "Unable to initialize admin connection.")
|
||||
|
||||
// Call get config API
|
||||
fatalIf(probe.NewError(client.RestoreConfigHistoryKV(globalContext, args.Get(1))), "Cannot restore server configuration.")
|
||||
fatalIf(probe.NewError(client.RestoreConfigHistoryKV(globalContext, args.Get(1))), "Unable to restore server configuration.")
|
||||
|
||||
// Print
|
||||
printMsg(configRestoreMessage{
|
||||
|
||||
+20
-12
@@ -29,11 +29,12 @@ import (
|
||||
)
|
||||
|
||||
var adminConfigSetCmd = cli.Command{
|
||||
Name: "set",
|
||||
Usage: "interactively set a config key parameters",
|
||||
Before: setGlobalsFromContext,
|
||||
Action: mainAdminConfigSet,
|
||||
Flags: append(adminConfigEnvFlags, globalFlags...),
|
||||
Name: "set",
|
||||
Usage: "interactively set a config key parameters",
|
||||
Before: setGlobalsFromContext,
|
||||
Action: mainAdminConfigSet,
|
||||
OnUsageError: onUsageError,
|
||||
Flags: append(adminConfigEnvFlags, globalFlags...),
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
@@ -49,6 +50,9 @@ EXAMPLES:
|
||||
|
||||
2. Change region name for the MinIO server to 'us-west-1'.
|
||||
{{.Prompt}} {{.HelpName}} myminio/ region name=us-west-1
|
||||
|
||||
3. Change healing settings on a distributed MinIO server setup.
|
||||
{{.Prompt}} {{.HelpName}} mydist/ heal max_delay=300ms max_io=50
|
||||
`,
|
||||
}
|
||||
|
||||
@@ -56,15 +60,18 @@ EXAMPLES:
|
||||
type configSetMessage struct {
|
||||
Status string `json:"status"`
|
||||
targetAlias string
|
||||
restart bool
|
||||
}
|
||||
|
||||
// String colorized service status message.
|
||||
func (u configSetMessage) String() (msg string) {
|
||||
msg += console.Colorize("SetConfigSuccess",
|
||||
"Setting new key has been successful.\n")
|
||||
suggestion := fmt.Sprintf("mc admin service restart %s", u.targetAlias)
|
||||
msg += console.Colorize("SetConfigSuccess",
|
||||
fmt.Sprintf("Please restart your server with `%s`.\n", suggestion))
|
||||
"Successfully applied new settings.")
|
||||
if u.restart {
|
||||
suggestion := fmt.Sprintf("\nmc admin service restart %s", u.targetAlias)
|
||||
msg += console.Colorize("SetConfigSuccess",
|
||||
fmt.Sprintf("Please restart your server with `%s`.\n", suggestion))
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
@@ -106,7 +113,7 @@ func mainAdminConfigSet(ctx *cli.Context) error {
|
||||
if !strings.Contains(input, madmin.KvSeparator) {
|
||||
// Call get config API
|
||||
hr, e := client.HelpConfigKV(globalContext, args.Get(1), args.Get(2), ctx.IsSet("env"))
|
||||
fatalIf(probe.NewError(e), "Cannot get help for the sub-system")
|
||||
fatalIf(probe.NewError(e), "Unable to get help for the sub-system")
|
||||
|
||||
// Print
|
||||
printMsg(configHelpMessage{
|
||||
@@ -119,12 +126,13 @@ func mainAdminConfigSet(ctx *cli.Context) error {
|
||||
}
|
||||
|
||||
// Call set config API
|
||||
fatalIf(probe.NewError(client.SetConfigKV(globalContext, input)),
|
||||
"Cannot set '%s' to server", input)
|
||||
restart, e := client.SetConfigKV(globalContext, input)
|
||||
fatalIf(probe.NewError(e), "Unable to set '%s' to server", input)
|
||||
|
||||
// Print set config result
|
||||
printMsg(configSetMessage{
|
||||
targetAlias: aliasedURL,
|
||||
restart: restart,
|
||||
})
|
||||
|
||||
return nil
|
||||
|
||||
+17
-15
@@ -18,27 +18,29 @@ package cmd
|
||||
|
||||
import "github.com/minio/cli"
|
||||
|
||||
var adminConfigSubcommands = []cli.Command{
|
||||
adminConfigGetCmd,
|
||||
adminConfigSetCmd,
|
||||
adminConfigResetCmd,
|
||||
adminConfigHistoryCmd,
|
||||
adminConfigRestoreCmd,
|
||||
adminConfigExportCmd,
|
||||
adminConfigImportCmd,
|
||||
}
|
||||
|
||||
var adminConfigCmd = cli.Command{
|
||||
Name: "config",
|
||||
Usage: "manage MinIO server configuration",
|
||||
Action: mainAdminConfig,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
Subcommands: []cli.Command{
|
||||
adminConfigGetCmd,
|
||||
adminConfigSetCmd,
|
||||
adminConfigResetCmd,
|
||||
adminConfigHistoryCmd,
|
||||
adminConfigRestoreCmd,
|
||||
adminConfigExportCmd,
|
||||
adminConfigImportCmd,
|
||||
},
|
||||
Name: "config",
|
||||
Usage: "manage MinIO server configuration",
|
||||
Action: mainAdminConfig,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
Subcommands: adminConfigSubcommands,
|
||||
HideHelpCommand: true,
|
||||
}
|
||||
|
||||
// mainAdminConfig is the handle for "mc admin config" command.
|
||||
func mainAdminConfig(ctx *cli.Context) error {
|
||||
cli.ShowCommandHelp(ctx, ctx.Args().First())
|
||||
commandNotFound(ctx, adminConfigSubcommands)
|
||||
return nil
|
||||
// Sub-commands like "get", "set" have their own main.
|
||||
}
|
||||
|
||||
@@ -49,6 +49,7 @@ var adminConsoleCmd = cli.Command{
|
||||
Name: "console",
|
||||
Usage: "show console logs for MinIO server",
|
||||
Action: mainAdminConsole,
|
||||
OnUsageError: onUsageError,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: append(adminConsoleFlags, globalFlags...),
|
||||
HideHelpCommand: true,
|
||||
@@ -81,11 +82,13 @@ func checkAdminLogSyntax(ctx *cli.Context) {
|
||||
|
||||
// Extend madmin.LogInfo to add String() and JSON() methods
|
||||
type logMessage struct {
|
||||
Status string `json:"status"`
|
||||
madmin.LogInfo
|
||||
}
|
||||
|
||||
// JSON - jsonify loginfo
|
||||
func (l logMessage) JSON() string {
|
||||
l.Status = "success"
|
||||
logJSON, err := json.MarshalIndent(&l, "", " ")
|
||||
fatalIf(probe.NewError(err), "Unable to marshal into JSON.")
|
||||
|
||||
@@ -192,7 +195,7 @@ func mainAdminConsole(ctx *cli.Context) error {
|
||||
// Create a new MinIO Admin Client
|
||||
client, err := newAdminClient(aliasedURL)
|
||||
if err != nil {
|
||||
fatalIf(err.Trace(aliasedURL), "Cannot initialize admin client.")
|
||||
fatalIf(err.Trace(aliasedURL), "Unable to initialize admin client.")
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -203,13 +206,13 @@ func mainAdminConsole(ctx *cli.Context) error {
|
||||
logCh := client.GetLogs(ctxt, node, limit, logType)
|
||||
for logInfo := range logCh {
|
||||
if logInfo.Err != nil {
|
||||
fatalIf(probe.NewError(logInfo.Err), "Cannot listen to console logs")
|
||||
fatalIf(probe.NewError(logInfo.Err), "Unable to listen to console logs")
|
||||
}
|
||||
// drop nodeName from output if specified as cli arg
|
||||
if node != "" {
|
||||
logInfo.NodeName = ""
|
||||
}
|
||||
printMsg(logMessage{logInfo})
|
||||
printMsg(logMessage{LogInfo: logInfo})
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -29,11 +29,12 @@ import (
|
||||
)
|
||||
|
||||
var adminGroupAddCmd = cli.Command{
|
||||
Name: "add",
|
||||
Usage: "add users to a new or existing group",
|
||||
Action: mainAdminGroupAdd,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
Name: "add",
|
||||
Usage: "add users to a new or existing group",
|
||||
Action: mainAdminGroupAdd,
|
||||
OnUsageError: onUsageError,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
@@ -131,7 +132,7 @@ func mainAdminGroupAdd(ctx *cli.Context) error {
|
||||
Members: members,
|
||||
IsRemove: false,
|
||||
}
|
||||
fatalIf(probe.NewError(client.UpdateGroupMembers(globalContext, gAddRemove)).Trace(args...), "Cannot add new group")
|
||||
fatalIf(probe.NewError(client.UpdateGroupMembers(globalContext, gAddRemove)).Trace(args...), "Unable to add new group")
|
||||
|
||||
printMsg(groupMessage{
|
||||
op: "add",
|
||||
|
||||
@@ -21,11 +21,12 @@ import (
|
||||
)
|
||||
|
||||
var adminGroupDisableCmd = cli.Command{
|
||||
Name: "disable",
|
||||
Usage: "Disable a group",
|
||||
Action: mainAdminGroupEnableDisable,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
Name: "disable",
|
||||
Usage: "disable a group",
|
||||
Action: mainAdminGroupEnableDisable,
|
||||
OnUsageError: onUsageError,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
|
||||
@@ -27,11 +27,12 @@ import (
|
||||
)
|
||||
|
||||
var adminGroupEnableCmd = cli.Command{
|
||||
Name: "enable",
|
||||
Usage: "Enable a group",
|
||||
Action: mainAdminGroupEnableDisable,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
Name: "enable",
|
||||
Usage: "enable a group",
|
||||
Action: mainAdminGroupEnableDisable,
|
||||
OnUsageError: onUsageError,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
|
||||
@@ -24,11 +24,12 @@ import (
|
||||
)
|
||||
|
||||
var adminGroupInfoCmd = cli.Command{
|
||||
Name: "info",
|
||||
Usage: "display group info",
|
||||
Action: mainAdminGroupInfo,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
Name: "info",
|
||||
Usage: "display group info",
|
||||
Action: mainAdminGroupInfo,
|
||||
OnUsageError: onUsageError,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
|
||||
@@ -24,11 +24,12 @@ import (
|
||||
)
|
||||
|
||||
var adminGroupListCmd = cli.Command{
|
||||
Name: "list",
|
||||
Usage: "display list of groups",
|
||||
Action: mainAdminGroupList,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
Name: "list",
|
||||
Usage: "display list of groups",
|
||||
Action: mainAdminGroupList,
|
||||
OnUsageError: onUsageError,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
|
||||
@@ -25,11 +25,12 @@ import (
|
||||
)
|
||||
|
||||
var adminGroupRemoveCmd = cli.Command{
|
||||
Name: "remove",
|
||||
Usage: "remove group or members from a group",
|
||||
Action: mainAdminGroupRemove,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
Name: "remove",
|
||||
Usage: "remove group or members from a group",
|
||||
Action: mainAdminGroupRemove,
|
||||
OnUsageError: onUsageError,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
|
||||
+16
-14
@@ -18,26 +18,28 @@ package cmd
|
||||
|
||||
import "github.com/minio/cli"
|
||||
|
||||
var adminGroupSubcommands = []cli.Command{
|
||||
adminGroupAddCmd,
|
||||
adminGroupRemoveCmd,
|
||||
adminGroupInfoCmd,
|
||||
adminGroupListCmd,
|
||||
adminGroupEnableCmd,
|
||||
adminGroupDisableCmd,
|
||||
}
|
||||
|
||||
var adminGroupCmd = cli.Command{
|
||||
Name: "group",
|
||||
Usage: "manage groups",
|
||||
Action: mainAdminGroup,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
Subcommands: []cli.Command{
|
||||
adminGroupAddCmd,
|
||||
adminGroupRemoveCmd,
|
||||
adminGroupInfoCmd,
|
||||
adminGroupListCmd,
|
||||
adminGroupEnableCmd,
|
||||
adminGroupDisableCmd,
|
||||
},
|
||||
Name: "group",
|
||||
Usage: "manage groups",
|
||||
Action: mainAdminGroup,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
Subcommands: adminGroupSubcommands,
|
||||
HideHelpCommand: true,
|
||||
}
|
||||
|
||||
// mainAdminGroup is the handle for "mc admin config" command.
|
||||
func mainAdminGroup(ctx *cli.Context) error {
|
||||
cli.ShowCommandHelp(ctx, ctx.Args().First())
|
||||
commandNotFound(ctx, adminGroupSubcommands)
|
||||
return nil
|
||||
// Sub-commands like "get", "set" have their own main.
|
||||
}
|
||||
|
||||
+13
-33
@@ -38,35 +38,36 @@ const (
|
||||
var adminHealFlags = []cli.Flag{
|
||||
cli.StringFlag{
|
||||
Name: "scan",
|
||||
Usage: "select the healing scan mode (normal/deep)",
|
||||
Usage: "[DEPRECATED] select the healing scan mode (normal/deep)",
|
||||
Value: scanNormalMode,
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "recursive, r",
|
||||
Usage: "heal recursively",
|
||||
Usage: "[DEPRECATED] heal recursively",
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "dry-run, n",
|
||||
Usage: "only inspect data, but do not mutate",
|
||||
Usage: "[DEPRECATED] only inspect data, but do not mutate",
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "force-start, f",
|
||||
Usage: "force start a new heal sequence",
|
||||
Usage: "[DEPRECATED] force start a new heal sequence",
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "force-stop, s",
|
||||
Usage: "Force stop a running heal sequence",
|
||||
Usage: "[DEPRECATED] force stop a running heal sequence",
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "remove",
|
||||
Usage: "remove dangling objects in heal sequence",
|
||||
Usage: "[DEPRECATED] remove dangling objects in heal sequence",
|
||||
},
|
||||
}
|
||||
|
||||
var adminHealCmd = cli.Command{
|
||||
Name: "heal",
|
||||
Usage: "heal disks, buckets and objects on MinIO server",
|
||||
Usage: "[DEPRECATED] heal disks, buckets and objects on MinIO server",
|
||||
Action: mainAdminHeal,
|
||||
OnUsageError: onUsageError,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: append(adminHealFlags, globalFlags...),
|
||||
HideHelpCommand: true,
|
||||
@@ -83,30 +84,8 @@ SCAN MODES:
|
||||
normal (default): Heal objects which are missing on one or more disks.
|
||||
deep : Heal objects which are missing or with silent data corruption on one or more disks.
|
||||
|
||||
EXAMPLES:
|
||||
1. To format newly replaced disks in a MinIO server with alias 'myminio'
|
||||
{{.Prompt}} {{.HelpName}} myminio
|
||||
|
||||
2. Heal 'testbucket' in a MinIO server with alias 'myminio'
|
||||
{{.Prompt}} {{.HelpName}} myminio/testbucket/
|
||||
|
||||
3. Heal all objects under 'dir' prefix
|
||||
{{.Prompt}} {{.HelpName}} --recursive myminio/testbucket/dir/
|
||||
|
||||
4. Issue a dry-run heal operation to inspect objects health but not heal them
|
||||
{{.Prompt}} {{.HelpName}} --dry-run myminio
|
||||
|
||||
5. Issue a dry-run heal operation to inspect objects health under 'dir' prefix
|
||||
{{.Prompt}} {{.HelpName}} --recursive --dry-run myminio/testbucket/dir/
|
||||
|
||||
6. Force start a running heal sequence (meaning it will force kill the running heal sequence and start a new one)
|
||||
{{.Prompt}} {{.HelpName}} --force-start myminio/testbucket/dir/
|
||||
|
||||
7. Force stop a running heal sequence (meaning it will force kill the running heal sequence)
|
||||
{{.Prompt}} {{.HelpName}} --force-stop myminio/testbucket/dir/
|
||||
|
||||
8. Issue a dry-run heal operation to inspect objects health under 'dir' prefix
|
||||
{{.Prompt}} {{.HelpName}} --dry-run myminio/testbucket/dir/
|
||||
DEPRECATED:
|
||||
MinIO server now supports auto-heal, this command will be removed in future.
|
||||
`,
|
||||
}
|
||||
|
||||
@@ -207,7 +186,7 @@ func mainAdminHeal(ctx *cli.Context) error {
|
||||
// Create a new MinIO Admin Client
|
||||
client, err := newAdminClient(aliasedURL)
|
||||
if err != nil {
|
||||
fatalIf(err.Trace(aliasedURL), "Cannot initialize admin client.")
|
||||
fatalIf(err.Trace(aliasedURL), "Unable to initialize admin client.")
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -221,7 +200,8 @@ 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{Recursive: false, ShowDir: DirNone}) {
|
||||
if content.Err != nil {
|
||||
fatalIf(content.Err.Trace(clnt.GetURL().String()), "Unable to heal bucket `"+bucket+"`.")
|
||||
return nil
|
||||
|
||||
+48
-11
@@ -35,11 +35,12 @@ import (
|
||||
)
|
||||
|
||||
var adminInfoCmd = cli.Command{
|
||||
Name: "info",
|
||||
Usage: "display MinIO server information",
|
||||
Action: mainAdminInfo,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
Name: "info",
|
||||
Usage: "display MinIO server information",
|
||||
Action: mainAdminInfo,
|
||||
OnUsageError: onUsageError,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
@@ -78,12 +79,12 @@ type clusterStruct struct {
|
||||
func (u clusterStruct) String() (msg string) {
|
||||
// Check cluster level "Status" field for error
|
||||
if u.Status == "error" {
|
||||
fatal(probe.NewError(errors.New(u.Error)), "Cannot get service status")
|
||||
fatal(probe.NewError(errors.New(u.Error)), "Unable to get service status")
|
||||
}
|
||||
|
||||
// If nothing has been collected, error out
|
||||
if u.Info.Servers == nil {
|
||||
fatal(probe.NewError(errors.New("Cannot get service status")), "")
|
||||
fatal(probe.NewError(errors.New("Unable to get service status")), "")
|
||||
}
|
||||
|
||||
// Initialization
|
||||
@@ -93,6 +94,7 @@ func (u clusterStruct) String() (msg string) {
|
||||
// Color palette initialization
|
||||
console.SetColor("Info", color.New(color.FgGreen, color.Bold))
|
||||
console.SetColor("InfoFail", color.New(color.FgRed, color.Bold))
|
||||
console.SetColor("InfoWarning", color.New(color.FgYellow, color.Bold))
|
||||
|
||||
// MinIO server type default
|
||||
backendType := "Unknown"
|
||||
@@ -108,6 +110,11 @@ func (u clusterStruct) String() (msg string) {
|
||||
}
|
||||
}
|
||||
|
||||
coloredDot := console.Colorize("Info", dot)
|
||||
if u.Info.Mode == madmin.ObjectLayerInitializing {
|
||||
coloredDot = console.Colorize("InfoWarning", dot)
|
||||
}
|
||||
|
||||
// Loop through each server and put together info for each one
|
||||
for _, srv := range u.Info.Servers {
|
||||
// Check if MinIO server is offline ("Mode" field),
|
||||
@@ -115,13 +122,40 @@ func (u clusterStruct) String() (msg string) {
|
||||
if srv.State == "offline" {
|
||||
// "PrintB" is color blue in console library package
|
||||
msg += fmt.Sprintf("%s %s\n", console.Colorize("InfoFail", dot), console.Colorize("PrintB", srv.Endpoint))
|
||||
msg += fmt.Sprintf(" Uptime: %s\n\n", console.Colorize("InfoFail", "offline"))
|
||||
msg += fmt.Sprintf(" Uptime: %s\n", console.Colorize("InfoFail", "offline"))
|
||||
|
||||
if backendType != "FS" {
|
||||
// Info about drives on a server, only available for non-FS types
|
||||
var OffDisks int
|
||||
var OnDisks int
|
||||
var dispNoOfDisks string
|
||||
for _, disk := range srv.Disks {
|
||||
switch disk.State {
|
||||
case madmin.DriveStateOk:
|
||||
fallthrough
|
||||
case madmin.DriveStateUnformatted:
|
||||
OnDisks++
|
||||
default:
|
||||
OffDisks++
|
||||
}
|
||||
}
|
||||
|
||||
totalDisksPerServer := OnDisks + OffDisks
|
||||
totalOnlineDisksCluster += OnDisks
|
||||
totalOfflineDisksCluster += OffDisks
|
||||
|
||||
dispNoOfDisks = strconv.Itoa(OnDisks) + "/" + strconv.Itoa(totalDisksPerServer)
|
||||
msg += fmt.Sprintf(" Drives: %s %s\n", dispNoOfDisks, console.Colorize("InfoFail", "OK "))
|
||||
}
|
||||
|
||||
msg += "\n"
|
||||
|
||||
// Continue to the next server
|
||||
continue
|
||||
}
|
||||
|
||||
// Print server title
|
||||
msg += fmt.Sprintf("%s %s\n", console.Colorize("Info", dot), console.Colorize("PrintB", srv.Endpoint))
|
||||
msg += fmt.Sprintf("%s %s\n", coloredDot, console.Colorize("PrintB", srv.Endpoint))
|
||||
|
||||
// Uptime
|
||||
msg += fmt.Sprintf(" Uptime: %s\n", console.Colorize("Info",
|
||||
@@ -153,9 +187,12 @@ func (u clusterStruct) String() (msg string) {
|
||||
var OnDisks int
|
||||
var dispNoOfDisks string
|
||||
for _, disk := range srv.Disks {
|
||||
if disk.State == "ok" {
|
||||
switch disk.State {
|
||||
case madmin.DriveStateOk:
|
||||
fallthrough
|
||||
case madmin.DriveStateUnformatted:
|
||||
OnDisks++
|
||||
} else {
|
||||
default:
|
||||
OffDisks++
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
/*
|
||||
* 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"
|
||||
"os"
|
||||
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/minio/pkg/console"
|
||||
"golang.org/x/crypto/ssh/terminal"
|
||||
)
|
||||
|
||||
var adminKMSCreateKeyCmd = cli.Command{
|
||||
Name: "create",
|
||||
Usage: "creates a new master key at the KMS",
|
||||
Action: mainAdminKMSCreateKey,
|
||||
OnUsageError: onUsageError,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
{{.HelpName}} TARGET [KEY_NAME]
|
||||
|
||||
FLAGS:
|
||||
{{range .VisibleFlags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
1. Create a new master key named 'my-key' default master key.
|
||||
$ {{.HelpName}} play my-key
|
||||
`,
|
||||
}
|
||||
|
||||
// adminKMSCreateKeyCmd is the handler for the "mc admin kms key create" command.
|
||||
func mainAdminKMSCreateKey(ctx *cli.Context) error {
|
||||
if len(ctx.Args()) != 2 {
|
||||
cli.ShowCommandHelpAndExit(ctx, "create", 1) // last argument is exit code
|
||||
}
|
||||
|
||||
client, err := newAdminClient(ctx.Args().Get(0))
|
||||
fatalIf(err, "Cannot get a configured admin connection.")
|
||||
|
||||
keyID := ctx.Args().Get(1)
|
||||
e := client.CreateKey(globalContext, keyID)
|
||||
fatalIf(probe.NewError(e), "Failed to create master key")
|
||||
|
||||
if terminal.IsTerminal(int(os.Stdout.Fd())) {
|
||||
console.Println(color.GreenString(fmt.Sprintf("Created master key `%s` successfully", keyID)))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
+52
-27
@@ -19,17 +19,20 @@ package cmd
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/cli"
|
||||
json "github.com/minio/mc/pkg/colorjson"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/minio/pkg/madmin"
|
||||
"github.com/minio/minio/pkg/console"
|
||||
)
|
||||
|
||||
var adminKMSKeyStatusCmd = cli.Command{
|
||||
Name: "status",
|
||||
Usage: "request status information for a KMS master key",
|
||||
Action: mainAdminKMSKeyStatus,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
Name: "status",
|
||||
Usage: "request status information for a KMS master key",
|
||||
Action: mainAdminKMSKeyStatus,
|
||||
OnUsageError: onUsageError,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
@@ -43,7 +46,7 @@ EXAMPLES:
|
||||
1. Get default master key and its status from a MinIO server/cluster.
|
||||
$ {{.HelpName}} play
|
||||
2. Get the status of one particular master key from a MinIO server/cluster.
|
||||
$ {{.HelpName}} play my-master-key
|
||||
$ {{.HelpName}} play my-master-key
|
||||
`,
|
||||
}
|
||||
|
||||
@@ -53,8 +56,11 @@ func mainAdminKMSKeyStatus(ctx *cli.Context) error {
|
||||
cli.ShowCommandHelpAndExit(ctx, "status", 1) // last argument is exit code
|
||||
}
|
||||
|
||||
console.SetColor("StatusSuccess", color.New(color.FgGreen, color.Bold))
|
||||
console.SetColor("StatusError", color.New(color.FgRed, color.Bold))
|
||||
|
||||
client, err := newAdminClient(ctx.Args().Get(0))
|
||||
fatalIf(err, "Cannot get a configured admin connection.")
|
||||
fatalIf(err, "Unable to get a configured admin connection.")
|
||||
|
||||
var keyID string
|
||||
if len(ctx.Args()) == 2 {
|
||||
@@ -63,29 +69,48 @@ func mainAdminKMSKeyStatus(ctx *cli.Context) error {
|
||||
status, e := client.GetKeyStatus(globalContext, keyID)
|
||||
fatalIf(probe.NewError(e), "Failed to get status information")
|
||||
|
||||
printMsg(kmsKeyStatusMsg(*status))
|
||||
printMsg(kmsKeyStatusMsg{
|
||||
KeyID: status.KeyID,
|
||||
Encryption: status.EncryptionErr == "",
|
||||
Decryption: status.DecryptionErr == "",
|
||||
EncryptionErr: status.EncryptionErr,
|
||||
DecryptionErr: status.DecryptionErr,
|
||||
})
|
||||
return nil
|
||||
}
|
||||
|
||||
type kmsKeyStatusMsg madmin.KMSKeyStatus
|
||||
|
||||
func (s kmsKeyStatusMsg) String() string {
|
||||
msg := fmt.Sprintf("Key: %s\n", s.KeyID)
|
||||
if s.EncryptionErr == "" {
|
||||
msg = fmt.Sprintf("%s %s", msg, "\t • Encryption ✔\n")
|
||||
} else {
|
||||
return fmt.Sprintf("%s \t • Encryption failed: %s\n", msg, s.EncryptionErr)
|
||||
}
|
||||
|
||||
if s.DecryptionErr == "" {
|
||||
msg = fmt.Sprintf("%s %s", msg, "\t • Decryption ✔\n")
|
||||
} else {
|
||||
return fmt.Sprintf("%s \t • Decryption failed: %s\n", msg, s.DecryptionErr)
|
||||
}
|
||||
return msg
|
||||
type kmsKeyStatusMsg struct {
|
||||
KeyID string `json:"keyId"`
|
||||
Encryption bool `json:"encryption"`
|
||||
Decryption bool `json:"decryption"`
|
||||
EncryptionErr string `json:"encryptionError,omitempty"`
|
||||
DecryptionErr string `json:"decryptionError,omitempty"`
|
||||
Status string `json:"status"`
|
||||
}
|
||||
|
||||
func (s kmsKeyStatusMsg) JSON() string {
|
||||
const fmtStr = `{"key-id":"%s","encryption-error":"%s","decryption-error":"%s"}`
|
||||
return fmt.Sprintf(fmtStr, s.KeyID, s.EncryptionErr, s.DecryptionErr)
|
||||
s.Status = "success"
|
||||
if !s.Encryption && !s.Decryption {
|
||||
s.Status = "error"
|
||||
}
|
||||
kmsBytes, e := json.MarshalIndent(s, "", " ")
|
||||
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
|
||||
|
||||
return string(kmsBytes)
|
||||
}
|
||||
|
||||
func (s kmsKeyStatusMsg) String() string {
|
||||
msg := fmt.Sprintf("Key: %s\n", s.KeyID)
|
||||
if s.Encryption {
|
||||
msg += " - Encryption " + console.Colorize("StatusSuccess", "✔") + "\n"
|
||||
} else {
|
||||
msg += fmt.Sprintf(" - Encryption %s (%s)\n", console.Colorize("StatusError", "✗"), s.EncryptionErr)
|
||||
}
|
||||
|
||||
if s.Decryption {
|
||||
msg += " - Decryption " + console.Colorize("StatusSuccess", "✔") + "\n"
|
||||
} else {
|
||||
msg += fmt.Sprintf(" - Decryption %s (%s)\n", console.Colorize("StatusError", "✗"), s.DecryptionErr)
|
||||
}
|
||||
return msg
|
||||
}
|
||||
|
||||
+12
-9
@@ -18,20 +18,23 @@ package cmd
|
||||
|
||||
import "github.com/minio/cli"
|
||||
|
||||
var adminKMSKeySubcommands = []cli.Command{
|
||||
adminKMSCreateKeyCmd,
|
||||
adminKMSKeyStatusCmd,
|
||||
}
|
||||
|
||||
var adminKMSKeyCmd = cli.Command{
|
||||
Name: "key",
|
||||
Usage: "Manage KMS master keys: Request key status information",
|
||||
Action: mainAdminKMSKey,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
Subcommands: []cli.Command{
|
||||
adminKMSKeyStatusCmd,
|
||||
},
|
||||
Name: "key",
|
||||
Usage: "manage KMS master keys: Request key status information",
|
||||
Action: mainAdminKMSKey,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
Subcommands: adminKMSKeySubcommands,
|
||||
HideHelpCommand: true,
|
||||
}
|
||||
|
||||
// mainAdminKMSKey is the handle for the "mc admin kms key" command.
|
||||
func mainAdminKMSKey(ctx *cli.Context) error {
|
||||
cli.ShowCommandHelp(ctx, ctx.Args().First())
|
||||
commandNotFound(ctx, adminKMSKeySubcommands)
|
||||
return nil
|
||||
}
|
||||
|
||||
+11
-9
@@ -18,20 +18,22 @@ package cmd
|
||||
|
||||
import "github.com/minio/cli"
|
||||
|
||||
var adminKMSSubcommands = []cli.Command{
|
||||
adminKMSKeyCmd,
|
||||
}
|
||||
|
||||
var adminKMSCmd = cli.Command{
|
||||
Name: "kms",
|
||||
Usage: "perform KMS management operations",
|
||||
Action: mainAdminKMS,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
Subcommands: []cli.Command{
|
||||
adminKMSKeyCmd,
|
||||
},
|
||||
Name: "kms",
|
||||
Usage: "perform KMS management operations",
|
||||
Action: mainAdminKMS,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
Subcommands: adminKMSSubcommands,
|
||||
HideHelpCommand: true,
|
||||
}
|
||||
|
||||
// mainAdminKMS is the handle for the "mc admin kms" command.
|
||||
func mainAdminKMS(ctx *cli.Context) error {
|
||||
cli.ShowCommandHelp(ctx, ctx.Args().First())
|
||||
commandNotFound(ctx, adminKMSSubcommands)
|
||||
return nil
|
||||
}
|
||||
|
||||
+22
-19
@@ -29,38 +29,41 @@ const (
|
||||
check = "✔"
|
||||
)
|
||||
|
||||
var adminCmdSubcommands = []cli.Command{
|
||||
adminServiceCmd,
|
||||
adminServerUpdateCmd,
|
||||
adminInfoCmd,
|
||||
adminUserCmd,
|
||||
adminGroupCmd,
|
||||
adminPolicyCmd,
|
||||
adminConfigCmd,
|
||||
adminHealCmd,
|
||||
adminProfileCmd,
|
||||
adminTopCmd,
|
||||
adminTraceCmd,
|
||||
adminConsoleCmd,
|
||||
adminPrometheusCmd,
|
||||
adminKMSCmd,
|
||||
adminHealthCmd,
|
||||
adminSubnetCmd,
|
||||
adminBucketCmd,
|
||||
}
|
||||
|
||||
var adminCmd = cli.Command{
|
||||
Name: "admin",
|
||||
Usage: "manage MinIO servers",
|
||||
Action: mainAdmin,
|
||||
Subcommands: adminCmdSubcommands,
|
||||
HideHelpCommand: true,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: append(adminFlags, globalFlags...),
|
||||
Subcommands: []cli.Command{
|
||||
adminServiceCmd,
|
||||
adminServerUpdateCmd,
|
||||
adminInfoCmd,
|
||||
adminUserCmd,
|
||||
adminGroupCmd,
|
||||
adminPolicyCmd,
|
||||
adminConfigCmd,
|
||||
adminHealCmd,
|
||||
adminProfileCmd,
|
||||
adminTopCmd,
|
||||
adminTraceCmd,
|
||||
adminConsoleCmd,
|
||||
adminPrometheusCmd,
|
||||
adminKMSCmd,
|
||||
adminOBDCmd,
|
||||
adminBucketCmd,
|
||||
},
|
||||
}
|
||||
|
||||
const dateTimeFormatFilename = "2006-01-02T15-04-05.999999-07-00"
|
||||
|
||||
// mainAdmin is the handle for "mc admin" command.
|
||||
func mainAdmin(ctx *cli.Context) error {
|
||||
cli.ShowCommandHelp(ctx, ctx.Args().First())
|
||||
commandNotFound(ctx, adminCmdSubcommands)
|
||||
return nil
|
||||
// Sub-commands like "service", "heal", "top" have their own main.
|
||||
}
|
||||
|
||||
@@ -30,11 +30,12 @@ import (
|
||||
)
|
||||
|
||||
var adminPolicyAddCmd = cli.Command{
|
||||
Name: "add",
|
||||
Usage: "add new policy",
|
||||
Action: mainAdminPolicyAdd,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
Name: "add",
|
||||
Usage: "add new policy",
|
||||
Action: mainAdminPolicyAdd,
|
||||
OnUsageError: onUsageError,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
|
||||
@@ -26,11 +26,12 @@ import (
|
||||
)
|
||||
|
||||
var adminPolicyInfoCmd = cli.Command{
|
||||
Name: "info",
|
||||
Usage: "show info on a policy",
|
||||
Action: mainAdminPolicyInfo,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
Name: "info",
|
||||
Usage: "show info on a policy",
|
||||
Action: mainAdminPolicyInfo,
|
||||
OnUsageError: onUsageError,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
@@ -73,7 +74,7 @@ func mainAdminPolicyInfo(ctx *cli.Context) error {
|
||||
fatalIf(err, "Unable to initialize admin connection")
|
||||
|
||||
policies, e := client.ListCannedPolicies(globalContext)
|
||||
fatalIf(probe.NewError(e).Trace(args...), "Cannot list policy")
|
||||
fatalIf(probe.NewError(e).Trace(args...), "Unable to list policy")
|
||||
|
||||
iamp, ok := policies[policyName]
|
||||
if ok {
|
||||
|
||||
@@ -24,11 +24,12 @@ import (
|
||||
)
|
||||
|
||||
var adminPolicyListCmd = cli.Command{
|
||||
Name: "list",
|
||||
Usage: "list all policies",
|
||||
Action: mainAdminPolicyList,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
Name: "list",
|
||||
Usage: "list all policies",
|
||||
Action: mainAdminPolicyList,
|
||||
OnUsageError: onUsageError,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
@@ -67,7 +68,7 @@ func mainAdminPolicyList(ctx *cli.Context) error {
|
||||
fatalIf(err, "Unable to initialize admin connection.")
|
||||
|
||||
policies, e := client.ListCannedPolicies(globalContext)
|
||||
fatalIf(probe.NewError(e).Trace(args...), "Cannot list policy")
|
||||
fatalIf(probe.NewError(e).Trace(args...), "Unable to list policy")
|
||||
|
||||
for k := range policies {
|
||||
printMsg(userPolicyMessage{
|
||||
|
||||
@@ -24,11 +24,12 @@ import (
|
||||
)
|
||||
|
||||
var adminPolicyRemoveCmd = cli.Command{
|
||||
Name: "remove",
|
||||
Usage: "remove policy",
|
||||
Action: mainAdminPolicyRemove,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
Name: "remove",
|
||||
Usage: "remove policy",
|
||||
Action: mainAdminPolicyRemove,
|
||||
OnUsageError: onUsageError,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
@@ -68,7 +69,7 @@ func mainAdminPolicyRemove(ctx *cli.Context) error {
|
||||
client, err := newAdminClient(aliasedURL)
|
||||
fatalIf(err, "Unable to initialize admin connection.")
|
||||
|
||||
fatalIf(probe.NewError(client.RemoveCannedPolicy(globalContext, args.Get(1))).Trace(args...), "Cannot remove policy")
|
||||
fatalIf(probe.NewError(client.RemoveCannedPolicy(globalContext, args.Get(1))).Trace(args...), "Unable to remove policy")
|
||||
|
||||
printMsg(userPolicyMessage{
|
||||
op: "remove",
|
||||
|
||||
@@ -27,11 +27,12 @@ import (
|
||||
)
|
||||
|
||||
var adminPolicySetCmd = cli.Command{
|
||||
Name: "set",
|
||||
Usage: "set IAM policy on a user or group",
|
||||
Action: mainAdminPolicySet,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
Name: "set",
|
||||
Usage: "set IAM policy on a user or group",
|
||||
Action: mainAdminPolicySet,
|
||||
OnUsageError: onUsageError,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
@@ -113,7 +114,7 @@ func mainAdminPolicySet(ctx *cli.Context) error {
|
||||
IsGroup: isGroup,
|
||||
})
|
||||
} else {
|
||||
fatalIf(probe.NewError(e), "Cannot set the policy")
|
||||
fatalIf(probe.NewError(e), "Unable to set the policy")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
+15
-13
@@ -18,25 +18,27 @@ package cmd
|
||||
|
||||
import "github.com/minio/cli"
|
||||
|
||||
var adminPolicySubcommands = []cli.Command{
|
||||
adminPolicyAddCmd,
|
||||
adminPolicyRemoveCmd,
|
||||
adminPolicyListCmd,
|
||||
adminPolicyInfoCmd,
|
||||
adminPolicySetCmd,
|
||||
}
|
||||
|
||||
var adminPolicyCmd = cli.Command{
|
||||
Name: "policy",
|
||||
Usage: "manage policies defined in the MinIO server",
|
||||
Action: mainAdminPolicy,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
Subcommands: []cli.Command{
|
||||
adminPolicyAddCmd,
|
||||
adminPolicyRemoveCmd,
|
||||
adminPolicyListCmd,
|
||||
adminPolicyInfoCmd,
|
||||
adminPolicySetCmd,
|
||||
},
|
||||
Name: "policy",
|
||||
Usage: "manage policies defined in the MinIO server",
|
||||
Action: mainAdminPolicy,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
Subcommands: adminPolicySubcommands,
|
||||
HideHelpCommand: true,
|
||||
}
|
||||
|
||||
// mainAdminPolicy is the handle for "mc admin policy" command.
|
||||
func mainAdminPolicy(ctx *cli.Context) error {
|
||||
cli.ShowCommandHelp(ctx, ctx.Args().First())
|
||||
commandNotFound(ctx, adminPolicySubcommands)
|
||||
return nil
|
||||
// Sub-commands like "get", "set" have their own main.
|
||||
}
|
||||
|
||||
@@ -21,7 +21,7 @@ import (
|
||||
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/minio-go/v6/pkg/set"
|
||||
"github.com/minio/minio-go/v7/pkg/set"
|
||||
"github.com/minio/minio/pkg/console"
|
||||
"github.com/minio/minio/pkg/madmin"
|
||||
)
|
||||
@@ -38,6 +38,7 @@ var adminProfileStartCmd = cli.Command{
|
||||
Name: "start",
|
||||
Usage: "start recording profile data",
|
||||
Action: mainAdminProfileStart,
|
||||
OnUsageError: onUsageError,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: append(adminProfileStartFlags, globalFlags...),
|
||||
HideHelpCommand: true,
|
||||
@@ -109,7 +110,7 @@ func mainAdminProfileStart(ctx *cli.Context) error {
|
||||
// Create a new MinIO Admin Client
|
||||
client, err := newAdminClient(aliasedURL)
|
||||
if err != nil {
|
||||
fatalIf(err.Trace(aliasedURL), "Cannot initialize admin client.")
|
||||
fatalIf(err.Trace(aliasedURL), "Unable to initialize admin client.")
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
@@ -31,6 +31,7 @@ var adminProfileStopCmd = cli.Command{
|
||||
Name: "stop",
|
||||
Usage: "stop and download profile data",
|
||||
Action: mainAdminProfileStop,
|
||||
OnUsageError: onUsageError,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
HideHelpCommand: true,
|
||||
@@ -94,7 +95,7 @@ func mainAdminProfileStop(ctx *cli.Context) error {
|
||||
// Create a new MinIO Admin Client
|
||||
client, err := newAdminClient(aliasedURL)
|
||||
if err != nil {
|
||||
fatalIf(err.Trace(aliasedURL), "Cannot initialize admin client.")
|
||||
fatalIf(err.Trace(aliasedURL), "Unable to initialize admin client.")
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
+13
-10
@@ -20,21 +20,24 @@ import (
|
||||
"github.com/minio/cli"
|
||||
)
|
||||
|
||||
var adminProfileSubcommands = []cli.Command{
|
||||
adminProfileStartCmd,
|
||||
adminProfileStopCmd,
|
||||
}
|
||||
|
||||
var adminProfileCmd = cli.Command{
|
||||
Name: "profile",
|
||||
Usage: "generate profile data for debugging purposes",
|
||||
Action: mainAdminProfile,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
Subcommands: []cli.Command{
|
||||
adminProfileStartCmd,
|
||||
adminProfileStopCmd,
|
||||
},
|
||||
Name: "profile",
|
||||
Usage: "generate profile data for debugging purposes",
|
||||
Action: mainAdminProfile,
|
||||
OnUsageError: onUsageError,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
Subcommands: adminProfileSubcommands,
|
||||
HideHelpCommand: true,
|
||||
}
|
||||
|
||||
// mainAdminProfile is the handle for "mc admin profile" command.
|
||||
func mainAdminProfile(ctx *cli.Context) error {
|
||||
cli.ShowCommandHelp(ctx, ctx.Args().First())
|
||||
commandNotFound(ctx, adminProfileSubcommands)
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -40,6 +40,7 @@ var adminPrometheusGenerateCmd = cli.Command{
|
||||
Name: "generate",
|
||||
Usage: "generates prometheus config",
|
||||
Action: mainAdminPrometheusGenerate,
|
||||
OnUsageError: onUsageError,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
HideHelpCommand: true,
|
||||
|
||||
@@ -18,6 +18,10 @@ package cmd
|
||||
|
||||
import "github.com/minio/cli"
|
||||
|
||||
var adminPrometheusSubcommands = []cli.Command{
|
||||
adminPrometheusGenerateCmd,
|
||||
}
|
||||
|
||||
var adminPrometheusCmd = cli.Command{
|
||||
Name: "prometheus",
|
||||
Usage: "manages prometheus config",
|
||||
@@ -25,9 +29,7 @@ var adminPrometheusCmd = cli.Command{
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
HideHelpCommand: true,
|
||||
Subcommands: []cli.Command{
|
||||
adminPrometheusGenerateCmd,
|
||||
},
|
||||
Subcommands: adminPrometheusSubcommands,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
@@ -42,6 +44,6 @@ FLAGS:
|
||||
|
||||
// mainAdminPrometheus is the handle for "mc admin prometheus" command.
|
||||
func mainAdminPrometheus(ctx *cli.Context) error {
|
||||
cli.ShowCommandHelp(ctx, ctx.Args().First())
|
||||
commandNotFound(ctx, adminPrometheusSubcommands)
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -27,11 +27,12 @@ import (
|
||||
)
|
||||
|
||||
var adminServiceRestartCmd = cli.Command{
|
||||
Name: "restart",
|
||||
Usage: "restart all MinIO servers",
|
||||
Action: mainAdminServiceRestart,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
Name: "restart",
|
||||
Usage: "restart all MinIO servers",
|
||||
Action: mainAdminServiceRestart,
|
||||
OnUsageError: onUsageError,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
@@ -113,7 +114,7 @@ func mainAdminServiceRestart(ctx *cli.Context) error {
|
||||
fatalIf(err, "Unable to initialize admin connection.")
|
||||
|
||||
// Restart the specified MinIO server
|
||||
fatalIf(probe.NewError(client.ServiceRestart(globalContext)), "Cannot restart the server.")
|
||||
fatalIf(probe.NewError(client.ServiceRestart(globalContext)), "Unable to restart the server.")
|
||||
|
||||
// Success..
|
||||
printMsg(serviceRestartCommand{Status: "success", ServerURL: aliasedURL})
|
||||
|
||||
@@ -25,11 +25,12 @@ import (
|
||||
)
|
||||
|
||||
var adminServiceStopCmd = cli.Command{
|
||||
Name: "stop",
|
||||
Usage: "stop MinIO server",
|
||||
Action: mainAdminServiceStop,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
Name: "stop",
|
||||
Usage: "stop MinIO server",
|
||||
Action: mainAdminServiceStop,
|
||||
OnUsageError: onUsageError,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
|
||||
@@ -18,6 +18,11 @@ package cmd
|
||||
|
||||
import "github.com/minio/cli"
|
||||
|
||||
var adminServiceSubcommands = []cli.Command{
|
||||
adminServiceRestartCmd,
|
||||
adminServiceStopCmd,
|
||||
}
|
||||
|
||||
var adminServiceCmd = cli.Command{
|
||||
Name: "service",
|
||||
Usage: "restart and stop all MinIO servers",
|
||||
@@ -25,15 +30,12 @@ var adminServiceCmd = cli.Command{
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
HideHelpCommand: true,
|
||||
Subcommands: []cli.Command{
|
||||
adminServiceRestartCmd,
|
||||
adminServiceStopCmd,
|
||||
},
|
||||
Subcommands: adminServiceSubcommands,
|
||||
}
|
||||
|
||||
// mainAdmin is the handle for "mc admin service" command.
|
||||
func mainAdminService(ctx *cli.Context) error {
|
||||
cli.ShowCommandHelp(ctx, ctx.Args().First())
|
||||
commandNotFound(ctx, adminServiceSubcommands)
|
||||
return nil
|
||||
// Sub-commands like "status", "restart" have their own main.
|
||||
}
|
||||
|
||||
@@ -18,7 +18,8 @@ package cmd
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
gojson "encoding/json"
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"os"
|
||||
@@ -30,34 +31,33 @@ import (
|
||||
"github.com/fatih/color"
|
||||
"github.com/klauspost/compress/gzip"
|
||||
"github.com/minio/cli"
|
||||
cjson "github.com/minio/mc/pkg/colorjson"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/minio/pkg/console"
|
||||
"github.com/minio/minio/pkg/madmin"
|
||||
)
|
||||
|
||||
var adminOBDFlags = []cli.Flag{
|
||||
OBDDataTypeFlag{
|
||||
Name: "tests",
|
||||
Usage: "choose OBD tests to run [" + options.String() + "]",
|
||||
var adminHealthFlags = []cli.Flag{
|
||||
HealthDataTypeFlag{
|
||||
Name: "test",
|
||||
Usage: "choose health tests to run [" + options.String() + "]",
|
||||
Value: nil,
|
||||
EnvVar: "MC_OBD_DATA",
|
||||
EnvVar: "MC_HEALTH_TEST,MC_OBD_TEST",
|
||||
Hidden: true,
|
||||
},
|
||||
cli.DurationFlag{
|
||||
Name: "deadline",
|
||||
Usage: "maximum duration that OBD tests should be allowed to run",
|
||||
Usage: "maximum duration that health tests should be allowed to run",
|
||||
Value: 3600 * time.Second,
|
||||
EnvVar: "MC_OBD_DEADLINE",
|
||||
EnvVar: "MC_HEALTH_DEADLINE,MC_OBD_DEADLINE",
|
||||
},
|
||||
}
|
||||
|
||||
var adminOBDCmd = cli.Command{
|
||||
Name: "obd",
|
||||
Usage: "run on-board diagnostics",
|
||||
Action: mainAdminOBD,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: append(adminOBDFlags, globalFlags...),
|
||||
var adminSubnetHealthCmd = cli.Command{
|
||||
Name: "health",
|
||||
Usage: "run health check for Subnet",
|
||||
OnUsageError: onUsageError,
|
||||
Action: mainAdminHealth,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: append(adminHealthFlags, globalFlags...),
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
@@ -73,39 +73,16 @@ EXAMPLES:
|
||||
`,
|
||||
}
|
||||
|
||||
type clusterOBDStruct struct {
|
||||
Status string `json:"status"`
|
||||
Error string `json:"error,omitempty"`
|
||||
Info madmin.OBDInfo `json:"obdInfo,omitempty"`
|
||||
}
|
||||
|
||||
func (u clusterOBDStruct) String() string {
|
||||
u.Status = ""
|
||||
data, err := json.Marshal(u)
|
||||
if err != nil {
|
||||
fatalIf(probe.NewError(err), "unable to marshal into JSON.")
|
||||
}
|
||||
return string(data)
|
||||
}
|
||||
|
||||
// JSON jsonifies service status message.
|
||||
func (u clusterOBDStruct) JSON() string {
|
||||
statusJSONBytes, e := json.MarshalIndent(u, " ", " ")
|
||||
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
|
||||
|
||||
return string(statusJSONBytes)
|
||||
}
|
||||
|
||||
// checkAdminInfoSyntax - validate arguments passed by a user
|
||||
func checkAdminOBDSyntax(ctx *cli.Context) {
|
||||
func checkAdminHealthSyntax(ctx *cli.Context) {
|
||||
if len(ctx.Args()) == 0 || len(ctx.Args()) > 1 {
|
||||
cli.ShowCommandHelpAndExit(ctx, "obd", 1) // last argument is exit code
|
||||
cli.ShowCommandHelpAndExit(ctx, "health", 1) // last argument is exit code
|
||||
}
|
||||
}
|
||||
|
||||
//compress and tar obd output
|
||||
func tarGZ(c clusterOBDStruct, alias string) error {
|
||||
filename := fmt.Sprintf("%s-obd_%s.json.gz", filepath.Clean(alias), time.Now().Format("20060102150405"))
|
||||
//compress and tar health report output
|
||||
func tarGZ(c HealthReportInfo, alias string) error {
|
||||
filename := fmt.Sprintf("%s-health_%s.json.gz", filepath.Clean(alias), time.Now().Format("20060102150405"))
|
||||
f, err := os.OpenFile(filename, os.O_CREATE|os.O_RDWR, 0666)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -113,13 +90,26 @@ func tarGZ(c clusterOBDStruct, alias string) error {
|
||||
defer f.Close()
|
||||
|
||||
defer func() {
|
||||
fmt.Println("OBD data saved to", filename)
|
||||
console.Infoln("Health data saved at", filename)
|
||||
}()
|
||||
|
||||
gzWriter := gzip.NewWriter(f)
|
||||
defer gzWriter.Close()
|
||||
|
||||
enc := json.NewEncoder(gzWriter)
|
||||
enc := gojson.NewEncoder(gzWriter)
|
||||
|
||||
header := HealthReportHeader{
|
||||
Subnet: Health{
|
||||
Health: SchemaVersion{
|
||||
Version: "v1",
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
if err := enc.Encode(header); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := enc.Encode(c); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -131,7 +121,7 @@ func tarGZ(c clusterOBDStruct, alias string) error {
|
||||
|
||||
warningMsgHeader := infoText(warningMsgBoundary)
|
||||
warningMsgTrailer := infoText(warningMsgBoundary)
|
||||
fmt.Printf("%s\n%s\n%s\n%s\n", warningMsgHeader, warning, warningContents, warningMsgTrailer)
|
||||
console.Printf("%s\n%s\n%s\n%s\n", warningMsgHeader, warning, warningContents, warningMsgTrailer)
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -151,8 +141,8 @@ func warnText(s string) string {
|
||||
return console.Colorize("WARN", s)
|
||||
}
|
||||
|
||||
func mainAdminOBD(ctx *cli.Context) error {
|
||||
checkAdminOBDSyntax(ctx)
|
||||
func mainAdminHealth(ctx *cli.Context) error {
|
||||
checkAdminHealthSyntax(ctx)
|
||||
|
||||
// Get the alias parameter from cli
|
||||
args := ctx.Args()
|
||||
@@ -162,6 +152,33 @@ func mainAdminOBD(ctx *cli.Context) error {
|
||||
client, err := newAdminClient(aliasedURL)
|
||||
fatalIf(err, "Unable to initialize admin connection.")
|
||||
|
||||
healthInfo, e := fetchServerHealthInfo(ctx, client)
|
||||
clusterHealthInfo := MapHealthInfoToV1(healthInfo, e)
|
||||
|
||||
if globalJSON {
|
||||
printMsg(clusterHealthInfo)
|
||||
return nil
|
||||
}
|
||||
|
||||
if clusterHealthInfo.GetError() != "" {
|
||||
console.Println(warnText("unable to obtain health information:"), clusterHealthInfo.GetError())
|
||||
return nil
|
||||
}
|
||||
|
||||
return tarGZ(clusterHealthInfo, aliasedURL)
|
||||
}
|
||||
|
||||
func fetchServerHealthInfo(ctx *cli.Context, client *madmin.AdminClient) (madmin.HealthInfo, error) {
|
||||
opts := GetHealthDataTypeSlice(ctx, "test")
|
||||
if len(*opts) == 0 {
|
||||
opts = &options
|
||||
}
|
||||
|
||||
optsMap := make(map[madmin.HealthDataType]struct{})
|
||||
for _, opt := range *opts {
|
||||
optsMap[opt] = struct{}{}
|
||||
}
|
||||
|
||||
spinners := []string{"/", "|", "\\", "--", "|"}
|
||||
|
||||
cont, cancel := context.WithCancel(globalContext)
|
||||
@@ -177,7 +194,7 @@ func mainAdminOBD(ctx *cli.Context) error {
|
||||
t = greenText(t)
|
||||
sp = infoText(sp)
|
||||
toPrint := fmt.Sprintf("%s %s %s ", dot, t, sp)
|
||||
fmt.Printf("%s\n", toPrint)
|
||||
console.Printf("%s\n", toPrint)
|
||||
}
|
||||
i := 0
|
||||
sp := func() string {
|
||||
@@ -191,7 +208,7 @@ func mainAdminOBD(ctx *cli.Context) error {
|
||||
go func() {
|
||||
printText(s, sp(), 0)
|
||||
for {
|
||||
<-time.After(500 * time.Millisecond) //2 fps
|
||||
time.Sleep(500 * time.Millisecond) // 2 fps
|
||||
if ctx.Err() != nil {
|
||||
printText(s, check, 1)
|
||||
done <- true
|
||||
@@ -209,12 +226,12 @@ func mainAdminOBD(ctx *cli.Context) error {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
spinner := func(resource string) func(bool) bool {
|
||||
spinner := func(resource string, opt madmin.HealthDataType) func(bool) bool {
|
||||
var spinStopper func()
|
||||
done := false
|
||||
|
||||
if globalJSON {
|
||||
_, ok := optsMap[opt] // check if option is enabled
|
||||
if globalJSON || !ok {
|
||||
return func(bool) bool {
|
||||
return true
|
||||
}
|
||||
@@ -228,27 +245,25 @@ func mainAdminOBD(ctx *cli.Context) error {
|
||||
spinStopper = startSpinner(resource)
|
||||
}
|
||||
if cond {
|
||||
spinStopper()
|
||||
done = true
|
||||
spinStopper()
|
||||
}
|
||||
return done
|
||||
}
|
||||
}
|
||||
|
||||
clusterOBDInfo := clusterOBDStruct{}
|
||||
admin := spinner("Admin Info", madmin.HealthDataTypeMinioInfo)
|
||||
cpu := spinner("CPU Info", madmin.HealthDataTypeSysCPU)
|
||||
diskHw := spinner("Disk Info", madmin.HealthDataTypeSysDiskHw)
|
||||
osInfo := spinner("OS Info", madmin.HealthDataTypeSysOsInfo)
|
||||
mem := spinner("Mem Info", madmin.HealthDataTypeSysMem)
|
||||
process := spinner("Process Info", madmin.HealthDataTypeSysLoad)
|
||||
config := spinner("Server Config", madmin.HealthDataTypeMinioConfig)
|
||||
drive := spinner("Drive Test", madmin.HealthDataTypePerfDrive)
|
||||
net := spinner("Network Test", madmin.HealthDataTypePerfNet)
|
||||
|
||||
admin := spinner("Admin Info")
|
||||
cpu := spinner("CPU")
|
||||
diskHw := spinner("Disk Hardware")
|
||||
osInfo := spinner("Os Info")
|
||||
mem := spinner("Mem Info")
|
||||
process := spinner("Process Info")
|
||||
config := spinner("Config")
|
||||
drive := spinner("Drive")
|
||||
net := spinner("Net")
|
||||
|
||||
progress := func(info madmin.OBDInfo) bool {
|
||||
return admin(len(info.Minio.Info.Servers) > 0) &&
|
||||
progress := func(info madmin.HealthInfo) {
|
||||
_ = admin(len(info.Minio.Info.Servers) > 0) &&
|
||||
cpu(len(info.Sys.CPUInfo) > 0) &&
|
||||
diskHw(len(info.Sys.DiskHwInfo) > 0) &&
|
||||
osInfo(len(info.Sys.OsInfo) > 0) &&
|
||||
@@ -256,55 +271,36 @@ func mainAdminOBD(ctx *cli.Context) error {
|
||||
process(len(info.Sys.ProcInfo) > 0) &&
|
||||
config(info.Minio.Config != nil) &&
|
||||
drive(len(info.Perf.DriveInfo) > 0) &&
|
||||
net(len(info.Perf.Net) > 1)
|
||||
net(len(info.Perf.Net) > 1 && len(info.Perf.NetParallel.Addr) > 0)
|
||||
}
|
||||
|
||||
var err error
|
||||
var healthInfo madmin.HealthInfo
|
||||
|
||||
// Fetch info of all servers (cluster or single server)
|
||||
obdChan := client.ServerOBDInfo(cont, options, ctx.Duration("deadline"))
|
||||
for adminOBDInfo := range obdChan {
|
||||
if adminOBDInfo.Error != "" {
|
||||
clusterOBDInfo.Status = "Error"
|
||||
clusterOBDInfo.Error = adminOBDInfo.Error
|
||||
clusterOBDInfo.Info.Error = ""
|
||||
clusterOBDInfo.Info.Minio.Info = madmin.InfoMessage{}
|
||||
obdChan := client.ServerHealthInfo(cont, *opts, ctx.Duration("deadline"))
|
||||
for adminHealthInfo := range obdChan {
|
||||
if adminHealthInfo.Error != "" {
|
||||
err = errors.New(adminHealthInfo.Error)
|
||||
break
|
||||
}
|
||||
|
||||
clusterOBDInfo.Status = "Success"
|
||||
clusterOBDInfo.Info = adminOBDInfo
|
||||
progress(adminOBDInfo)
|
||||
healthInfo = adminHealthInfo
|
||||
progress(adminHealthInfo)
|
||||
}
|
||||
|
||||
// If MinIO is not a global distXL cluster, net will never stop spinning.
|
||||
// add this extra check to ensure that doesn't happen
|
||||
if clusterOBDInfo.Error == "" && !progress(clusterOBDInfo.Info) {
|
||||
net(true)
|
||||
}
|
||||
|
||||
if globalJSON {
|
||||
jsonBytes, err := cjson.MarshalIndent(clusterOBDInfo, "", " ")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Println(string(jsonBytes))
|
||||
return nil
|
||||
}
|
||||
|
||||
if clusterOBDInfo.Error != "" {
|
||||
fmt.Println(warnText("Error obtaining obd information:"), clusterOBDInfo.Error)
|
||||
return nil
|
||||
}
|
||||
|
||||
return tarGZ(clusterOBDInfo, aliasedURL)
|
||||
// cancel the context if obdChan has returned.
|
||||
cancel()
|
||||
return healthInfo, err
|
||||
}
|
||||
|
||||
// OBDDataTypeSlice is a typed list of OBD tests
|
||||
type OBDDataTypeSlice []madmin.OBDDataType
|
||||
// HealthDataTypeSlice is a typed list of health tests
|
||||
type HealthDataTypeSlice []madmin.HealthDataType
|
||||
|
||||
// Set - sets the flag to the given value
|
||||
func (d *OBDDataTypeSlice) Set(value string) error {
|
||||
func (d *HealthDataTypeSlice) Set(value string) error {
|
||||
for _, v := range strings.Split(value, ",") {
|
||||
if obdData, ok := madmin.OBDDataTypesMap[strings.Trim(v, " ")]; ok {
|
||||
if obdData, ok := madmin.HealthDataTypesMap[strings.Trim(v, " ")]; ok {
|
||||
*d = append(*d, obdData)
|
||||
} else {
|
||||
return fmt.Errorf("valid options include %s", options.String())
|
||||
@@ -313,8 +309,8 @@ func (d *OBDDataTypeSlice) Set(value string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// String - returns the string representation of the OBD datatypes
|
||||
func (d *OBDDataTypeSlice) String() string {
|
||||
// String - returns the string representation of the health datatypes
|
||||
func (d *HealthDataTypeSlice) String() string {
|
||||
val := ""
|
||||
for _, obdData := range *d {
|
||||
formatStr := "%s"
|
||||
@@ -329,74 +325,68 @@ func (d *OBDDataTypeSlice) String() string {
|
||||
}
|
||||
|
||||
// Value - returns the value
|
||||
func (d *OBDDataTypeSlice) Value() []madmin.OBDDataType {
|
||||
func (d *HealthDataTypeSlice) Value() []madmin.HealthDataType {
|
||||
return *d
|
||||
}
|
||||
|
||||
// Get - returns the value
|
||||
func (d *OBDDataTypeSlice) Get() interface{} {
|
||||
func (d *HealthDataTypeSlice) Get() interface{} {
|
||||
return *d
|
||||
}
|
||||
|
||||
// OBDDataTypeFlag is a typed flag to represent OBD datatypes
|
||||
type OBDDataTypeFlag struct {
|
||||
// HealthDataTypeFlag is a typed flag to represent health datatypes
|
||||
type HealthDataTypeFlag struct {
|
||||
Name string
|
||||
Usage string
|
||||
EnvVar string
|
||||
Hidden bool
|
||||
Value *OBDDataTypeSlice
|
||||
Value *HealthDataTypeSlice
|
||||
}
|
||||
|
||||
// String - returns the string to be shown in the help message
|
||||
func (f OBDDataTypeFlag) String() string {
|
||||
func (f HealthDataTypeFlag) String() string {
|
||||
return fmt.Sprintf("--%s %s", f.Name, f.Usage)
|
||||
}
|
||||
|
||||
// GetName - returns the name of the flag
|
||||
func (f OBDDataTypeFlag) GetName() string {
|
||||
func (f HealthDataTypeFlag) GetName() string {
|
||||
return f.Name
|
||||
}
|
||||
|
||||
// GetOBDDataTypeSlice - returns the list of set OBD tests
|
||||
func GetOBDDataTypeSlice(c *cli.Context, name string) *OBDDataTypeSlice {
|
||||
// GetHealthDataTypeSlice - returns the list of set health tests
|
||||
func GetHealthDataTypeSlice(c *cli.Context, name string) *HealthDataTypeSlice {
|
||||
generic := c.Generic(name)
|
||||
if generic == nil {
|
||||
return nil
|
||||
}
|
||||
if obdData, ok := generic.(*OBDDataTypeSlice); ok {
|
||||
return obdData
|
||||
}
|
||||
return nil
|
||||
return generic.(*HealthDataTypeSlice)
|
||||
}
|
||||
|
||||
// GetGlobalOBDDataTypeSlice - returns the list of set OBD tests set globally
|
||||
func GetGlobalOBDDataTypeSlice(c *cli.Context, name string) *OBDDataTypeSlice {
|
||||
// GetGlobalHealthDataTypeSlice - returns the list of set health tests set globally
|
||||
func GetGlobalHealthDataTypeSlice(c *cli.Context, name string) *HealthDataTypeSlice {
|
||||
generic := c.GlobalGeneric(name)
|
||||
if generic == nil {
|
||||
return nil
|
||||
}
|
||||
if obdData, ok := generic.(*OBDDataTypeSlice); ok {
|
||||
return obdData
|
||||
}
|
||||
return nil
|
||||
return generic.(*HealthDataTypeSlice)
|
||||
}
|
||||
|
||||
// Apply - applies the flag
|
||||
func (f OBDDataTypeFlag) Apply(set *flag.FlagSet) {
|
||||
func (f HealthDataTypeFlag) Apply(set *flag.FlagSet) {
|
||||
f.ApplyWithError(set)
|
||||
}
|
||||
|
||||
// ApplyWithError - applies with error
|
||||
func (f OBDDataTypeFlag) ApplyWithError(set *flag.FlagSet) error {
|
||||
func (f HealthDataTypeFlag) ApplyWithError(set *flag.FlagSet) error {
|
||||
if f.EnvVar != "" {
|
||||
for _, envVar := range strings.Split(f.EnvVar, ",") {
|
||||
envVar = strings.TrimSpace(envVar)
|
||||
if envVal, ok := syscall.Getenv(envVar); ok {
|
||||
newVal := &OBDDataTypeSlice{}
|
||||
newVal := &HealthDataTypeSlice{}
|
||||
for _, s := range strings.Split(envVal, ",") {
|
||||
s = strings.TrimSpace(s)
|
||||
if err := newVal.Set(s); err != nil {
|
||||
return fmt.Errorf("could not parse %s as OBD datatype value for flag %s: %s", envVal, f.Name, err)
|
||||
return fmt.Errorf("could not parse %s as health datatype value for flag %s: %s", envVal, f.Name, err)
|
||||
}
|
||||
}
|
||||
f.Value = newVal
|
||||
@@ -408,11 +398,11 @@ func (f OBDDataTypeFlag) ApplyWithError(set *flag.FlagSet) error {
|
||||
for _, name := range strings.Split(f.Name, ",") {
|
||||
name = strings.Trim(name, " ")
|
||||
if f.Value == nil {
|
||||
f.Value = &OBDDataTypeSlice{}
|
||||
f.Value = &HealthDataTypeSlice{}
|
||||
}
|
||||
set.Var(f.Value, name, f.Usage)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
var options = OBDDataTypeSlice(madmin.OBDDataTypesList)
|
||||
var options = HealthDataTypeSlice(madmin.HealthDataTypesList)
|
||||
@@ -0,0 +1,60 @@
|
||||
/*
|
||||
* 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"
|
||||
)
|
||||
|
||||
var subnetHealthSubcommands = []cli.Command{
|
||||
adminSubnetHealthCmd,
|
||||
// adminSubnetRegister to be added
|
||||
}
|
||||
|
||||
var adminSubnetCmd = cli.Command{
|
||||
Name: "subnet",
|
||||
Usage: "Subnet related commands",
|
||||
Action: mainAdminSubnet,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
Subcommands: subnetHealthSubcommands,
|
||||
HideHelpCommand: true,
|
||||
}
|
||||
|
||||
// mainAdminSubnet is the handle for "mc admin subnet" command.
|
||||
func mainAdminSubnet(ctx *cli.Context) error {
|
||||
commandNotFound(ctx, subnetHealthSubcommands)
|
||||
return nil
|
||||
// Sub-commands like "health", "register" have their own main.
|
||||
}
|
||||
|
||||
// Deprecated - to be removed in a future release
|
||||
// mainAdminSubnet is the handle for "mc admin subnet" command.
|
||||
func mainAdminOBD(ctx *cli.Context) error {
|
||||
color.Yellow("Deprecated - please use 'mc admin subnet health'")
|
||||
return nil
|
||||
}
|
||||
|
||||
var adminHealthCmd = cli.Command{
|
||||
Name: "health",
|
||||
Aliases: []string{"obd"},
|
||||
Usage: "Deprecated - please use 'mc admin subnet health'",
|
||||
Action: mainAdminOBD,
|
||||
CustomHelpTemplate: `{{.Usage}}`,
|
||||
Hidden: true,
|
||||
}
|
||||
+31
-16
@@ -28,12 +28,26 @@ import (
|
||||
"github.com/minio/minio/pkg/madmin"
|
||||
)
|
||||
|
||||
var topLocksFlag = []cli.Flag{
|
||||
cli.BoolFlag{
|
||||
Name: "stale",
|
||||
Usage: "list stale locks",
|
||||
},
|
||||
cli.IntFlag{
|
||||
Name: "count",
|
||||
Usage: "number of top locks",
|
||||
Hidden: true,
|
||||
Value: 10,
|
||||
},
|
||||
}
|
||||
|
||||
var adminTopLocksCmd = cli.Command{
|
||||
Name: "locks",
|
||||
Usage: "Get a list of the 10 oldest locks on a MinIO cluster.",
|
||||
Before: setGlobalsFromContext,
|
||||
Action: mainAdminTopLocks,
|
||||
Flags: globalFlags,
|
||||
Name: "locks",
|
||||
Usage: "get a list of the 10 oldest locks on a MinIO cluster.",
|
||||
Before: setGlobalsFromContext,
|
||||
Action: mainAdminTopLocks,
|
||||
OnUsageError: onUsageError,
|
||||
Flags: append(globalFlags, topLocksFlag...),
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
@@ -72,18 +86,18 @@ func getTimeDiff(timeStamp time.Time) (string, string) {
|
||||
|
||||
// String colorized oldest locks message.
|
||||
func (u lockMessage) String() string {
|
||||
timeFieldMaxLen := 20
|
||||
resourceFieldMaxLen := -1
|
||||
typeFieldMaxLen := 6
|
||||
ownerFieldMaxLen := 20
|
||||
const (
|
||||
timeFieldMaxLen = 20
|
||||
resourceFieldMaxLen = -1
|
||||
typeFieldMaxLen = 6
|
||||
)
|
||||
|
||||
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.
|
||||
@@ -114,8 +128,11 @@ func mainAdminTopLocks(ctx *cli.Context) error {
|
||||
fatalIf(err, "Unable to initialize admin connection.")
|
||||
|
||||
// Call top locks API
|
||||
entries, e := client.TopLocks(globalContext)
|
||||
fatalIf(probe.NewError(e), "Cannot get server locks list.")
|
||||
entries, e := client.TopLocksWithOpts(globalContext, madmin.TopLockOpts{
|
||||
Count: ctx.Int("count"),
|
||||
Stale: ctx.Bool("stale"),
|
||||
})
|
||||
fatalIf(probe.NewError(e), "Unable to get server locks list.")
|
||||
|
||||
console.SetColor("StaleLock", color.New(color.FgRed, color.Bold))
|
||||
console.SetColor("Lock", color.New(color.FgBlue, color.Bold))
|
||||
@@ -130,13 +147,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.
|
||||
|
||||
+11
-9
@@ -18,21 +18,23 @@ package cmd
|
||||
|
||||
import "github.com/minio/cli"
|
||||
|
||||
var adminTopSubcommands = []cli.Command{
|
||||
adminTopLocksCmd,
|
||||
}
|
||||
|
||||
var adminTopCmd = cli.Command{
|
||||
Name: "top",
|
||||
Usage: "provide top like statistics for MinIO",
|
||||
Action: mainAdminTop,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
Subcommands: []cli.Command{
|
||||
adminTopLocksCmd,
|
||||
},
|
||||
Name: "top",
|
||||
Usage: "provide top like statistics for MinIO",
|
||||
Action: mainAdminTop,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
Subcommands: adminTopSubcommands,
|
||||
HideHelpCommand: true,
|
||||
}
|
||||
|
||||
// mainAdminTop is the handle for "mc admin top" command.
|
||||
func mainAdminTop(ctx *cli.Context) error {
|
||||
cli.ShowCommandHelp(ctx, ctx.Args().First())
|
||||
commandNotFound(ctx, adminTopSubcommands)
|
||||
return nil
|
||||
// Sub-commands like "locks" have their own main.
|
||||
}
|
||||
|
||||
+87
-4
@@ -22,6 +22,7 @@ import (
|
||||
"fmt"
|
||||
"hash/fnv"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -43,6 +44,18 @@ var adminTraceFlags = []cli.Flag{
|
||||
Name: "all, a",
|
||||
Usage: "trace all traffic (including internode traffic between MinIO servers)",
|
||||
},
|
||||
cli.StringFlag{
|
||||
Name: "status-codes",
|
||||
Usage: "trace only specific status codes",
|
||||
},
|
||||
cli.StringFlag{
|
||||
Name: "methods",
|
||||
Usage: "trace only specific HTTP methods",
|
||||
},
|
||||
cli.StringFlag{
|
||||
Name: "path",
|
||||
Usage: "trace only specific paths",
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "errors, e",
|
||||
Usage: "trace failed requests only",
|
||||
@@ -53,6 +66,7 @@ var adminTraceCmd = cli.Command{
|
||||
Name: "trace",
|
||||
Usage: "show http trace for MinIO server",
|
||||
Action: mainAdminTrace,
|
||||
OnUsageError: onUsageError,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: append(adminTraceFlags, globalFlags...),
|
||||
HideHelpCommand: true,
|
||||
@@ -61,7 +75,7 @@ var adminTraceCmd = cli.Command{
|
||||
|
||||
USAGE:
|
||||
{{.HelpName}} [FLAGS] TARGET
|
||||
|
||||
|
||||
FLAGS:
|
||||
{{range .VisibleFlags}}{{.}}
|
||||
{{end}}
|
||||
@@ -71,6 +85,13 @@ EXAMPLES:
|
||||
|
||||
2. Show trace only for failed requests for a MinIO server with alias 'myminio'
|
||||
{{.Prompt}} {{.HelpName}} -v -e myminio
|
||||
|
||||
3. Show the content of 503 failed requests
|
||||
{{.Prompt}} {{.HelpName}} -v --status-codes 503 myminio
|
||||
|
||||
4. Show all requests for a specific prefix
|
||||
{{.Prompt}} {{.HelpName}} --path my-bucket/my-prefix/ myminio
|
||||
|
||||
`,
|
||||
}
|
||||
|
||||
@@ -93,6 +114,27 @@ func mainAdminTrace(ctx *cli.Context) error {
|
||||
verbose := ctx.Bool("verbose")
|
||||
all := ctx.Bool("all")
|
||||
errfltr := ctx.Bool("errors")
|
||||
|
||||
statusCodes := []int{}
|
||||
for _, sc := range strings.Split(ctx.String("status-codes"), ",") {
|
||||
if sc == "" {
|
||||
continue
|
||||
}
|
||||
statusCode, e := strconv.Atoi(sc)
|
||||
fatalIf(probe.NewError(e), "Invalid passed status code.")
|
||||
statusCodes = append(statusCodes, statusCode)
|
||||
}
|
||||
|
||||
methods := []string{}
|
||||
for _, method := range strings.Split(ctx.String("methods"), ",") {
|
||||
if method == "" {
|
||||
continue
|
||||
}
|
||||
methods = append(methods, strings.ToUpper(method))
|
||||
}
|
||||
|
||||
path := ctx.String("path")
|
||||
|
||||
aliasedURL := ctx.Args().Get(0)
|
||||
console.SetColor("Stat", color.New(color.FgYellow))
|
||||
|
||||
@@ -115,7 +157,7 @@ func mainAdminTrace(ctx *cli.Context) error {
|
||||
// Create a new MinIO Admin Client
|
||||
client, err := newAdminClient(aliasedURL)
|
||||
if err != nil {
|
||||
fatalIf(err.Trace(aliasedURL), "Cannot initialize admin client.")
|
||||
fatalIf(err.Trace(aliasedURL), "Unable to initialize admin client.")
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -126,10 +168,44 @@ func mainAdminTrace(ctx *cli.Context) error {
|
||||
traceCh := client.ServiceTrace(ctxt, all, errfltr)
|
||||
for traceInfo := range traceCh {
|
||||
if traceInfo.Err != nil {
|
||||
fatalIf(probe.NewError(traceInfo.Err), "Cannot listen to http trace")
|
||||
fatalIf(probe.NewError(traceInfo.Err), "Unable to listen to http trace")
|
||||
}
|
||||
// Filter response status codes if passed by the user
|
||||
if len(statusCodes) > 0 {
|
||||
var found bool
|
||||
for _, code := range statusCodes {
|
||||
if traceInfo.Trace.RespInfo.StatusCode == code {
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
continue
|
||||
}
|
||||
}
|
||||
// Filter request method if passed by the user
|
||||
if len(methods) > 0 {
|
||||
var found bool
|
||||
for _, method := range methods {
|
||||
if traceInfo.Trace.ReqInfo.Method == method {
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
continue
|
||||
}
|
||||
}
|
||||
// Filter request path if passed by the user
|
||||
if path != "" {
|
||||
found := pathMatch("/"+path, traceInfo.Trace.ReqInfo.Path)
|
||||
if !found {
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
if verbose {
|
||||
printMsg(traceMessage{traceInfo})
|
||||
printMsg(traceMessage{ServiceTraceInfo: traceInfo})
|
||||
continue
|
||||
}
|
||||
printMsg(shortTrace(traceInfo))
|
||||
@@ -139,6 +215,7 @@ func mainAdminTrace(ctx *cli.Context) error {
|
||||
|
||||
// Short trace record
|
||||
type shortTraceMsg struct {
|
||||
Status string `json:"status"`
|
||||
Host string `json:"host"`
|
||||
Time time.Time `json:"time"`
|
||||
Client string `json:"client"`
|
||||
@@ -151,11 +228,13 @@ type shortTraceMsg struct {
|
||||
}
|
||||
|
||||
type traceMessage struct {
|
||||
Status string `json:"status"`
|
||||
madmin.ServiceTraceInfo
|
||||
}
|
||||
|
||||
type requestInfo struct {
|
||||
Time time.Time `json:"time"`
|
||||
Proto string `json:"proto"`
|
||||
Method string `json:"method"`
|
||||
Path string `json:"path,omitempty"`
|
||||
RawQuery string `json:"rawQuery,omitempty"`
|
||||
@@ -206,6 +285,7 @@ func shortTrace(ti madmin.ServiceTraceInfo) shortTraceMsg {
|
||||
}
|
||||
|
||||
func (s shortTraceMsg) JSON() string {
|
||||
s.Status = "success"
|
||||
buf := &bytes.Buffer{}
|
||||
enc := json.NewEncoder(buf)
|
||||
enc.SetIndent("", " ")
|
||||
@@ -258,6 +338,7 @@ func colorizedNodeName(nodeName string) string {
|
||||
}
|
||||
|
||||
func (t traceMessage) JSON() string {
|
||||
t.Status = "success"
|
||||
rqHdrs := make(map[string]string)
|
||||
rspHdrs := make(map[string]string)
|
||||
rq := t.Trace.ReqInfo
|
||||
@@ -273,6 +354,7 @@ func (t traceMessage) JSON() string {
|
||||
FuncName: t.Trace.FuncName,
|
||||
RequestInfo: requestInfo{
|
||||
Time: rq.Time,
|
||||
Proto: rq.Proto,
|
||||
Method: rq.Method,
|
||||
Path: rq.Path,
|
||||
RawQuery: rq.RawQuery,
|
||||
@@ -321,6 +403,7 @@ func (t traceMessage) String() string {
|
||||
fmt.Fprintf(b, "?%s", ri.RawQuery)
|
||||
}
|
||||
fmt.Fprint(b, "\n")
|
||||
fmt.Fprintf(b, "%s%s", nodeNameStr, console.Colorize("Method", fmt.Sprintf("Proto: %s\n", ri.Proto)))
|
||||
host, ok := ri.Headers["Host"]
|
||||
if ok {
|
||||
delete(ri.Headers, "Host")
|
||||
|
||||
+6
-5
@@ -27,11 +27,12 @@ import (
|
||||
)
|
||||
|
||||
var adminServerUpdateCmd = cli.Command{
|
||||
Name: "update",
|
||||
Usage: "update all MinIO servers",
|
||||
Action: mainAdminServerUpdate,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
Name: "update",
|
||||
Usage: "update all MinIO servers",
|
||||
Action: mainAdminServerUpdate,
|
||||
OnUsageError: onUsageError,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
|
||||
@@ -31,11 +31,12 @@ import (
|
||||
)
|
||||
|
||||
var adminUserAddCmd = cli.Command{
|
||||
Name: "add",
|
||||
Usage: "add a new user",
|
||||
Action: mainAdminUserAdd,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
Name: "add",
|
||||
Usage: "add a new user",
|
||||
Action: mainAdminUserAdd,
|
||||
OnUsageError: onUsageError,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
@@ -180,7 +181,7 @@ func mainAdminUserAdd(ctx *cli.Context) error {
|
||||
client, err := newAdminClient(aliasedURL)
|
||||
fatalIf(err, "Unable to initialize admin connection.")
|
||||
|
||||
fatalIf(probe.NewError(client.AddUser(globalContext, accessKey, secretKey)).Trace(args...), "Cannot add new user")
|
||||
fatalIf(probe.NewError(client.AddUser(globalContext, accessKey, secretKey)).Trace(args...), "Unable to add new user")
|
||||
|
||||
printMsg(userMessage{
|
||||
op: "add",
|
||||
|
||||
@@ -25,11 +25,12 @@ import (
|
||||
)
|
||||
|
||||
var adminUserDisableCmd = cli.Command{
|
||||
Name: "disable",
|
||||
Usage: "disable user",
|
||||
Action: mainAdminUserDisable,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
Name: "disable",
|
||||
Usage: "disable user",
|
||||
Action: mainAdminUserDisable,
|
||||
OnUsageError: onUsageError,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
@@ -67,7 +68,7 @@ func mainAdminUserDisable(ctx *cli.Context) error {
|
||||
fatalIf(err, "Unable to initialize admin connection.")
|
||||
|
||||
e := client.SetUserStatus(globalContext, args.Get(1), madmin.AccountDisabled)
|
||||
fatalIf(probe.NewError(e).Trace(args...), "Cannot disable user")
|
||||
fatalIf(probe.NewError(e).Trace(args...), "Unable to disable user")
|
||||
|
||||
printMsg(userMessage{
|
||||
op: "disable",
|
||||
|
||||
@@ -25,11 +25,12 @@ import (
|
||||
)
|
||||
|
||||
var adminUserEnableCmd = cli.Command{
|
||||
Name: "enable",
|
||||
Usage: "enable user",
|
||||
Action: mainAdminUserEnable,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
Name: "enable",
|
||||
Usage: "enable user",
|
||||
Action: mainAdminUserEnable,
|
||||
OnUsageError: onUsageError,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
@@ -67,7 +68,7 @@ func mainAdminUserEnable(ctx *cli.Context) error {
|
||||
fatalIf(err, "Unable to initialize admin connection.")
|
||||
|
||||
e := client.SetUserStatus(globalContext, args.Get(1), madmin.AccountEnabled)
|
||||
fatalIf(probe.NewError(e).Trace(args...), "Cannot enable user")
|
||||
fatalIf(probe.NewError(e).Trace(args...), "Unable to enable user")
|
||||
|
||||
printMsg(userMessage{
|
||||
op: "enable",
|
||||
|
||||
@@ -24,11 +24,12 @@ import (
|
||||
)
|
||||
|
||||
var adminUserInfoCmd = cli.Command{
|
||||
Name: "info",
|
||||
Usage: "display info of a user",
|
||||
Action: mainAdminUserInfo,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
Name: "info",
|
||||
Usage: "display info of a user",
|
||||
Action: mainAdminUserInfo,
|
||||
OnUsageError: onUsageError,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
@@ -66,7 +67,7 @@ func mainAdminUserInfo(ctx *cli.Context) error {
|
||||
fatalIf(err, "Unable to initialize admin connection.")
|
||||
|
||||
user, e := client.GetUserInfo(globalContext, args.Get(1))
|
||||
fatalIf(probe.NewError(e).Trace(args...), "Cannot get user info")
|
||||
fatalIf(probe.NewError(e).Trace(args...), "Unable to get user info")
|
||||
|
||||
printMsg(userMessage{
|
||||
op: "info",
|
||||
|
||||
@@ -24,11 +24,12 @@ import (
|
||||
)
|
||||
|
||||
var adminUserListCmd = cli.Command{
|
||||
Name: "list",
|
||||
Usage: "list all users",
|
||||
Action: mainAdminUserList,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
Name: "list",
|
||||
Usage: "list all users",
|
||||
Action: mainAdminUserList,
|
||||
OnUsageError: onUsageError,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
@@ -70,7 +71,7 @@ func mainAdminUserList(ctx *cli.Context) error {
|
||||
fatalIf(err, "Unable to initialize admin connection.")
|
||||
|
||||
users, e := client.ListUsers(globalContext)
|
||||
fatalIf(probe.NewError(e).Trace(args...), "Cannot list user")
|
||||
fatalIf(probe.NewError(e).Trace(args...), "Unable to list user")
|
||||
|
||||
for k, v := range users {
|
||||
printMsg(userMessage{
|
||||
|
||||
@@ -24,11 +24,12 @@ import (
|
||||
)
|
||||
|
||||
var adminUserRemoveCmd = cli.Command{
|
||||
Name: "remove",
|
||||
Usage: "remove user",
|
||||
Action: mainAdminUserRemove,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
Name: "remove",
|
||||
Usage: "remove user",
|
||||
Action: mainAdminUserRemove,
|
||||
OnUsageError: onUsageError,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
@@ -66,7 +67,7 @@ func mainAdminUserRemove(ctx *cli.Context) error {
|
||||
fatalIf(err, "Unable to initialize admin connection.")
|
||||
|
||||
e := client.RemoveUser(globalContext, args.Get(1))
|
||||
fatalIf(probe.NewError(e).Trace(args...), "Cannot remove %s", args.Get(1))
|
||||
fatalIf(probe.NewError(e).Trace(args...), "Unable to remove %s", args.Get(1))
|
||||
|
||||
printMsg(userMessage{
|
||||
op: "remove",
|
||||
|
||||
+16
-14
@@ -18,26 +18,28 @@ package cmd
|
||||
|
||||
import "github.com/minio/cli"
|
||||
|
||||
var adminUserSubcommands = []cli.Command{
|
||||
adminUserAddCmd,
|
||||
adminUserDisableCmd,
|
||||
adminUserEnableCmd,
|
||||
adminUserRemoveCmd,
|
||||
adminUserListCmd,
|
||||
adminUserInfoCmd,
|
||||
}
|
||||
|
||||
var adminUserCmd = cli.Command{
|
||||
Name: "user",
|
||||
Usage: "manage users",
|
||||
Action: mainAdminUser,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
Subcommands: []cli.Command{
|
||||
adminUserAddCmd,
|
||||
adminUserDisableCmd,
|
||||
adminUserEnableCmd,
|
||||
adminUserRemoveCmd,
|
||||
adminUserListCmd,
|
||||
adminUserInfoCmd,
|
||||
},
|
||||
Name: "user",
|
||||
Usage: "manage users",
|
||||
Action: mainAdminUser,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
Subcommands: adminUserSubcommands,
|
||||
HideHelpCommand: true,
|
||||
}
|
||||
|
||||
// mainAdminUser is the handle for "mc admin config" command.
|
||||
func mainAdminUser(ctx *cli.Context) error {
|
||||
cli.ShowCommandHelp(ctx, ctx.Args().First())
|
||||
commandNotFound(ctx, adminUserSubcommands)
|
||||
return nil
|
||||
// Sub-commands like "get", "set" have their own main.
|
||||
}
|
||||
|
||||
@@ -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,13 +25,16 @@ 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,
|
||||
OnUsageError: onUsageError,
|
||||
HideHelpCommand: true,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
@@ -43,110 +46,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,46 @@ 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 aliasSubcommands = []cli.Command{
|
||||
aliasSetCmd,
|
||||
aliasListCmd,
|
||||
aliasRemoveCmd,
|
||||
}
|
||||
|
||||
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: aliasSubcommands,
|
||||
}
|
||||
|
||||
// mainConfigHost is the handle for "mc config host" command.
|
||||
func mainConfigHost(ctx *cli.Context) error {
|
||||
cli.ShowCommandHelp(ctx, ctx.Args().First())
|
||||
// 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 {
|
||||
commandNotFound(ctx, aliasSubcommands)
|
||||
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 +71,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 +89,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,14 +22,17 @@ 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,
|
||||
OnUsageError: onUsageError,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
@@ -40,19 +43,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 +64,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,45 @@ 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)
|
||||
},
|
||||
OnUsageError: onUsageError,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: append(hostAddFlags, globalFlags...),
|
||||
Flags: append(aliasSetFlags, globalFlags...),
|
||||
HideHelpCommand: true,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
@@ -67,10 +73,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 +86,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 +136,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 +191,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 +222,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 +237,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 +247,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 +284,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
|
||||
}
|
||||
+85
-32
@@ -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{Recursive: 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+"/")
|
||||
}
|
||||
@@ -228,38 +228,75 @@ var fsCompleter = fsComplete{}
|
||||
// with their bash completer function
|
||||
var completeCmds = map[string]complete.Predictor{
|
||||
// S3 API level commands
|
||||
"/ls": complete.PredictOr(s3Completer, fsCompleter),
|
||||
"/cp": complete.PredictOr(s3Completer, fsCompleter),
|
||||
"/rm": complete.PredictOr(s3Completer, fsCompleter),
|
||||
"/rb": complete.PredictOr(s3Complete{deepLevel: 2}, fsCompleter),
|
||||
"/cat": complete.PredictOr(s3Completer, fsCompleter),
|
||||
"/head": complete.PredictOr(s3Completer, fsCompleter),
|
||||
"/diff": complete.PredictOr(s3Completer, fsCompleter),
|
||||
"/find": complete.PredictOr(s3Completer, fsCompleter),
|
||||
"/mirror": complete.PredictOr(s3Completer, fsCompleter),
|
||||
"/pipe": complete.PredictOr(s3Completer, fsCompleter),
|
||||
"/stat": complete.PredictOr(s3Completer, fsCompleter),
|
||||
"/watch": complete.PredictOr(s3Completer, fsCompleter),
|
||||
"/policy": complete.PredictOr(s3Completer, fsCompleter),
|
||||
"/tree": complete.PredictOr(s3Complete{deepLevel: 2}, fsCompleter),
|
||||
"/du": complete.PredictOr(s3Complete{deepLevel: 2}, fsCompleter),
|
||||
"/retention": s3Completer,
|
||||
"/sql": s3Completer,
|
||||
"/lock": complete.PredictOr(s3Complete{deepLevel: 2}),
|
||||
"/mb": aliasCompleter,
|
||||
"/ls": complete.PredictOr(s3Completer, fsCompleter),
|
||||
"/cp": complete.PredictOr(s3Completer, fsCompleter),
|
||||
"/mv": complete.PredictOr(s3Completer, fsCompleter),
|
||||
"/rm": complete.PredictOr(s3Completer, fsCompleter),
|
||||
"/rb": complete.PredictOr(s3Complete{deepLevel: 2}, fsCompleter),
|
||||
"/cat": complete.PredictOr(s3Completer, fsCompleter),
|
||||
"/head": complete.PredictOr(s3Completer, fsCompleter),
|
||||
"/diff": complete.PredictOr(s3Completer, fsCompleter),
|
||||
"/find": complete.PredictOr(s3Completer, fsCompleter),
|
||||
"/mirror": complete.PredictOr(s3Completer, fsCompleter),
|
||||
"/pipe": complete.PredictOr(s3Completer, fsCompleter),
|
||||
"/stat": complete.PredictOr(s3Completer, fsCompleter),
|
||||
"/watch": complete.PredictOr(s3Completer, fsCompleter),
|
||||
"/policy": complete.PredictOr(s3Completer, fsCompleter),
|
||||
"/tree": complete.PredictOr(s3Complete{deepLevel: 2}, fsCompleter),
|
||||
"/du": complete.PredictOr(s3Complete{deepLevel: 2}, fsCompleter),
|
||||
|
||||
"/event/add": aliasCompleter,
|
||||
"/event/list": aliasCompleter,
|
||||
"/event/remove": aliasCompleter,
|
||||
"/retention/set": s3Completer,
|
||||
"/retention/clear": s3Completer,
|
||||
"/retention/info": s3Completer,
|
||||
|
||||
"/legalhold/set": s3Completer,
|
||||
"/legalhold/clear": s3Completer,
|
||||
"/legalhold/info": s3Completer,
|
||||
|
||||
"/sql": s3Completer,
|
||||
"/mb": 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/edit": 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/ls": s3Complete{deepLevel: 2},
|
||||
"/ilm/add": s3Complete{deepLevel: 2},
|
||||
"/ilm/edit": s3Complete{deepLevel: 2},
|
||||
"/ilm/rm": s3Complete{deepLevel: 2},
|
||||
"/ilm/export": s3Complete{deepLevel: 2},
|
||||
"/ilm/import": s3Complete{deepLevel: 2},
|
||||
|
||||
"/undo": s3Completer,
|
||||
|
||||
// Admin API commands MinIO only.
|
||||
"/admin/heal": s3Completer,
|
||||
|
||||
@@ -306,12 +343,22 @@ var completeCmds = map[string]complete.Predictor{
|
||||
"/admin/group/remove": aliasCompleter,
|
||||
"/admin/group/info": aliasCompleter,
|
||||
|
||||
"/config/host/add": nil,
|
||||
"/config/host/list": aliasCompleter,
|
||||
"/config/host/remove": aliasCompleter,
|
||||
"/admin/bucket/remote/add": aliasCompleter,
|
||||
"/admin/bucket/remote/edit": aliasCompleter,
|
||||
"/admin/bucket/remote/ls": aliasCompleter,
|
||||
"/admin/bucket/remote/rm": aliasCompleter,
|
||||
"/admin/bucket/quota": aliasCompleter,
|
||||
|
||||
"/update": nil,
|
||||
"/version": nil,
|
||||
"/admin/kms/key/create": aliasCompleter,
|
||||
"/admin/kms/key/status": aliasCompleter,
|
||||
|
||||
"/admin/subnet/health": aliasCompleter,
|
||||
|
||||
"/alias/set": nil,
|
||||
"/alias/list": aliasCompleter,
|
||||
"/alias/remove": aliasCompleter,
|
||||
|
||||
"/update": nil,
|
||||
}
|
||||
|
||||
// flagsToCompleteFlags transforms a cli.Flag to complete.Flags
|
||||
@@ -340,6 +387,9 @@ func cmdToCompleteCmd(cmd cli.Command, parentPath string) complete.Command {
|
||||
complCmd.Sub = make(complete.Commands)
|
||||
|
||||
for _, subCmd := range cmd.Subcommands {
|
||||
if subCmd.Hidden {
|
||||
continue
|
||||
}
|
||||
complCmd.Sub[subCmd.Name] = cmdToCompleteCmd(subCmd, parentPath+"/"+cmd.Name)
|
||||
}
|
||||
|
||||
@@ -354,6 +404,9 @@ func mainComplete() error {
|
||||
// along with global and local flags
|
||||
var complCmds = make(complete.Commands)
|
||||
for _, cmd := range appCmds {
|
||||
if cmd.Hidden {
|
||||
continue
|
||||
}
|
||||
complCmds[cmd.Name] = cmdToCompleteCmd(cmd, "")
|
||||
}
|
||||
complFlags := flagsToCompleteFlags(globalFlags)
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
/*
|
||||
* 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"
|
||||
"testing"
|
||||
|
||||
"github.com/minio/cli"
|
||||
)
|
||||
|
||||
func TestAutoCompletionCompletness(t *testing.T) {
|
||||
|
||||
var checkCompletion func(cmd cli.Command, cmdPath string) error
|
||||
|
||||
checkCompletion = func(cmd cli.Command, cmdPath string) error {
|
||||
if cmd.Subcommands != nil {
|
||||
for _, subCmd := range cmd.Subcommands {
|
||||
if cmd.Hidden {
|
||||
continue
|
||||
}
|
||||
err := checkCompletion(subCmd, cmdPath+"/"+subCmd.Name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
_, ok := completeCmds[cmdPath]
|
||||
if !ok && !cmd.Hidden {
|
||||
return fmt.Errorf("Completion for `%s` not found", cmdPath)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
for _, cmd := range appCmds {
|
||||
if cmd.Hidden {
|
||||
continue
|
||||
}
|
||||
err := checkCompletion(cmd, "/"+cmd.Name)
|
||||
if err != nil {
|
||||
t.Fatalf("Missing completion function: %v", err)
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
+67
-30
@@ -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,19 +34,26 @@ 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: "display an earlier object version",
|
||||
},
|
||||
cli.StringFlag{
|
||||
Name: "version-id, vid",
|
||||
Usage: "display a specific version of an object",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
// Display contents of a file.
|
||||
var catCmd = cli.Command{
|
||||
Name: "cat",
|
||||
Usage: "display object contents",
|
||||
Action: mainCat,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: append(append(catFlags, ioFlags...), globalFlags...),
|
||||
Name: "cat",
|
||||
Usage: "display object contents",
|
||||
Action: mainCat,
|
||||
OnUsageError: onUsageError,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: append(append(catFlags, ioFlags...), globalFlags...),
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
@@ -73,6 +82,12 @@ 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
|
||||
|
||||
7. Display the content of a particular object version
|
||||
{{.Prompt}} {{.HelpName}} --vid "3ddac055-89a7-40fa-8cd3-530a5581b6b8" play/my-bucket/my-object
|
||||
`,
|
||||
}
|
||||
|
||||
@@ -125,38 +140,58 @@ 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() {
|
||||
args = []string{"-"}
|
||||
// parseCatSyntax performs command-line input validation for cat command.
|
||||
func parseCatSyntax(ctx *cli.Context) (args []string, versionID string, timeRef time.Time) {
|
||||
args = ctx.Args()
|
||||
|
||||
versionID = ctx.String("version-id")
|
||||
rewind := ctx.String("rewind")
|
||||
|
||||
if versionID != "" && rewind != "" {
|
||||
fatalIf(errInvalidArgument().Trace(), "You cannot specify --version-id and --rewind at the same time")
|
||||
}
|
||||
|
||||
if versionID != "" && len(args) != 1 {
|
||||
fatalIf(errInvalidArgument().Trace(), "You need to pass at least one argument if --version-id is specified")
|
||||
}
|
||||
|
||||
for _, arg := range args {
|
||||
if strings.HasPrefix(arg, "-") && len(arg) > 1 {
|
||||
fatalIf(probe.NewError(errors.New("")), fmt.Sprintf("Unknown flag `%s` passed.", arg))
|
||||
}
|
||||
}
|
||||
|
||||
timeRef = parseRewindFlag(rewind)
|
||||
return
|
||||
}
|
||||
|
||||
// catURL displays contents of a URL to stdout.
|
||||
func catURL(sourceURL string, encKeyDB map[string][]prefixSSEPair) *probe.Error {
|
||||
func catURL(ctx context.Context, sourceURL, sourceVersion 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 = sourceVersion
|
||||
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, sourceVersion, false, encKeyDB, timeRef); err == nil {
|
||||
if sourceVersion == "" {
|
||||
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 +245,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, versionID, rewind := parseCatSyntax(cliCtx)
|
||||
|
||||
// Set command flags from context.
|
||||
stdinMode := false
|
||||
if !ctx.Args().Present() {
|
||||
if len(args) == 0 {
|
||||
stdinMode = true
|
||||
}
|
||||
|
||||
@@ -231,11 +269,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 +281,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, versionID, rewind, encKeyDB).Trace(url), "Unable to read from `"+url+"`.")
|
||||
}
|
||||
|
||||
return nil
|
||||
|
||||
+5
-34
@@ -17,12 +17,11 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"crypto/x509"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/minio/pkg/certs"
|
||||
)
|
||||
|
||||
// getCertsDir - return the full path of certs dir
|
||||
@@ -96,40 +95,12 @@ func createCAsDir() *probe.Error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// mustGetCAFiles - get the list of the CA certificates stored in MinIO config dir
|
||||
func mustGetCAFiles() (caCerts []string) {
|
||||
CAsDir := mustGetCAsDir()
|
||||
caFiles, _ := ioutil.ReadDir(CAsDir)
|
||||
for _, cert := range caFiles {
|
||||
caCerts = append(caCerts, filepath.Join(CAsDir, cert.Name()))
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// mustGetSystemCertPool - return system CAs or empty pool in case of error (or windows)
|
||||
func mustGetSystemCertPool() *x509.CertPool {
|
||||
pool, err := x509.SystemCertPool()
|
||||
if err != nil {
|
||||
return x509.NewCertPool()
|
||||
}
|
||||
return pool
|
||||
}
|
||||
|
||||
// loadRootCAs fetches CA files provided in MinIO config and adds them to globalRootCAs
|
||||
// Currently under Windows, there is no way to load system + user CAs at the same time
|
||||
func loadRootCAs() {
|
||||
caFiles := mustGetCAFiles()
|
||||
if len(caFiles) == 0 {
|
||||
return
|
||||
}
|
||||
// Get system cert pool, and empty cert pool under Windows because it is not supported
|
||||
globalRootCAs = mustGetSystemCertPool()
|
||||
// Load custom root CAs for client requests
|
||||
for _, caFile := range caFiles {
|
||||
caCert, err := ioutil.ReadFile(caFile)
|
||||
if err != nil {
|
||||
fatalIf(probe.NewError(err), "Unable to load a CA file.")
|
||||
}
|
||||
globalRootCAs.AppendCertsFromPEM(caCert)
|
||||
var e error
|
||||
globalRootCAs, e = certs.GetRootCAs(mustGetCAsDir())
|
||||
if e != nil {
|
||||
fatalIf(probe.NewError(e), "Unable to load certificates.")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
/*
|
||||
* 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 (
|
||||
"testing"
|
||||
|
||||
"github.com/minio/cli"
|
||||
)
|
||||
|
||||
func TestCLIOnUsageError(t *testing.T) {
|
||||
var checkOnUsageError func(cli.Command, string)
|
||||
checkOnUsageError = func(cmd cli.Command, parentCmd string) {
|
||||
if cmd.Subcommands != nil {
|
||||
for _, subCmd := range cmd.Subcommands {
|
||||
if cmd.Hidden {
|
||||
continue
|
||||
}
|
||||
checkOnUsageError(subCmd, parentCmd+" "+cmd.Name)
|
||||
}
|
||||
return
|
||||
}
|
||||
if !cmd.Hidden && cmd.OnUsageError == nil {
|
||||
t.Errorf("On usage error for `%s` not found", parentCmd+" "+cmd.Name)
|
||||
}
|
||||
}
|
||||
|
||||
for _, cmd := range appCmds {
|
||||
if cmd.Hidden {
|
||||
continue
|
||||
}
|
||||
checkOnUsageError(cmd, "")
|
||||
}
|
||||
}
|
||||
+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 {
|
||||
|
||||
+18
-2
@@ -16,7 +16,10 @@
|
||||
|
||||
package cmd
|
||||
|
||||
import "fmt"
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
)
|
||||
|
||||
/// Collection of standard errors
|
||||
|
||||
@@ -154,12 +157,25 @@ 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"
|
||||
}
|
||||
|
||||
// ObjectIsDeleteMarker - object is a delete marker as latest
|
||||
type ObjectIsDeleteMarker struct {
|
||||
}
|
||||
|
||||
func (e ObjectIsDeleteMarker) Error() string {
|
||||
return "Object is marked as deleted"
|
||||
}
|
||||
|
||||
// UnexpectedShortWrite - write wrote less bytes than expected.
|
||||
type UnexpectedShortWrite struct {
|
||||
InputSize int
|
||||
|
||||
+183
-96
@@ -19,6 +19,7 @@ package cmd
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path"
|
||||
@@ -33,14 +34,16 @@ 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/notification"
|
||||
"github.com/minio/minio-go/v7/pkg/replication"
|
||||
"github.com/minio/minio/pkg/console"
|
||||
)
|
||||
|
||||
// filesystem client
|
||||
@@ -49,9 +52,10 @@ type fsClient struct {
|
||||
}
|
||||
|
||||
const (
|
||||
partSuffix = ".part.minio"
|
||||
slashSeperator = "/"
|
||||
metaDataKey = "X-Amz-Meta-Mc-Attrs"
|
||||
partSuffix = ".part.minio"
|
||||
slashSeperator = "/"
|
||||
metadataKey = "X-Amz-Meta-Mc-Attrs"
|
||||
metadataKeyS3Cmd = "X-Amz-Meta-S3cmd-Attrs"
|
||||
)
|
||||
|
||||
var ( // GOOS specific ignore list.
|
||||
@@ -119,7 +123,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 +131,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{})
|
||||
@@ -145,7 +149,8 @@ func (f *fsClient) Watch(options WatchOptions) (*WatchObject, *probe.Error) {
|
||||
case "get":
|
||||
fsEvents = append(fsEvents, EventTypeGet...)
|
||||
default:
|
||||
return nil, errInvalidArgument().Trace(event)
|
||||
// Event type not supported by FS client, such as
|
||||
// bucket creation or deletion, ignore it.
|
||||
}
|
||||
}
|
||||
|
||||
@@ -197,19 +202,19 @@ func (f *fsClient) Watch(options WatchOptions) (*WatchObject, *probe.Error) {
|
||||
Time: UTCNow().Format(timeFormatFS),
|
||||
Size: i.Size(),
|
||||
Path: event.Path(),
|
||||
Type: EventCreate,
|
||||
Type: notification.ObjectCreatedPut,
|
||||
}}
|
||||
} else if IsDeleteEvent(event.Event()) {
|
||||
eventChan <- []EventInfo{{
|
||||
Time: UTCNow().Format(timeFormatFS),
|
||||
Path: event.Path(),
|
||||
Type: EventRemove,
|
||||
Type: notification.ObjectRemovedDelete,
|
||||
}}
|
||||
} else if IsGetEvent(event.Event()) {
|
||||
eventChan <- []EventInfo{{
|
||||
Time: UTCNow().Format(timeFormatFS),
|
||||
Path: event.Path(),
|
||||
Type: EventAccessed,
|
||||
Type: notification.ObjectAccessedGet,
|
||||
}}
|
||||
}
|
||||
}
|
||||
@@ -223,28 +228,34 @@ 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 {
|
||||
// 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 e error
|
||||
if val, ok := attr["uid"]; ok {
|
||||
uid, e = strconv.Atoi(val)
|
||||
if e != nil {
|
||||
uid = -1
|
||||
}
|
||||
}
|
||||
|
||||
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 {
|
||||
gid = -1
|
||||
}
|
||||
}
|
||||
|
||||
// Attempt to change the owner.
|
||||
if e := fd.Chown(uid, gid); e != nil {
|
||||
if e = fd.Chown(uid, gid); e != nil {
|
||||
return probe.NewError(e)
|
||||
}
|
||||
|
||||
@@ -253,7 +264,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,15 +300,15 @@ 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)
|
||||
if e != nil {
|
||||
tmpFile.Close()
|
||||
return 0, probe.NewError(e)
|
||||
}
|
||||
if err := preserveAttributes(tmpFile, attr); err != nil {
|
||||
tmpFile.Close()
|
||||
return 0, err.Trace(objectPath)
|
||||
err := preserveAttributes(tmpFile, attr)
|
||||
if err != nil {
|
||||
console.Println(console.Colorize("Error", fmt.Sprintf("unable to preserve attributes, continuing to copy the content %s\n", err.ToGoError())))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -347,20 +358,15 @@ 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 {
|
||||
atime, mtime, err := parseAtimeMtime(attr)
|
||||
if err != nil {
|
||||
return totalWritten, err.Trace()
|
||||
}
|
||||
|
||||
mtime, e := strconv.ParseInt(attr["mtime"], 10, 64)
|
||||
if e != nil {
|
||||
return totalWritten, probe.NewError(e)
|
||||
}
|
||||
|
||||
// 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 !atime.IsZero() && !mtime.IsZero() {
|
||||
if e := os.Chtimes(objectPath, atime, mtime); e != nil {
|
||||
return totalWritten, probe.NewError(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -368,17 +374,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, versionID string, expires time.Duration) (string, *probe.Error) {
|
||||
return "", probe.NewError(APINotImplemented{
|
||||
API: "ShareDownload",
|
||||
APIType: "filesystem",
|
||||
@@ -386,7 +387,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 +395,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 +404,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 +465,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 +504,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.Recursive {
|
||||
if opts.ShowDir == DirNone {
|
||||
go f.listRecursiveInRoutine(contentCh, opts.WithMetadata)
|
||||
} else {
|
||||
go f.listDirOpt(contentCh, isIncomplete, isMetadata, showDir)
|
||||
go f.listDirOpt(contentCh, opts.Incomplete, opts.WithMetadata, opts.ShowDir)
|
||||
}
|
||||
} else {
|
||||
go f.listInRoutine(contentCh, isMetadata)
|
||||
go f.listInRoutine(contentCh, opts.WithMetadata)
|
||||
}
|
||||
|
||||
// This function filters entries from any listing go routine
|
||||
@@ -522,7 +523,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.Incomplete {
|
||||
if !strings.HasSuffix(c.URL.Path, partSuffix) {
|
||||
continue
|
||||
}
|
||||
@@ -572,9 +573,7 @@ func readDir(dirname string) ([]os.FileInfo, error) {
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
if e = f.Close(); e != nil {
|
||||
return nil, e
|
||||
}
|
||||
defer f.Close()
|
||||
sort.Sort(byDirName(list))
|
||||
return list, nil
|
||||
}
|
||||
@@ -877,7 +876,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 +889,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,15 +897,15 @@ 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) {
|
||||
return "", 0, "", probe.NewError(APINotImplemented{
|
||||
func (f *fsClient) GetObjectLockConfig(ctx context.Context) (status string, mode minio.RetentionMode, validity uint64, unit minio.ValidityUnit, err *probe.Error) {
|
||||
return "", "", 0, "", probe.NewError(APINotImplemented{
|
||||
API: "GetObjectLockConfig",
|
||||
APIType: "filesystem",
|
||||
})
|
||||
}
|
||||
|
||||
// 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,23 +913,38 @@ 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, versionID string, mode minio.RetentionMode, retainUntilDate time.Time, bypassGovernance bool) *probe.Error {
|
||||
return probe.NewError(APINotImplemented{
|
||||
API: "PutObjectRetention",
|
||||
APIType: "filesystem",
|
||||
})
|
||||
}
|
||||
|
||||
func (f *fsClient) GetObjectRetention(ctx context.Context, versionID string) (minio.RetentionMode, time.Time, *probe.Error) {
|
||||
return "", time.Time{}, probe.NewError(APINotImplemented{
|
||||
API: "GetObjectRetention",
|
||||
APIType: "filesystem",
|
||||
})
|
||||
}
|
||||
|
||||
// Set object legal hold for a given object.
|
||||
func (f *fsClient) PutObjectLegalHold(lhold minio.LegalHoldStatus) *probe.Error {
|
||||
func (f *fsClient) PutObjectLegalHold(ctx context.Context, versionID string, lhold minio.LegalHoldStatus) *probe.Error {
|
||||
return probe.NewError(APINotImplemented{
|
||||
API: "PutObjectLegalHold",
|
||||
APIType: "filesystem",
|
||||
})
|
||||
}
|
||||
|
||||
// Get object legal hold for a given object.
|
||||
func (f *fsClient) GetObjectLegalHold(ctx context.Context, versionID string) (minio.LegalHoldStatus, *probe.Error) {
|
||||
return "", probe.NewError(APINotImplemented{
|
||||
API: "GetObjectLegalHold",
|
||||
APIType: "filesystem",
|
||||
})
|
||||
}
|
||||
|
||||
// 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 +969,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 +1001,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 +1017,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 +1077,7 @@ func (f *fsClient) AddUserAgent(_, _ string) {
|
||||
}
|
||||
|
||||
// Get Object Tags
|
||||
func (f *fsClient) GetTags() (*tags.Tags, *probe.Error) {
|
||||
func (f *fsClient) GetTags(ctx context.Context, _ string) (map[string]string, *probe.Error) {
|
||||
return nil, probe.NewError(APINotImplemented{
|
||||
API: "GetObjectTagging",
|
||||
APIType: "filesystem",
|
||||
@@ -1071,7 +1085,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, versionID, tags string) *probe.Error {
|
||||
return probe.NewError(APINotImplemented{
|
||||
API: "SetObjectTagging",
|
||||
APIType: "filesystem",
|
||||
@@ -1079,7 +1093,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, versionID string) *probe.Error {
|
||||
return probe.NewError(APINotImplemented{
|
||||
API: "DeleteObjectTagging",
|
||||
APIType: "filesystem",
|
||||
@@ -1087,17 +1101,90 @@ 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",
|
||||
})
|
||||
}
|
||||
|
||||
// Gets bucket info
|
||||
func (f *fsClient) GetBucketInfo(ctx context.Context) (BucketInfo, *probe.Error) {
|
||||
return BucketInfo{}, probe.NewError(APINotImplemented{
|
||||
API: "GetBucketInfo",
|
||||
APIType: "filesystem",
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
// +build freebsd
|
||||
|
||||
/*
|
||||
* MinIO Client (C) 2017 MinIO, Inc.
|
||||
* MinIO Client (C) 2020 MinIO, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this fs except in compliance with the License.
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
/*
|
||||
* MinIO Client (C) 2020 MinIO, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this fs except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"github.com/pkg/xattr"
|
||||
"github.com/rjeczalik/notify"
|
||||
)
|
||||
|
||||
var (
|
||||
// EventTypePut contains the notify events that will cause a put (writer)
|
||||
EventTypePut = []notify.Event{notify.Create, notify.Write, notify.Rename}
|
||||
// EventTypeDelete contains the notify events that will cause a delete (remove)
|
||||
EventTypeDelete = []notify.Event{notify.Remove}
|
||||
// EventTypeGet contains the notify events that will cause a get (read)
|
||||
EventTypeGet = []notify.Event{} // On macOS, FreeBSD, Solaris this is not available.
|
||||
)
|
||||
|
||||
// IsGetEvent checks if the event return is a get event.
|
||||
func IsGetEvent(event notify.Event) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
// IsPutEvent checks if the event returned is a put event
|
||||
func IsPutEvent(event notify.Event) bool {
|
||||
for _, ev := range EventTypePut {
|
||||
if event&ev != 0 {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// IsDeleteEvent checks if the event returned is a delete event
|
||||
func IsDeleteEvent(event notify.Event) bool {
|
||||
return event¬ify.Remove != 0
|
||||
}
|
||||
|
||||
// getXAttr fetches the extended attribute for a particular key on
|
||||
// file
|
||||
func getXAttr(path, key string) (string, error) {
|
||||
data, e := xattr.Get(path, key)
|
||||
if e != nil {
|
||||
return "", e
|
||||
}
|
||||
return string(data), nil
|
||||
}
|
||||
|
||||
// getAllXattrs returns the extended attributes for a file if supported
|
||||
// by the OS
|
||||
func getAllXattrs(path string) (map[string]string, error) {
|
||||
xMetadata := make(map[string]string)
|
||||
list, e := xattr.List(path)
|
||||
if e != nil {
|
||||
if isNotSupported(e) {
|
||||
return nil, nil
|
||||
}
|
||||
return nil, e
|
||||
}
|
||||
for _, key := range list {
|
||||
xMetadata[key], e = getXAttr(path, key)
|
||||
if e != nil {
|
||||
if isNotSupported(e) {
|
||||
return nil, nil
|
||||
}
|
||||
return nil, e
|
||||
}
|
||||
|
||||
}
|
||||
return xMetadata, nil
|
||||
}
|
||||
+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{Recursive: 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{Recursive: 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)
|
||||
}
|
||||
|
||||
@@ -71,8 +71,8 @@ func (t traceV2) Response(resp *http.Response) (err error) {
|
||||
console.Debug(string(respTrace))
|
||||
}
|
||||
|
||||
if globalInsecure && resp.TLS != nil {
|
||||
dumpTLSCertificates(resp.TLS)
|
||||
if resp.TLS != nil {
|
||||
printTLSCertInfo(resp.TLS)
|
||||
}
|
||||
|
||||
return err
|
||||
|
||||
@@ -86,8 +86,8 @@ func (t traceV4) Response(resp *http.Response) (err error) {
|
||||
console.Debug(string(respTrace))
|
||||
}
|
||||
|
||||
if globalInsecure && resp.TLS != nil {
|
||||
dumpTLSCertificates(resp.TLS)
|
||||
if resp.TLS != nil {
|
||||
printTLSCertInfo(resp.TLS)
|
||||
}
|
||||
|
||||
return err
|
||||
|
||||
+880
-626
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{Recursive: false, Incomplete: incomplete, WithMetadata: false, ShowDir: DirNone}) {
|
||||
return entry.Err == nil
|
||||
}
|
||||
return false
|
||||
|
||||
+101
-38
@@ -19,14 +19,15 @@ package cmd
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"net/http"
|
||||
"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,80 +45,141 @@ 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 {
|
||||
Recursive bool
|
||||
Incomplete bool
|
||||
WithMetadata 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) (status string, 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, versionID string, mode minio.RetentionMode, retainUntilDate time.Time, bypassGovernance bool) *probe.Error
|
||||
GetObjectRetention(ctx context.Context, versionID string) (minio.RetentionMode, time.Time, *probe.Error)
|
||||
PutObjectLegalHold(ctx context.Context, versionID string, hold minio.LegalHoldStatus) *probe.Error
|
||||
GetObjectLegalHold(ctx context.Context, versionID string) (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, versionID string, 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, versionID string) (map[string]string, *probe.Error)
|
||||
SetTags(ctx context.Context, versionID, tags string) *probe.Error
|
||||
DeleteTags(ctx context.Context, versionID string) *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
|
||||
// Bucket info operation
|
||||
GetBucketInfo(ctx context.Context) (BucketInfo, *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
|
||||
|
||||
Err *probe.Error
|
||||
VersionID string
|
||||
IsDeleteMarker bool
|
||||
IsLatest bool
|
||||
ReplicationStatus string
|
||||
Err *probe.Error
|
||||
}
|
||||
|
||||
// Config - see http://docs.amazonwebservices.com/AmazonS3/latest/dev/index.html?RESTAuthentication.html
|
||||
@@ -133,6 +195,7 @@ type Config struct {
|
||||
Debug bool
|
||||
Insecure bool
|
||||
Lookup minio.BucketLookupType
|
||||
Transport *http.Transport
|
||||
}
|
||||
|
||||
// SelectObjectOpts - opts entered for select API
|
||||
|
||||
+87
-50
@@ -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,31 @@ 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, aliasedURL, versionID string, timeRef time.Time, encKeyDB map[string][]prefixSSEPair) (reader io.ReadCloser,
|
||||
metadata map[string]string, err *probe.Error) {
|
||||
alias, urlStrFull, _, err := expandAlias(urlStr)
|
||||
alias, urlStrFull, _, err := expandAlias(aliasedURL)
|
||||
if err != nil {
|
||||
return nil, nil, err.Trace(urlStr)
|
||||
return nil, nil, err.Trace(aliasedURL)
|
||||
}
|
||||
sseKey := getSSE(urlStr, encKeyDB[alias])
|
||||
return getSourceStream(alias, urlStrFull, true, sseKey, false)
|
||||
if !timeRef.IsZero() {
|
||||
_, content, err := url2Stat(ctx, aliasedURL, "", false, nil, timeRef)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
versionID = content.VersionID
|
||||
}
|
||||
sseKey := getSSE(aliasedURL, encKeyDB[alias])
|
||||
return getSourceStream(ctx, alias, urlStrFull, versionID, 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 +217,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 +248,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 +297,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 +319,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 +327,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 +337,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 +351,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 +384,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 +413,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
|
||||
@@ -415,10 +432,13 @@ func uploadSourceToTargetURL(ctx context.Context, urls URLs, progress io.Reader,
|
||||
// for the most part source metadata is copied over.
|
||||
if urls.TargetContent.RetentionEnabled {
|
||||
m := minio.RetentionMode(strings.ToUpper(urls.TargetContent.RetentionMode))
|
||||
if !m.IsValid() {
|
||||
return urls.WithError(probe.NewError(errors.New("invalid retention mode")).Trace(targetURL.String()))
|
||||
}
|
||||
|
||||
var dur uint64
|
||||
var unit minio.ValidityUnit
|
||||
dur, unit, err = parseRetentionValidity(urls.TargetContent.RetentionDuration, m)
|
||||
dur, unit, err = parseRetentionValidity(urls.TargetContent.RetentionDuration)
|
||||
if err != nil {
|
||||
return urls.WithError(err.Trace(targetURL.String()))
|
||||
}
|
||||
@@ -453,13 +473,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 +500,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 +539,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)) {
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user