Compare commits
18
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7e9625733d | ||
|
|
1513d76ca9 | ||
|
|
87dc0bf80e | ||
|
|
69c0d33543 | ||
|
|
8d891755e0 | ||
|
|
a9cd7869eb | ||
|
|
c40ab338a3 | ||
|
|
0fcd10d793 | ||
|
|
b7b75c5f46 | ||
|
|
b97b7b8987 | ||
|
|
8f3d514e3b | ||
|
|
bb3c0d45f2 | ||
|
|
9ebde383d4 | ||
|
|
cfea4fdc75 | ||
|
|
dd47bdfeaa | ||
|
|
ec9b92cbb7 | ||
|
|
975423abe2 | ||
|
|
3dd971f673 |
@@ -4,6 +4,9 @@ on:
|
||||
pull_request:
|
||||
branches:
|
||||
- master
|
||||
push:
|
||||
branches:
|
||||
- master
|
||||
|
||||
jobs:
|
||||
build:
|
||||
@@ -11,7 +14,7 @@ jobs:
|
||||
runs-on: ${{ matrix.os }}
|
||||
strategy:
|
||||
matrix:
|
||||
go-version: [1.16.x]
|
||||
go-version: [1.13.x]
|
||||
os: [ubuntu-latest, windows-latest]
|
||||
steps:
|
||||
- name: Set up Go ${{ matrix.go-version }} on ${{ matrix.os }}
|
||||
|
||||
+5
-10
@@ -1,4 +1,4 @@
|
||||
FROM golang:1.15-alpine as builder
|
||||
FROM golang:1.13-alpine as build
|
||||
|
||||
LABEL maintainer="MinIO Inc <dev@min.io>"
|
||||
|
||||
@@ -11,17 +11,12 @@ RUN \
|
||||
git clone https://github.com/minio/mc && cd mc && \
|
||||
go install -v -ldflags "$(go run buildscripts/gen-ldflags.go)"
|
||||
|
||||
FROM registry.access.redhat.com/ubi8/ubi-minimal:8.3
|
||||
FROM alpine:3.12
|
||||
|
||||
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
|
||||
COPY --from=build /go/bin/mc /usr/bin/mc
|
||||
|
||||
RUN \
|
||||
microdnf update --nodocs && \
|
||||
microdnf install ca-certificates --nodocs && \
|
||||
microdnf clean all
|
||||
apk add --no-cache ca-certificates 'curl>7.61.0' && \
|
||||
curl -s -q -O https://raw.githubusercontent.com/minio/minio/master/CREDITS
|
||||
|
||||
ENTRYPOINT ["mc"]
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
FROM multiarch/qemu-user-static:x86_64-arm as qemu
|
||||
FROM arm32v7/alpine:3.12
|
||||
|
||||
LABEL maintainer="MinIO Inc <dev@min.io>"
|
||||
|
||||
COPY --from=qemu /usr/bin/qemu-arm-static /usr/bin
|
||||
COPY mc /usr/bin/mc
|
||||
|
||||
RUN apk add --no-cache ca-certificates 'curl>7.61.0' && \
|
||||
curl -s -q -O https://raw.githubusercontent.com/minio/minio/release/CREDITS
|
||||
|
||||
ENTRYPOINT ["mc"]
|
||||
@@ -0,0 +1,12 @@
|
||||
FROM multiarch/qemu-user-static:x86_64-arm as qemu
|
||||
FROM arm64v8/alpine:3.12
|
||||
|
||||
LABEL maintainer="MinIO Inc <dev@min.io>"
|
||||
|
||||
COPY --from=qemu /usr/bin/qemu-arm-static /usr/bin
|
||||
COPY mc /usr/bin/mc
|
||||
|
||||
RUN apk add --no-cache ca-certificates 'curl>7.61.0' && \
|
||||
curl -s -q -O https://raw.githubusercontent.com/minio/minio/release/CREDITS
|
||||
|
||||
ENTRYPOINT ["mc"]
|
||||
+3
-9
@@ -1,14 +1,8 @@
|
||||
FROM registry.access.redhat.com/ubi8/ubi-minimal:8.3
|
||||
|
||||
LABEL maintainer="MinIO Inc <dev@min.io>"
|
||||
FROM alpine:3.12
|
||||
|
||||
COPY mc /usr/bin/
|
||||
COPY CREDITS /licenses/CREDITS
|
||||
COPY LICENSE /licenses/LICENSE
|
||||
COPY CREDITS /
|
||||
|
||||
RUN \
|
||||
microdnf update --nodocs && \
|
||||
microdnf install ca-certificates --nodocs && \
|
||||
microdnf clean all
|
||||
RUN apk add --no-cache ca-certificates
|
||||
|
||||
ENTRYPOINT ["mc"]
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
FROM multiarch/qemu-user-static:x86_64-arm as qemu
|
||||
FROM ppc64le/alpine:3.12
|
||||
|
||||
LABEL maintainer="MinIO Inc <dev@min.io>"
|
||||
|
||||
COPY --from=qemu /usr/bin/qemu-arm-static /usr/bin
|
||||
COPY mc /usr/bin/mc
|
||||
|
||||
RUN apk add --no-cache ca-certificates 'curl>7.61.0' && \
|
||||
curl -s -q -O https://raw.githubusercontent.com/minio/minio/release/CREDITS
|
||||
|
||||
ENTRYPOINT ["mc"]
|
||||
+6
-15
@@ -1,19 +1,10 @@
|
||||
FROM registry.access.redhat.com/ubi8/ubi-minimal:8.3
|
||||
FROM alpine:3.12
|
||||
|
||||
ARG TARGETARCH
|
||||
MAINTAINER MinIO Inc <dev@min.io>
|
||||
|
||||
ARG RELEASE
|
||||
|
||||
LABEL maintainer="MinIO Inc <dev@min.io>"
|
||||
|
||||
COPY CREDITS /licenses/CREDITS
|
||||
COPY LICENSE /licenses/LICENSE
|
||||
|
||||
RUN \
|
||||
microdnf update --nodocs && \
|
||||
microdnf install curl ca-certificates shadow-utils --nodocs && \
|
||||
microdnf clean all && \
|
||||
curl -s -q https://dl.minio.io/client/mc/release/linux-${TARGETARCH}/archive/mc.${RELEASE} -o /usr/bin/mc && \
|
||||
chmod +x /usr/bin/mc
|
||||
COPY mc /usr/bin/mc
|
||||
|
||||
RUN apk add --no-cache ca-certificates 'curl>7.61.0' && \
|
||||
curl -s -q -O https://raw.githubusercontent.com/minio/minio/release/CREDITS
|
||||
|
||||
ENTRYPOINT ["mc"]
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
FROM multiarch/qemu-user-static:x86_64-arm as qemu
|
||||
FROM s390x/alpine:3.12
|
||||
|
||||
LABEL maintainer="MinIO Inc <dev@min.io>"
|
||||
|
||||
COPY --from=qemu /usr/bin/qemu-arm-static /usr/bin
|
||||
COPY mc /usr/bin/mc
|
||||
|
||||
RUN apk add --no-cache ca-certificates 'curl>7.61.0' && \
|
||||
curl -s -q -O https://raw.githubusercontent.com/minio/minio/release/CREDITS
|
||||
|
||||
ENTRYPOINT ["mc"]
|
||||
@@ -19,7 +19,6 @@ 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)
|
||||
|
||||
@@ -4,37 +4,31 @@
|
||||
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).
|
||||
|
||||
```
|
||||
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
|
||||
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
|
||||
```
|
||||
|
||||
## Docker Container
|
||||
@@ -58,21 +52,6 @@ docker run -it --entrypoint=/bin/sh minio/mc
|
||||
|
||||
then use the [`mc config` command](#add-a-cloud-storage-service).
|
||||
|
||||
### GitLab CI
|
||||
When using the Docker container in GitLab CI, you must [set the entrypoint to an empty string](https://docs.gitlab.com/ee/ci/docker/using_docker_images.html#overriding-the-entrypoint-of-an-image).
|
||||
|
||||
```
|
||||
deploy:
|
||||
image:
|
||||
name: minio/mc
|
||||
entrypoint: ['']
|
||||
stage: deploy
|
||||
before_script:
|
||||
- mc alias set minio $MINIO_HOST $MINIO_ACCESS_KEY $MINIO_SECRET_KEY
|
||||
script:
|
||||
- mc cp <source> <destination>
|
||||
```
|
||||
|
||||
## macOS
|
||||
### Homebrew
|
||||
Install mc packages using [Homebrew](http://brew.sh/)
|
||||
@@ -118,25 +97,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 alias set <ALIAS> <YOUR-S3-ENDPOINT> <YOUR-ACCESS-KEY> <YOUR-SECRET-KEY> --api <API-SIGNATURE> --path <BUCKET-LOOKUP-TYPE>
|
||||
mc config host add <ALIAS> <YOUR-S3-ENDPOINT> <YOUR-ACCESS-KEY> <YOUR-SECRET-KEY> --api <API-SIGNATURE> --lookup <BUCKET-LOOKUP-TYPE>
|
||||
```
|
||||
|
||||
<ALIAS> is simply a short name to your cloud storage service. S3 end-point, access and secret keys are supplied by your cloud storage provider. API signature is an optional argument. By default, it is set to "S3v4".
|
||||
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".
|
||||
|
||||
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.
|
||||
Lookup is an optional argument. It is used to indicate whether dns or path style url requests are supported by the server. It accepts "dns", "path" or "auto" as valid values. By default, it is set to "auto" and SDK automatically determines the type of url lookup to use.
|
||||
|
||||
### Example - MinIO Cloud Storage
|
||||
MinIO server displays URL, access and secret keys.
|
||||
|
||||
```
|
||||
mc alias set minio http://192.168.1.51 BKIKJAA5BMMU2RHO6IBB V7f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12
|
||||
mc config host add minio http://192.168.1.51 BKIKJAA5BMMU2RHO6IBB V7f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12
|
||||
```
|
||||
|
||||
### Example - Amazon S3 Cloud Storage
|
||||
Get your AccessKeyID and SecretAccessKey by following [AWS Credentials Guide](http://docs.aws.amazon.com/general/latest/gr/aws-security-credentials.html).
|
||||
|
||||
```
|
||||
mc alias set s3 https://s3.amazonaws.com BKIKJAA5BMMU2RHO6IBB V7f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12
|
||||
mc config host add s3 https://s3.amazonaws.com BKIKJAA5BMMU2RHO6IBB V7f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12
|
||||
```
|
||||
|
||||
**Note**: As an IAM user on Amazon S3 you need to make sure the user has full access to the buckets or set the following restricted policy for your IAM user
|
||||
@@ -170,7 +149,7 @@ mc alias set s3 https://s3.amazonaws.com BKIKJAA5BMMU2RHO6IBB V7f1CwQqAcwo80UEIJ
|
||||
Get your AccessKeyID and SecretAccessKey by following [Google Credentials Guide](https://cloud.google.com/storage/docs/migrating?hl=en#keys)
|
||||
|
||||
```
|
||||
mc alias set gcs https://storage.googleapis.com BKIKJAA5BMMU2RHO6IBB V8f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12
|
||||
mc config host add gcs https://storage.googleapis.com BKIKJAA5BMMU2RHO6IBB V8f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12
|
||||
```
|
||||
|
||||
## Test Your Setup
|
||||
@@ -242,4 +221,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
|
||||
Use of `mc` is governed by the Apache 2.0 License found at [LICENSE](https://github.com/minio/mc/blob/master/LICENSE).
|
||||
[](https://app.fossa.io/projects/git%2Bgithub.com%2Fminio%2Fmc?ref=badge_large)
|
||||
|
||||
+4
-4
@@ -92,7 +92,7 @@ make
|
||||
添加一个或多个S3兼容的服务,请参考下面说明。`mc`将所有的配置信息都存储在``~/.mc/config.json``文件中。
|
||||
|
||||
```
|
||||
mc alias set <ALIAS> <YOUR-S3-ENDPOINT> <YOUR-ACCESS-KEY> <YOUR-SECRET-KEY> [--api API-SIGNATURE]
|
||||
mc config host add <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 alias set <ALIAS> <YOUR-S3-ENDPOINT> <YOUR-ACCESS-KEY> <YOUR-SECRET-KEY> [--a
|
||||
从MinIO服务获得URL、access key和secret key。
|
||||
|
||||
```
|
||||
mc alias set minio http://192.168.1.51 BKIKJAA5BMMU2RHO6IBB V7f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12 --api s3v4
|
||||
mc config host add 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 alias set s3 https://s3.amazonaws.com BKIKJAA5BMMU2RHO6IBB V7f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12 --api s3v4
|
||||
mc config host add 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 alias set gcs https://storage.googleapis.com BKIKJAA5BMMU2RHO6IBB V8f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12 --api s3v2
|
||||
mc config host add gcs https://storage.googleapis.com BKIKJAA5BMMU2RHO6IBB V8f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12 --api s3v2
|
||||
```
|
||||
|
||||
注意:Google云存储只支持旧版签名版本V2,所以你需要选择S3v2。
|
||||
|
||||
@@ -1,9 +1,7 @@
|
||||
#!/bin/bash
|
||||
|
||||
set -e
|
||||
|
||||
# Enable tracing if set.
|
||||
[ -n "$BASH_XTRACEFD" ] && set -x
|
||||
[ -n "$BASH_XTRACEFD" ] && set -ex
|
||||
|
||||
function _init() {
|
||||
## All binaries are static make sure to disable CGO.
|
||||
|
||||
+27
-28
@@ -74,47 +74,46 @@ func (q quotaMessage) JSON() string {
|
||||
}
|
||||
|
||||
var adminBucketQuotaCmd = cli.Command{
|
||||
Name: "quota",
|
||||
Usage: "manage bucket quota",
|
||||
Action: mainAdminBucketQuota,
|
||||
OnUsageError: onUsageError,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: append(adminQuotaFlags, globalFlags...),
|
||||
Name: "quota",
|
||||
Usage: "Manage bucket quota",
|
||||
Action: mainAdminBucketQuota,
|
||||
Before: initBeforeRunningCmd,
|
||||
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
|
||||
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
|
||||
|
||||
2. Set FIFO quota for a bucket "mybucket" on MinIO.
|
||||
{{.Prompt}} {{.HelpName}} myminio/mybucket --fifo 10GB
|
||||
3. Set hard quota of 1gb for a bucket "mybucket" on MinIO.
|
||||
{{.Prompt}} {{.HelpName}} myminio/mybucket --hard 1gb
|
||||
|
||||
3. Set hard quota of 1gb for a bucket "mybucket" on MinIO.
|
||||
{{.Prompt}} {{.HelpName}} myminio/mybucket --hard 1GB
|
||||
|
||||
4. Clear bucket quota configured for bucket "mybucket" on MinIO.
|
||||
{{.Prompt}} {{.HelpName}} myminio/mybucket --clear
|
||||
4. Clear bucket quota configured for bucket "mybucket" on MinIO.
|
||||
{{.Prompt}} {{.HelpName}} myminio/mybucket --clear
|
||||
`,
|
||||
}
|
||||
|
||||
// checkAdminBucketQuotaSyntax - validate all the passed arguments
|
||||
func checkAdminBucketQuotaSyntax(ctx *cli.Context) {
|
||||
if len(ctx.Args()) == 0 || len(ctx.Args()) > 1 {
|
||||
cli.ShowCommandHelpAndExit(ctx, ctx.Command.Name, 1) // last argument is exit code
|
||||
cli.ShowCommandHelpAndExit(ctx, "quota", 1) // last argument is exit code
|
||||
}
|
||||
|
||||
if ctx.IsSet("hard") && ctx.IsSet("fifo") {
|
||||
|
||||
@@ -1,272 +0,0 @@
|
||||
/*
|
||||
* MinIO Client (C) 2020 MinIO, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
humanize "github.com/dustin/go-humanize"
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/cli"
|
||||
json "github.com/minio/mc/pkg/colorjson"
|
||||
"github.com/minio/mc/pkg/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)",
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "sync",
|
||||
Usage: "enable synchronous replication for this target. Default is async",
|
||||
},
|
||||
cli.UintFlag{
|
||||
Name: "healthcheck-seconds",
|
||||
Usage: "health check duration in seconds",
|
||||
Value: 60,
|
||||
},
|
||||
}
|
||||
var adminBucketRemoteAddCmd = cli.Command{
|
||||
Name: "add",
|
||||
Usage: "add a new remote target",
|
||||
Action: mainAdminBucketRemoteAdd,
|
||||
OnUsageError: onUsageError,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: append(globalFlags, adminBucketRemoteAddFlags...),
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
{{.HelpName}} TARGET http(s)://ACCESSKEY:SECRETKEY@DEST_URL/DEST_BUCKET [--path | --region | --bandwidth] --service
|
||||
|
||||
TARGET:
|
||||
Also called as alias/sourcebucketname
|
||||
|
||||
DEST_BUCKET:
|
||||
Also called as remote target bucket.
|
||||
|
||||
DEST_URL:
|
||||
Also called as remote endpoint.
|
||||
|
||||
ACCESSKEY:
|
||||
Also called as username.
|
||||
|
||||
SECRETKEY:
|
||||
Also called as password.
|
||||
|
||||
FLAGS:
|
||||
{{range .VisibleFlags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
1. Set a new remote replication target "targetbucket" in region "us-west-1" on https://minio.siteb.example.com for bucket 'sourcebucket'.
|
||||
{{.Prompt}} {{.HelpName}} sitea/sourcebucket https://foobar:foo12345@minio.siteb.example.com/targetbucket \
|
||||
--service "replication" --region "us-west-1"
|
||||
|
||||
2. Set a new remote replication target 'targetbucket' in region "us-west-1" on https://minio.siteb.example.com for
|
||||
bucket 'sourcebucket' with bandwidth set to 2 gigabits per second. Enable synchronous replication to the target
|
||||
and perform health check of target every 100 seconds
|
||||
{{.Prompt}} {{.HelpName}} sitea/sourcebucket https://foobar:foo12345@minio.siteb.example.com/targetbucket \
|
||||
--service "replication" --region "us-west-1 --bandwidth "2G" --sync
|
||||
`,
|
||||
}
|
||||
|
||||
// checkAdminBucketRemoteAddSyntax - validate all the passed arguments
|
||||
func checkAdminBucketRemoteAddSyntax(ctx *cli.Context) {
|
||||
argsNr := len(ctx.Args())
|
||||
if argsNr < 2 {
|
||||
cli.ShowCommandHelpAndExit(ctx, ctx.Command.Name, 1) // last argument is exit code
|
||||
}
|
||||
if argsNr > 2 {
|
||||
fatalIf(errInvalidArgument().Trace(ctx.Args().Tail()...),
|
||||
"Incorrect number of arguments for remote add command.")
|
||||
}
|
||||
}
|
||||
|
||||
// RemoteMessage container for content message structure
|
||||
type RemoteMessage struct {
|
||||
op string
|
||||
Status string `json:"status"`
|
||||
AccessKey string `json:"accessKey,omitempty"`
|
||||
SecretKey string `json:"secretKey,omitempty"`
|
||||
SourceBucket string `json:"sourceBucket"`
|
||||
TargetURL string `json:"TargetURL,omitempty"`
|
||||
TargetBucket string `json:"TargetBucket,omitempty"`
|
||||
RemoteARN string `json:"RemoteARN,omitempty"`
|
||||
Path string `json:"path,omitempty"`
|
||||
Region string `json:"region,omitempty"`
|
||||
ServiceType string `json:"service"`
|
||||
Bandwidth int64 `json:"bandwidth"`
|
||||
ReplicationSync bool `json:"replicationSync"`
|
||||
HealthCheckDuration time.Duration `json:"healthcheckDuration"`
|
||||
}
|
||||
|
||||
func (r RemoteMessage) String() string {
|
||||
switch r.op {
|
||||
case "ls":
|
||||
message := console.Colorize("TargetURL", fmt.Sprintf("%s ", r.TargetURL))
|
||||
message += console.Colorize("SourceBucket", r.SourceBucket)
|
||||
message += console.Colorize("Arrow", "->")
|
||||
message += console.Colorize("TargetBucket", r.TargetBucket)
|
||||
message += " "
|
||||
message += console.Colorize("ARN", r.RemoteARN)
|
||||
if r.ReplicationSync && r.ServiceType == string(madmin.ReplicationService) {
|
||||
message += " "
|
||||
message += console.Colorize("SyncLabel", "sync")
|
||||
}
|
||||
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]`.")
|
||||
}
|
||||
if cli.IsSet("sync") && serviceType != string(madmin.ReplicationService) {
|
||||
fatalIf(errInvalidArgument(), "Invalid usage. --sync flag applies only to replication service")
|
||||
}
|
||||
bandwidthStr := cli.String("bandwidth")
|
||||
bandwidth, err := getBandwidthInBytes(bandwidthStr)
|
||||
if err != nil {
|
||||
fatalIf(errInvalidArgument().Trace(bandwidthStr), "Invalid bandwidth number")
|
||||
}
|
||||
console.SetColor(cred, color.New(color.FgYellow, color.Italic))
|
||||
creds := &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),
|
||||
ReplicationSync: cli.Bool("sync"),
|
||||
HealthCheckDuration: time.Duration(cli.Uint("healthcheck-seconds")) * time.Second,
|
||||
}
|
||||
return sourceBucket, bktTarget
|
||||
}
|
||||
|
||||
func getBandwidthInBytes(bandwidthStr string) (bandwidth uint64, err error) {
|
||||
if bandwidthStr != "" {
|
||||
bandwidth, err = humanize.ParseBytes(bandwidthStr)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
bandwidth = bandwidth / 8
|
||||
return
|
||||
}
|
||||
|
||||
// mainAdminBucketRemoteAdd is the handle for "mc admin bucket remote set" command.
|
||||
func mainAdminBucketRemoteAdd(ctx *cli.Context) error {
|
||||
checkAdminBucketRemoteAddSyntax(ctx)
|
||||
|
||||
console.SetColor("RemoteMessage", color.New(color.FgGreen))
|
||||
|
||||
// Get the alias parameter from cli
|
||||
args := ctx.Args()
|
||||
aliasedURL := args.Get(0)
|
||||
// Create a new MinIO Admin Client
|
||||
client, cerr := newAdminClient(aliasedURL)
|
||||
fatalIf(cerr, "Unable to initialize admin connection.")
|
||||
|
||||
sourceBucket, bktTarget := fetchRemoteTarget(ctx)
|
||||
arn, e := client.SetRemoteTarget(globalContext, sourceBucket, bktTarget)
|
||||
if e != nil {
|
||||
fatalIf(probe.NewError(e).Trace(args...), "Unable to configure remote target")
|
||||
}
|
||||
|
||||
printMsg(RemoteMessage{
|
||||
op: ctx.Command.Name,
|
||||
TargetURL: bktTarget.URL().String(),
|
||||
TargetBucket: bktTarget.TargetBucket,
|
||||
AccessKey: bktTarget.Credentials.AccessKey,
|
||||
SourceBucket: sourceBucket,
|
||||
RemoteARN: arn,
|
||||
ReplicationSync: bktTarget.ReplicationSync,
|
||||
})
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -1,114 +0,0 @@
|
||||
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)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,194 +0,0 @@
|
||||
/*
|
||||
* MinIO Client (C) 2020 MinIO, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"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/console"
|
||||
"github.com/minio/minio/pkg/madmin"
|
||||
)
|
||||
|
||||
var adminBandwidthInfoCmdFlags = []cli.Flag{
|
||||
cli.StringFlag{
|
||||
Name: "unit",
|
||||
Value: "b",
|
||||
Usage: "[b|bi|B|Bi] Display bandwidth in bits (IEC [bi] or SI [b]) or bytes (IEC [Bi] or SI [B])",
|
||||
},
|
||||
}
|
||||
|
||||
var adminBwInfoCmd = cli.Command{
|
||||
Name: "bandwidth",
|
||||
Usage: "Show bandwidth info for buckets on the MinIO server in bits or bytes per second. Ki,Bi,Mi,Gi represent IEC units.",
|
||||
Action: mainAdminBwInfo,
|
||||
Before: setGlobalsFromContext,
|
||||
OnUsageError: onUsageError,
|
||||
Flags: append(globalFlags, adminBandwidthInfoCmdFlags...),
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
{{.HelpName}} FLAGS TARGET
|
||||
|
||||
FLAGS:
|
||||
{{range .VisibleFlags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
1. Show the bandwidth usage for all the buckets in a MinIO server setup
|
||||
{{.Prompt}} {{.HelpName}} play/
|
||||
2. Show the bandwidth usage for the bucket 'source-bucket' in a MinIO server setup
|
||||
{{.Prompt}} {{.HelpName}} play/source-bucket
|
||||
`,
|
||||
}
|
||||
|
||||
func printTable(report madmin.Report, bits bool, iec bool) {
|
||||
bucketMaxLength := 63
|
||||
bucketColLength := 6
|
||||
var bucketKeys []string
|
||||
for bucket := range report.Report.BucketStats {
|
||||
if len(bucket) <= bucketMaxLength && len(bucket) > bucketColLength {
|
||||
bucketColLength = len(bucket)
|
||||
}
|
||||
bucketKeys = append(bucketKeys, bucket)
|
||||
}
|
||||
sort.Strings(bucketKeys)
|
||||
dspOrder := []col{colGreen} // Header
|
||||
for i := 0; i < len(report.Report.BucketStats); i++ {
|
||||
dspOrder = append(dspOrder, colGrey)
|
||||
}
|
||||
var printColors []*color.Color
|
||||
for _, c := range dspOrder {
|
||||
printColors = append(printColors, getPrintCol(c))
|
||||
}
|
||||
|
||||
cellText := make([][]string, len(report.Report.BucketStats)+1) // 1 for the header
|
||||
tbl := console.NewTable(printColors, []bool{false, false, false}, 0)
|
||||
bucketTitle := fmt.Sprintf("%-16v", "Bucket")
|
||||
cellText[0] = []string{
|
||||
bucketTitle,
|
||||
"Configured Max Bandwidth",
|
||||
"Current Bandwidth",
|
||||
}
|
||||
tbl.HeaderRowSeparator = true
|
||||
index := 1
|
||||
|
||||
for _, bucket := range bucketKeys {
|
||||
values := report.Report.BucketStats[bucket]
|
||||
if len(bucket) > bucketMaxLength {
|
||||
bucket = bucket[:bucketMaxLength] + ".."
|
||||
}
|
||||
var mul uint64
|
||||
mul = 1
|
||||
if bits {
|
||||
mul = 8
|
||||
}
|
||||
limit := humanize.Bytes(uint64(values.LimitInBytesPerSecond) * mul)
|
||||
current := humanize.Bytes(uint64(values.CurrentBandwidthInBytesPerSecond) * mul)
|
||||
if iec {
|
||||
limit = humanize.IBytes(uint64(values.LimitInBytesPerSecond)*mul) + "/sec"
|
||||
current = humanize.IBytes(uint64(values.CurrentBandwidthInBytesPerSecond)*mul) + "/sec"
|
||||
}
|
||||
if bits {
|
||||
limit = strings.ToLower(limit) + "/sec"
|
||||
current = strings.ToLower(current) + "/sec"
|
||||
}
|
||||
if values.LimitInBytesPerSecond == 0 {
|
||||
limit = "N/A" // N/A means cluster bandwidth is not configured
|
||||
}
|
||||
cellText[index] = []string{
|
||||
bucket,
|
||||
limit,
|
||||
current,
|
||||
}
|
||||
index++
|
||||
}
|
||||
if len(report.Report.BucketStats) > 0 {
|
||||
err := tbl.DisplayTable(cellText)
|
||||
if err != nil {
|
||||
console.Error(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
func checkAdminBwInfoSyntax(ctx *cli.Context) {
|
||||
u := ctx.String("unit")
|
||||
if u != "bi" &&
|
||||
u != "b" &&
|
||||
u != "Bi" &&
|
||||
u != "B" &&
|
||||
u != "" {
|
||||
cli.ShowCommandHelpAndExit(ctx, "bandwidth", globalErrorExitStatus)
|
||||
}
|
||||
if len(ctx.Args()) > 1 || len(ctx.Args()) == 0 {
|
||||
cli.ShowCommandHelpAndExit(ctx, "bandwidth", globalErrorExitStatus)
|
||||
}
|
||||
}
|
||||
|
||||
func mainAdminBwInfo(ctx *cli.Context) {
|
||||
checkAdminBwInfoSyntax(ctx)
|
||||
aliasURL, bucket := getAliasAndBucket(ctx)
|
||||
client := getClient(aliasURL)
|
||||
reportCh := client.GetBucketBandwidth(globalContext, bucket)
|
||||
firstPrint := true
|
||||
bandwidthUnitsString := ctx.String("unit")
|
||||
for {
|
||||
select {
|
||||
case report := <-reportCh:
|
||||
if len(report.Report.BucketStats) == 0 {
|
||||
continue
|
||||
}
|
||||
if report.Err != nil {
|
||||
if strings.Contains(report.Err.Error(), "EOF") {
|
||||
continue
|
||||
}
|
||||
console.Error(report.Err)
|
||||
}
|
||||
printBandwidth(report, firstPrint, bandwidthUnitsString == "bi" || bandwidthUnitsString == "b",
|
||||
bandwidthUnitsString == "bi" || bandwidthUnitsString == "Bi")
|
||||
firstPrint = false
|
||||
case <-globalContext.Done():
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func printBandwidth(report madmin.Report, firstPrint bool, bits bool, iec bool) {
|
||||
rewindLines := len(report.Report.BucketStats) + 4
|
||||
if firstPrint {
|
||||
rewindLines = 0
|
||||
}
|
||||
if globalJSON {
|
||||
reportJSON, e := json.MarshalIndent(report, "", " ")
|
||||
fatalIf(probe.NewError(e), "Unable to marshal to JSON")
|
||||
console.Println(string(reportJSON))
|
||||
time.Sleep(1 * time.Second)
|
||||
return
|
||||
}
|
||||
if len(report.Report.BucketStats) > 0 {
|
||||
console.RewindLines(rewindLines)
|
||||
// For the next iteration, rewind lines
|
||||
printTable(report, bits, iec)
|
||||
}
|
||||
time.Sleep(1 * time.Second)
|
||||
}
|
||||
@@ -1,180 +0,0 @@
|
||||
/*
|
||||
* MinIO Client (C) 2020 MinIO, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"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"),
|
||||
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
|
||||
}
|
||||
@@ -1,152 +0,0 @@
|
||||
/*
|
||||
* MinIO Client (C) 2020 MinIO, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"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("ARN", color.New(color.FgCyan))
|
||||
console.SetColor("Arrow", color.New(color.FgHiWhite))
|
||||
console.SetColor("SyncLabel", color.New(color.FgHiYellow))
|
||||
|
||||
// Get the alias parameter from cli
|
||||
args := ctx.Args()
|
||||
aliasedURL := args.Get(0)
|
||||
aliasedURL = filepath.Clean(aliasedURL)
|
||||
_, sourceBucket := url2Alias(aliasedURL)
|
||||
// Create a new MinIO Admin Client
|
||||
client, err := newAdminClient(aliasedURL)
|
||||
fatalIf(err, "Unable to initialize admin connection.")
|
||||
targets, e := client.ListRemoteTargets(globalContext, sourceBucket, ctx.String("service"))
|
||||
fatalIf(probe.NewError(e).Trace(args...), "Unable to list remote target")
|
||||
printRemotes(ctx, aliasedURL, targets)
|
||||
return nil
|
||||
}
|
||||
|
||||
func printRemotes(ctx *cli.Context, urlStr string, targets []madmin.BucketTarget) {
|
||||
|
||||
maxURLLen := 10
|
||||
maxTgtLen := 6
|
||||
maxSrcLen := 6
|
||||
if !globalJSON {
|
||||
if len(targets) == 0 {
|
||||
console.Print(console.Colorize("RemoteListEmpty", fmt.Sprintf("No remote targets found for `%s`. \n", urlStr)))
|
||||
return
|
||||
}
|
||||
for _, t := range targets {
|
||||
l := len(t.Endpoint)
|
||||
if l > maxURLLen {
|
||||
maxURLLen = l
|
||||
}
|
||||
if len(t.TargetBucket) > maxTgtLen {
|
||||
maxTgtLen = len(t.TargetBucket)
|
||||
}
|
||||
if len(t.SourceBucket) > maxSrcLen {
|
||||
maxSrcLen = len(t.SourceBucket)
|
||||
}
|
||||
}
|
||||
if maxURLLen > 0 {
|
||||
console.Println(console.Colorize("RemoteListMessage", fmt.Sprintf("%-*.*s %-*.*s->%-*.*s %s", maxURLLen+8, maxURLLen+8, "Remote URL", maxSrcLen, maxSrcLen, "Source", maxTgtLen, maxTgtLen, "Target", "ARN")))
|
||||
}
|
||||
}
|
||||
for _, target := range targets {
|
||||
targetURL := target.URL().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)
|
||||
}
|
||||
}
|
||||
printMsg(RemoteMessage{
|
||||
op: ctx.Command.Name,
|
||||
AccessKey: target.Credentials.AccessKey,
|
||||
TargetBucket: target.TargetBucket,
|
||||
TargetURL: targetURL,
|
||||
SourceBucket: target.SourceBucket,
|
||||
RemoteARN: target.Arn,
|
||||
ServiceType: string(target.Type),
|
||||
ReplicationSync: target.ReplicationSync,
|
||||
Bandwidth: target.BandwidthLimit,
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,44 +0,0 @@
|
||||
/*
|
||||
* MinIO Client (C) 2020 MinIO, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package cmd
|
||||
|
||||
import "github.com/minio/cli"
|
||||
|
||||
var adminBucketRemoteSubcommands = []cli.Command{
|
||||
adminBucketRemoteAddCmd,
|
||||
adminBucketRemoteEditCmd,
|
||||
adminBucketRemoteListCmd,
|
||||
adminBucketRemoteRmCmd,
|
||||
adminBwInfoCmd,
|
||||
}
|
||||
|
||||
var adminBucketRemoteCmd = cli.Command{
|
||||
Name: "remote",
|
||||
Usage: "configure remote target buckets",
|
||||
Action: mainadminBucketRemote,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
Subcommands: adminBucketRemoteSubcommands,
|
||||
HideHelpCommand: true,
|
||||
}
|
||||
|
||||
// mainadminBucketRemote is the handle for "mc admin bucket remote" command.
|
||||
func mainadminBucketRemote(ctx *cli.Context) error {
|
||||
commandNotFound(ctx, adminBucketRemoteSubcommands)
|
||||
return nil
|
||||
// Sub-commands like "add", "ls", "rm" have their own main.
|
||||
}
|
||||
@@ -1,92 +0,0 @@
|
||||
/*
|
||||
* MinIO Client (C) 2020 MinIO, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"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
|
||||
}
|
||||
+9
-13
@@ -18,24 +18,20 @@ 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: adminBucketSubcommands,
|
||||
Name: "bucket",
|
||||
Usage: "manage buckets defined in the MinIO server",
|
||||
Action: mainAdminBucket,
|
||||
Flags: globalFlags,
|
||||
Subcommands: []cli.Command{
|
||||
adminBucketQuotaCmd,
|
||||
},
|
||||
HideHelpCommand: true,
|
||||
}
|
||||
|
||||
// mainAdminBucket is the handle for "mc admin bucket" command.
|
||||
func mainAdminBucket(ctx *cli.Context) error {
|
||||
commandNotFound(ctx, adminBucketSubcommands)
|
||||
cli.ShowCommandHelp(ctx, ctx.Args().First())
|
||||
return nil
|
||||
// Sub-commands like "quota", "remote" have their own main.
|
||||
// Sub-commands like "quota", "usage" have their own main.
|
||||
}
|
||||
|
||||
@@ -23,12 +23,11 @@ import (
|
||||
)
|
||||
|
||||
var adminConfigExportCmd = cli.Command{
|
||||
Name: "export",
|
||||
Usage: "export all config keys to STDOUT",
|
||||
Before: setGlobalsFromContext,
|
||||
Action: mainAdminConfigExport,
|
||||
OnUsageError: onUsageError,
|
||||
Flags: globalFlags,
|
||||
Name: "export",
|
||||
Usage: "export all config keys to STDOUT",
|
||||
Before: initBeforeRunningCmd,
|
||||
Action: mainAdminConfigExport,
|
||||
Flags: globalFlags,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
@@ -85,7 +84,7 @@ func mainAdminConfigExport(ctx *cli.Context) error {
|
||||
|
||||
// Call get config API
|
||||
buf, e := client.GetConfig(globalContext)
|
||||
fatalIf(probe.NewError(e), "Unable to get server config")
|
||||
fatalIf(probe.NewError(e), "Cannot get server config")
|
||||
|
||||
// Print
|
||||
printMsg(configExportMessage{
|
||||
|
||||
@@ -25,12 +25,11 @@ import (
|
||||
)
|
||||
|
||||
var adminConfigGetCmd = cli.Command{
|
||||
Name: "get",
|
||||
Usage: "interactively retrieve a config key parameters",
|
||||
Before: setGlobalsFromContext,
|
||||
Action: mainAdminConfigGet,
|
||||
OnUsageError: onUsageError,
|
||||
Flags: globalFlags,
|
||||
Name: "get",
|
||||
Usage: "interactively retrieve a config key parameters",
|
||||
Before: initBeforeRunningCmd,
|
||||
Action: mainAdminConfigGet,
|
||||
Flags: globalFlags,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
@@ -97,7 +96,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), "Unable to get help for the sub-system")
|
||||
fatalIf(probe.NewError(e), "Cannot get help for the sub-system")
|
||||
|
||||
// Print
|
||||
printMsg(configHelpMessage{
|
||||
@@ -110,7 +109,7 @@ func mainAdminConfigGet(ctx *cli.Context) error {
|
||||
|
||||
// Call get config API
|
||||
buf, e := client.GetConfigKV(globalContext, strings.Join(args.Tail(), " "))
|
||||
fatalIf(probe.NewError(e), "Unable to get server '%s' config", args.Tail())
|
||||
fatalIf(probe.NewError(e), "Cannot 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), "Unable to initialize template writer")
|
||||
fatalIf(probe.NewError(e), "Cannot initialize template writer")
|
||||
|
||||
w.Flush()
|
||||
|
||||
|
||||
@@ -41,12 +41,11 @@ var historyListFlags = []cli.Flag{
|
||||
}
|
||||
|
||||
var adminConfigHistoryCmd = cli.Command{
|
||||
Name: "history",
|
||||
Usage: "show all historic configuration changes",
|
||||
Before: setGlobalsFromContext,
|
||||
Action: mainAdminConfigHistory,
|
||||
OnUsageError: onUsageError,
|
||||
Flags: append(append([]cli.Flag{}, globalFlags...), historyListFlags...),
|
||||
Name: "history",
|
||||
Usage: "show all historic configuration changes",
|
||||
Before: initBeforeRunningCmd,
|
||||
Action: mainAdminConfigHistory,
|
||||
Flags: append(append([]cli.Flag{}, globalFlags...), historyListFlags...),
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
@@ -90,7 +89,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), "Unable to initialize template writer")
|
||||
fatalIf(probe.NewError(e), "Cannot initialize template writer")
|
||||
|
||||
w.Flush()
|
||||
return s.String()
|
||||
@@ -128,7 +127,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")), "Unable to clear server configuration.")
|
||||
fatalIf(probe.NewError(client.ClearConfigHistoryKV(globalContext, "all")), "Cannot clear server configuration.")
|
||||
|
||||
// Print
|
||||
printMsg(configHistoryMessage{})
|
||||
@@ -136,7 +135,7 @@ func mainAdminConfigHistory(ctx *cli.Context) error {
|
||||
}
|
||||
|
||||
chEntries, e := client.ListConfigHistoryKV(globalContext, ctx.Int("count"))
|
||||
fatalIf(probe.NewError(e), "Unable to list server history configuration.")
|
||||
fatalIf(probe.NewError(e), "Cannot list server history configuration.")
|
||||
|
||||
hentries := make([]historyEntry, len(chEntries))
|
||||
for i, chEntry := range chEntries {
|
||||
|
||||
@@ -28,12 +28,11 @@ import (
|
||||
)
|
||||
|
||||
var adminConfigImportCmd = cli.Command{
|
||||
Name: "import",
|
||||
Usage: "import multiple config keys from STDIN",
|
||||
Before: setGlobalsFromContext,
|
||||
Action: mainAdminConfigImport,
|
||||
OnUsageError: onUsageError,
|
||||
Flags: globalFlags,
|
||||
Name: "import",
|
||||
Usage: "import multiple config keys from STDIN",
|
||||
Before: initBeforeRunningCmd,
|
||||
Action: mainAdminConfigImport,
|
||||
Flags: globalFlags,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
@@ -97,7 +96,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)), "Unable to set server config")
|
||||
fatalIf(probe.NewError(client.SetConfig(globalContext, os.Stdin)), "Cannot set server config")
|
||||
|
||||
// Print
|
||||
printMsg(configImportMessage{
|
||||
|
||||
@@ -35,12 +35,11 @@ var adminConfigEnvFlags = []cli.Flag{
|
||||
}
|
||||
|
||||
var adminConfigResetCmd = cli.Command{
|
||||
Name: "reset",
|
||||
Usage: "interactively reset a config key parameters",
|
||||
Before: setGlobalsFromContext,
|
||||
Action: mainAdminConfigReset,
|
||||
OnUsageError: onUsageError,
|
||||
Flags: append(adminConfigEnvFlags, globalFlags...),
|
||||
Name: "reset",
|
||||
Usage: "interactively reset a config key parameters",
|
||||
Before: initBeforeRunningCmd,
|
||||
Action: mainAdminConfigReset,
|
||||
Flags: append(adminConfigEnvFlags, globalFlags...),
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
@@ -109,7 +108,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), "Unable to get help for the sub-system")
|
||||
fatalIf(probe.NewError(e), "Cannot get help for the sub-system")
|
||||
|
||||
// Print
|
||||
printMsg(configHelpMessage{
|
||||
@@ -123,7 +122,7 @@ func mainAdminConfigReset(ctx *cli.Context) error {
|
||||
// Call reset config API
|
||||
input := strings.Join(args.Tail(), " ")
|
||||
fatalIf(probe.NewError(client.DelConfigKV(globalContext, input)),
|
||||
"Unable to reset '%s' on the server", input)
|
||||
"Cannot reset '%s' on the server", input)
|
||||
|
||||
// Print set config result
|
||||
printMsg(configResetMessage{
|
||||
|
||||
@@ -27,12 +27,11 @@ import (
|
||||
)
|
||||
|
||||
var adminConfigRestoreCmd = cli.Command{
|
||||
Name: "restore",
|
||||
Usage: "rollback back changes to a specific config history",
|
||||
Before: setGlobalsFromContext,
|
||||
Action: mainAdminConfigRestore,
|
||||
OnUsageError: onUsageError,
|
||||
Flags: globalFlags,
|
||||
Name: "restore",
|
||||
Usage: "rollback back changes to a specific config history",
|
||||
Before: initBeforeRunningCmd,
|
||||
Action: mainAdminConfigRestore,
|
||||
Flags: globalFlags,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
@@ -95,7 +94,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))), "Unable to restore server configuration.")
|
||||
fatalIf(probe.NewError(client.RestoreConfigHistoryKV(globalContext, args.Get(1))), "Cannot restore server configuration.")
|
||||
|
||||
// Print
|
||||
printMsg(configRestoreMessage{
|
||||
|
||||
+12
-20
@@ -29,12 +29,11 @@ import (
|
||||
)
|
||||
|
||||
var adminConfigSetCmd = cli.Command{
|
||||
Name: "set",
|
||||
Usage: "interactively set a config key parameters",
|
||||
Before: setGlobalsFromContext,
|
||||
Action: mainAdminConfigSet,
|
||||
OnUsageError: onUsageError,
|
||||
Flags: append(adminConfigEnvFlags, globalFlags...),
|
||||
Name: "set",
|
||||
Usage: "interactively set a config key parameters",
|
||||
Before: initBeforeRunningCmd,
|
||||
Action: mainAdminConfigSet,
|
||||
Flags: append(adminConfigEnvFlags, globalFlags...),
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
@@ -50,9 +49,6 @@ 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
|
||||
`,
|
||||
}
|
||||
|
||||
@@ -60,18 +56,15 @@ 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",
|
||||
"Successfully applied new settings.")
|
||||
if u.restart {
|
||||
suggestion := color.RedString("mc admin service restart %s", u.targetAlias)
|
||||
msg += console.Colorize("SetConfigSuccess",
|
||||
fmt.Sprintf("\nPlease restart your server '%s'.", suggestion))
|
||||
}
|
||||
"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))
|
||||
return
|
||||
}
|
||||
|
||||
@@ -113,7 +106,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), "Unable to get help for the sub-system")
|
||||
fatalIf(probe.NewError(e), "Cannot get help for the sub-system")
|
||||
|
||||
// Print
|
||||
printMsg(configHelpMessage{
|
||||
@@ -126,13 +119,12 @@ func mainAdminConfigSet(ctx *cli.Context) error {
|
||||
}
|
||||
|
||||
// Call set config API
|
||||
restart, e := client.SetConfigKV(globalContext, input)
|
||||
fatalIf(probe.NewError(e), "Unable to set '%s' to server", input)
|
||||
fatalIf(probe.NewError(client.SetConfigKV(globalContext, input)),
|
||||
"Cannot set '%s' to server", input)
|
||||
|
||||
// Print set config result
|
||||
printMsg(configSetMessage{
|
||||
targetAlias: aliasedURL,
|
||||
restart: restart,
|
||||
})
|
||||
|
||||
return nil
|
||||
|
||||
+14
-17
@@ -18,29 +18,26 @@ 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: adminConfigSubcommands,
|
||||
Name: "config",
|
||||
Usage: "manage MinIO server configuration",
|
||||
Action: mainAdminConfig,
|
||||
Flags: globalFlags,
|
||||
Subcommands: []cli.Command{
|
||||
adminConfigGetCmd,
|
||||
adminConfigSetCmd,
|
||||
adminConfigResetCmd,
|
||||
adminConfigHistoryCmd,
|
||||
adminConfigRestoreCmd,
|
||||
adminConfigExportCmd,
|
||||
adminConfigImportCmd,
|
||||
},
|
||||
HideHelpCommand: true,
|
||||
}
|
||||
|
||||
// mainAdminConfig is the handle for "mc admin config" command.
|
||||
func mainAdminConfig(ctx *cli.Context) error {
|
||||
commandNotFound(ctx, adminConfigSubcommands)
|
||||
cli.ShowCommandHelp(ctx, ctx.Args().First())
|
||||
return nil
|
||||
// Sub-commands like "get", "set" have their own main.
|
||||
}
|
||||
|
||||
@@ -49,8 +49,7 @@ var adminConsoleCmd = cli.Command{
|
||||
Name: "console",
|
||||
Usage: "show console logs for MinIO server",
|
||||
Action: mainAdminConsole,
|
||||
OnUsageError: onUsageError,
|
||||
Before: setGlobalsFromContext,
|
||||
Before: initBeforeRunningCmd,
|
||||
Flags: append(adminConsoleFlags, globalFlags...),
|
||||
HideHelpCommand: true,
|
||||
CustomHelpTemplate: `NAME:
|
||||
@@ -82,13 +81,11 @@ 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.")
|
||||
|
||||
@@ -195,7 +192,7 @@ func mainAdminConsole(ctx *cli.Context) error {
|
||||
// Create a new MinIO Admin Client
|
||||
client, err := newAdminClient(aliasedURL)
|
||||
if err != nil {
|
||||
fatalIf(err.Trace(aliasedURL), "Unable to initialize admin client.")
|
||||
fatalIf(err.Trace(aliasedURL), "Cannot initialize admin client.")
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -206,13 +203,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), "Unable to listen to console logs")
|
||||
fatalIf(probe.NewError(logInfo.Err), "Cannot listen to console logs")
|
||||
}
|
||||
// drop nodeName from output if specified as cli arg
|
||||
if node != "" {
|
||||
logInfo.NodeName = ""
|
||||
}
|
||||
printMsg(logMessage{LogInfo: logInfo})
|
||||
printMsg(logMessage{logInfo})
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -29,12 +29,11 @@ import (
|
||||
)
|
||||
|
||||
var adminGroupAddCmd = cli.Command{
|
||||
Name: "add",
|
||||
Usage: "add users to a new or existing group",
|
||||
Action: mainAdminGroupAdd,
|
||||
OnUsageError: onUsageError,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
Name: "add",
|
||||
Usage: "add users to a new or existing group",
|
||||
Action: mainAdminGroupAdd,
|
||||
Before: initBeforeRunningCmd,
|
||||
Flags: globalFlags,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
@@ -132,7 +131,7 @@ func mainAdminGroupAdd(ctx *cli.Context) error {
|
||||
Members: members,
|
||||
IsRemove: false,
|
||||
}
|
||||
fatalIf(probe.NewError(client.UpdateGroupMembers(globalContext, gAddRemove)).Trace(args...), "Unable to add new group")
|
||||
fatalIf(probe.NewError(client.UpdateGroupMembers(globalContext, gAddRemove)).Trace(args...), "Cannot add new group")
|
||||
|
||||
printMsg(groupMessage{
|
||||
op: "add",
|
||||
|
||||
@@ -21,12 +21,11 @@ import (
|
||||
)
|
||||
|
||||
var adminGroupDisableCmd = cli.Command{
|
||||
Name: "disable",
|
||||
Usage: "disable a group",
|
||||
Action: mainAdminGroupEnableDisable,
|
||||
OnUsageError: onUsageError,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
Name: "disable",
|
||||
Usage: "Disable a group",
|
||||
Action: mainAdminGroupEnableDisable,
|
||||
Before: initBeforeRunningCmd,
|
||||
Flags: globalFlags,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
|
||||
@@ -27,12 +27,11 @@ import (
|
||||
)
|
||||
|
||||
var adminGroupEnableCmd = cli.Command{
|
||||
Name: "enable",
|
||||
Usage: "enable a group",
|
||||
Action: mainAdminGroupEnableDisable,
|
||||
OnUsageError: onUsageError,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
Name: "enable",
|
||||
Usage: "Enable a group",
|
||||
Action: mainAdminGroupEnableDisable,
|
||||
Before: initBeforeRunningCmd,
|
||||
Flags: globalFlags,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
|
||||
@@ -24,12 +24,11 @@ import (
|
||||
)
|
||||
|
||||
var adminGroupInfoCmd = cli.Command{
|
||||
Name: "info",
|
||||
Usage: "display group info",
|
||||
Action: mainAdminGroupInfo,
|
||||
OnUsageError: onUsageError,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
Name: "info",
|
||||
Usage: "display group info",
|
||||
Action: mainAdminGroupInfo,
|
||||
Before: initBeforeRunningCmd,
|
||||
Flags: globalFlags,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
|
||||
@@ -24,12 +24,11 @@ import (
|
||||
)
|
||||
|
||||
var adminGroupListCmd = cli.Command{
|
||||
Name: "list",
|
||||
Usage: "display list of groups",
|
||||
Action: mainAdminGroupList,
|
||||
OnUsageError: onUsageError,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
Name: "list",
|
||||
Usage: "display list of groups",
|
||||
Action: mainAdminGroupList,
|
||||
Before: initBeforeRunningCmd,
|
||||
Flags: globalFlags,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
|
||||
@@ -25,12 +25,11 @@ import (
|
||||
)
|
||||
|
||||
var adminGroupRemoveCmd = cli.Command{
|
||||
Name: "remove",
|
||||
Usage: "remove group or members from a group",
|
||||
Action: mainAdminGroupRemove,
|
||||
OnUsageError: onUsageError,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
Name: "remove",
|
||||
Usage: "remove group or members from a group",
|
||||
Action: mainAdminGroupRemove,
|
||||
Before: initBeforeRunningCmd,
|
||||
Flags: globalFlags,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
|
||||
+13
-16
@@ -18,28 +18,25 @@ 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: adminGroupSubcommands,
|
||||
Name: "group",
|
||||
Usage: "manage groups",
|
||||
Action: mainAdminGroup,
|
||||
Flags: globalFlags,
|
||||
Subcommands: []cli.Command{
|
||||
adminGroupAddCmd,
|
||||
adminGroupRemoveCmd,
|
||||
adminGroupInfoCmd,
|
||||
adminGroupListCmd,
|
||||
adminGroupEnableCmd,
|
||||
adminGroupDisableCmd,
|
||||
},
|
||||
HideHelpCommand: true,
|
||||
}
|
||||
|
||||
// mainAdminGroup is the handle for "mc admin config" command.
|
||||
func mainAdminGroup(ctx *cli.Context) error {
|
||||
commandNotFound(ctx, adminGroupSubcommands)
|
||||
cli.ShowCommandHelp(ctx, ctx.Args().First())
|
||||
return nil
|
||||
// Sub-commands like "get", "set" have their own main.
|
||||
}
|
||||
|
||||
+47
-14
@@ -20,6 +20,7 @@ import (
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/cli"
|
||||
@@ -37,37 +38,36 @@ const (
|
||||
var adminHealFlags = []cli.Flag{
|
||||
cli.StringFlag{
|
||||
Name: "scan",
|
||||
Usage: "[DEPRECATED] select the healing scan mode (normal/deep)",
|
||||
Usage: "select the healing scan mode (normal/deep)",
|
||||
Value: scanNormalMode,
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "recursive, r",
|
||||
Usage: "[DEPRECATED] heal recursively",
|
||||
Usage: "heal recursively",
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "dry-run, n",
|
||||
Usage: "[DEPRECATED] only inspect data, but do not mutate",
|
||||
Usage: "only inspect data, but do not mutate",
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "force-start, f",
|
||||
Usage: "[DEPRECATED] force start a new heal sequence",
|
||||
Usage: "force start a new heal sequence",
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "force-stop, s",
|
||||
Usage: "[DEPRECATED] force stop a running heal sequence",
|
||||
Usage: "Force stop a running heal sequence",
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "remove",
|
||||
Usage: "[DEPRECATED] remove dangling objects in heal sequence",
|
||||
Usage: "remove dangling objects in heal sequence",
|
||||
},
|
||||
}
|
||||
|
||||
var adminHealCmd = cli.Command{
|
||||
Name: "heal",
|
||||
Usage: "[DEPRECATED] heal disks, buckets and objects on MinIO server",
|
||||
Usage: "heal disks, buckets and objects on MinIO server",
|
||||
Action: mainAdminHeal,
|
||||
OnUsageError: onUsageError,
|
||||
Before: setGlobalsFromContext,
|
||||
Before: initBeforeRunningCmd,
|
||||
Flags: append(adminHealFlags, globalFlags...),
|
||||
HideHelpCommand: true,
|
||||
CustomHelpTemplate: `NAME:
|
||||
@@ -83,8 +83,30 @@ 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.
|
||||
|
||||
DEPRECATED:
|
||||
MinIO server now supports auto-heal, this command will be removed in future.
|
||||
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/
|
||||
`,
|
||||
}
|
||||
|
||||
@@ -134,6 +156,18 @@ func (s backgroundHealStatusMessage) String() string {
|
||||
healPrettyMsg += dot + fmt.Sprintf("%s item(s) scanned in total\n",
|
||||
console.Colorize("HealBackground", s.HealInfo.ScannedItemsCount))
|
||||
|
||||
lastHealingTime := dot + "Never executed"
|
||||
if !s.HealInfo.LastHealActivity.IsZero() {
|
||||
lastHealingTime = dot + "Completed " + timeDurationToHumanizedDuration(time.Since(s.HealInfo.LastHealActivity)).StringShort() + " ago"
|
||||
}
|
||||
healPrettyMsg += console.Colorize("HealBackground", lastHealingTime) + "\n"
|
||||
|
||||
now := time.Now()
|
||||
if !s.HealInfo.NextHealRound.IsZero() && s.HealInfo.NextHealRound.After(now) {
|
||||
nextHealingRound := timeDurationToHumanizedDuration(s.HealInfo.NextHealRound.Sub(now)).StringShort()
|
||||
healPrettyMsg += dot + fmt.Sprintf("Next scheduled in %s\n", console.Colorize("HealBackground", nextHealingRound))
|
||||
}
|
||||
|
||||
return healPrettyMsg
|
||||
}
|
||||
|
||||
@@ -173,7 +207,7 @@ func mainAdminHeal(ctx *cli.Context) error {
|
||||
// Create a new MinIO Admin Client
|
||||
client, err := newAdminClient(aliasedURL)
|
||||
if err != nil {
|
||||
fatalIf(err.Trace(aliasedURL), "Unable to initialize admin client.")
|
||||
fatalIf(err.Trace(aliasedURL), "Cannot initialize admin client.")
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -187,8 +221,7 @@ func mainAdminHeal(ctx *cli.Context) error {
|
||||
fatalIf(err.Trace(clnt.GetURL().String()), "Unable to create client for URL ", aliasedURL)
|
||||
return nil
|
||||
}
|
||||
|
||||
for content := range clnt.List(globalContext, ListOptions{Recursive: false, ShowDir: DirNone}) {
|
||||
for content := range clnt.List(globalContext, false, false, false, DirNone) {
|
||||
if content.Err != nil {
|
||||
fatalIf(content.Err.Trace(clnt.GetURL().String()), "Unable to heal bucket `"+bucket+"`.")
|
||||
return nil
|
||||
|
||||
+11
-48
@@ -35,12 +35,11 @@ import (
|
||||
)
|
||||
|
||||
var adminInfoCmd = cli.Command{
|
||||
Name: "info",
|
||||
Usage: "display MinIO server information",
|
||||
Action: mainAdminInfo,
|
||||
OnUsageError: onUsageError,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
Name: "info",
|
||||
Usage: "display MinIO server information",
|
||||
Action: mainAdminInfo,
|
||||
Before: initBeforeRunningCmd,
|
||||
Flags: globalFlags,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
@@ -79,12 +78,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)), "Unable to get service status")
|
||||
fatal(probe.NewError(errors.New(u.Error)), "Cannot get service status")
|
||||
}
|
||||
|
||||
// If nothing has been collected, error out
|
||||
if u.Info.Servers == nil {
|
||||
fatal(probe.NewError(errors.New("Unable to get service status")), "")
|
||||
fatal(probe.NewError(errors.New("Cannot get service status")), "")
|
||||
}
|
||||
|
||||
// Initialization
|
||||
@@ -94,7 +93,6 @@ 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"
|
||||
@@ -110,11 +108,6 @@ func (u clusterStruct) String() (msg string) {
|
||||
}
|
||||
}
|
||||
|
||||
coloredDot := console.Colorize("Info", dot)
|
||||
if madmin.ItemState(u.Info.Mode) == madmin.ItemInitializing {
|
||||
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),
|
||||
@@ -122,40 +115,13 @@ 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", 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"
|
||||
|
||||
msg += fmt.Sprintf(" Uptime: %s\n\n", console.Colorize("InfoFail", "offline"))
|
||||
// Continue to the next server
|
||||
continue
|
||||
}
|
||||
|
||||
// Print server title
|
||||
msg += fmt.Sprintf("%s %s\n", coloredDot, console.Colorize("PrintB", srv.Endpoint))
|
||||
msg += fmt.Sprintf("%s %s\n", console.Colorize("Info", dot), console.Colorize("PrintB", srv.Endpoint))
|
||||
|
||||
// Uptime
|
||||
msg += fmt.Sprintf(" Uptime: %s\n", console.Colorize("Info",
|
||||
@@ -187,12 +153,9 @@ func (u clusterStruct) String() (msg string) {
|
||||
var OnDisks int
|
||||
var dispNoOfDisks string
|
||||
for _, disk := range srv.Disks {
|
||||
switch disk.State {
|
||||
case madmin.DriveStateOk:
|
||||
fallthrough
|
||||
case madmin.DriveStateUnformatted:
|
||||
if disk.State == "ok" {
|
||||
OnDisks++
|
||||
default:
|
||||
} else {
|
||||
OffDisks++
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,69 +0,0 @@
|
||||
/*
|
||||
* MinIO Client (C) 2020 MinIO, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"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
|
||||
}
|
||||
+21
-46
@@ -19,20 +19,17 @@ 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/console"
|
||||
"github.com/minio/minio/pkg/madmin"
|
||||
)
|
||||
|
||||
var adminKMSKeyStatusCmd = cli.Command{
|
||||
Name: "status",
|
||||
Usage: "request status information for a KMS master key",
|
||||
Action: mainAdminKMSKeyStatus,
|
||||
OnUsageError: onUsageError,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
Name: "status",
|
||||
Usage: "request status information for a KMS master key",
|
||||
Action: mainAdminKMSKeyStatus,
|
||||
Before: initBeforeRunningCmd,
|
||||
Flags: globalFlags,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
@@ -46,7 +43,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
|
||||
`,
|
||||
}
|
||||
|
||||
@@ -56,11 +53,8 @@ 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, "Unable to get a configured admin connection.")
|
||||
fatalIf(err, "Cannot get a configured admin connection.")
|
||||
|
||||
var keyID string
|
||||
if len(ctx.Args()) == 2 {
|
||||
@@ -69,48 +63,29 @@ func mainAdminKMSKeyStatus(ctx *cli.Context) error {
|
||||
status, e := client.GetKeyStatus(globalContext, keyID)
|
||||
fatalIf(probe.NewError(e), "Failed to get status information")
|
||||
|
||||
printMsg(kmsKeyStatusMsg{
|
||||
KeyID: status.KeyID,
|
||||
Encryption: status.EncryptionErr == "",
|
||||
Decryption: status.DecryptionErr == "",
|
||||
EncryptionErr: status.EncryptionErr,
|
||||
DecryptionErr: status.DecryptionErr,
|
||||
})
|
||||
printMsg(kmsKeyStatusMsg(*status))
|
||||
return nil
|
||||
}
|
||||
|
||||
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 {
|
||||
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)
|
||||
}
|
||||
type kmsKeyStatusMsg madmin.KMSKeyStatus
|
||||
|
||||
func (s kmsKeyStatusMsg) String() string {
|
||||
msg := fmt.Sprintf("Key: %s\n", s.KeyID)
|
||||
if s.Encryption {
|
||||
msg += " - Encryption " + console.Colorize("StatusSuccess", "✔") + "\n"
|
||||
if s.EncryptionErr == "" {
|
||||
msg = fmt.Sprintf("%s %s", msg, "\t • Encryption ✔\n")
|
||||
} else {
|
||||
msg += fmt.Sprintf(" - Encryption %s (%s)\n", console.Colorize("StatusError", "✗"), s.EncryptionErr)
|
||||
return fmt.Sprintf("%s \t • Encryption failed: %s\n", msg, s.EncryptionErr)
|
||||
}
|
||||
|
||||
if s.Decryption {
|
||||
msg += " - Decryption " + console.Colorize("StatusSuccess", "✔") + "\n"
|
||||
if s.DecryptionErr == "" {
|
||||
msg = fmt.Sprintf("%s %s", msg, "\t • Decryption ✔\n")
|
||||
} else {
|
||||
msg += fmt.Sprintf(" - Decryption %s (%s)\n", console.Colorize("StatusError", "✗"), s.DecryptionErr)
|
||||
return fmt.Sprintf("%s \t • Decryption failed: %s\n", msg, s.DecryptionErr)
|
||||
}
|
||||
return msg
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
+8
-12
@@ -18,23 +18,19 @@ 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: adminKMSKeySubcommands,
|
||||
Name: "key",
|
||||
Usage: "Manage KMS master keys: Request key status information",
|
||||
Action: mainAdminKMSKey,
|
||||
Flags: globalFlags,
|
||||
Subcommands: []cli.Command{
|
||||
adminKMSKeyStatusCmd,
|
||||
},
|
||||
HideHelpCommand: true,
|
||||
}
|
||||
|
||||
// mainAdminKMSKey is the handle for the "mc admin kms key" command.
|
||||
func mainAdminKMSKey(ctx *cli.Context) error {
|
||||
commandNotFound(ctx, adminKMSKeySubcommands)
|
||||
cli.ShowCommandHelp(ctx, ctx.Args().First())
|
||||
return nil
|
||||
}
|
||||
|
||||
+8
-11
@@ -18,22 +18,19 @@ 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: adminKMSSubcommands,
|
||||
Name: "kms",
|
||||
Usage: "perform KMS management operations",
|
||||
Action: mainAdminKMS,
|
||||
Flags: globalFlags,
|
||||
Subcommands: []cli.Command{
|
||||
adminKMSKeyCmd,
|
||||
},
|
||||
HideHelpCommand: true,
|
||||
}
|
||||
|
||||
// mainAdminKMS is the handle for the "mc admin kms" command.
|
||||
func mainAdminKMS(ctx *cli.Context) error {
|
||||
commandNotFound(ctx, adminKMSSubcommands)
|
||||
cli.ShowCommandHelp(ctx, ctx.Args().First())
|
||||
return nil
|
||||
}
|
||||
|
||||
+19
-23
@@ -29,41 +29,37 @@ 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 {
|
||||
commandNotFound(ctx, adminCmdSubcommands)
|
||||
cli.ShowCommandHelp(ctx, ctx.Args().First())
|
||||
return nil
|
||||
// Sub-commands like "service", "heal", "top" have their own main.
|
||||
}
|
||||
|
||||
@@ -0,0 +1,418 @@
|
||||
/*
|
||||
* MinIO Client (C) 2020 MinIO, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"flag"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"github.com/fatih/color"
|
||||
"github.com/klauspost/compress/gzip"
|
||||
"github.com/minio/cli"
|
||||
cjson "github.com/minio/mc/pkg/colorjson"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/minio/pkg/console"
|
||||
"github.com/minio/minio/pkg/madmin"
|
||||
)
|
||||
|
||||
var adminOBDFlags = []cli.Flag{
|
||||
OBDDataTypeFlag{
|
||||
Name: "tests",
|
||||
Usage: "choose OBD tests to run [" + options.String() + "]",
|
||||
Value: nil,
|
||||
EnvVar: "MC_OBD_DATA",
|
||||
Hidden: true,
|
||||
},
|
||||
cli.DurationFlag{
|
||||
Name: "deadline",
|
||||
Usage: "maximum duration that OBD tests should be allowed to run",
|
||||
Value: 3600 * time.Second,
|
||||
EnvVar: "MC_OBD_DEADLINE",
|
||||
},
|
||||
}
|
||||
|
||||
var adminOBDCmd = cli.Command{
|
||||
Name: "obd",
|
||||
Usage: "run on-board diagnostics",
|
||||
Action: mainAdminOBD,
|
||||
Before: initBeforeRunningCmd,
|
||||
Flags: append(adminOBDFlags, globalFlags...),
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
{{.HelpName}} TARGET
|
||||
|
||||
FLAGS:
|
||||
{{range .VisibleFlags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
1. Get server information of the 'play' MinIO server.
|
||||
{{.Prompt}} {{.HelpName}} play/
|
||||
`,
|
||||
}
|
||||
|
||||
type clusterOBDStruct struct {
|
||||
Status string `json:"status"`
|
||||
Error string `json:"error,omitempty"`
|
||||
Info madmin.OBDInfo `json:"obdInfo,omitempty"`
|
||||
}
|
||||
|
||||
func (u clusterOBDStruct) String() string {
|
||||
u.Status = ""
|
||||
data, err := json.Marshal(u)
|
||||
if err != nil {
|
||||
fatalIf(probe.NewError(err), "unable to marshal into JSON.")
|
||||
}
|
||||
return string(data)
|
||||
}
|
||||
|
||||
// JSON jsonifies service status message.
|
||||
func (u clusterOBDStruct) JSON() string {
|
||||
statusJSONBytes, e := json.MarshalIndent(u, " ", " ")
|
||||
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
|
||||
|
||||
return string(statusJSONBytes)
|
||||
}
|
||||
|
||||
// checkAdminInfoSyntax - validate arguments passed by a user
|
||||
func checkAdminOBDSyntax(ctx *cli.Context) {
|
||||
if len(ctx.Args()) == 0 || len(ctx.Args()) > 1 {
|
||||
cli.ShowCommandHelpAndExit(ctx, "obd", 1) // last argument is exit code
|
||||
}
|
||||
}
|
||||
|
||||
//compress and tar obd output
|
||||
func tarGZ(c clusterOBDStruct, alias string) error {
|
||||
filename := fmt.Sprintf("%s-obd_%s.json.gz", filepath.Clean(alias), time.Now().Format("20060102150405"))
|
||||
f, err := os.OpenFile(filename, os.O_CREATE|os.O_RDWR, 0666)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
defer func() {
|
||||
fmt.Println("OBD data saved to", filename)
|
||||
}()
|
||||
|
||||
gzWriter := gzip.NewWriter(f)
|
||||
defer gzWriter.Close()
|
||||
|
||||
enc := json.NewEncoder(gzWriter)
|
||||
if err := enc.Encode(c); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
warningMsgBoundary := "*********************************************************************************"
|
||||
warning := warnText(" WARNING!!")
|
||||
warningContents := infoText(` ** THIS FILE MAY CONTAIN SENSITIVE INFORMATION ABOUT YOUR ENVIRONMENT **
|
||||
** PLEASE INSPECT CONTENTS BEFORE SHARING IT ON ANY PUBLIC FORUM **`)
|
||||
|
||||
warningMsgHeader := infoText(warningMsgBoundary)
|
||||
warningMsgTrailer := infoText(warningMsgBoundary)
|
||||
fmt.Printf("%s\n%s\n%s\n%s\n", warningMsgHeader, warning, warningContents, warningMsgTrailer)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func infoText(s string) string {
|
||||
console.SetColor("INFO", color.New(color.FgGreen, color.Bold))
|
||||
return console.Colorize("INFO", s)
|
||||
}
|
||||
|
||||
func greenText(s string) string {
|
||||
console.SetColor("GREEN", color.New(color.FgGreen))
|
||||
return console.Colorize("GREEN", s)
|
||||
}
|
||||
|
||||
func warnText(s string) string {
|
||||
console.SetColor("WARN", color.New(color.FgRed, color.Bold))
|
||||
return console.Colorize("WARN", s)
|
||||
}
|
||||
|
||||
func mainAdminOBD(ctx *cli.Context) error {
|
||||
checkAdminOBDSyntax(ctx)
|
||||
|
||||
// Get the alias parameter from cli
|
||||
args := ctx.Args()
|
||||
aliasedURL := args.Get(0)
|
||||
|
||||
// Create a new MinIO Admin Client
|
||||
client, err := newAdminClient(aliasedURL)
|
||||
fatalIf(err, "Unable to initialize admin connection.")
|
||||
|
||||
spinners := []string{"/", "|", "\\", "--", "|"}
|
||||
|
||||
cont, cancel := context.WithCancel(globalContext)
|
||||
defer cancel()
|
||||
|
||||
startSpinner := func(s string) func() {
|
||||
ctx, cancel := context.WithCancel(cont)
|
||||
printText := func(t string, sp string, rewind int) {
|
||||
console.RewindLines(rewind)
|
||||
|
||||
dot := infoText(dot)
|
||||
t = fmt.Sprintf("%s ...", t)
|
||||
t = greenText(t)
|
||||
sp = infoText(sp)
|
||||
toPrint := fmt.Sprintf("%s %s %s ", dot, t, sp)
|
||||
fmt.Printf("%s\n", toPrint)
|
||||
}
|
||||
i := 0
|
||||
sp := func() string {
|
||||
i = i + 1
|
||||
i = i % len(spinners)
|
||||
return spinners[i]
|
||||
}
|
||||
|
||||
done := make(chan bool)
|
||||
doneToggle := false
|
||||
go func() {
|
||||
printText(s, sp(), 0)
|
||||
for {
|
||||
<-time.After(500 * time.Millisecond) //2 fps
|
||||
if ctx.Err() != nil {
|
||||
printText(s, check, 1)
|
||||
done <- true
|
||||
return
|
||||
}
|
||||
printText(s, sp(), 1)
|
||||
}
|
||||
}()
|
||||
return func() {
|
||||
cancel()
|
||||
if !doneToggle {
|
||||
<-done
|
||||
os.Stdout.Sync()
|
||||
doneToggle = true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
spinner := func(resource string) func(bool) bool {
|
||||
var spinStopper func()
|
||||
done := false
|
||||
|
||||
if globalJSON {
|
||||
return func(bool) bool {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
return func(cond bool) bool {
|
||||
if done {
|
||||
return done
|
||||
}
|
||||
if spinStopper == nil {
|
||||
spinStopper = startSpinner(resource)
|
||||
}
|
||||
if cond {
|
||||
spinStopper()
|
||||
done = true
|
||||
}
|
||||
return done
|
||||
}
|
||||
}
|
||||
|
||||
clusterOBDInfo := clusterOBDStruct{}
|
||||
|
||||
admin := spinner("Admin Info")
|
||||
cpu := spinner("CPU")
|
||||
diskHw := spinner("Disk Hardware")
|
||||
osInfo := spinner("Os Info")
|
||||
mem := spinner("Mem Info")
|
||||
process := spinner("Process Info")
|
||||
config := spinner("Config")
|
||||
drive := spinner("Drive")
|
||||
net := spinner("Net")
|
||||
|
||||
progress := func(info madmin.OBDInfo) bool {
|
||||
return admin(len(info.Minio.Info.Servers) > 0) &&
|
||||
cpu(len(info.Sys.CPUInfo) > 0) &&
|
||||
diskHw(len(info.Sys.DiskHwInfo) > 0) &&
|
||||
osInfo(len(info.Sys.OsInfo) > 0) &&
|
||||
mem(len(info.Sys.MemInfo) > 0) &&
|
||||
process(len(info.Sys.ProcInfo) > 0) &&
|
||||
config(info.Minio.Config != nil) &&
|
||||
drive(len(info.Perf.DriveInfo) > 0) &&
|
||||
net(len(info.Perf.Net) > 1)
|
||||
}
|
||||
|
||||
// Fetch info of all servers (cluster or single server)
|
||||
obdChan := client.ServerOBDInfo(cont, options, ctx.Duration("deadline"))
|
||||
for adminOBDInfo := range obdChan {
|
||||
if adminOBDInfo.Error != "" {
|
||||
clusterOBDInfo.Status = "Error"
|
||||
clusterOBDInfo.Error = adminOBDInfo.Error
|
||||
clusterOBDInfo.Info.Error = ""
|
||||
clusterOBDInfo.Info.Minio.Info = madmin.InfoMessage{}
|
||||
break
|
||||
}
|
||||
|
||||
clusterOBDInfo.Status = "Success"
|
||||
clusterOBDInfo.Info = adminOBDInfo
|
||||
progress(adminOBDInfo)
|
||||
}
|
||||
|
||||
// If MinIO is not a global distXL cluster, net will never stop spinning.
|
||||
// add this extra check to ensure that doesn't happen
|
||||
if clusterOBDInfo.Error == "" && !progress(clusterOBDInfo.Info) {
|
||||
net(true)
|
||||
}
|
||||
|
||||
if globalJSON {
|
||||
jsonBytes, err := cjson.MarshalIndent(clusterOBDInfo, "", " ")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Println(string(jsonBytes))
|
||||
return nil
|
||||
}
|
||||
|
||||
if clusterOBDInfo.Error != "" {
|
||||
fmt.Println(warnText("Error obtaining obd information:"), clusterOBDInfo.Error)
|
||||
return nil
|
||||
}
|
||||
|
||||
return tarGZ(clusterOBDInfo, aliasedURL)
|
||||
}
|
||||
|
||||
// OBDDataTypeSlice is a typed list of OBD tests
|
||||
type OBDDataTypeSlice []madmin.OBDDataType
|
||||
|
||||
// Set - sets the flag to the given value
|
||||
func (d *OBDDataTypeSlice) Set(value string) error {
|
||||
for _, v := range strings.Split(value, ",") {
|
||||
if obdData, ok := madmin.OBDDataTypesMap[strings.Trim(v, " ")]; ok {
|
||||
*d = append(*d, obdData)
|
||||
} else {
|
||||
return fmt.Errorf("valid options include %s", options.String())
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// String - returns the string representation of the OBD datatypes
|
||||
func (d *OBDDataTypeSlice) String() string {
|
||||
val := ""
|
||||
for _, obdData := range *d {
|
||||
formatStr := "%s"
|
||||
if val != "" {
|
||||
formatStr = fmt.Sprintf("%s,%%s", formatStr)
|
||||
} else {
|
||||
formatStr = fmt.Sprintf("%s%%s", formatStr)
|
||||
}
|
||||
val = fmt.Sprintf(formatStr, val, string(obdData))
|
||||
}
|
||||
return val
|
||||
}
|
||||
|
||||
// Value - returns the value
|
||||
func (d *OBDDataTypeSlice) Value() []madmin.OBDDataType {
|
||||
return *d
|
||||
}
|
||||
|
||||
// Get - returns the value
|
||||
func (d *OBDDataTypeSlice) Get() interface{} {
|
||||
return *d
|
||||
}
|
||||
|
||||
// OBDDataTypeFlag is a typed flag to represent OBD datatypes
|
||||
type OBDDataTypeFlag struct {
|
||||
Name string
|
||||
Usage string
|
||||
EnvVar string
|
||||
Hidden bool
|
||||
Value *OBDDataTypeSlice
|
||||
}
|
||||
|
||||
// String - returns the string to be shown in the help message
|
||||
func (f OBDDataTypeFlag) String() string {
|
||||
return fmt.Sprintf("--%s %s", f.Name, f.Usage)
|
||||
}
|
||||
|
||||
// GetName - returns the name of the flag
|
||||
func (f OBDDataTypeFlag) GetName() string {
|
||||
return f.Name
|
||||
}
|
||||
|
||||
// GetOBDDataTypeSlice - returns the list of set OBD tests
|
||||
func GetOBDDataTypeSlice(c *cli.Context, name string) *OBDDataTypeSlice {
|
||||
generic := c.Generic(name)
|
||||
if generic == nil {
|
||||
return nil
|
||||
}
|
||||
if obdData, ok := generic.(*OBDDataTypeSlice); ok {
|
||||
return obdData
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetGlobalOBDDataTypeSlice - returns the list of set OBD tests set globally
|
||||
func GetGlobalOBDDataTypeSlice(c *cli.Context, name string) *OBDDataTypeSlice {
|
||||
generic := c.GlobalGeneric(name)
|
||||
if generic == nil {
|
||||
return nil
|
||||
}
|
||||
if obdData, ok := generic.(*OBDDataTypeSlice); ok {
|
||||
return obdData
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Apply - applies the flag
|
||||
func (f OBDDataTypeFlag) Apply(set *flag.FlagSet) {
|
||||
f.ApplyWithError(set)
|
||||
}
|
||||
|
||||
// ApplyWithError - applies with error
|
||||
func (f OBDDataTypeFlag) ApplyWithError(set *flag.FlagSet) error {
|
||||
if f.EnvVar != "" {
|
||||
for _, envVar := range strings.Split(f.EnvVar, ",") {
|
||||
envVar = strings.TrimSpace(envVar)
|
||||
if envVal, ok := syscall.Getenv(envVar); ok {
|
||||
newVal := &OBDDataTypeSlice{}
|
||||
for _, s := range strings.Split(envVal, ",") {
|
||||
s = strings.TrimSpace(s)
|
||||
if err := newVal.Set(s); err != nil {
|
||||
return fmt.Errorf("could not parse %s as OBD datatype value for flag %s: %s", envVal, f.Name, err)
|
||||
}
|
||||
}
|
||||
f.Value = newVal
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for _, name := range strings.Split(f.Name, ",") {
|
||||
name = strings.Trim(name, " ")
|
||||
if f.Value == nil {
|
||||
f.Value = &OBDDataTypeSlice{}
|
||||
}
|
||||
set.Var(f.Value, name, f.Usage)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
var options = OBDDataTypeSlice(madmin.OBDDataTypesList)
|
||||
+11
-23
@@ -30,12 +30,11 @@ import (
|
||||
)
|
||||
|
||||
var adminPolicyAddCmd = cli.Command{
|
||||
Name: "add",
|
||||
Usage: "add new policy",
|
||||
Action: mainAdminPolicyAdd,
|
||||
OnUsageError: onUsageError,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
Name: "add",
|
||||
Usage: "add new policy",
|
||||
Action: mainAdminPolicyAdd,
|
||||
Before: initBeforeRunningCmd,
|
||||
Flags: globalFlags,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
@@ -74,17 +73,6 @@ type userPolicyMessage struct {
|
||||
IsGroup bool `json:"isGroup"`
|
||||
}
|
||||
|
||||
func (u userPolicyMessage) accountType() string {
|
||||
switch u.op {
|
||||
case "set", "unset", "update":
|
||||
if u.IsGroup {
|
||||
return "group"
|
||||
}
|
||||
return "user"
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (u userPolicyMessage) String() string {
|
||||
switch u.op {
|
||||
case "info":
|
||||
@@ -101,14 +89,14 @@ func (u userPolicyMessage) String() string {
|
||||
return console.Colorize("PolicyMessage", "Removed policy `"+u.Policy+"` successfully.")
|
||||
case "add":
|
||||
return console.Colorize("PolicyMessage", "Added policy `"+u.Policy+"` successfully.")
|
||||
case "set", "unset":
|
||||
case "set":
|
||||
fragment := "user"
|
||||
if u.IsGroup {
|
||||
fragment = "group"
|
||||
}
|
||||
return console.Colorize("PolicyMessage",
|
||||
fmt.Sprintf("Policy `%s` is %s on %s `%s`", u.Policy, u.op, u.accountType(), u.UserOrGroup))
|
||||
case "update":
|
||||
return console.Colorize("PolicyMessage",
|
||||
fmt.Sprintf("Policy `%s` is added to %s `%s`", u.Policy, u.accountType(), u.UserOrGroup))
|
||||
fmt.Sprintf("Policy %s is set on %s `%s`", u.Policy, fragment, u.UserOrGroup))
|
||||
}
|
||||
|
||||
return ""
|
||||
}
|
||||
|
||||
|
||||
@@ -26,12 +26,11 @@ import (
|
||||
)
|
||||
|
||||
var adminPolicyInfoCmd = cli.Command{
|
||||
Name: "info",
|
||||
Usage: "show info on a policy",
|
||||
Action: mainAdminPolicyInfo,
|
||||
OnUsageError: onUsageError,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
Name: "info",
|
||||
Usage: "show info on a policy",
|
||||
Action: mainAdminPolicyInfo,
|
||||
Before: initBeforeRunningCmd,
|
||||
Flags: globalFlags,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
@@ -74,7 +73,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...), "Unable to list policy")
|
||||
fatalIf(probe.NewError(e).Trace(args...), "Cannot list policy")
|
||||
|
||||
iamp, ok := policies[policyName]
|
||||
if ok {
|
||||
|
||||
@@ -24,12 +24,11 @@ import (
|
||||
)
|
||||
|
||||
var adminPolicyListCmd = cli.Command{
|
||||
Name: "list",
|
||||
Usage: "list all policies",
|
||||
Action: mainAdminPolicyList,
|
||||
OnUsageError: onUsageError,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
Name: "list",
|
||||
Usage: "list all policies",
|
||||
Action: mainAdminPolicyList,
|
||||
Before: initBeforeRunningCmd,
|
||||
Flags: globalFlags,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
@@ -68,7 +67,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...), "Unable to list policy")
|
||||
fatalIf(probe.NewError(e).Trace(args...), "Cannot list policy")
|
||||
|
||||
for k := range policies {
|
||||
printMsg(userPolicyMessage{
|
||||
|
||||
@@ -24,12 +24,11 @@ import (
|
||||
)
|
||||
|
||||
var adminPolicyRemoveCmd = cli.Command{
|
||||
Name: "remove",
|
||||
Usage: "remove policy",
|
||||
Action: mainAdminPolicyRemove,
|
||||
OnUsageError: onUsageError,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
Name: "remove",
|
||||
Usage: "remove policy",
|
||||
Action: mainAdminPolicyRemove,
|
||||
Before: initBeforeRunningCmd,
|
||||
Flags: globalFlags,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
@@ -69,7 +68,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...), "Unable to remove policy")
|
||||
fatalIf(probe.NewError(client.RemoveCannedPolicy(globalContext, args.Get(1))).Trace(args...), "Cannot remove policy")
|
||||
|
||||
printMsg(userPolicyMessage{
|
||||
op: "remove",
|
||||
|
||||
+12
-10
@@ -27,12 +27,11 @@ import (
|
||||
)
|
||||
|
||||
var adminPolicySetCmd = cli.Command{
|
||||
Name: "set",
|
||||
Usage: "set IAM policy on a user or group",
|
||||
Action: mainAdminPolicySet,
|
||||
OnUsageError: onUsageError,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
Name: "set",
|
||||
Usage: "set IAM policy on a user or group",
|
||||
Action: mainAdminPolicySet,
|
||||
Before: initBeforeRunningCmd,
|
||||
Flags: globalFlags,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
@@ -65,9 +64,11 @@ func checkAdminPolicySetSyntax(ctx *cli.Context) {
|
||||
}
|
||||
|
||||
func parseEntityArg(arg string) (userOrGroup string, isGroup bool, err error) {
|
||||
parts := strings.SplitN(arg, "=", 2)
|
||||
parts := strings.Split(arg, "=")
|
||||
switch {
|
||||
case len(parts) != 2 || parts[1] == "":
|
||||
case len(parts) != 2:
|
||||
fallthrough
|
||||
case parts[1] == "":
|
||||
err = errBadUserGroupArg
|
||||
case strings.ToLower(parts[0]) == "user":
|
||||
userOrGroup = parts[1]
|
||||
@@ -92,7 +93,7 @@ func mainAdminPolicySet(ctx *cli.Context) error {
|
||||
// Get the alias parameter from cli
|
||||
args := ctx.Args()
|
||||
aliasedURL := args.Get(0)
|
||||
policyName := strings.TrimSpace(args.Get(1))
|
||||
policyName := args.Get(1)
|
||||
entityArg := args.Get(2)
|
||||
|
||||
userOrGroup, isGroup, e1 := parseEntityArg(entityArg)
|
||||
@@ -103,6 +104,7 @@ func mainAdminPolicySet(ctx *cli.Context) error {
|
||||
fatalIf(err, "Unable to initialize admin connection.")
|
||||
|
||||
e := client.SetPolicy(globalContext, policyName, userOrGroup, isGroup)
|
||||
|
||||
if e == nil {
|
||||
printMsg(userPolicyMessage{
|
||||
op: "set",
|
||||
@@ -111,7 +113,7 @@ func mainAdminPolicySet(ctx *cli.Context) error {
|
||||
IsGroup: isGroup,
|
||||
})
|
||||
} else {
|
||||
fatalIf(probe.NewError(e), "Unable to set the policy")
|
||||
fatalIf(probe.NewError(e), "Cannot set the policy")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -1,136 +0,0 @@
|
||||
/*
|
||||
* MinIO Client (C) 2021 MinIO, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/minio/pkg/console"
|
||||
)
|
||||
|
||||
var adminPolicyUnsetCmd = cli.Command{
|
||||
Name: "unset",
|
||||
Usage: "unset an IAM policy for a user or group",
|
||||
Action: mainAdminPolicyUnset,
|
||||
OnUsageError: onUsageError,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
{{.HelpName}} TARGET POLICYNAME [ user=username1 | group=groupname1 ]
|
||||
|
||||
POLICYNAME:
|
||||
Name of the policy on the MinIO server.
|
||||
|
||||
FLAGS:
|
||||
{{range .VisibleFlags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
1. Unset the "diagnostics" policy for user "james".
|
||||
{{.Prompt}} {{.HelpName}} myminio diagnostics user=james
|
||||
|
||||
2. Set the "diagnostics" policy for group "auditors".
|
||||
{{.Prompt}} {{.HelpName}} myminio diagnostics group=auditors
|
||||
`,
|
||||
}
|
||||
|
||||
func checkAdminPolicyUnsetSyntax(ctx *cli.Context) {
|
||||
if len(ctx.Args()) != 3 {
|
||||
cli.ShowCommandHelpAndExit(ctx, "unset", 1) // last argument is exit code
|
||||
}
|
||||
}
|
||||
|
||||
func removeCannedPolicies(existingPolicies, policiesToRemove string) (string, error) {
|
||||
policiesToRemove = strings.TrimSpace(policiesToRemove)
|
||||
if policiesToRemove == "" {
|
||||
return "", errors.New("empty policy name is not supported")
|
||||
}
|
||||
filteredPolicies := strings.Split(existingPolicies, ",")
|
||||
for _, p1 := range strings.Split(policiesToRemove, ",") {
|
||||
found := false
|
||||
for i, p2 := range filteredPolicies {
|
||||
if p1 == p2 {
|
||||
found = true
|
||||
filteredPolicies = append(filteredPolicies[:i], filteredPolicies[i+1:]...)
|
||||
break
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
return "", fmt.Errorf("policy `%s` not found", p1)
|
||||
}
|
||||
|
||||
}
|
||||
return strings.Join(filteredPolicies, ","), nil
|
||||
}
|
||||
|
||||
// mainAdminPolicyUnset is the handler for "mc admin policy unset" command.
|
||||
func mainAdminPolicyUnset(ctx *cli.Context) error {
|
||||
checkAdminPolicyUnsetSyntax(ctx)
|
||||
|
||||
console.SetColor("PolicyMessage", color.New(color.FgGreen))
|
||||
console.SetColor("Policy", color.New(color.FgBlue))
|
||||
|
||||
// Get the alias parameter from cli
|
||||
args := ctx.Args()
|
||||
aliasedURL := args.Get(0)
|
||||
policiesToUnset := args.Get(1)
|
||||
entityArg := args.Get(2)
|
||||
|
||||
userOrGroup, isGroup, e1 := parseEntityArg(entityArg)
|
||||
fatalIf(probe.NewError(e1).Trace(args...), "Bad last argument")
|
||||
|
||||
// Create a new MinIO Admin Client
|
||||
client, err := newAdminClient(aliasedURL)
|
||||
fatalIf(err, "Unable to initialize admin connection.")
|
||||
|
||||
var existingPolicies string
|
||||
|
||||
if !isGroup {
|
||||
userInfo, e := client.GetUserInfo(globalContext, userOrGroup)
|
||||
fatalIf(probe.NewError(e).Trace(args...), "Unable to get user policy info")
|
||||
existingPolicies = userInfo.PolicyName
|
||||
} else {
|
||||
groupInfo, e := client.GetGroupDescription(globalContext, userOrGroup)
|
||||
fatalIf(probe.NewError(e).Trace(args...), "Unable to get group policy info")
|
||||
existingPolicies = groupInfo.Policy
|
||||
}
|
||||
|
||||
newPolicies, e := removeCannedPolicies(existingPolicies, policiesToUnset)
|
||||
if e != nil {
|
||||
fatalIf(probe.NewError(e).Trace(args...), "Unable to unset the policy")
|
||||
}
|
||||
|
||||
e = client.SetPolicy(globalContext, newPolicies, userOrGroup, isGroup)
|
||||
if e == nil {
|
||||
printMsg(userPolicyMessage{
|
||||
op: "unset",
|
||||
Policy: policiesToUnset,
|
||||
UserOrGroup: userOrGroup,
|
||||
IsGroup: isGroup,
|
||||
})
|
||||
} else {
|
||||
fatalIf(probe.NewError(e), "Unable to unset the policy")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -1,141 +0,0 @@
|
||||
/*
|
||||
* MinIO Client (C) 2021 MinIO, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/minio/pkg/console"
|
||||
)
|
||||
|
||||
var adminPolicyUpdateCmd = cli.Command{
|
||||
Name: "update",
|
||||
Usage: "Attach new IAM policy to a user or group",
|
||||
Action: mainAdminPolicyUpdate,
|
||||
OnUsageError: onUsageError,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
{{.HelpName}} TARGET POLICYNAME [ user=username1 | group=groupname1 ]
|
||||
|
||||
POLICYNAME:
|
||||
Name of the policy on the MinIO server.
|
||||
|
||||
FLAGS:
|
||||
{{range .VisibleFlags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
1. Add the "diagnostics" policy for user "james".
|
||||
{{.Prompt}} {{.HelpName}} myminio diagnostics user=james
|
||||
|
||||
2. add the "diagnostics" policy for group "auditors".
|
||||
{{.Prompt}} {{.HelpName}} myminio diagnostics group=auditors
|
||||
`,
|
||||
}
|
||||
|
||||
func checkAdminPolicyUpdateSyntax(ctx *cli.Context) {
|
||||
if len(ctx.Args()) != 3 {
|
||||
cli.ShowCommandHelpAndExit(ctx, "update", 1) // last argument is exit code
|
||||
}
|
||||
}
|
||||
|
||||
func updateCannedPolicies(existingPolicies, policiesToAdd string) (string, error) {
|
||||
policiesToAdd = strings.TrimSpace(policiesToAdd)
|
||||
if policiesToAdd == "" {
|
||||
return "", errors.New("empty policy name is unsupported")
|
||||
}
|
||||
var updatedPolicies []string
|
||||
if existingPolicies != "" {
|
||||
updatedPolicies = strings.Split(existingPolicies, ",")
|
||||
}
|
||||
|
||||
for _, p1 := range strings.Split(policiesToAdd, ",") {
|
||||
found := false
|
||||
p1 = strings.TrimSpace(p1)
|
||||
for _, p2 := range updatedPolicies {
|
||||
if p1 == p2 {
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if found {
|
||||
return "", fmt.Errorf("policy `%s` already exists", p1)
|
||||
}
|
||||
updatedPolicies = append(updatedPolicies, p1)
|
||||
}
|
||||
|
||||
return strings.Join(updatedPolicies, ","), nil
|
||||
}
|
||||
|
||||
// mainAdminPolicyUpdate is the handler for "mc admin policy update" command.
|
||||
func mainAdminPolicyUpdate(ctx *cli.Context) error {
|
||||
checkAdminPolicyUpdateSyntax(ctx)
|
||||
|
||||
console.SetColor("PolicyMessage", color.New(color.FgGreen))
|
||||
console.SetColor("Policy", color.New(color.FgBlue))
|
||||
|
||||
// Get the alias parameter from cli
|
||||
args := ctx.Args()
|
||||
aliasedURL := args.Get(0)
|
||||
policiesToAdd := args.Get(1)
|
||||
entityArg := args.Get(2)
|
||||
|
||||
userOrGroup, isGroup, e1 := parseEntityArg(entityArg)
|
||||
fatalIf(probe.NewError(e1).Trace(args...), "Bad last argument")
|
||||
|
||||
// Create a new MinIO Admin Client
|
||||
client, err := newAdminClient(aliasedURL)
|
||||
fatalIf(err, "Unable to initialize admin connection.")
|
||||
|
||||
var existingPolicies string
|
||||
|
||||
if !isGroup {
|
||||
userInfo, e := client.GetUserInfo(globalContext, userOrGroup)
|
||||
fatalIf(probe.NewError(e).Trace(args...), "Unable to get user policy info")
|
||||
existingPolicies = userInfo.PolicyName
|
||||
} else {
|
||||
groupInfo, e := client.GetGroupDescription(globalContext, userOrGroup)
|
||||
fatalIf(probe.NewError(e).Trace(args...), "Unable to get group policy info")
|
||||
existingPolicies = groupInfo.Policy
|
||||
}
|
||||
|
||||
updatedPolicies, e := updateCannedPolicies(existingPolicies, policiesToAdd)
|
||||
if err != nil {
|
||||
fatalIf(probe.NewError(e).Trace(args...), "Unable to update the policy")
|
||||
}
|
||||
|
||||
e = client.SetPolicy(globalContext, updatedPolicies, userOrGroup, isGroup)
|
||||
if e == nil {
|
||||
printMsg(userPolicyMessage{
|
||||
op: "update",
|
||||
Policy: policiesToAdd,
|
||||
UserOrGroup: userOrGroup,
|
||||
IsGroup: isGroup,
|
||||
})
|
||||
} else {
|
||||
fatalIf(probe.NewError(e), "Unable to unset the policy")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
+12
-17
@@ -18,29 +18,24 @@ package cmd
|
||||
|
||||
import "github.com/minio/cli"
|
||||
|
||||
var adminPolicySubcommands = []cli.Command{
|
||||
adminPolicyAddCmd,
|
||||
adminPolicyRemoveCmd,
|
||||
adminPolicyListCmd,
|
||||
adminPolicyInfoCmd,
|
||||
adminPolicySetCmd,
|
||||
adminPolicyUnsetCmd,
|
||||
adminPolicyUpdateCmd,
|
||||
}
|
||||
|
||||
var adminPolicyCmd = cli.Command{
|
||||
Name: "policy",
|
||||
Usage: "manage policies defined in the MinIO server",
|
||||
Action: mainAdminPolicy,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
Subcommands: adminPolicySubcommands,
|
||||
Name: "policy",
|
||||
Usage: "manage policies defined in the MinIO server",
|
||||
Action: mainAdminPolicy,
|
||||
Flags: globalFlags,
|
||||
Subcommands: []cli.Command{
|
||||
adminPolicyAddCmd,
|
||||
adminPolicyRemoveCmd,
|
||||
adminPolicyListCmd,
|
||||
adminPolicyInfoCmd,
|
||||
adminPolicySetCmd,
|
||||
},
|
||||
HideHelpCommand: true,
|
||||
}
|
||||
|
||||
// mainAdminPolicy is the handle for "mc admin policy" command.
|
||||
func mainAdminPolicy(ctx *cli.Context) error {
|
||||
commandNotFound(ctx, adminPolicySubcommands)
|
||||
cli.ShowCommandHelp(ctx, ctx.Args().First())
|
||||
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/v7/pkg/set"
|
||||
"github.com/minio/minio-go/v6/pkg/set"
|
||||
"github.com/minio/minio/pkg/console"
|
||||
"github.com/minio/minio/pkg/madmin"
|
||||
)
|
||||
@@ -30,7 +30,7 @@ var adminProfileStartFlags = []cli.Flag{
|
||||
cli.StringFlag{
|
||||
Name: "type",
|
||||
Usage: "start profiler type, possible values are 'cpu', 'mem', 'block', 'mutex', 'trace', 'threads' and 'goroutines'",
|
||||
Value: "cpu,mem,block,goroutines",
|
||||
Value: "cpu,mem,block",
|
||||
},
|
||||
}
|
||||
|
||||
@@ -38,8 +38,7 @@ var adminProfileStartCmd = cli.Command{
|
||||
Name: "start",
|
||||
Usage: "start recording profile data",
|
||||
Action: mainAdminProfileStart,
|
||||
OnUsageError: onUsageError,
|
||||
Before: setGlobalsFromContext,
|
||||
Before: initBeforeRunningCmd,
|
||||
Flags: append(adminProfileStartFlags, globalFlags...),
|
||||
HideHelpCommand: true,
|
||||
CustomHelpTemplate: `NAME:
|
||||
@@ -110,7 +109,7 @@ func mainAdminProfileStart(ctx *cli.Context) error {
|
||||
// Create a new MinIO Admin Client
|
||||
client, err := newAdminClient(aliasedURL)
|
||||
if err != nil {
|
||||
fatalIf(err.Trace(aliasedURL), "Unable to initialize admin client.")
|
||||
fatalIf(err.Trace(aliasedURL), "Cannot initialize admin client.")
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
@@ -31,8 +31,7 @@ var adminProfileStopCmd = cli.Command{
|
||||
Name: "stop",
|
||||
Usage: "stop and download profile data",
|
||||
Action: mainAdminProfileStop,
|
||||
OnUsageError: onUsageError,
|
||||
Before: setGlobalsFromContext,
|
||||
Before: initBeforeRunningCmd,
|
||||
Flags: globalFlags,
|
||||
HideHelpCommand: true,
|
||||
CustomHelpTemplate: `NAME:
|
||||
@@ -95,7 +94,7 @@ func mainAdminProfileStop(ctx *cli.Context) error {
|
||||
// Create a new MinIO Admin Client
|
||||
client, err := newAdminClient(aliasedURL)
|
||||
if err != nil {
|
||||
fatalIf(err.Trace(aliasedURL), "Unable to initialize admin client.")
|
||||
fatalIf(err.Trace(aliasedURL), "Cannot initialize admin client.")
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
+9
-13
@@ -20,24 +20,20 @@ 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,
|
||||
OnUsageError: onUsageError,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
Subcommands: adminProfileSubcommands,
|
||||
Name: "profile",
|
||||
Usage: "generate profile data for debugging purposes",
|
||||
Action: mainAdminProfile,
|
||||
Flags: globalFlags,
|
||||
Subcommands: []cli.Command{
|
||||
adminProfileStartCmd,
|
||||
adminProfileStopCmd,
|
||||
},
|
||||
HideHelpCommand: true,
|
||||
}
|
||||
|
||||
// mainAdminProfile is the handle for "mc admin profile" command.
|
||||
func mainAdminProfile(ctx *cli.Context) error {
|
||||
commandNotFound(ctx, adminProfileSubcommands)
|
||||
cli.ShowCommandHelp(ctx, ctx.Args().First())
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -33,16 +33,14 @@ import (
|
||||
|
||||
const (
|
||||
defaultJobName = "minio-job"
|
||||
legacyMetricsPath = "/minio/prometheus/metrics"
|
||||
defaultMetricsPath = "/minio/v2/metrics/cluster"
|
||||
defaultMetricsPath = "/minio/prometheus/metrics"
|
||||
)
|
||||
|
||||
var adminPrometheusGenerateCmd = cli.Command{
|
||||
Name: "generate",
|
||||
Usage: "generates prometheus config",
|
||||
Action: mainAdminPrometheusGenerate,
|
||||
OnUsageError: onUsageError,
|
||||
Before: setGlobalsFromContext,
|
||||
Before: initBeforeRunningCmd,
|
||||
Flags: globalFlags,
|
||||
HideHelpCommand: true,
|
||||
CustomHelpTemplate: `NAME:
|
||||
@@ -129,19 +127,6 @@ var defaultConfig = PrometheusConfig{
|
||||
},
|
||||
},
|
||||
}
|
||||
var legacyConfig = PrometheusConfig{
|
||||
ScrapeConfigs: []ScrapeConfig{
|
||||
{
|
||||
JobName: defaultJobName,
|
||||
MetricsPath: legacyMetricsPath,
|
||||
StaticConfigs: []StatConfig{
|
||||
{
|
||||
Targets: []string{""},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
// checkAdminPrometheusSyntax - validate all the passed arguments
|
||||
func checkAdminPrometheusSyntax(ctx *cli.Context) {
|
||||
@@ -180,20 +165,6 @@ func generatePrometheusConfig(ctx *cli.Context) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
client, cerr := newAdminClient(alias)
|
||||
fatalIf(cerr, "Unable to initialize admin connection.")
|
||||
|
||||
info, e := client.ServerInfo(globalContext)
|
||||
if e != nil {
|
||||
fatalIf(probe.NewError(e), "Failed to get server info.")
|
||||
}
|
||||
if info.Servers[0].Version < "2021-01-30T00-20-58Z" {
|
||||
legacyConfig.ScrapeConfigs[0].BearerToken = token
|
||||
legacyConfig.ScrapeConfigs[0].Scheme = u.Scheme
|
||||
legacyConfig.ScrapeConfigs[0].StaticConfigs[0].Targets[0] = u.Host
|
||||
printMsg(legacyConfig)
|
||||
return nil
|
||||
}
|
||||
|
||||
// Setting the values
|
||||
defaultConfig.ScrapeConfigs[0].BearerToken = token
|
||||
|
||||
@@ -18,18 +18,15 @@ package cmd
|
||||
|
||||
import "github.com/minio/cli"
|
||||
|
||||
var adminPrometheusSubcommands = []cli.Command{
|
||||
adminPrometheusGenerateCmd,
|
||||
}
|
||||
|
||||
var adminPrometheusCmd = cli.Command{
|
||||
Name: "prometheus",
|
||||
Usage: "manages prometheus config",
|
||||
Action: mainAdminPrometheus,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
HideHelpCommand: true,
|
||||
Subcommands: adminPrometheusSubcommands,
|
||||
Subcommands: []cli.Command{
|
||||
adminPrometheusGenerateCmd,
|
||||
},
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
@@ -44,6 +41,6 @@ FLAGS:
|
||||
|
||||
// mainAdminPrometheus is the handle for "mc admin prometheus" command.
|
||||
func mainAdminPrometheus(ctx *cli.Context) error {
|
||||
commandNotFound(ctx, adminPrometheusSubcommands)
|
||||
cli.ShowCommandHelp(ctx, ctx.Args().First())
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -17,7 +17,6 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/fatih/color"
|
||||
@@ -25,16 +24,14 @@ import (
|
||||
json "github.com/minio/mc/pkg/colorjson"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/minio/pkg/console"
|
||||
"github.com/minio/minio/pkg/madmin"
|
||||
)
|
||||
|
||||
var adminServiceRestartCmd = cli.Command{
|
||||
Name: "restart",
|
||||
Usage: "restart all MinIO servers",
|
||||
Action: mainAdminServiceRestart,
|
||||
OnUsageError: onUsageError,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
Name: "restart",
|
||||
Usage: "restart all MinIO servers",
|
||||
Action: mainAdminServiceRestart,
|
||||
Before: initBeforeRunningCmd,
|
||||
Flags: globalFlags,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
@@ -58,7 +55,7 @@ type serviceRestartCommand struct {
|
||||
|
||||
// String colorized service restart command message.
|
||||
func (s serviceRestartCommand) String() string {
|
||||
return console.Colorize("ServiceRestart", "Restart command successfully sent to `"+s.ServerURL+"`. Type Ctrl-C or wait to see the status of the restart.")
|
||||
return console.Colorize("ServiceRestart", "Restart command successfully sent to `"+s.ServerURL+"`.")
|
||||
}
|
||||
|
||||
// JSON jsonified service restart command message.
|
||||
@@ -79,7 +76,7 @@ type serviceRestartMessage struct {
|
||||
// String colorized service restart message.
|
||||
func (s serviceRestartMessage) String() string {
|
||||
if s.Err == nil {
|
||||
return console.Colorize("ServiceRestart", "\nRestarted `"+s.ServerURL+"` successfully.")
|
||||
return console.Colorize("ServiceRestart", "Restarted `"+s.ServerURL+"` successfully.")
|
||||
}
|
||||
return console.Colorize("FailedServiceRestart", "Failed to restart `"+s.ServerURL+"`. error: "+s.Err.Error())
|
||||
}
|
||||
@@ -105,8 +102,6 @@ func mainAdminServiceRestart(ctx *cli.Context) error {
|
||||
checkAdminServiceRestartSyntax(ctx)
|
||||
|
||||
// Set color.
|
||||
console.SetColor("ServiceOffline", color.New(color.FgRed, color.Bold))
|
||||
console.SetColor("ServiceInitializing", color.New(color.FgYellow, color.Bold))
|
||||
console.SetColor("ServiceRestart", color.New(color.FgGreen, color.Bold))
|
||||
console.SetColor("FailedServiceRestart", color.New(color.FgRed, color.Bold))
|
||||
|
||||
@@ -118,41 +113,25 @@ func mainAdminServiceRestart(ctx *cli.Context) error {
|
||||
fatalIf(err, "Unable to initialize admin connection.")
|
||||
|
||||
// Restart the specified MinIO server
|
||||
fatalIf(probe.NewError(client.ServiceRestart(globalContext)), "Unable to restart the server.")
|
||||
fatalIf(probe.NewError(client.ServiceRestart(globalContext)), "Cannot restart the server.")
|
||||
|
||||
// Success..
|
||||
printMsg(serviceRestartCommand{Status: "success", ServerURL: aliasedURL})
|
||||
|
||||
coloring := color.New(color.FgRed)
|
||||
mark := "."
|
||||
// Max. time taken by the server to shutdown is 5 seconds.
|
||||
// This can happen when there are lot of s3 requests pending when the server
|
||||
// receives a restart command.
|
||||
// Sleep for 6 seconds and then check if the server is online.
|
||||
time.Sleep(6 * time.Second)
|
||||
|
||||
// Print restart progress
|
||||
printProgress := func() {
|
||||
if !globalQuiet && !globalJSON {
|
||||
coloring.Printf(mark)
|
||||
}
|
||||
// Fetch the service status of the specified MinIO server
|
||||
_, e := client.ServerInfo(globalContext)
|
||||
|
||||
if e != nil {
|
||||
printMsg(serviceRestartMessage{Status: "failure", Err: e, ServerURL: aliasedURL})
|
||||
} else {
|
||||
printMsg(serviceRestartMessage{Status: "success", ServerURL: aliasedURL})
|
||||
}
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-globalContext.Done():
|
||||
return globalContext.Err()
|
||||
case <-time.NewTimer(3 * time.Second).C:
|
||||
ctx, cancel := context.WithTimeout(globalContext, 1*time.Second)
|
||||
// Fetch the service status of the specified MinIO server
|
||||
info, e := client.ServerInfo(ctx)
|
||||
cancel()
|
||||
switch {
|
||||
case e == nil && info.Mode == string(madmin.ItemOnline):
|
||||
printMsg(serviceRestartMessage{Status: "success", ServerURL: aliasedURL})
|
||||
return nil
|
||||
case err == nil && info.Mode == string(madmin.ItemInitializing):
|
||||
coloring = color.New(color.FgYellow)
|
||||
mark = "!"
|
||||
fallthrough
|
||||
default:
|
||||
printProgress()
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -25,12 +25,11 @@ import (
|
||||
)
|
||||
|
||||
var adminServiceStopCmd = cli.Command{
|
||||
Name: "stop",
|
||||
Usage: "stop MinIO server",
|
||||
Action: mainAdminServiceStop,
|
||||
OnUsageError: onUsageError,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
Name: "stop",
|
||||
Usage: "stop MinIO server",
|
||||
Action: mainAdminServiceStop,
|
||||
Before: initBeforeRunningCmd,
|
||||
Flags: globalFlags,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
|
||||
@@ -18,24 +18,21 @@ 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",
|
||||
Action: mainAdminService,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
HideHelpCommand: true,
|
||||
Subcommands: adminServiceSubcommands,
|
||||
Subcommands: []cli.Command{
|
||||
adminServiceRestartCmd,
|
||||
adminServiceStopCmd,
|
||||
},
|
||||
}
|
||||
|
||||
// mainAdmin is the handle for "mc admin service" command.
|
||||
func mainAdminService(ctx *cli.Context) error {
|
||||
commandNotFound(ctx, adminServiceSubcommands)
|
||||
cli.ShowCommandHelp(ctx, ctx.Args().First())
|
||||
return nil
|
||||
// Sub-commands like "status", "restart" have their own main.
|
||||
}
|
||||
|
||||
@@ -1,505 +0,0 @@
|
||||
/*
|
||||
* MinIO Client (C) 2020 MinIO, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
gojson "encoding/json"
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"mime/multipart"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"github.com/fatih/color"
|
||||
"github.com/klauspost/compress/gzip"
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/minio/pkg/console"
|
||||
"github.com/minio/minio/pkg/madmin"
|
||||
"github.com/tidwall/gjson"
|
||||
)
|
||||
|
||||
var adminHealthFlags = []cli.Flag{
|
||||
HealthDataTypeFlag{
|
||||
Name: "test",
|
||||
Usage: "choose health tests to run [" + options.String() + "]",
|
||||
Value: nil,
|
||||
EnvVar: "MC_HEALTH_TEST,MC_OBD_TEST",
|
||||
Hidden: true,
|
||||
},
|
||||
cli.DurationFlag{
|
||||
Name: "deadline",
|
||||
Usage: "maximum duration that health tests should be allowed to run",
|
||||
Value: 3600 * time.Second,
|
||||
EnvVar: "MC_HEALTH_DEADLINE,MC_OBD_DEADLINE",
|
||||
},
|
||||
cli.StringFlag{
|
||||
Name: "license",
|
||||
Usage: "Subnet license key",
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "dev",
|
||||
Usage: "Development mode",
|
||||
Hidden: true,
|
||||
},
|
||||
}
|
||||
|
||||
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}}
|
||||
|
||||
USAGE:
|
||||
{{.HelpName}} TARGET
|
||||
|
||||
FLAGS:
|
||||
{{range .VisibleFlags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
1. Get server information of the 'play' MinIO server.
|
||||
{{.Prompt}} {{.HelpName}} play/
|
||||
`,
|
||||
}
|
||||
|
||||
// checkAdminHealthSyntax - validate arguments passed by a user
|
||||
func checkAdminHealthSyntax(ctx *cli.Context) {
|
||||
if len(ctx.Args()) == 0 || len(ctx.Args()) > 1 {
|
||||
cli.ShowCommandHelpAndExit(ctx, "health", 1) // last argument is exit code
|
||||
}
|
||||
}
|
||||
|
||||
//compress and tar health report output
|
||||
func tarGZ(c HealthReportInfo, filename string) error {
|
||||
f, err := os.OpenFile(filename, os.O_CREATE|os.O_RDWR, 0666)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
defer func() {
|
||||
console.Infoln("Health data saved at", filename)
|
||||
}()
|
||||
|
||||
gzWriter := gzip.NewWriter(f)
|
||||
defer gzWriter.Close()
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
warningMsgBoundary := "*********************************************************************************"
|
||||
warning := warnText(" WARNING!!")
|
||||
warningContents := infoText(` ** THIS FILE MAY CONTAIN SENSITIVE INFORMATION ABOUT YOUR ENVIRONMENT **
|
||||
** PLEASE INSPECT CONTENTS BEFORE SHARING IT ON ANY PUBLIC FORUM **`)
|
||||
|
||||
warningMsgHeader := infoText(warningMsgBoundary)
|
||||
warningMsgTrailer := infoText(warningMsgBoundary)
|
||||
console.Printf("%s\n%s\n%s\n%s\n", warningMsgHeader, warning, warningContents, warningMsgTrailer)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func infoText(s string) string {
|
||||
console.SetColor("INFO", color.New(color.FgGreen, color.Bold))
|
||||
return console.Colorize("INFO", s)
|
||||
}
|
||||
|
||||
func greenText(s string) string {
|
||||
console.SetColor("GREEN", color.New(color.FgGreen))
|
||||
return console.Colorize("GREEN", s)
|
||||
}
|
||||
|
||||
func warnText(s string) string {
|
||||
console.SetColor("WARN", color.New(color.FgRed, color.Bold))
|
||||
return console.Colorize("WARN", s)
|
||||
}
|
||||
|
||||
func mainAdminHealth(ctx *cli.Context) error {
|
||||
checkAdminHealthSyntax(ctx)
|
||||
|
||||
// Get the alias parameter from cli
|
||||
args := ctx.Args()
|
||||
aliasedURL := args.Get(0)
|
||||
|
||||
// Create a new MinIO Admin Client
|
||||
client, err := newAdminClient(aliasedURL)
|
||||
fatalIf(err, "Unable to initialize admin connection.")
|
||||
|
||||
healthInfo, e := fetchServerHealthInfo(ctx, client)
|
||||
clusterHealthInfo := MapHealthInfoToV1(healthInfo, e)
|
||||
|
||||
if globalJSON {
|
||||
printMsg(clusterHealthInfo)
|
||||
return nil
|
||||
}
|
||||
|
||||
if clusterHealthInfo.GetError() != "" {
|
||||
e = errors.New(clusterHealthInfo.GetError())
|
||||
fatalIf(probe.NewError(e), "Unable to obtain health information")
|
||||
}
|
||||
|
||||
filename := fmt.Sprintf("%s-health_%s.json.gz", filepath.Clean(aliasedURL), time.Now().Format("20060102150405"))
|
||||
e = tarGZ(clusterHealthInfo, filename)
|
||||
fatalIf(probe.NewError(e), "Unable to create health report file")
|
||||
|
||||
license := ctx.String("license")
|
||||
if len(license) > 0 {
|
||||
e = uploadHealthReport(aliasedURL, filename, license, ctx.Bool("dev"))
|
||||
fatalIf(probe.NewError(e), "Unable to upload health report to Subnet portal")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func uploadHealthReport(alias string, filename string, license string, dev bool) error {
|
||||
uploadURL := subnetUploadURL(alias, filename, license, dev)
|
||||
req, e := subnetUploadReq(uploadURL, filename)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
|
||||
resp, herr := httpClient(10 * time.Second).Do(req)
|
||||
if herr != nil {
|
||||
return herr
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
var respBody []byte
|
||||
respBody, e = ioutil.ReadAll(resp.Body)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
|
||||
if resp.StatusCode == http.StatusOK {
|
||||
msg := "MinIO Health data was successfully uploaded to Subnet."
|
||||
clusterURL, _ := url.PathUnescape(gjson.Get(string(respBody), "cluster_url").String())
|
||||
if len(clusterURL) > 0 {
|
||||
msg += fmt.Sprintf(" Can be viewed at: %s", clusterURL)
|
||||
}
|
||||
console.Infoln(msg)
|
||||
return nil
|
||||
}
|
||||
|
||||
return fmt.Errorf("Upload to subnet failed with status code %d: %s", resp.StatusCode, respBody)
|
||||
}
|
||||
|
||||
func subnetUploadURL(alias string, filename string, license string, dev bool) string {
|
||||
const apiPath = "/api/auth/health_reports"
|
||||
baseURL := "https://subnet.min.io"
|
||||
if dev {
|
||||
baseURL = "http://localhost:9000"
|
||||
}
|
||||
return fmt.Sprintf("%s%s?license=%s&clustername=%s&filename=%s", baseURL, apiPath, license, alias, filename)
|
||||
}
|
||||
|
||||
func subnetUploadReq(url string, filename string) (*http.Request, error) {
|
||||
console.Println(infoText("Uploading health report to subnet"))
|
||||
|
||||
file, _ := os.Open(filename)
|
||||
defer file.Close()
|
||||
|
||||
body := &bytes.Buffer{}
|
||||
writer := multipart.NewWriter(body)
|
||||
part, err := writer.CreateFormFile("file", filepath.Base(file.Name()))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
_, err = io.Copy(part, file)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
writer.Close()
|
||||
|
||||
r, _ := http.NewRequest("POST", url, body)
|
||||
r.Header.Add("Content-Type", writer.FormDataContentType())
|
||||
|
||||
return r, nil
|
||||
}
|
||||
|
||||
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)
|
||||
defer cancel()
|
||||
|
||||
startSpinner := func(s string) func() {
|
||||
ctx, cancel := context.WithCancel(cont)
|
||||
printText := func(t string, sp string, rewind int) {
|
||||
console.RewindLines(rewind)
|
||||
|
||||
dot := infoText(dot)
|
||||
t = fmt.Sprintf("%s ...", t)
|
||||
t = greenText(t)
|
||||
sp = infoText(sp)
|
||||
toPrint := fmt.Sprintf("%s %s %s ", dot, t, sp)
|
||||
console.Printf("%s\n", toPrint)
|
||||
}
|
||||
i := 0
|
||||
sp := func() string {
|
||||
i = i + 1
|
||||
i = i % len(spinners)
|
||||
return spinners[i]
|
||||
}
|
||||
|
||||
done := make(chan bool)
|
||||
doneToggle := false
|
||||
go func() {
|
||||
printText(s, sp(), 0)
|
||||
for {
|
||||
time.Sleep(500 * time.Millisecond) // 2 fps
|
||||
if ctx.Err() != nil {
|
||||
printText(s, check, 1)
|
||||
done <- true
|
||||
return
|
||||
}
|
||||
printText(s, sp(), 1)
|
||||
}
|
||||
}()
|
||||
return func() {
|
||||
cancel()
|
||||
if !doneToggle {
|
||||
<-done
|
||||
os.Stdout.Sync()
|
||||
doneToggle = true
|
||||
}
|
||||
}
|
||||
}
|
||||
spinner := func(resource string, opt madmin.HealthDataType) func(bool) bool {
|
||||
var spinStopper func()
|
||||
done := false
|
||||
|
||||
_, ok := optsMap[opt] // check if option is enabled
|
||||
if globalJSON || !ok {
|
||||
return func(bool) bool {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
return func(cond bool) bool {
|
||||
if done {
|
||||
return done
|
||||
}
|
||||
if spinStopper == nil {
|
||||
spinStopper = startSpinner(resource)
|
||||
}
|
||||
if cond {
|
||||
done = true
|
||||
spinStopper()
|
||||
}
|
||||
return done
|
||||
}
|
||||
}
|
||||
|
||||
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)
|
||||
|
||||
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) &&
|
||||
mem(len(info.Sys.MemInfo) > 0) &&
|
||||
process(len(info.Sys.ProcInfo) > 0) &&
|
||||
config(info.Minio.Config != nil) &&
|
||||
drive(len(info.Perf.DriveInfo) > 0) &&
|
||||
net(len(info.Perf.Net) > 1 && len(info.Perf.NetParallel.Addr) > 0)
|
||||
}
|
||||
|
||||
var err error
|
||||
var healthInfo madmin.HealthInfo
|
||||
|
||||
// Fetch info of all servers (cluster or single server)
|
||||
obdChan := client.ServerHealthInfo(cont, *opts, ctx.Duration("deadline"))
|
||||
for adminHealthInfo := range obdChan {
|
||||
if adminHealthInfo.Error != "" {
|
||||
err = errors.New(adminHealthInfo.Error)
|
||||
break
|
||||
}
|
||||
|
||||
healthInfo = adminHealthInfo
|
||||
progress(adminHealthInfo)
|
||||
}
|
||||
|
||||
// In case any of the spinners have not stopped yet (can happen in some
|
||||
// cases e.g. net perf data is empty in case of single server deployment)
|
||||
// explicitly stop them
|
||||
_ = admin(true) && cpu(true) && diskHw(true) && osInfo(true) &&
|
||||
mem(true) && process(true) && config(true) && drive(true) && net(true)
|
||||
|
||||
// cancel the context if obdChan has returned.
|
||||
cancel()
|
||||
return healthInfo, err
|
||||
}
|
||||
|
||||
// HealthDataTypeSlice is a typed list of health tests
|
||||
type HealthDataTypeSlice []madmin.HealthDataType
|
||||
|
||||
// Set - sets the flag to the given value
|
||||
func (d *HealthDataTypeSlice) Set(value string) error {
|
||||
for _, v := range strings.Split(value, ",") {
|
||||
if obdData, ok := madmin.HealthDataTypesMap[strings.Trim(v, " ")]; ok {
|
||||
*d = append(*d, obdData)
|
||||
} else {
|
||||
return fmt.Errorf("valid options include %s", options.String())
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// String - returns the string representation of the health datatypes
|
||||
func (d *HealthDataTypeSlice) String() string {
|
||||
val := ""
|
||||
for _, obdData := range *d {
|
||||
formatStr := "%s"
|
||||
if val != "" {
|
||||
formatStr = fmt.Sprintf("%s,%%s", formatStr)
|
||||
} else {
|
||||
formatStr = fmt.Sprintf("%s%%s", formatStr)
|
||||
}
|
||||
val = fmt.Sprintf(formatStr, val, string(obdData))
|
||||
}
|
||||
return val
|
||||
}
|
||||
|
||||
// Value - returns the value
|
||||
func (d *HealthDataTypeSlice) Value() []madmin.HealthDataType {
|
||||
return *d
|
||||
}
|
||||
|
||||
// Get - returns the value
|
||||
func (d *HealthDataTypeSlice) Get() interface{} {
|
||||
return *d
|
||||
}
|
||||
|
||||
// HealthDataTypeFlag is a typed flag to represent health datatypes
|
||||
type HealthDataTypeFlag struct {
|
||||
Name string
|
||||
Usage string
|
||||
EnvVar string
|
||||
Hidden bool
|
||||
Value *HealthDataTypeSlice
|
||||
}
|
||||
|
||||
// String - returns the string to be shown in the help message
|
||||
func (f HealthDataTypeFlag) String() string {
|
||||
return fmt.Sprintf("--%s %s", f.Name, f.Usage)
|
||||
}
|
||||
|
||||
// GetName - returns the name of the flag
|
||||
func (f HealthDataTypeFlag) GetName() string {
|
||||
return f.Name
|
||||
}
|
||||
|
||||
// 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
|
||||
}
|
||||
return generic.(*HealthDataTypeSlice)
|
||||
}
|
||||
|
||||
// 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
|
||||
}
|
||||
return generic.(*HealthDataTypeSlice)
|
||||
}
|
||||
|
||||
// Apply - applies the flag
|
||||
func (f HealthDataTypeFlag) Apply(set *flag.FlagSet) {
|
||||
f.ApplyWithError(set)
|
||||
}
|
||||
|
||||
// ApplyWithError - applies with 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 := &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 health datatype value for flag %s: %s", envVal, f.Name, err)
|
||||
}
|
||||
}
|
||||
f.Value = newVal
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for _, name := range strings.Split(f.Name, ",") {
|
||||
name = strings.Trim(name, " ")
|
||||
if f.Value == nil {
|
||||
f.Value = &HealthDataTypeSlice{}
|
||||
}
|
||||
set.Var(f.Value, name, f.Usage)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
var options = HealthDataTypeSlice(madmin.HealthDataTypesList)
|
||||
@@ -1,60 +0,0 @@
|
||||
/*
|
||||
* MinIO Client (C) 2020 MinIO, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"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,
|
||||
}
|
||||
+16
-31
@@ -28,26 +28,12 @@ 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,
|
||||
OnUsageError: onUsageError,
|
||||
Flags: append(globalFlags, topLocksFlag...),
|
||||
Name: "locks",
|
||||
Usage: "Get a list of the 10 oldest locks on a MinIO cluster.",
|
||||
Before: initBeforeRunningCmd,
|
||||
Action: mainAdminTopLocks,
|
||||
Flags: globalFlags,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
@@ -86,18 +72,18 @@ func getTimeDiff(timeStamp time.Time) (string, string) {
|
||||
|
||||
// String colorized oldest locks message.
|
||||
func (u lockMessage) String() string {
|
||||
const (
|
||||
timeFieldMaxLen = 20
|
||||
resourceFieldMaxLen = -1
|
||||
typeFieldMaxLen = 6
|
||||
)
|
||||
timeFieldMaxLen := 20
|
||||
resourceFieldMaxLen := -1
|
||||
typeFieldMaxLen := 6
|
||||
ownerFieldMaxLen := 20
|
||||
|
||||
lockState, timeDiff := getTimeDiff(u.Lock.Timestamp)
|
||||
return console.Colorize(lockState, newPrettyTable(" ",
|
||||
Field{"Time", timeFieldMaxLen},
|
||||
Field{"Type", typeFieldMaxLen},
|
||||
Field{"Owner", ownerFieldMaxLen},
|
||||
Field{"Resource", resourceFieldMaxLen},
|
||||
).buildRow(timeDiff, u.Lock.Type, u.Lock.Resource))
|
||||
).buildRow(timeDiff, u.Lock.Type, u.Lock.Owner, u.Lock.Resource))
|
||||
}
|
||||
|
||||
// JSON jsonified top oldest locks message.
|
||||
@@ -128,11 +114,8 @@ func mainAdminTopLocks(ctx *cli.Context) error {
|
||||
fatalIf(err, "Unable to initialize admin connection.")
|
||||
|
||||
// Call top locks API
|
||||
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.")
|
||||
entries, e := client.TopLocks(globalContext)
|
||||
fatalIf(probe.NewError(e), "Cannot get server locks list.")
|
||||
|
||||
console.SetColor("StaleLock", color.New(color.FgRed, color.Bold))
|
||||
console.SetColor("Lock", color.New(color.FgBlue, color.Bold))
|
||||
@@ -147,11 +130,13 @@ 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", "Resource")))
|
||||
).buildRow("Time", "Type", "Owner", "Resource")))
|
||||
}
|
||||
|
||||
// Prints oldest locks.
|
||||
|
||||
+8
-11
@@ -18,23 +18,20 @@ 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: adminTopSubcommands,
|
||||
Name: "top",
|
||||
Usage: "provide top like statistics for MinIO",
|
||||
Action: mainAdminTop,
|
||||
Flags: globalFlags,
|
||||
Subcommands: []cli.Command{
|
||||
adminTopLocksCmd,
|
||||
},
|
||||
HideHelpCommand: true,
|
||||
}
|
||||
|
||||
// mainAdminTop is the handle for "mc admin top" command.
|
||||
func mainAdminTop(ctx *cli.Context) error {
|
||||
commandNotFound(ctx, adminTopSubcommands)
|
||||
cli.ShowCommandHelp(ctx, ctx.Args().First())
|
||||
return nil
|
||||
// Sub-commands like "locks" have their own main.
|
||||
}
|
||||
|
||||
+37
-284
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* MinIO Client (C) 2019, 2020, 2021 MinIO, Inc.
|
||||
* MinIO Client (C) 2019 MinIO, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -22,7 +22,6 @@ import (
|
||||
"fmt"
|
||||
"hash/fnv"
|
||||
"net/http"
|
||||
"path"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -33,7 +32,6 @@ import (
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/minio/pkg/console"
|
||||
"github.com/minio/minio/pkg/madmin"
|
||||
"github.com/minio/minio/pkg/trace"
|
||||
)
|
||||
|
||||
var adminTraceFlags = []cli.Flag{
|
||||
@@ -43,36 +41,11 @@ var adminTraceFlags = []cli.Flag{
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "all, a",
|
||||
Usage: "trace all call types",
|
||||
},
|
||||
cli.StringSliceFlag{
|
||||
Name: "call",
|
||||
Usage: "trace only matching Call types (values: `s3`, `internal`, `storage`, `os`)",
|
||||
},
|
||||
cli.StringFlag{
|
||||
Name: "response-threshold",
|
||||
Usage: "trace calls only with response duration greater than this threshold (e.g. `5ms`)",
|
||||
},
|
||||
|
||||
cli.IntSliceFlag{
|
||||
Name: "status-code",
|
||||
Usage: "trace only matching status code",
|
||||
},
|
||||
cli.StringSliceFlag{
|
||||
Name: "method",
|
||||
Usage: "trace only matching HTTP method",
|
||||
},
|
||||
cli.StringSliceFlag{
|
||||
Name: "funcname",
|
||||
Usage: "trace only matching func name",
|
||||
},
|
||||
cli.StringSliceFlag{
|
||||
Name: "path",
|
||||
Usage: "trace only matching path",
|
||||
Usage: "trace all traffic (including internode traffic between MinIO servers)",
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "errors, e",
|
||||
Usage: "trace only failed requests",
|
||||
Usage: "trace failed requests only",
|
||||
},
|
||||
}
|
||||
|
||||
@@ -80,8 +53,7 @@ var adminTraceCmd = cli.Command{
|
||||
Name: "trace",
|
||||
Usage: "show http trace for MinIO server",
|
||||
Action: mainAdminTrace,
|
||||
OnUsageError: onUsageError,
|
||||
Before: setGlobalsFromContext,
|
||||
Before: initBeforeRunningCmd,
|
||||
Flags: append(adminTraceFlags, globalFlags...),
|
||||
HideHelpCommand: true,
|
||||
CustomHelpTemplate: `NAME:
|
||||
@@ -89,25 +61,16 @@ var adminTraceCmd = cli.Command{
|
||||
|
||||
USAGE:
|
||||
{{.HelpName}} [FLAGS] TARGET
|
||||
|
||||
|
||||
FLAGS:
|
||||
{{range .VisibleFlags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
1. Show verbose console trace for MinIO server
|
||||
{{.Prompt}} {{.HelpName}} -v -a myminio
|
||||
1. Show console trace for a MinIO server with alias 'play'
|
||||
{{.Prompt}} {{.HelpName}} -v -a play
|
||||
|
||||
2. Show trace only for failed requests for MinIO server
|
||||
2. Show trace only for failed requests for a MinIO server with alias 'myminio'
|
||||
{{.Prompt}} {{.HelpName}} -v -e myminio
|
||||
|
||||
3. Show verbose console trace for requests with '503' status code
|
||||
{{.Prompt}} {{.HelpName}} -v --status-code 503 myminio
|
||||
|
||||
4. Show console trace for a specific path
|
||||
{{.Prompt}} {{.HelpName}} --path my-bucket/my-prefix/ myminio
|
||||
|
||||
5. Show console trace for requests with '404' and '503' status code
|
||||
{{.Prompt}} {{.HelpName}} --status-code 404 --status-code 503 myminio
|
||||
`,
|
||||
}
|
||||
|
||||
@@ -123,141 +86,14 @@ func checkAdminTraceSyntax(ctx *cli.Context) {
|
||||
}
|
||||
}
|
||||
|
||||
func printTrace(verbose bool, traceInfo madmin.ServiceTraceInfo) {
|
||||
if verbose {
|
||||
printMsg(traceMessage{ServiceTraceInfo: traceInfo})
|
||||
} else {
|
||||
printMsg(shortTrace(traceInfo))
|
||||
}
|
||||
}
|
||||
|
||||
func matchTrace(ctx *cli.Context, traceInfo madmin.ServiceTraceInfo) bool {
|
||||
statusCodes := ctx.IntSlice("status-code")
|
||||
methods := ctx.StringSlice("method")
|
||||
funcNames := ctx.StringSlice("funcname")
|
||||
apiPaths := ctx.StringSlice("path")
|
||||
|
||||
if len(statusCodes) == 0 && len(methods) == 0 && len(funcNames) == 0 && len(apiPaths) == 0 {
|
||||
// no specific filtering found trace all the requests
|
||||
return true
|
||||
}
|
||||
|
||||
// Filter request path if passed by the user
|
||||
if len(apiPaths) > 0 {
|
||||
matched := false
|
||||
for _, apiPath := range apiPaths {
|
||||
if pathMatch(path.Join("/", apiPath), traceInfo.Trace.ReqInfo.Path) {
|
||||
matched = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !matched {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// Filter response status codes if passed by the user
|
||||
if len(statusCodes) > 0 {
|
||||
matched := false
|
||||
for _, code := range statusCodes {
|
||||
if traceInfo.Trace.RespInfo.StatusCode == code {
|
||||
matched = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !matched {
|
||||
return false
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// Filter request method if passed by the user
|
||||
if len(methods) > 0 {
|
||||
matched := false
|
||||
for _, method := range methods {
|
||||
if traceInfo.Trace.ReqInfo.Method == method {
|
||||
matched = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !matched {
|
||||
return false
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
if len(funcNames) > 0 {
|
||||
matched := false
|
||||
// Filter request function handler names if passed by the user.
|
||||
for _, funcName := range funcNames {
|
||||
if nameMatch(funcName, traceInfo.Trace.FuncName) {
|
||||
matched = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !matched {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
// Calculate tracing options for command line flags
|
||||
func tracingOpts(ctx *cli.Context) (opts madmin.ServiceTraceOpts, e error) {
|
||||
|
||||
if t := ctx.String("response-threshold"); t != "" {
|
||||
d, e := time.ParseDuration(t)
|
||||
if e != nil {
|
||||
return opts, fmt.Errorf("Unable to parse threshold argument: %w", e)
|
||||
}
|
||||
opts.Threshold = d
|
||||
}
|
||||
|
||||
opts.OnlyErrors = ctx.Bool("errors")
|
||||
|
||||
if ctx.Bool("all") {
|
||||
opts.All = true // Deprecated
|
||||
|
||||
opts.S3 = true
|
||||
opts.Internal = true
|
||||
opts.Storage = true
|
||||
opts.OS = true
|
||||
return
|
||||
}
|
||||
|
||||
apis := ctx.StringSlice("call")
|
||||
if len(apis) == 0 {
|
||||
// If api flag is not specified, then we will
|
||||
// trace only S3 requests by default.
|
||||
opts.S3 = true
|
||||
return
|
||||
}
|
||||
|
||||
for _, api := range apis {
|
||||
switch api {
|
||||
case "storage":
|
||||
opts.Storage = true
|
||||
case "internal":
|
||||
opts.Internal = true
|
||||
case "s3":
|
||||
opts.S3 = true
|
||||
case "os":
|
||||
opts.OS = true
|
||||
}
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// mainAdminTrace - the entry function of trace command
|
||||
func mainAdminTrace(ctx *cli.Context) error {
|
||||
// Check for command syntax
|
||||
checkAdminTraceSyntax(ctx)
|
||||
|
||||
verbose := ctx.Bool("verbose")
|
||||
all := ctx.Bool("all")
|
||||
errfltr := ctx.Bool("errors")
|
||||
aliasedURL := ctx.Args().Get(0)
|
||||
|
||||
console.SetColor("Stat", color.New(color.FgYellow))
|
||||
|
||||
console.SetColor("Request", color.New(color.FgCyan))
|
||||
@@ -279,32 +115,30 @@ func mainAdminTrace(ctx *cli.Context) error {
|
||||
// Create a new MinIO Admin Client
|
||||
client, err := newAdminClient(aliasedURL)
|
||||
if err != nil {
|
||||
fatalIf(err.Trace(aliasedURL), "Unable to initialize admin client.")
|
||||
fatalIf(err.Trace(aliasedURL), "Cannot initialize admin client.")
|
||||
return nil
|
||||
}
|
||||
|
||||
ctxt, cancel := context.WithCancel(globalContext)
|
||||
defer cancel()
|
||||
|
||||
opts, e := tracingOpts(ctx)
|
||||
fatalIf(probe.NewError(e), "Unable to start tracing")
|
||||
|
||||
// Start listening on all trace activity.
|
||||
traceCh := client.ServiceTrace(ctxt, opts)
|
||||
traceCh := client.ServiceTrace(ctxt, all, errfltr)
|
||||
for traceInfo := range traceCh {
|
||||
if traceInfo.Err != nil {
|
||||
fatalIf(probe.NewError(traceInfo.Err), "Unable to listen to http trace")
|
||||
fatalIf(probe.NewError(traceInfo.Err), "Cannot listen to http trace")
|
||||
}
|
||||
if matchTrace(ctx, traceInfo) {
|
||||
printTrace(verbose, traceInfo)
|
||||
if verbose {
|
||||
printMsg(traceMessage{traceInfo})
|
||||
continue
|
||||
}
|
||||
printMsg(shortTrace(traceInfo))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Short trace record
|
||||
type shortTraceMsg struct {
|
||||
Status string `json:"status"`
|
||||
Host string `json:"host"`
|
||||
Time time.Time `json:"time"`
|
||||
Client string `json:"client"`
|
||||
@@ -314,20 +148,14 @@ type shortTraceMsg struct {
|
||||
Query string `json:"query"`
|
||||
StatusCode int `json:"statusCode"`
|
||||
StatusMsg string `json:"statusMsg"`
|
||||
|
||||
StorageStats storageStats `json:"storageStats"`
|
||||
OSStats osStats `json:"osStats"`
|
||||
Type trace.Type `json:"type"`
|
||||
}
|
||||
|
||||
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"`
|
||||
@@ -341,7 +169,6 @@ type responseInfo struct {
|
||||
Body string `json:"body,omitempty"`
|
||||
StatusCode int `json:"statusCode,omitempty"`
|
||||
}
|
||||
|
||||
type callStats struct {
|
||||
Rx int `json:"rx"`
|
||||
Tx int `json:"tx"`
|
||||
@@ -349,68 +176,36 @@ type callStats struct {
|
||||
Ttfb time.Duration `json:"timeToFirstByte"`
|
||||
}
|
||||
|
||||
type osStats struct {
|
||||
Duration time.Duration `json:"duration"`
|
||||
Path string `json:"path"`
|
||||
}
|
||||
|
||||
type storageStats struct {
|
||||
Duration time.Duration `json:"duration"`
|
||||
Path string `json:"path"`
|
||||
}
|
||||
|
||||
type verboseTrace struct {
|
||||
Type trace.Type `json:"type"`
|
||||
|
||||
NodeName string `json:"host"`
|
||||
FuncName string `json:"api"`
|
||||
Time time.Time `json:"time"`
|
||||
|
||||
type trace struct {
|
||||
NodeName string `json:"host"`
|
||||
FuncName string `json:"api"`
|
||||
RequestInfo requestInfo `json:"request"`
|
||||
ResponseInfo responseInfo `json:"response"`
|
||||
CallStats callStats `json:"callStats"`
|
||||
|
||||
StorageStats storageStats `json:"storageStats"`
|
||||
OSStats osStats `json:"osStats"`
|
||||
}
|
||||
|
||||
// return a struct with minimal trace info.
|
||||
func shortTrace(ti madmin.ServiceTraceInfo) shortTraceMsg {
|
||||
s := shortTraceMsg{}
|
||||
t := ti.Trace
|
||||
|
||||
s.Type = t.TraceType
|
||||
s.FuncName = t.FuncName
|
||||
s.Time = t.Time
|
||||
|
||||
switch t.TraceType {
|
||||
case trace.Storage:
|
||||
s.Path = t.StorageStats.Path
|
||||
s.Host = t.NodeName
|
||||
s.StorageStats.Duration = t.StorageStats.Duration
|
||||
case trace.OS:
|
||||
s.Path = t.OSStats.Path
|
||||
s.Host = t.NodeName
|
||||
s.OSStats.Duration = t.OSStats.Duration
|
||||
case trace.HTTP:
|
||||
s.Host = t.NodeName
|
||||
s.Path = t.ReqInfo.Path
|
||||
s.Query = t.ReqInfo.RawQuery
|
||||
s.StatusCode = t.RespInfo.StatusCode
|
||||
s.StatusMsg = http.StatusText(t.RespInfo.StatusCode)
|
||||
s.Client = t.ReqInfo.Client
|
||||
s.CallStats.Duration = t.CallStats.Latency
|
||||
s.CallStats.Rx = t.CallStats.InputBytes
|
||||
s.CallStats.Tx = t.CallStats.OutputBytes
|
||||
|
||||
// Support older versions of MinIO server
|
||||
s.Time = t.ReqInfo.Time
|
||||
s.Time = t.ReqInfo.Time
|
||||
if host, ok := t.ReqInfo.Headers["Host"]; ok {
|
||||
s.Host = strings.Join(host, "")
|
||||
}
|
||||
s.Path = t.ReqInfo.Path
|
||||
s.Query = t.ReqInfo.RawQuery
|
||||
s.FuncName = t.FuncName
|
||||
s.StatusCode = t.RespInfo.StatusCode
|
||||
s.StatusMsg = http.StatusText(t.RespInfo.StatusCode)
|
||||
cSlice := strings.Split(t.ReqInfo.Client, ":")
|
||||
s.Client = cSlice[0]
|
||||
s.CallStats.Duration = t.CallStats.Latency
|
||||
s.CallStats.Rx = t.CallStats.InputBytes
|
||||
s.CallStats.Tx = t.CallStats.OutputBytes
|
||||
return s
|
||||
}
|
||||
|
||||
func (s shortTraceMsg) JSON() string {
|
||||
s.Status = "success"
|
||||
buf := &bytes.Buffer{}
|
||||
enc := json.NewEncoder(buf)
|
||||
enc.SetIndent("", " ")
|
||||
@@ -429,29 +224,10 @@ func (s shortTraceMsg) String() string {
|
||||
hostStr = colorizedNodeName(s.Host)
|
||||
}
|
||||
fmt.Fprintf(b, "%s ", s.Time.Format(timeFormat))
|
||||
|
||||
switch s.Type {
|
||||
case trace.Storage:
|
||||
fmt.Fprintf(b, "[%s] %s %s %s %2s", console.Colorize("RespStatus", "STORAGE"), console.Colorize("FuncName", s.FuncName),
|
||||
hostStr,
|
||||
s.Path,
|
||||
console.Colorize("HeaderValue", s.StorageStats.Duration))
|
||||
return b.String()
|
||||
case trace.OS:
|
||||
fmt.Fprintf(b, "[%s] %s %s %s %2s", console.Colorize("RespStatus", "OS"), console.Colorize("FuncName", s.FuncName),
|
||||
hostStr,
|
||||
s.Path,
|
||||
console.Colorize("HeaderValue", s.OSStats.Duration))
|
||||
return b.String()
|
||||
}
|
||||
|
||||
statusStr := fmt.Sprintf("%d %s", s.StatusCode, s.StatusMsg)
|
||||
statusStr := console.Colorize("RespStatus", fmt.Sprintf("%d %s", s.StatusCode, s.StatusMsg))
|
||||
if s.StatusCode >= http.StatusBadRequest {
|
||||
statusStr = console.Colorize("ErrStatus", statusStr)
|
||||
} else {
|
||||
statusStr = console.Colorize("RespStatus", statusStr)
|
||||
statusStr = console.Colorize("ErrStatus", fmt.Sprintf("%d %s", s.StatusCode, s.StatusMsg))
|
||||
}
|
||||
|
||||
fmt.Fprintf(b, "[%s] %s ", statusStr, console.Colorize("FuncName", s.FuncName))
|
||||
fmt.Fprintf(b, "%s%s", hostStr, s.Path)
|
||||
|
||||
@@ -459,7 +235,6 @@ func (s shortTraceMsg) String() string {
|
||||
fmt.Fprintf(b, "?%s ", s.Query)
|
||||
}
|
||||
fmt.Fprintf(b, " %s ", s.Client)
|
||||
|
||||
spaces := 15 - len(s.Client)
|
||||
fmt.Fprintf(b, "%*s", spaces, " ")
|
||||
fmt.Fprint(b, console.Colorize("HeaderValue", fmt.Sprintf(" %2s", s.CallStats.Duration.Round(time.Microsecond))))
|
||||
@@ -483,7 +258,6 @@ 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
|
||||
@@ -494,14 +268,11 @@ func (t traceMessage) JSON() string {
|
||||
for k, v := range rs.Headers {
|
||||
rspHdrs[k] = strings.Join(v, " ")
|
||||
}
|
||||
trc := verboseTrace{
|
||||
Type: t.Trace.TraceType,
|
||||
trc := trace{
|
||||
NodeName: t.Trace.NodeName,
|
||||
FuncName: t.Trace.FuncName,
|
||||
Time: t.Trace.Time,
|
||||
RequestInfo: requestInfo{
|
||||
Time: rq.Time,
|
||||
Proto: rq.Proto,
|
||||
Method: rq.Method,
|
||||
Path: rq.Path,
|
||||
RawQuery: rq.RawQuery,
|
||||
@@ -520,14 +291,6 @@ func (t traceMessage) JSON() string {
|
||||
Tx: t.Trace.CallStats.OutputBytes,
|
||||
Ttfb: t.Trace.CallStats.TimeToFirstByte,
|
||||
},
|
||||
OSStats: osStats{
|
||||
Duration: t.Trace.OSStats.Duration,
|
||||
Path: t.Trace.OSStats.Path,
|
||||
},
|
||||
StorageStats: storageStats{
|
||||
Duration: t.Trace.StorageStats.Duration,
|
||||
Path: t.Trace.StorageStats.Path,
|
||||
},
|
||||
}
|
||||
buf := &bytes.Buffer{}
|
||||
enc := json.NewEncoder(buf)
|
||||
@@ -549,25 +312,15 @@ func (t traceMessage) String() string {
|
||||
nodeNameStr = fmt.Sprintf("%s ", colorizedNodeName(trc.NodeName))
|
||||
}
|
||||
|
||||
switch trc.TraceType {
|
||||
case trace.Storage:
|
||||
fmt.Fprintf(b, "%s %s [%s] %s %s", nodeNameStr, console.Colorize("Request", fmt.Sprintf("[STORAGE %s]", trc.FuncName)), trc.Time.Format(timeFormat), trc.StorageStats.Path, trc.StorageStats.Duration)
|
||||
return b.String()
|
||||
case trace.OS:
|
||||
fmt.Fprintf(b, "%s %s [%s] %s %s", nodeNameStr, console.Colorize("Request", fmt.Sprintf("[OS %s]", trc.FuncName)), trc.Time.Format(timeFormat), trc.OSStats.Path, trc.OSStats.Duration)
|
||||
return b.String()
|
||||
}
|
||||
|
||||
ri := trc.ReqInfo
|
||||
rs := trc.RespInfo
|
||||
fmt.Fprintf(b, "%s%s", nodeNameStr, console.Colorize("Request", fmt.Sprintf("[REQUEST %s] ", trc.FuncName)))
|
||||
fmt.Fprintf(b, "[%s] %s\n", ri.Time.Format(timeFormat), console.Colorize("Host", fmt.Sprintf("[Client IP: %s]", ri.Client)))
|
||||
fmt.Fprintf(b, "%s\n", ri.Time.Format(timeFormat))
|
||||
fmt.Fprintf(b, "%s%s", nodeNameStr, console.Colorize("Method", fmt.Sprintf("%s %s", ri.Method, ri.Path)))
|
||||
if ri.RawQuery != "" {
|
||||
fmt.Fprintf(b, "?%s", ri.RawQuery)
|
||||
}
|
||||
fmt.Fprint(b, "\n")
|
||||
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")
|
||||
|
||||
+5
-6
@@ -27,12 +27,11 @@ import (
|
||||
)
|
||||
|
||||
var adminServerUpdateCmd = cli.Command{
|
||||
Name: "update",
|
||||
Usage: "update all MinIO servers",
|
||||
Action: mainAdminServerUpdate,
|
||||
OnUsageError: onUsageError,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
Name: "update",
|
||||
Usage: "update all MinIO servers",
|
||||
Action: mainAdminServerUpdate,
|
||||
Before: initBeforeRunningCmd,
|
||||
Flags: globalFlags,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
|
||||
@@ -31,12 +31,11 @@ import (
|
||||
)
|
||||
|
||||
var adminUserAddCmd = cli.Command{
|
||||
Name: "add",
|
||||
Usage: "add a new user",
|
||||
Action: mainAdminUserAdd,
|
||||
OnUsageError: onUsageError,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
Name: "add",
|
||||
Usage: "add a new user",
|
||||
Action: mainAdminUserAdd,
|
||||
Before: initBeforeRunningCmd,
|
||||
Flags: globalFlags,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
@@ -181,7 +180,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...), "Unable to add new user")
|
||||
fatalIf(probe.NewError(client.AddUser(globalContext, accessKey, secretKey)).Trace(args...), "Cannot add new user")
|
||||
|
||||
printMsg(userMessage{
|
||||
op: "add",
|
||||
|
||||
@@ -25,12 +25,11 @@ import (
|
||||
)
|
||||
|
||||
var adminUserDisableCmd = cli.Command{
|
||||
Name: "disable",
|
||||
Usage: "disable user",
|
||||
Action: mainAdminUserDisable,
|
||||
OnUsageError: onUsageError,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
Name: "disable",
|
||||
Usage: "disable user",
|
||||
Action: mainAdminUserDisable,
|
||||
Before: initBeforeRunningCmd,
|
||||
Flags: globalFlags,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
@@ -68,7 +67,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...), "Unable to disable user")
|
||||
fatalIf(probe.NewError(e).Trace(args...), "Cannot disable user")
|
||||
|
||||
printMsg(userMessage{
|
||||
op: "disable",
|
||||
|
||||
@@ -25,12 +25,11 @@ import (
|
||||
)
|
||||
|
||||
var adminUserEnableCmd = cli.Command{
|
||||
Name: "enable",
|
||||
Usage: "enable user",
|
||||
Action: mainAdminUserEnable,
|
||||
OnUsageError: onUsageError,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
Name: "enable",
|
||||
Usage: "enable user",
|
||||
Action: mainAdminUserEnable,
|
||||
Before: initBeforeRunningCmd,
|
||||
Flags: globalFlags,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
@@ -68,7 +67,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...), "Unable to enable user")
|
||||
fatalIf(probe.NewError(e).Trace(args...), "Cannot enable user")
|
||||
|
||||
printMsg(userMessage{
|
||||
op: "enable",
|
||||
|
||||
@@ -24,12 +24,11 @@ import (
|
||||
)
|
||||
|
||||
var adminUserInfoCmd = cli.Command{
|
||||
Name: "info",
|
||||
Usage: "display info of a user",
|
||||
Action: mainAdminUserInfo,
|
||||
OnUsageError: onUsageError,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
Name: "info",
|
||||
Usage: "display info of a user",
|
||||
Action: mainAdminUserInfo,
|
||||
Before: initBeforeRunningCmd,
|
||||
Flags: globalFlags,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
@@ -67,7 +66,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...), "Unable to get user info")
|
||||
fatalIf(probe.NewError(e).Trace(args...), "Cannot get user info")
|
||||
|
||||
printMsg(userMessage{
|
||||
op: "info",
|
||||
|
||||
@@ -24,12 +24,11 @@ import (
|
||||
)
|
||||
|
||||
var adminUserListCmd = cli.Command{
|
||||
Name: "list",
|
||||
Usage: "list all users",
|
||||
Action: mainAdminUserList,
|
||||
OnUsageError: onUsageError,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
Name: "list",
|
||||
Usage: "list all users",
|
||||
Action: mainAdminUserList,
|
||||
Before: initBeforeRunningCmd,
|
||||
Flags: globalFlags,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
@@ -71,7 +70,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...), "Unable to list user")
|
||||
fatalIf(probe.NewError(e).Trace(args...), "Cannot list user")
|
||||
|
||||
for k, v := range users {
|
||||
printMsg(userMessage{
|
||||
|
||||
@@ -1,95 +0,0 @@
|
||||
/*
|
||||
* MinIO Client (C) 2021 MinIO, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/fatih/color"
|
||||
jsoniter "github.com/json-iterator/go"
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/minio/pkg/console"
|
||||
iampolicy "github.com/minio/minio/pkg/iam/policy"
|
||||
)
|
||||
|
||||
var adminUserPolicyCmd = cli.Command{
|
||||
Name: "policy",
|
||||
Usage: "export user policies in JSON format",
|
||||
Action: mainAdminUserPolicy,
|
||||
OnUsageError: onUsageError,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
{{.HelpName}} TARGET USERNAME
|
||||
|
||||
FLAGS:
|
||||
{{range .VisibleFlags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
1. Display the policy document of a user "foobar" in JSON format.
|
||||
{{.Prompt}} {{.HelpName}} myminio foobar
|
||||
|
||||
`,
|
||||
}
|
||||
|
||||
// checkAdminUserPolicySyntax - validate all the passed arguments
|
||||
func checkAdminUserPolicySyntax(ctx *cli.Context) {
|
||||
if len(ctx.Args()) != 2 {
|
||||
cli.ShowCommandHelpAndExit(ctx, "policy", 1) // last argument is exit code
|
||||
}
|
||||
}
|
||||
|
||||
// mainAdminUserPolicy is the handler for "mc admin user policy" command.
|
||||
func mainAdminUserPolicy(ctx *cli.Context) error {
|
||||
checkAdminUserPolicySyntax(ctx)
|
||||
|
||||
console.SetColor("UserMessage", color.New(color.FgGreen))
|
||||
|
||||
// Get the alias parameter from cli
|
||||
args := ctx.Args()
|
||||
aliasedURL := args.Get(0)
|
||||
|
||||
// Create a new MinIO Admin Client
|
||||
client, err := newAdminClient(aliasedURL)
|
||||
fatalIf(err, "Unable to initialize admin connection.")
|
||||
|
||||
user, e := client.GetUserInfo(globalContext, args.Get(1))
|
||||
fatalIf(probe.NewError(e).Trace(args...), "Unable to get user info")
|
||||
|
||||
var combinedPolicy iampolicy.Policy
|
||||
|
||||
policies := strings.Split(user.PolicyName, ",")
|
||||
|
||||
for _, p := range policies {
|
||||
policy, e := client.InfoCannedPolicy(globalContext, p)
|
||||
fatalIf(probe.NewError(e).Trace(args...), "Unable to get user's policy document")
|
||||
combinedPolicy = combinedPolicy.Merge(*policy)
|
||||
}
|
||||
|
||||
var jsoniter = jsoniter.ConfigCompatibleWithStandardLibrary
|
||||
policyJSON, e := jsoniter.MarshalIndent(combinedPolicy, "", " ")
|
||||
fatalIf(probe.NewError(e).Trace(args...), "Unable to parse user's policy document")
|
||||
|
||||
fmt.Println(string(policyJSON))
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -24,12 +24,11 @@ import (
|
||||
)
|
||||
|
||||
var adminUserRemoveCmd = cli.Command{
|
||||
Name: "remove",
|
||||
Usage: "remove user",
|
||||
Action: mainAdminUserRemove,
|
||||
OnUsageError: onUsageError,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
Name: "remove",
|
||||
Usage: "remove user",
|
||||
Action: mainAdminUserRemove,
|
||||
Before: initBeforeRunningCmd,
|
||||
Flags: globalFlags,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
@@ -67,7 +66,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...), "Unable to remove %s", args.Get(1))
|
||||
fatalIf(probe.NewError(e).Trace(args...), "Cannot remove %s", args.Get(1))
|
||||
|
||||
printMsg(userMessage{
|
||||
op: "remove",
|
||||
|
||||
@@ -1,188 +0,0 @@
|
||||
/*
|
||||
* MinIO Client (C) 2021 MinIO, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* 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"
|
||||
"strings"
|
||||
|
||||
"github.com/minio/cli"
|
||||
json "github.com/minio/mc/pkg/colorjson"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/minio/pkg/console"
|
||||
iampolicy "github.com/minio/minio/pkg/iam/policy"
|
||||
"github.com/minio/minio/pkg/madmin"
|
||||
)
|
||||
|
||||
var adminUserSvcAcctAddFlags = []cli.Flag{
|
||||
cli.StringFlag{
|
||||
Name: "access-key",
|
||||
Usage: "set an access key for the service account",
|
||||
},
|
||||
cli.StringFlag{
|
||||
Name: "secret-key",
|
||||
Usage: "set a secret key for the service account",
|
||||
},
|
||||
cli.StringFlag{
|
||||
Name: "policy",
|
||||
Usage: "path to a JSON policy file",
|
||||
},
|
||||
}
|
||||
|
||||
var adminUserSvcAcctAddCmd = cli.Command{
|
||||
Name: "add",
|
||||
Usage: "add a new service account",
|
||||
Action: mainAdminUserSvcAcctAdd,
|
||||
OnUsageError: onUsageError,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: append(adminUserSvcAcctAddFlags, globalFlags...),
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
{{.HelpName}} ALIAS ACCOUNT
|
||||
|
||||
ACCOUNT:
|
||||
An account could be a regular MinIO user, STS ou LDAP user.
|
||||
|
||||
FLAGS:
|
||||
{{range .VisibleFlags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
1. Add a new service account for user 'foobar' to MinIO server.
|
||||
{{.Prompt}} {{.HelpName}} myminio foobar
|
||||
`,
|
||||
}
|
||||
|
||||
// checkAdminUserSvcAcctAddSyntax - validate all the passed arguments
|
||||
func checkAdminUserSvcAcctAddSyntax(ctx *cli.Context) {
|
||||
if len(ctx.Args()) != 2 {
|
||||
fatalIf(errInvalidArgument().Trace(ctx.Args().Tail()...),
|
||||
"Incorrect number of arguments for user svcacct add command.")
|
||||
}
|
||||
}
|
||||
|
||||
// svcAcctMessage container for content message structure
|
||||
type svcAcctMessage struct {
|
||||
op string
|
||||
Status string `json:"status"`
|
||||
AccessKey string `json:"accessKey,omitempty"`
|
||||
SecretKey string `json:"secretKey,omitempty"`
|
||||
ParentUser string `json:"parentUser,omitempty"`
|
||||
ImpliedPolicy bool `json:"impliedPolicy,omitempty"`
|
||||
Policy string `json:"policy,omitempty"`
|
||||
AccountStatus string `json:"accountStatus,omitempty"`
|
||||
MemberOf []string `json:"memberOf,omitempty"`
|
||||
}
|
||||
|
||||
func (u svcAcctMessage) String() string {
|
||||
switch u.op {
|
||||
case "ls":
|
||||
accessFieldMaxLen := 20
|
||||
/*
|
||||
userFieldMaxLen := 9
|
||||
policyFieldMaxLen := 20
|
||||
*/
|
||||
|
||||
// Create a new pretty table with cols configuration
|
||||
return newPrettyTable(" ",
|
||||
Field{"AccessKey", accessFieldMaxLen},
|
||||
).buildRow(u.AccessKey)
|
||||
case "info":
|
||||
policyField := ""
|
||||
if u.ImpliedPolicy {
|
||||
policyField = "implied"
|
||||
} else {
|
||||
policyField = "embedded"
|
||||
}
|
||||
return console.Colorize("UserMessage", strings.Join(
|
||||
[]string{
|
||||
fmt.Sprintf("AccessKey: %s", u.AccessKey),
|
||||
fmt.Sprintf("ParentUser: %s", u.ParentUser),
|
||||
fmt.Sprintf("Status: %s", u.AccountStatus),
|
||||
fmt.Sprintf("Policy: %s", policyField),
|
||||
// fmt.Sprintf("MemberOf: %s", strings.Join(u.MemberOf, ",")),
|
||||
}, "\n"))
|
||||
case "rm":
|
||||
return console.Colorize("UserMessage", "Removed service account `"+u.AccessKey+"` successfully.")
|
||||
case "disable":
|
||||
return console.Colorize("UserMessage", "Disabled service account `"+u.AccessKey+"` successfully.")
|
||||
case "enable":
|
||||
return console.Colorize("UserMessage", "Enabled service account `"+u.AccessKey+"` successfully.")
|
||||
case "add":
|
||||
return console.Colorize("UserMessage", "Added service account `"+u.AccessKey+"` successfully.")
|
||||
case "set":
|
||||
return console.Colorize("UserMessage", "Edited service account `"+u.AccessKey+"` successfully.")
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (u svcAcctMessage) JSON() string {
|
||||
u.Status = "success"
|
||||
jsonMessageBytes, e := json.MarshalIndent(u, "", " ")
|
||||
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
|
||||
|
||||
return string(jsonMessageBytes)
|
||||
}
|
||||
|
||||
// mainAdminUserSvcAcctAdd is the handle for "mc admin user svcacct add" command.
|
||||
func mainAdminUserSvcAcctAdd(ctx *cli.Context) error {
|
||||
checkAdminUserSvcAcctAddSyntax(ctx)
|
||||
|
||||
// Get the alias parameter from cli
|
||||
args := ctx.Args()
|
||||
aliasedURL := args.Get(0)
|
||||
user := args.Get(1)
|
||||
|
||||
accessKey := ctx.String("access-key")
|
||||
secretKey := ctx.String("secret-key")
|
||||
policyPath := ctx.String("policy")
|
||||
|
||||
// Create a new MinIO Admin Client
|
||||
client, err := newAdminClient(aliasedURL)
|
||||
fatalIf(err, "Unable to initialize admin connection.")
|
||||
|
||||
var policy *iampolicy.Policy
|
||||
|
||||
if policyPath != "" {
|
||||
var e error
|
||||
f, e := os.Open(policyPath)
|
||||
fatalIf(probe.NewError(e), "Unable to open the policy document.")
|
||||
policy, e = iampolicy.ParseConfig(f)
|
||||
fatalIf(probe.NewError(e), "Unable to parse the policy document.")
|
||||
}
|
||||
|
||||
opts := madmin.AddServiceAccountReq{
|
||||
Policy: policy,
|
||||
AccessKey: accessKey,
|
||||
SecretKey: secretKey,
|
||||
TargetUser: user,
|
||||
}
|
||||
|
||||
creds, e := client.AddServiceAccount(globalContext, opts)
|
||||
fatalIf(probe.NewError(e).Trace(args...), "Unable to add a new service account")
|
||||
|
||||
printMsg(svcAcctMessage{
|
||||
op: "add",
|
||||
AccessKey: creds.AccessKey,
|
||||
SecretKey: creds.SecretKey,
|
||||
AccountStatus: "enabled",
|
||||
})
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -1,81 +0,0 @@
|
||||
/*
|
||||
* MinIO Client (C) 2021 MinIO, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* 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"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/minio/pkg/madmin"
|
||||
)
|
||||
|
||||
var adminUserSvcAcctDisableCmd = cli.Command{
|
||||
Name: "disable",
|
||||
Usage: "Disable a services account",
|
||||
Action: mainAdminUserSvcAcctDisable,
|
||||
OnUsageError: onUsageError,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
{{.HelpName}} ALIAS SERVICE-ACCOUNT
|
||||
|
||||
FLAGS:
|
||||
{{range .VisibleFlags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
1. Disable the service account 'J123C4ZXEQN8RK6ND35I' in MinIO server.
|
||||
{{.Prompt}} {{.HelpName}} myminio/ J123C4ZXEQN8RK6ND35I
|
||||
`,
|
||||
}
|
||||
|
||||
// checkAdminUserSvcAcctDisableSyntax - validate all the passed arguments
|
||||
func checkAdminUserSvcAcctDisableSyntax(ctx *cli.Context) {
|
||||
if len(ctx.Args()) != 2 {
|
||||
fatalIf(errInvalidArgument().Trace(ctx.Args().Tail()...),
|
||||
"Incorrect number of arguments for user svcacct disable command.")
|
||||
}
|
||||
}
|
||||
|
||||
// mainAdminUserSvcAcctDisable is the handle for "mc admin user svcacct disable" command.
|
||||
func mainAdminUserSvcAcctDisable(ctx *cli.Context) error {
|
||||
checkAdminUserSvcAcctDisableSyntax(ctx)
|
||||
|
||||
// Get the alias parameter from cli
|
||||
args := ctx.Args()
|
||||
aliasedURL := args.Get(0)
|
||||
svcAccount := args.Get(1)
|
||||
|
||||
// Create a new MinIO Admin Client
|
||||
client, err := newAdminClient(aliasedURL)
|
||||
fatalIf(err, "Unable to initialize admin connection.")
|
||||
|
||||
opts := madmin.UpdateServiceAccountReq{
|
||||
NewStatus: "off",
|
||||
}
|
||||
|
||||
e := client.UpdateServiceAccount(globalContext, svcAccount, opts)
|
||||
fatalIf(probe.NewError(e).Trace(args...), "Unable to get disable the specified service account")
|
||||
|
||||
printMsg(svcAcctMessage{
|
||||
op: "disable",
|
||||
AccessKey: svcAccount,
|
||||
})
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -1,81 +0,0 @@
|
||||
/*
|
||||
* MinIO Client (C) 2021 MinIO, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* 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"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/minio/pkg/madmin"
|
||||
)
|
||||
|
||||
var adminUserSvcAcctEnableCmd = cli.Command{
|
||||
Name: "enable",
|
||||
Usage: "Enable a service account",
|
||||
Action: mainAdminUserSvcAcctEnable,
|
||||
OnUsageError: onUsageError,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
{{.HelpName}} ALIAS SERVICE-ACCOUNT
|
||||
|
||||
FLAGS:
|
||||
{{range .VisibleFlags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
1. Enable the service account 'J123C4ZXEQN8RK6ND35I' in MinIO server.
|
||||
{{.Prompt}} {{.HelpName}} myminio/ J123C4ZXEQN8RK6ND35I
|
||||
`,
|
||||
}
|
||||
|
||||
// checkAdminUserSvcAcctEnableSyntax - validate all the passed arguments
|
||||
func checkAdminUserSvcAcctEnableSyntax(ctx *cli.Context) {
|
||||
if len(ctx.Args()) != 2 {
|
||||
fatalIf(errInvalidArgument().Trace(ctx.Args().Tail()...),
|
||||
"Incorrect number of arguments for user svcacct enable command.")
|
||||
}
|
||||
}
|
||||
|
||||
// mainAdminUserSvcAcctEnable is the handle for "mc admin user svcacct enable" command.
|
||||
func mainAdminUserSvcAcctEnable(ctx *cli.Context) error {
|
||||
checkAdminUserSvcAcctEnableSyntax(ctx)
|
||||
|
||||
// Get the alias parameter from cli
|
||||
args := ctx.Args()
|
||||
aliasedURL := args.Get(0)
|
||||
svcAccount := args.Get(1)
|
||||
|
||||
// Create a new MinIO Admin Client
|
||||
client, err := newAdminClient(aliasedURL)
|
||||
fatalIf(err, "Unable to initialize admin connection.")
|
||||
|
||||
opts := madmin.UpdateServiceAccountReq{
|
||||
NewStatus: "on",
|
||||
}
|
||||
|
||||
e := client.UpdateServiceAccount(globalContext, svcAccount, opts)
|
||||
fatalIf(probe.NewError(e).Trace(args...), "Unable to get enable the specified service account")
|
||||
|
||||
printMsg(svcAcctMessage{
|
||||
op: "enable",
|
||||
AccessKey: svcAccount,
|
||||
})
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -1,97 +0,0 @@
|
||||
/*
|
||||
* MinIO Client (C) 2021 MinIO, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
)
|
||||
|
||||
var adminUserSvcAcctInfoFlags = []cli.Flag{
|
||||
cli.BoolFlag{
|
||||
Name: "policy",
|
||||
Usage: "print policy is JSON format",
|
||||
},
|
||||
}
|
||||
|
||||
var adminUserSvcAcctInfoCmd = cli.Command{
|
||||
Name: "info",
|
||||
Usage: "Get a service account info",
|
||||
Action: mainAdminUserSvcAcctInfo,
|
||||
OnUsageError: onUsageError,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: append(adminUserSvcAcctInfoFlags, globalFlags...),
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
{{.HelpName}} ALIAS SERVICE-ACCOUNT
|
||||
|
||||
FLAGS:
|
||||
{{range .VisibleFlags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
1. Get information of service account 'J123C4ZXEQN8RK6ND35I'
|
||||
{{.Prompt}} {{.HelpName}} myminio/ J123C4ZXEQN8RK6ND35I
|
||||
`,
|
||||
}
|
||||
|
||||
// checkAdminUserSvcAcctInfoSyntax - validate all the passed arguments
|
||||
func checkAdminUserSvcAcctInfoSyntax(ctx *cli.Context) {
|
||||
if len(ctx.Args()) != 2 {
|
||||
fatalIf(errInvalidArgument().Trace(ctx.Args().Tail()...),
|
||||
"Incorrect number of arguments for user svcacct info command.")
|
||||
}
|
||||
}
|
||||
|
||||
// mainAdminUserSvcAcctInfo is the handle for "mc admin user svcacct info" command.
|
||||
func mainAdminUserSvcAcctInfo(ctx *cli.Context) error {
|
||||
checkAdminUserSvcAcctInfoSyntax(ctx)
|
||||
|
||||
// Get the alias parameter from cli
|
||||
args := ctx.Args()
|
||||
aliasedURL := args.Get(0)
|
||||
svcAccount := args.Get(1)
|
||||
|
||||
// Create a new MinIO Admin Client
|
||||
client, err := newAdminClient(aliasedURL)
|
||||
fatalIf(err, "Unable to initialize admin connection.")
|
||||
|
||||
svcInfo, e := client.InfoServiceAccount(globalContext, svcAccount)
|
||||
fatalIf(probe.NewError(e).Trace(args...), "Unable to get information of the specified service account")
|
||||
|
||||
if ctx.Bool("policy") {
|
||||
if svcInfo.Policy == "" {
|
||||
fatalIf(errDummy().Trace(args...), "No policy found associated to the specified service account. Check the policy of its parent user.")
|
||||
}
|
||||
fmt.Println(svcInfo.Policy)
|
||||
return nil
|
||||
}
|
||||
|
||||
printMsg(svcAcctMessage{
|
||||
op: "info",
|
||||
AccessKey: svcAccount,
|
||||
AccountStatus: svcInfo.AccountStatus,
|
||||
ParentUser: svcInfo.ParentUser,
|
||||
ImpliedPolicy: svcInfo.ImpliedPolicy,
|
||||
Policy: svcInfo.Policy,
|
||||
})
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -1,81 +0,0 @@
|
||||
/*
|
||||
* MinIO Client (C) 2021 MinIO, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* 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"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
)
|
||||
|
||||
var adminUserSvcAcctListCmd = cli.Command{
|
||||
Name: "ls",
|
||||
Usage: "List services accounts",
|
||||
Action: mainAdminUserSvcAcctList,
|
||||
OnUsageError: onUsageError,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
{{.HelpName}} ALIAS TARGET-ACCOUNT
|
||||
|
||||
TARGET-ACCOUNT:
|
||||
Could be a MinIO user, STS or LDAP account.
|
||||
|
||||
FLAGS:
|
||||
{{range .VisibleFlags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
1. List all service accounts for user 'foobar'.
|
||||
{{.Prompt}} {{.HelpName}} myminio/ foobar
|
||||
`,
|
||||
}
|
||||
|
||||
// checkAdminUserSvcAcctListSyntax - validate all the passed arguments
|
||||
func checkAdminUserSvcAcctListSyntax(ctx *cli.Context) {
|
||||
if len(ctx.Args()) != 2 {
|
||||
fatalIf(errInvalidArgument().Trace(ctx.Args().Tail()...),
|
||||
"Incorrect number of arguments for user svcacct ls command.")
|
||||
}
|
||||
}
|
||||
|
||||
// mainAdminUserSvcAcctList is the handle for "mc admin user svcacct ls" command.
|
||||
func mainAdminUserSvcAcctList(ctx *cli.Context) error {
|
||||
checkAdminUserSvcAcctListSyntax(ctx)
|
||||
|
||||
// Get the alias parameter from cli
|
||||
args := ctx.Args()
|
||||
aliasedURL := args.Get(0)
|
||||
user := args.Get(1)
|
||||
|
||||
// Create a new MinIO Admin Client
|
||||
client, err := newAdminClient(aliasedURL)
|
||||
fatalIf(err, "Unable to initialize admin connection.")
|
||||
|
||||
svcList, e := client.ListServiceAccounts(globalContext, user)
|
||||
fatalIf(probe.NewError(e).Trace(args...), "Unable to add a new service account")
|
||||
|
||||
for _, svc := range svcList.Accounts {
|
||||
printMsg(svcAcctMessage{
|
||||
op: "ls",
|
||||
AccessKey: svc,
|
||||
})
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -1,76 +0,0 @@
|
||||
/*
|
||||
* MinIO Client (C) 2021 MinIO, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* 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"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
)
|
||||
|
||||
var adminUserSvcAcctRemoveCmd = cli.Command{
|
||||
Name: "rm",
|
||||
Usage: "Remove a service account",
|
||||
Action: mainAdminUserSvcAcctRemove,
|
||||
OnUsageError: onUsageError,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
{{.HelpName}} ALIAS SERVICE-ACCOUNT
|
||||
|
||||
FLAGS:
|
||||
{{range .VisibleFlags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
1. Remove the service account 'J123C4ZXEQN8RK6ND35I' from MinIO server.
|
||||
{{.Prompt}} {{.HelpName}} myminio/ J123C4ZXEQN8RK6ND35I
|
||||
`,
|
||||
}
|
||||
|
||||
// checkAdminUserSvcAcctRemoveSyntax - validate all the passed arguments
|
||||
func checkAdminUserSvcAcctRemoveSyntax(ctx *cli.Context) {
|
||||
if len(ctx.Args()) != 2 {
|
||||
fatalIf(errInvalidArgument().Trace(ctx.Args().Tail()...),
|
||||
"Incorrect number of arguments for user svcacct rm command.")
|
||||
}
|
||||
}
|
||||
|
||||
// mainAdminUserSvcAcctRemove is the handle for "mc admin user svcacct rm" command.
|
||||
func mainAdminUserSvcAcctRemove(ctx *cli.Context) error {
|
||||
checkAdminUserSvcAcctRemoveSyntax(ctx)
|
||||
|
||||
// Get the alias parameter from cli
|
||||
args := ctx.Args()
|
||||
aliasedURL := args.Get(0)
|
||||
svcAccount := args.Get(1)
|
||||
|
||||
// Create a new MinIO Admin Client
|
||||
client, err := newAdminClient(aliasedURL)
|
||||
fatalIf(err, "Unable to initialize admin connection.")
|
||||
|
||||
e := client.DeleteServiceAccount(globalContext, svcAccount)
|
||||
fatalIf(probe.NewError(e).Trace(args...), "Unable to remove a new service account")
|
||||
|
||||
printMsg(svcAcctMessage{
|
||||
op: "ls",
|
||||
AccessKey: svcAccount,
|
||||
})
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -1,108 +0,0 @@
|
||||
/*
|
||||
* MinIO Client (C) 2021 MinIO, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"os"
|
||||
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
iampolicy "github.com/minio/minio/pkg/iam/policy"
|
||||
"github.com/minio/minio/pkg/madmin"
|
||||
)
|
||||
|
||||
var adminUserSvcAcctSetFlags = []cli.Flag{
|
||||
cli.StringFlag{
|
||||
Name: "secret-key",
|
||||
Usage: "set a secret key for the service account",
|
||||
},
|
||||
cli.StringFlag{
|
||||
Name: "policy",
|
||||
Usage: "path to a JSON policy file",
|
||||
},
|
||||
}
|
||||
|
||||
var adminUserSvcAcctSetCmd = cli.Command{
|
||||
Name: "set",
|
||||
Usage: "edit an existing service account",
|
||||
Action: mainAdminUserSvcAcctSet,
|
||||
OnUsageError: onUsageError,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: append(adminUserSvcAcctSetFlags, globalFlags...),
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
{{.HelpName}} ALIAS SERVICE-ACCOUNT
|
||||
|
||||
FLAGS:
|
||||
{{range .VisibleFlags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
1. Change the secret key of the service account 'J123C4ZXEQN8RK6ND35I' in MinIO server.
|
||||
{{.Prompt}} {{.HelpName}} myminio/ 'J123C4ZXEQN8RK6ND35I' --secret-key 'xxxxxxx'
|
||||
`,
|
||||
}
|
||||
|
||||
// checkAdminUserSvcAcctSetSyntax - validate all the passed arguments
|
||||
func checkAdminUserSvcAcctSetSyntax(ctx *cli.Context) {
|
||||
if len(ctx.Args()) != 2 {
|
||||
fatalIf(errInvalidArgument().Trace(ctx.Args().Tail()...),
|
||||
"Incorrect number of arguments for user svcacct set command.")
|
||||
}
|
||||
}
|
||||
|
||||
// mainAdminUserSvcAcctSet is the handle for "mc admin user svcacct set" command.
|
||||
func mainAdminUserSvcAcctSet(ctx *cli.Context) error {
|
||||
checkAdminUserSvcAcctSetSyntax(ctx)
|
||||
|
||||
// Get the alias parameter from cli
|
||||
args := ctx.Args()
|
||||
aliasedURL := args.Get(0)
|
||||
svcAccount := args.Get(1)
|
||||
|
||||
secretKey := ctx.String("secret-key")
|
||||
policyPath := ctx.String("policy")
|
||||
|
||||
// Create a new MinIO Admin Client
|
||||
client, err := newAdminClient(aliasedURL)
|
||||
fatalIf(err, "Unable to initialize admin connection.")
|
||||
|
||||
var policy *iampolicy.Policy
|
||||
if policyPath != "" {
|
||||
var e error
|
||||
f, e := os.Open(policyPath)
|
||||
fatalIf(probe.NewError(e), "Unable to open the policy document.")
|
||||
policy, e = iampolicy.ParseConfig(f)
|
||||
fatalIf(probe.NewError(e), "Unable to parse the policy document.")
|
||||
}
|
||||
|
||||
opts := madmin.UpdateServiceAccountReq{
|
||||
NewPolicy: policy,
|
||||
NewSecretKey: secretKey,
|
||||
}
|
||||
|
||||
e := client.UpdateServiceAccount(globalContext, svcAccount, opts)
|
||||
fatalIf(probe.NewError(e).Trace(args...), "Unable to add a new service account")
|
||||
|
||||
printMsg(svcAcctMessage{
|
||||
op: "set",
|
||||
AccessKey: svcAccount,
|
||||
})
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -1,45 +0,0 @@
|
||||
/*
|
||||
* MinIO Client (C) 2021 MinIO, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* 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 adminUserSvcAcctSubcommands = []cli.Command{
|
||||
adminUserSvcAcctAddCmd,
|
||||
adminUserSvcAcctListCmd,
|
||||
adminUserSvcAcctRemoveCmd,
|
||||
adminUserSvcAcctInfoCmd,
|
||||
adminUserSvcAcctSetCmd,
|
||||
adminUserSvcAcctEnableCmd,
|
||||
adminUserSvcAcctDisableCmd,
|
||||
}
|
||||
|
||||
var adminUserSvcAcctCmd = cli.Command{
|
||||
Name: "svcacct",
|
||||
Usage: "manage service accounts",
|
||||
Action: mainAdminUserSvcAcct,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
Subcommands: adminUserSvcAcctSubcommands,
|
||||
HideHelpCommand: true,
|
||||
}
|
||||
|
||||
// mainAdminUserSvcAcct is the handle for "mc admin user svcacct" command.
|
||||
func mainAdminUserSvcAcct(ctx *cli.Context) error {
|
||||
commandNotFound(ctx, adminUserSvcAcctSubcommands)
|
||||
return nil
|
||||
}
|
||||
+13
-18
@@ -18,30 +18,25 @@ package cmd
|
||||
|
||||
import "github.com/minio/cli"
|
||||
|
||||
var adminUserSubcommands = []cli.Command{
|
||||
adminUserAddCmd,
|
||||
adminUserDisableCmd,
|
||||
adminUserEnableCmd,
|
||||
adminUserRemoveCmd,
|
||||
adminUserListCmd,
|
||||
adminUserInfoCmd,
|
||||
adminUserPolicyCmd,
|
||||
adminUserSvcAcctCmd,
|
||||
}
|
||||
|
||||
var adminUserCmd = cli.Command{
|
||||
Name: "user",
|
||||
Usage: "manage users",
|
||||
Action: mainAdminUser,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
Subcommands: adminUserSubcommands,
|
||||
Name: "user",
|
||||
Usage: "manage users",
|
||||
Action: mainAdminUser,
|
||||
Flags: globalFlags,
|
||||
Subcommands: []cli.Command{
|
||||
adminUserAddCmd,
|
||||
adminUserDisableCmd,
|
||||
adminUserEnableCmd,
|
||||
adminUserRemoveCmd,
|
||||
adminUserListCmd,
|
||||
adminUserInfoCmd,
|
||||
},
|
||||
HideHelpCommand: true,
|
||||
}
|
||||
|
||||
// mainAdminUser is the handle for "mc admin config" command.
|
||||
func mainAdminUser(ctx *cli.Context) error {
|
||||
commandNotFound(ctx, adminUserSubcommands)
|
||||
cli.ShowCommandHelp(ctx, ctx.Args().First())
|
||||
return nil
|
||||
// Sub-commands like "get", "set" have their own main.
|
||||
}
|
||||
|
||||
+32
-98
@@ -96,7 +96,7 @@ func completeS3Path(s3Path string) (prediction []string) {
|
||||
|
||||
// List dirPath content and only pick elements that corresponds
|
||||
// to the path that we want to complete
|
||||
for content := range clnt.List(globalContext, ListOptions{Recursive: false, ShowDir: DirFirst}) {
|
||||
for content := range clnt.List(globalContext, false, false, false, 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.Aliases[filepath.Clean(a.LastCompleted)]; !ok {
|
||||
if _, ok := conf.Hosts[filepath.Clean(a.LastCompleted)]; !ok {
|
||||
if strings.IndexByte(arg, '/') == -1 {
|
||||
// Only predict alias since '/' is not found
|
||||
for alias := range conf.Aliases {
|
||||
for alias := range conf.Hosts {
|
||||
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.Aliases {
|
||||
for alias := range conf.Hosts {
|
||||
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.Aliases {
|
||||
for alias := range conf.Hosts {
|
||||
if strings.HasPrefix(alias, arg) {
|
||||
prediction = append(prediction, alias+"/")
|
||||
}
|
||||
@@ -228,76 +228,38 @@ 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),
|
||||
"/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),
|
||||
"/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,
|
||||
|
||||
"/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},
|
||||
"/replicate/status": s3Complete{deepLevel: 2},
|
||||
"/event/add": aliasCompleter,
|
||||
"/event/list": aliasCompleter,
|
||||
"/event/remove": aliasCompleter,
|
||||
|
||||
"/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,
|
||||
|
||||
@@ -326,8 +288,6 @@ var completeCmds = map[string]complete.Predictor{
|
||||
|
||||
"/admin/policy/info": aliasCompleter,
|
||||
"/admin/policy/set": aliasCompleter,
|
||||
"/admin/policy/unset": aliasCompleter,
|
||||
"/admin/policy/update": aliasCompleter,
|
||||
"/admin/policy/add": aliasCompleter,
|
||||
"/admin/policy/list": aliasCompleter,
|
||||
"/admin/policy/remove": aliasCompleter,
|
||||
@@ -338,15 +298,6 @@ var completeCmds = map[string]complete.Predictor{
|
||||
"/admin/user/list": aliasCompleter,
|
||||
"/admin/user/remove": aliasCompleter,
|
||||
"/admin/user/info": aliasCompleter,
|
||||
"/admin/user/policy": aliasCompleter,
|
||||
|
||||
"/admin/user/svcacct/add": aliasCompleter,
|
||||
"/admin/user/svcacct/ls": aliasCompleter,
|
||||
"/admin/user/svcacct/rm": aliasCompleter,
|
||||
"/admin/user/svcacct/info": aliasCompleter,
|
||||
"/admin/user/svcacct/set": aliasCompleter,
|
||||
"/admin/user/svcacct/enable": aliasCompleter,
|
||||
"/admin/user/svcacct/disable": aliasCompleter,
|
||||
|
||||
"/admin/group/add": aliasCompleter,
|
||||
"/admin/group/disable": aliasCompleter,
|
||||
@@ -355,23 +306,12 @@ var completeCmds = map[string]complete.Predictor{
|
||||
"/admin/group/remove": aliasCompleter,
|
||||
"/admin/group/info": aliasCompleter,
|
||||
|
||||
"/admin/bucket/remote/add": aliasCompleter,
|
||||
"/admin/bucket/remote/edit": aliasCompleter,
|
||||
"/admin/bucket/remote/ls": aliasCompleter,
|
||||
"/admin/bucket/remote/rm": aliasCompleter,
|
||||
"/admin/bucket/remote/bandwidth": aliasCompleter,
|
||||
"/admin/bucket/quota": aliasCompleter,
|
||||
"/config/host/add": nil,
|
||||
"/config/host/list": aliasCompleter,
|
||||
"/config/host/remove": aliasCompleter,
|
||||
|
||||
"/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,
|
||||
"/update": nil,
|
||||
"/version": nil,
|
||||
}
|
||||
|
||||
// flagsToCompleteFlags transforms a cli.Flag to complete.Flags
|
||||
@@ -400,9 +340,6 @@ 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)
|
||||
}
|
||||
|
||||
@@ -417,9 +354,6 @@ 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)
|
||||
|
||||
@@ -1,60 +0,0 @@
|
||||
/*
|
||||
* MinIO Client (C) 2020 MinIO, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"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)
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
+27
-60
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* MinIO Client, (C) 2015-2020 MinIO, Inc.
|
||||
* MinIO Client, (C) 2015, 2016, 2017 MinIO, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -25,7 +25,6 @@ import (
|
||||
"os"
|
||||
"strings"
|
||||
"syscall"
|
||||
"time"
|
||||
"unicode"
|
||||
"unicode/utf8"
|
||||
|
||||
@@ -34,26 +33,19 @@ import (
|
||||
)
|
||||
|
||||
var (
|
||||
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",
|
||||
},
|
||||
}
|
||||
// This is kept dummy for future purposes
|
||||
// and also to add ioFlags and globalFlags
|
||||
// in CLI registration.
|
||||
catFlags = []cli.Flag{}
|
||||
)
|
||||
|
||||
// Display contents of a file.
|
||||
var catCmd = cli.Command{
|
||||
Name: "cat",
|
||||
Usage: "display object contents",
|
||||
Action: mainCat,
|
||||
OnUsageError: onUsageError,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: append(append(catFlags, ioFlags...), globalFlags...),
|
||||
Name: "cat",
|
||||
Usage: "display object contents",
|
||||
Action: mainCat,
|
||||
Before: initBeforeRunningCmd,
|
||||
Flags: append(append(catFlags, ioFlags...), globalFlags...),
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
@@ -82,12 +74,6 @@ 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
|
||||
`,
|
||||
}
|
||||
|
||||
@@ -140,58 +126,38 @@ func (s prettyStdout) Write(input []byte) (int, error) {
|
||||
return inputLen, nil
|
||||
}
|
||||
|
||||
// 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")
|
||||
// checkCatSyntax performs command-line input validation for cat command.
|
||||
func checkCatSyntax(ctx *cli.Context) {
|
||||
args := ctx.Args()
|
||||
if !args.Present() {
|
||||
args = []string{"-"}
|
||||
}
|
||||
|
||||
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(ctx context.Context, sourceURL, sourceVersion string, timeRef time.Time, encKeyDB map[string][]prefixSSEPair) *probe.Error {
|
||||
func catURL(ctx context.Context, sourceURL string, 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:
|
||||
// 1. extract the size of S3 object so we can check if the size of the
|
||||
// Try to stat the object, the purpose is to extract the
|
||||
// size of S3 object so we can check if the size of the
|
||||
// downloaded object is equal to the original one. FS files
|
||||
// are ignored since some of them have zero size though they
|
||||
// have contents like files under /proc.
|
||||
// 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)
|
||||
client, content, err := url2Stat(ctx, sourceURL, false, encKeyDB)
|
||||
if err == nil && client.GetURL().Type == objectStorage {
|
||||
size = content.Size
|
||||
}
|
||||
if reader, err = getSourceStreamFromURL(ctx, sourceURL, versionID, encKeyDB); err != nil {
|
||||
if reader, err = getSourceStreamFromURL(ctx, sourceURL, encKeyDB); err != nil {
|
||||
return err.Trace(sourceURL)
|
||||
}
|
||||
defer reader.Close()
|
||||
@@ -254,11 +220,11 @@ func mainCat(cliCtx *cli.Context) error {
|
||||
fatalIf(err, "Unable to parse encryption keys.")
|
||||
|
||||
// check 'cat' cli arguments.
|
||||
args, versionID, rewind := parseCatSyntax(cliCtx)
|
||||
checkCatSyntax(cliCtx)
|
||||
|
||||
// Set command flags from context.
|
||||
stdinMode := false
|
||||
if len(args) == 0 {
|
||||
if !cliCtx.Args().Present() {
|
||||
stdinMode = true
|
||||
}
|
||||
|
||||
@@ -269,7 +235,8 @@ func mainCat(cliCtx *cli.Context) error {
|
||||
}
|
||||
|
||||
// if Args contain `-`, we need to preserve its order specially.
|
||||
if len(args) > 0 && args[0] == "-" {
|
||||
args := []string(cliCtx.Args())
|
||||
if cliCtx.Args().First() == "-" {
|
||||
for i, arg := range os.Args {
|
||||
if arg == "cat" {
|
||||
// Overwrite cliCtx.Args with os.Args.
|
||||
@@ -281,7 +248,7 @@ func mainCat(cliCtx *cli.Context) error {
|
||||
|
||||
// Convert arguments to URLs: expand alias, fix format.
|
||||
for _, url := range args {
|
||||
fatalIf(catURL(ctx, url, versionID, rewind, encKeyDB).Trace(url), "Unable to read from `"+url+"`.")
|
||||
fatalIf(catURL(ctx, url, encKeyDB).Trace(url), "Unable to read from `"+url+"`.")
|
||||
}
|
||||
|
||||
return nil
|
||||
|
||||
+34
-5
@@ -17,11 +17,12 @@
|
||||
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
|
||||
@@ -95,12 +96,40 @@ 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() {
|
||||
var e error
|
||||
globalRootCAs, e = certs.GetRootCAs(mustGetCAsDir())
|
||||
if e != nil {
|
||||
fatalIf(probe.NewError(e), "Unable to load certificates.")
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
+5
-5
@@ -29,7 +29,7 @@ import (
|
||||
"github.com/mattn/go-ieproxy"
|
||||
"github.com/minio/mc/pkg/httptracer"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/minio-go/v7/pkg/credentials"
|
||||
"github.com/minio/minio-go/v6/pkg/credentials"
|
||||
"github.com/minio/minio/pkg/madmin"
|
||||
)
|
||||
|
||||
@@ -131,21 +131,21 @@ func NewAdminFactory() func(config *Config) (*madmin.AdminClient, *probe.Error)
|
||||
|
||||
// newAdminClient gives a new client interface
|
||||
func newAdminClient(aliasedURL string) (*madmin.AdminClient, *probe.Error) {
|
||||
alias, urlStrFull, aliasCfg, err := expandAlias(aliasedURL)
|
||||
alias, urlStrFull, hostCfg, err := expandAlias(aliasedURL)
|
||||
if err != nil {
|
||||
return nil, err.Trace(aliasedURL)
|
||||
}
|
||||
// Verify if the aliasedURL is a real URL, fail in those cases
|
||||
// indicating the user to add alias.
|
||||
if aliasCfg == nil && urlRgx.MatchString(aliasedURL) {
|
||||
if hostCfg == nil && urlRgx.MatchString(aliasedURL) {
|
||||
return nil, errInvalidAliasedURL(aliasedURL).Trace(aliasedURL)
|
||||
}
|
||||
|
||||
if aliasCfg == nil {
|
||||
if hostCfg == nil {
|
||||
return nil, probe.NewError(fmt.Errorf("No valid configuration found for '%s' host alias", urlStrFull))
|
||||
}
|
||||
|
||||
s3Config := NewS3Config(urlStrFull, aliasCfg)
|
||||
s3Config := NewS3Config(urlStrFull, hostCfg)
|
||||
|
||||
s3Client, err := s3AdminNew(s3Config)
|
||||
if err != nil {
|
||||
|
||||
+2
-18
@@ -16,10 +16,7 @@
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
)
|
||||
import "fmt"
|
||||
|
||||
/// Collection of standard errors
|
||||
|
||||
@@ -157,25 +154,12 @@ func (e EmptyPath) Error() string {
|
||||
}
|
||||
|
||||
// ObjectMissing (EINVAL) - object key missing.
|
||||
type ObjectMissing struct {
|
||||
timeRef time.Time
|
||||
}
|
||||
type ObjectMissing struct{}
|
||||
|
||||
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
|
||||
|
||||
+107
-174
@@ -19,7 +19,6 @@ package cmd
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path"
|
||||
@@ -34,16 +33,14 @@ import (
|
||||
"github.com/pkg/xattr"
|
||||
"github.com/rjeczalik/notify"
|
||||
|
||||
"github.com/minio/mc/cmd/ilm"
|
||||
"github.com/minio/mc/pkg/disk"
|
||||
"github.com/minio/mc/pkg/hookreader"
|
||||
"github.com/minio/mc/pkg/ioutils"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
minio "github.com/minio/minio-go/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"
|
||||
minio "github.com/minio/minio-go/v6"
|
||||
"github.com/minio/minio-go/v6/pkg/encrypt"
|
||||
"github.com/minio/minio-go/v6/pkg/tags"
|
||||
)
|
||||
|
||||
// filesystem client
|
||||
@@ -52,10 +49,9 @@ type fsClient struct {
|
||||
}
|
||||
|
||||
const (
|
||||
partSuffix = ".part.minio"
|
||||
slashSeperator = "/"
|
||||
metadataKey = "X-Amz-Meta-Mc-Attrs"
|
||||
metadataKeyS3Cmd = "X-Amz-Meta-S3cmd-Attrs"
|
||||
partSuffix = ".part.minio"
|
||||
slashSeperator = "/"
|
||||
metaDataKey = "X-Amz-Meta-Mc-Attrs"
|
||||
)
|
||||
|
||||
var ( // GOOS specific ignore list.
|
||||
@@ -149,8 +145,7 @@ func (f *fsClient) Watch(ctx context.Context, options WatchOptions) (*WatchObjec
|
||||
case "get":
|
||||
fsEvents = append(fsEvents, EventTypeGet...)
|
||||
default:
|
||||
// Event type not supported by FS client, such as
|
||||
// bucket creation or deletion, ignore it.
|
||||
return nil, errInvalidArgument().Trace(event)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -202,19 +197,19 @@ func (f *fsClient) Watch(ctx context.Context, options WatchOptions) (*WatchObjec
|
||||
Time: UTCNow().Format(timeFormatFS),
|
||||
Size: i.Size(),
|
||||
Path: event.Path(),
|
||||
Type: notification.ObjectCreatedPut,
|
||||
Type: EventCreate,
|
||||
}}
|
||||
} else if IsDeleteEvent(event.Event()) {
|
||||
eventChan <- []EventInfo{{
|
||||
Time: UTCNow().Format(timeFormatFS),
|
||||
Path: event.Path(),
|
||||
Type: notification.ObjectRemovedDelete,
|
||||
Type: EventRemove,
|
||||
}}
|
||||
} else if IsGetEvent(event.Event()) {
|
||||
eventChan <- []EventInfo{{
|
||||
Time: UTCNow().Format(timeFormatFS),
|
||||
Path: event.Path(),
|
||||
Type: notification.ObjectAccessedGet,
|
||||
Type: EventAccessed,
|
||||
}}
|
||||
}
|
||||
}
|
||||
@@ -230,33 +225,49 @@ func (f *fsClient) Watch(ctx context.Context, options WatchOptions) (*WatchObjec
|
||||
func preserveAttributes(fd *os.File, attr map[string]string) *probe.Error {
|
||||
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)
|
||||
}
|
||||
if e != nil {
|
||||
return probe.NewError(e)
|
||||
}
|
||||
|
||||
// Attempt to change the file mode.
|
||||
if e := fd.Chmod(os.FileMode(mode)); e != nil {
|
||||
return probe.NewError(e)
|
||||
}
|
||||
}
|
||||
|
||||
var uid, gid int
|
||||
var gidExists, uidExists bool
|
||||
var e error
|
||||
if val, ok := attr["uid"]; ok {
|
||||
uid, e = strconv.Atoi(val)
|
||||
if e != nil {
|
||||
uid = -1
|
||||
return probe.NewError(e)
|
||||
}
|
||||
uidExists = true
|
||||
}
|
||||
|
||||
if val, ok := attr["gid"]; ok {
|
||||
gid, e = strconv.Atoi(val)
|
||||
if e != nil {
|
||||
gid = -1
|
||||
return probe.NewError(e)
|
||||
}
|
||||
gidExists = true
|
||||
}
|
||||
|
||||
// Attempt to change the owner.
|
||||
if e = fd.Chown(uid, gid); e != nil {
|
||||
return probe.NewError(e)
|
||||
if gidExists && uidExists {
|
||||
if e := fd.Chown(uid, gid); e != nil {
|
||||
return probe.NewError(e)
|
||||
}
|
||||
} else if uidExists {
|
||||
if e := fd.Chown(uid, -1); e != nil {
|
||||
return probe.NewError(e)
|
||||
}
|
||||
|
||||
} else {
|
||||
if e := fd.Chown(-1, gid); e != nil {
|
||||
return probe.NewError(e)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
@@ -264,7 +275,7 @@ func preserveAttributes(fd *os.File, attr map[string]string) *probe.Error {
|
||||
|
||||
/// Object operations.
|
||||
|
||||
func (f *fsClient) put(ctx context.Context, reader io.Reader, size int64, progress io.Reader, opts PutOptions) (int64, *probe.Error) {
|
||||
func (f *fsClient) put(ctx context.Context, reader io.Reader, size int64, metadata map[string][]string, progress io.Reader, preserve bool) (int64, *probe.Error) {
|
||||
// ContentType is not handled on purpose.
|
||||
// For filesystem this is a redundant information.
|
||||
|
||||
@@ -300,15 +311,15 @@ func (f *fsClient) put(ctx context.Context, reader io.Reader, size int64, progre
|
||||
}
|
||||
|
||||
attr := make(map[string]string)
|
||||
if _, ok := opts.metadata[metadataKey]; ok && opts.isPreserve {
|
||||
attr, e = parseAttribute(opts.metadata)
|
||||
if len(metadata[metaDataKey]) != 0 && preserve {
|
||||
attr, e = parseAttribute(metadata[metaDataKey][0])
|
||||
if e != nil {
|
||||
tmpFile.Close()
|
||||
return 0, probe.NewError(e)
|
||||
}
|
||||
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())))
|
||||
if err := preserveAttributes(tmpFile, attr); err != nil {
|
||||
tmpFile.Close()
|
||||
return 0, err.Trace(objectPath)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -358,13 +369,29 @@ func (f *fsClient) put(ctx context.Context, reader io.Reader, size int64, progre
|
||||
return totalWritten, err.Trace(objectPartPath, objectPath)
|
||||
}
|
||||
|
||||
if len(attr) != 0 && opts.isPreserve {
|
||||
atime, mtime, err := parseAtimeMtime(attr)
|
||||
if err != nil {
|
||||
return totalWritten, err.Trace()
|
||||
if len(attr) != 0 && preserve {
|
||||
var atime, mtime int64
|
||||
var e error
|
||||
var atimeChanged, mtimeChanged bool
|
||||
if val, ok := attr["atime"]; ok {
|
||||
atime, e = strconv.ParseInt(val, 10, 64)
|
||||
if e != nil {
|
||||
return totalWritten, probe.NewError(e)
|
||||
}
|
||||
atimeChanged = true
|
||||
}
|
||||
if !atime.IsZero() && !mtime.IsZero() {
|
||||
if e := os.Chtimes(objectPath, atime, mtime); e != nil {
|
||||
|
||||
if val, ok := attr["mtime"]; ok {
|
||||
mtime, e = strconv.ParseInt(val, 10, 64)
|
||||
if e != nil {
|
||||
return totalWritten, probe.NewError(e)
|
||||
}
|
||||
mtimeChanged = true
|
||||
}
|
||||
|
||||
// Attempt to change the access and modify time
|
||||
if atimeChanged && mtimeChanged {
|
||||
if e := os.Chtimes(objectPath, time.Unix(atime, 0), time.Unix(mtime, 0)); e != nil {
|
||||
return totalWritten, probe.NewError(e)
|
||||
}
|
||||
}
|
||||
@@ -374,12 +401,17 @@ func (f *fsClient) put(ctx context.Context, reader io.Reader, size int64, progre
|
||||
}
|
||||
|
||||
// Put - create a new file with metadata.
|
||||
func (f *fsClient) Put(ctx context.Context, reader io.Reader, size int64, progress io.Reader, opts PutOptions) (int64, *probe.Error) {
|
||||
return f.put(ctx, reader, size, progress, opts)
|
||||
func (f *fsClient) Put(ctx context.Context, reader io.Reader, size int64, metadata map[string]string, progress io.Reader, sse encrypt.ServerSide, md5, disableMultipart, preserve bool) (int64, *probe.Error) {
|
||||
if metadata[metaDataKey] != "" {
|
||||
meta := make(map[string][]string)
|
||||
meta[metaDataKey] = append(meta[metaDataKey], metadata[metaDataKey])
|
||||
return f.put(ctx, reader, size, meta, progress, preserve)
|
||||
}
|
||||
return f.put(ctx, reader, size, nil, progress, preserve)
|
||||
}
|
||||
|
||||
// ShareDownload - share download not implemented for filesystem.
|
||||
func (f *fsClient) ShareDownload(ctx context.Context, versionID string, expires time.Duration) (string, *probe.Error) {
|
||||
func (f *fsClient) ShareDownload(ctx context.Context, expires time.Duration) (string, *probe.Error) {
|
||||
return "", probe.NewError(APINotImplemented{
|
||||
API: "ShareDownload",
|
||||
APIType: "filesystem",
|
||||
@@ -387,7 +419,7 @@ func (f *fsClient) ShareDownload(ctx context.Context, versionID string, expires
|
||||
}
|
||||
|
||||
// ShareUpload - share upload not implemented for filesystem.
|
||||
func (f *fsClient) ShareUpload(ctx context.Context, startsWith bool, expires time.Duration, contentType string) (string, map[string]string, *probe.Error) {
|
||||
func (f *fsClient) ShareUpload(startsWith bool, expires time.Duration, contentType string) (string, map[string]string, *probe.Error) {
|
||||
return "", nil, probe.NewError(APINotImplemented{
|
||||
API: "ShareUpload",
|
||||
APIType: "filesystem",
|
||||
@@ -395,7 +427,7 @@ func (f *fsClient) ShareUpload(ctx context.Context, startsWith bool, expires tim
|
||||
}
|
||||
|
||||
// Copy - copy data from source to destination
|
||||
func (f *fsClient) Copy(ctx context.Context, source string, opts CopyOptions, progress io.Reader) *probe.Error {
|
||||
func (f *fsClient) Copy(ctx context.Context, source string, size int64, progress io.Reader, srcSSE, tgtSSE encrypt.ServerSide, metadata map[string]string, disableMultipart, preserve bool) *probe.Error {
|
||||
rc, e := os.Open(source)
|
||||
if e != nil {
|
||||
err := f.toClientError(e, source)
|
||||
@@ -403,20 +435,15 @@ func (f *fsClient) Copy(ctx context.Context, source string, opts CopyOptions, pr
|
||||
}
|
||||
defer rc.Close()
|
||||
|
||||
putOpts := PutOptions{
|
||||
metadata: opts.metadata,
|
||||
isPreserve: opts.isPreserve,
|
||||
}
|
||||
|
||||
destination := f.PathURL.Path
|
||||
if _, err := f.put(ctx, rc, opts.size, progress, putOpts); err != nil {
|
||||
if _, err := f.put(ctx, rc, size, map[string][]string{}, progress, preserve); err != nil {
|
||||
return err.Trace(destination, source)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Get returns reader and any additional metadata.
|
||||
func (f *fsClient) Get(ctx context.Context, opts GetOptions) (io.ReadCloser, *probe.Error) {
|
||||
func (f *fsClient) Get(ctx context.Context, sse encrypt.ServerSide) (io.ReadCloser, *probe.Error) {
|
||||
fileData, e := os.Open(f.PathURL.Path)
|
||||
if e != nil {
|
||||
err := f.toClientError(e, f.PathURL.Path)
|
||||
@@ -509,18 +536,18 @@ func (f *fsClient) Remove(ctx context.Context, isIncomplete, isRemoveBucket, isB
|
||||
}
|
||||
|
||||
// List - list files and folders.
|
||||
func (f *fsClient) List(ctx context.Context, opts ListOptions) <-chan *ClientContent {
|
||||
func (f *fsClient) List(ctx context.Context, isRecursive, isIncomplete, isMetadata bool, showDir DirOpt) <-chan *ClientContent {
|
||||
contentCh := make(chan *ClientContent)
|
||||
filteredCh := make(chan *ClientContent)
|
||||
|
||||
if opts.Recursive {
|
||||
if opts.ShowDir == DirNone {
|
||||
go f.listRecursiveInRoutine(contentCh, opts.WithMetadata)
|
||||
if isRecursive {
|
||||
if showDir == DirNone {
|
||||
go f.listRecursiveInRoutine(contentCh, isMetadata)
|
||||
} else {
|
||||
go f.listDirOpt(contentCh, opts.Incomplete, opts.WithMetadata, opts.ShowDir)
|
||||
go f.listDirOpt(contentCh, isIncomplete, isMetadata, showDir)
|
||||
}
|
||||
} else {
|
||||
go f.listInRoutine(contentCh, opts.WithMetadata)
|
||||
go f.listInRoutine(contentCh, isMetadata)
|
||||
}
|
||||
|
||||
// This function filters entries from any listing go routine
|
||||
@@ -528,7 +555,7 @@ func (f *fsClient) List(ctx context.Context, opts ListOptions) <-chan *ClientCon
|
||||
// only show partly uploaded files,
|
||||
go func() {
|
||||
for c := range contentCh {
|
||||
if opts.Incomplete {
|
||||
if isIncomplete {
|
||||
if !strings.HasSuffix(c.URL.Path, partSuffix) {
|
||||
continue
|
||||
}
|
||||
@@ -578,7 +605,9 @@ func readDir(dirname string) ([]os.FileInfo, error) {
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
defer f.Close()
|
||||
if e = f.Close(); e != nil {
|
||||
return nil, e
|
||||
}
|
||||
sort.Sort(byDirName(list))
|
||||
return list, nil
|
||||
}
|
||||
@@ -902,8 +931,8 @@ func (f *fsClient) SetObjectLockConfig(ctx context.Context, mode minio.Retention
|
||||
}
|
||||
|
||||
// Get object lock configuration of bucket.
|
||||
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{
|
||||
func (f *fsClient) GetObjectLockConfig(ctx context.Context) (mode minio.RetentionMode, validity uint64, unit minio.ValidityUnit, err *probe.Error) {
|
||||
return "", 0, "", probe.NewError(APINotImplemented{
|
||||
API: "GetObjectLockConfig",
|
||||
APIType: "filesystem",
|
||||
})
|
||||
@@ -918,36 +947,21 @@ func (f *fsClient) GetAccessRules(ctx context.Context) (map[string]string, *prob
|
||||
}
|
||||
|
||||
// Set object retention for a given object.
|
||||
func (f *fsClient) PutObjectRetention(ctx context.Context, versionID string, mode minio.RetentionMode, retainUntilDate time.Time, bypassGovernance bool) *probe.Error {
|
||||
func (f *fsClient) PutObjectRetention(ctx context.Context, mode minio.RetentionMode, retainUntilDate time.Time, bypassGovernance bool) *probe.Error {
|
||||
return probe.NewError(APINotImplemented{
|
||||
API: "PutObjectRetention",
|
||||
APIType: "filesystem",
|
||||
})
|
||||
}
|
||||
|
||||
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(ctx context.Context, versionID string, lhold minio.LegalHoldStatus) *probe.Error {
|
||||
func (f *fsClient) PutObjectLegalHold(ctx context.Context, lhold minio.LegalHoldStatus) *probe.Error {
|
||||
return probe.NewError(APINotImplemented{
|
||||
API: "PutObjectLegalHold",
|
||||
APIType: "filesystem",
|
||||
})
|
||||
}
|
||||
|
||||
// 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(ctx context.Context) (access string, policyJSON string, err *probe.Error) {
|
||||
// For windows this feature is not implemented.
|
||||
@@ -1006,8 +1020,8 @@ func (f *fsClient) SetAccess(ctx context.Context, access string, isJSON bool) *p
|
||||
}
|
||||
|
||||
// Stat - get metadata from path.
|
||||
func (f *fsClient) Stat(ctx context.Context, opts StatOptions) (content *ClientContent, err *probe.Error) {
|
||||
st, err := f.fsStat(opts.incomplete)
|
||||
func (f *fsClient) Stat(ctx context.Context, isIncomplete, isPreserve bool, sse encrypt.ServerSide) (content *ClientContent, err *probe.Error) {
|
||||
st, err := f.fsStat(isIncomplete)
|
||||
if err != nil {
|
||||
return nil, err.Trace(f.PathURL.String())
|
||||
}
|
||||
@@ -1022,21 +1036,21 @@ func (f *fsClient) Stat(ctx context.Context, opts StatOptions) (content *ClientC
|
||||
}
|
||||
|
||||
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 opts.preserve {
|
||||
if isPreserve {
|
||||
fileAttr, err := disk.GetFileSystemAttrs(path)
|
||||
if err != nil {
|
||||
return content, nil
|
||||
}
|
||||
metaData, pErr := getAllXattrs(path)
|
||||
if pErr != nil {
|
||||
return content, nil
|
||||
}
|
||||
for k, v := range metaData {
|
||||
content.Metadata[k] = v
|
||||
}
|
||||
content.Metadata[metadataKey] = fileAttr
|
||||
content.Metadata[metaDataKey] = fileAttr
|
||||
}
|
||||
|
||||
return content, nil
|
||||
@@ -1082,7 +1096,7 @@ func (f *fsClient) AddUserAgent(_, _ string) {
|
||||
}
|
||||
|
||||
// Get Object Tags
|
||||
func (f *fsClient) GetTags(ctx context.Context, _ string) (map[string]string, *probe.Error) {
|
||||
func (f *fsClient) GetTags(ctx context.Context) (*tags.Tags, *probe.Error) {
|
||||
return nil, probe.NewError(APINotImplemented{
|
||||
API: "GetObjectTagging",
|
||||
APIType: "filesystem",
|
||||
@@ -1090,7 +1104,7 @@ func (f *fsClient) GetTags(ctx context.Context, _ string) (map[string]string, *p
|
||||
}
|
||||
|
||||
// Set Object tags
|
||||
func (f *fsClient) SetTags(ctx context.Context, versionID, tags string) *probe.Error {
|
||||
func (f *fsClient) SetTags(ctx context.Context, tags string) *probe.Error {
|
||||
return probe.NewError(APINotImplemented{
|
||||
API: "SetObjectTagging",
|
||||
APIType: "filesystem",
|
||||
@@ -1098,7 +1112,7 @@ func (f *fsClient) SetTags(ctx context.Context, versionID, tags string) *probe.E
|
||||
}
|
||||
|
||||
// Delete object tags
|
||||
func (f *fsClient) DeleteTags(ctx context.Context, versionID string) *probe.Error {
|
||||
func (f *fsClient) DeleteTags(ctx context.Context) *probe.Error {
|
||||
return probe.NewError(APINotImplemented{
|
||||
API: "DeleteObjectTagging",
|
||||
APIType: "filesystem",
|
||||
@@ -1106,98 +1120,17 @@ func (f *fsClient) DeleteTags(ctx context.Context, versionID string) *probe.Erro
|
||||
}
|
||||
|
||||
// Get lifecycle configuration for a given bucket, not implemented.
|
||||
func (f *fsClient) GetLifecycle(ctx context.Context) (*lifecycle.Configuration, *probe.Error) {
|
||||
return nil, probe.NewError(APINotImplemented{
|
||||
func (f *fsClient) GetLifecycle(ctx context.Context) (ilm.LifecycleConfiguration, *probe.Error) {
|
||||
return ilm.LifecycleConfiguration{}, probe.NewError(APINotImplemented{
|
||||
API: "GetLifecycle",
|
||||
APIType: "filesystem",
|
||||
})
|
||||
}
|
||||
|
||||
// Set lifecycle configuration for a given bucket, not implemented.
|
||||
func (f *fsClient) SetLifecycle(ctx context.Context, _ *lifecycle.Configuration) *probe.Error {
|
||||
func (f *fsClient) SetLifecycle(ctx context.Context, _ ilm.LifecycleConfiguration) *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",
|
||||
})
|
||||
|
||||
}
|
||||
|
||||
// GetReplicationMetrics - Get replication metrics for a given bucket, not implemented.
|
||||
func (f *fsClient) GetReplicationMetrics(ctx context.Context) (replication.Metrics, *probe.Error) {
|
||||
return replication.Metrics{}, probe.NewError(APINotImplemented{
|
||||
API: "GetReplicationMetrics",
|
||||
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,5 +1,7 @@
|
||||
// +build freebsd
|
||||
|
||||
/*
|
||||
* MinIO Client (C) 2020 MinIO, Inc.
|
||||
* MinIO Client (C) 2017 MinIO, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this fs except in compliance with the License.
|
||||
|
||||
@@ -1,85 +0,0 @@
|
||||
/*
|
||||
* 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
|
||||
}
|
||||
+37
-57
@@ -43,12 +43,9 @@ func (s *TestSuite) TestList(c *C) {
|
||||
|
||||
reader := bytes.NewReader([]byte(data))
|
||||
var n int64
|
||||
n, err = fsClient.Put(context.Background(), reader, int64(len(data)), nil, PutOptions{
|
||||
metadata: map[string]string{
|
||||
"Content-Type": "application/octet-stream",
|
||||
},
|
||||
},
|
||||
)
|
||||
n, err = fsClient.Put(context.Background(), reader, int64(len(data)), map[string]string{
|
||||
"Content-Type": "application/octet-stream",
|
||||
}, nil, nil, false, false, false)
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(n, Equals, int64(len(data)))
|
||||
|
||||
@@ -57,11 +54,9 @@ func (s *TestSuite) TestList(c *C) {
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
reader = bytes.NewReader([]byte(data))
|
||||
n, err = fsClient.Put(context.Background(), reader, int64(len(data)), nil, PutOptions{
|
||||
metadata: map[string]string{
|
||||
"Content-Type": "application/octet-stream",
|
||||
},
|
||||
})
|
||||
n, err = fsClient.Put(context.Background(), reader, int64(len(data)), map[string]string{
|
||||
"Content-Type": "application/octet-stream",
|
||||
}, nil, nil, false, false, false)
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(n, Equals, int64(len(data)))
|
||||
|
||||
@@ -70,7 +65,7 @@ func (s *TestSuite) TestList(c *C) {
|
||||
|
||||
// Verify previously create files and list them.
|
||||
var contents []*ClientContent
|
||||
for content := range fsClient.List(globalContext, ListOptions{ShowDir: DirNone}) {
|
||||
for content := range fsClient.List(globalContext, false, false, false, DirNone) {
|
||||
if content.Err != nil {
|
||||
err = content.Err
|
||||
break
|
||||
@@ -87,11 +82,9 @@ func (s *TestSuite) TestList(c *C) {
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
reader = bytes.NewReader([]byte(data))
|
||||
n, err = fsClient.Put(context.Background(), reader, int64(len(data)), nil, PutOptions{
|
||||
metadata: map[string]string{
|
||||
"Content-Type": "application/octet-stream",
|
||||
},
|
||||
})
|
||||
n, err = fsClient.Put(context.Background(), reader, int64(len(data)), map[string]string{
|
||||
"Content-Type": "application/octet-stream",
|
||||
}, nil, nil, false, false, false)
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(n, Equals, int64(len(data)))
|
||||
|
||||
@@ -100,7 +93,7 @@ func (s *TestSuite) TestList(c *C) {
|
||||
|
||||
contents = nil
|
||||
// List non recursive to list only top level files.
|
||||
for content := range fsClient.List(globalContext, ListOptions{ShowDir: DirNone}) {
|
||||
for content := range fsClient.List(globalContext, false, false, false, DirNone) {
|
||||
if content.Err != nil {
|
||||
err = content.Err
|
||||
break
|
||||
@@ -116,7 +109,7 @@ func (s *TestSuite) TestList(c *C) {
|
||||
|
||||
contents = nil
|
||||
// List recursively all files and verify.
|
||||
for content := range fsClient.List(globalContext, ListOptions{Recursive: true, ShowDir: DirNone}) {
|
||||
for content := range fsClient.List(globalContext, true, false, false, DirNone) {
|
||||
if content.Err != nil {
|
||||
err = content.Err
|
||||
break
|
||||
@@ -149,11 +142,9 @@ func (s *TestSuite) TestList(c *C) {
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
reader = bytes.NewReader([]byte(data))
|
||||
n, err = fsClient.Put(context.Background(), reader, int64(len(data)), nil, PutOptions{
|
||||
metadata: map[string]string{
|
||||
"Content-Type": "application/octet-stream",
|
||||
},
|
||||
})
|
||||
n, err = fsClient.Put(context.Background(), reader, int64(len(data)), map[string]string{
|
||||
"Content-Type": "application/octet-stream",
|
||||
}, nil, nil, false, false, false)
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(n, Equals, int64(len(data)))
|
||||
|
||||
@@ -162,7 +153,7 @@ func (s *TestSuite) TestList(c *C) {
|
||||
|
||||
contents = nil
|
||||
// List recursively all files and verify.
|
||||
for content := range fsClient.List(globalContext, ListOptions{Recursive: true, ShowDir: DirNone}) {
|
||||
for content := range fsClient.List(globalContext, true, false, false, DirNone) {
|
||||
if content.Err != nil {
|
||||
err = content.Err
|
||||
break
|
||||
@@ -219,7 +210,7 @@ func (s *TestSuite) TestStatBucket(c *C) {
|
||||
c.Assert(err, IsNil)
|
||||
err = fsClient.MakeBucket(context.Background(), "us-east-1", true, false)
|
||||
c.Assert(err, IsNil)
|
||||
_, err = fsClient.Stat(context.Background(), StatOptions{})
|
||||
_, err = fsClient.Stat(context.Background(), false, false, nil)
|
||||
c.Assert(err, IsNil)
|
||||
}
|
||||
|
||||
@@ -258,13 +249,9 @@ func (s *TestSuite) TestPut(c *C) {
|
||||
data := "hello"
|
||||
reader := bytes.NewReader([]byte(data))
|
||||
var n int64
|
||||
n, err = fsClient.Put(context.Background(), reader, int64(len(data)), nil, PutOptions{
|
||||
metadata: map[string]string{
|
||||
"Content-Type": "application/octet-stream",
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
n, err = fsClient.Put(context.Background(), reader, int64(len(data)), map[string]string{
|
||||
"Content-Type": "application/octet-stream",
|
||||
}, nil, nil, false, false, false)
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(n, Equals, int64(len(data)))
|
||||
}
|
||||
@@ -282,14 +269,13 @@ func (s *TestSuite) TestGet(c *C) {
|
||||
data := "hello"
|
||||
var reader io.Reader
|
||||
reader = bytes.NewReader([]byte(data))
|
||||
n, err := fsClient.Put(context.Background(), reader, int64(len(data)), nil, PutOptions{
|
||||
metadata: map[string]string{
|
||||
"Content-Type": "application/octet-stream",
|
||||
}})
|
||||
n, err := fsClient.Put(context.Background(), reader, int64(len(data)), map[string]string{
|
||||
"Content-Type": "application/octet-stream",
|
||||
}, nil, nil, false, false, false)
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(n, Equals, int64(len(data)))
|
||||
|
||||
reader, err = fsClient.Get(context.Background(), GetOptions{})
|
||||
reader, err = fsClient.Get(context.Background(), nil)
|
||||
c.Assert(err, IsNil)
|
||||
var results bytes.Buffer
|
||||
_, e = io.Copy(&results, reader)
|
||||
@@ -311,15 +297,13 @@ func (s *TestSuite) TestGetRange(c *C) {
|
||||
data := "hello world"
|
||||
var reader io.Reader
|
||||
reader = bytes.NewReader([]byte(data))
|
||||
n, err := fsClient.Put(context.Background(), reader, int64(len(data)), nil, PutOptions{
|
||||
metadata: map[string]string{
|
||||
"Content-Type": "application/octet-stream",
|
||||
},
|
||||
})
|
||||
n, err := fsClient.Put(context.Background(), reader, int64(len(data)), map[string]string{
|
||||
"Content-Type": "application/octet-stream",
|
||||
}, nil, nil, false, false, false)
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(n, Equals, int64(len(data)))
|
||||
|
||||
reader, err = fsClient.Get(context.Background(), GetOptions{})
|
||||
reader, err = fsClient.Get(context.Background(), nil)
|
||||
c.Assert(err, IsNil)
|
||||
var results bytes.Buffer
|
||||
buf := make([]byte, 5)
|
||||
@@ -344,16 +328,13 @@ func (s *TestSuite) TestStatObject(c *C) {
|
||||
data := "hello"
|
||||
dataLen := len(data)
|
||||
reader := bytes.NewReader([]byte(data))
|
||||
n, err := fsClient.Put(context.Background(), reader, int64(dataLen), nil, PutOptions{
|
||||
metadata: map[string]string{
|
||||
"Content-Type": "application/octet-stream",
|
||||
},
|
||||
},
|
||||
)
|
||||
n, err := fsClient.Put(context.Background(), reader, int64(dataLen), map[string]string{
|
||||
"Content-Type": "application/octet-stream",
|
||||
}, nil, nil, false, false, false)
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(n, Equals, int64(len(data)))
|
||||
|
||||
content, err := fsClient.Stat(context.Background(), StatOptions{})
|
||||
content, err := fsClient.Stat(context.Background(), false, false, nil)
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(content.Size, Equals, int64(dataLen))
|
||||
}
|
||||
@@ -372,13 +353,12 @@ func (s *TestSuite) TestCopy(c *C) {
|
||||
|
||||
data := "hello world"
|
||||
reader := bytes.NewReader([]byte(data))
|
||||
n, err := fsClientSource.Put(context.Background(), reader, int64(len(data)), nil, PutOptions{
|
||||
metadata: map[string]string{
|
||||
"Content-Type": "application/octet-stream",
|
||||
},
|
||||
})
|
||||
n, err := fsClientSource.Put(context.Background(), reader, int64(len(data)), map[string]string{
|
||||
"Content-Type": "application/octet-stream",
|
||||
}, nil, nil, false, false, false)
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(n, Equals, int64(len(data)))
|
||||
err = fsClientTarget.Copy(context.Background(), sourcePath, CopyOptions{size: int64(len(data))}, nil)
|
||||
|
||||
err = fsClientTarget.Copy(context.Background(), sourcePath, int64(len(data)), nil, nil, nil, nil, false, false)
|
||||
c.Assert(err, IsNil)
|
||||
}
|
||||
|
||||
@@ -71,8 +71,8 @@ func (t traceV2) Response(resp *http.Response) (err error) {
|
||||
console.Debug(string(respTrace))
|
||||
}
|
||||
|
||||
if resp.TLS != nil {
|
||||
printTLSCertInfo(resp.TLS)
|
||||
if globalInsecure && resp.TLS != nil {
|
||||
dumpTLSCertificates(resp.TLS)
|
||||
}
|
||||
|
||||
return err
|
||||
|
||||
@@ -86,8 +86,8 @@ func (t traceV4) Response(resp *http.Response) (err error) {
|
||||
console.Debug(string(respTrace))
|
||||
}
|
||||
|
||||
if resp.TLS != nil {
|
||||
printTLSCertInfo(resp.TLS)
|
||||
if globalInsecure && resp.TLS != nil {
|
||||
dumpTLSCertificates(resp.TLS)
|
||||
}
|
||||
|
||||
return err
|
||||
|
||||
+618
-903
File diff suppressed because it is too large
Load Diff
+8
-10
@@ -25,7 +25,7 @@ import (
|
||||
"net/http/httptest"
|
||||
"strconv"
|
||||
|
||||
minio "github.com/minio/minio-go/v7"
|
||||
minio "github.com/minio/minio-go/v6"
|
||||
. "gopkg.in/check.v1"
|
||||
)
|
||||
|
||||
@@ -178,7 +178,7 @@ func (s *TestSuite) TestBucketOperations(c *C) {
|
||||
s3c, err = S3New(conf)
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
for content := range s3c.List(globalContext, ListOptions{ShowDir: DirNone}) {
|
||||
for content := range s3c.List(globalContext, false, false, false, DirNone) {
|
||||
c.Assert(content.Err, IsNil)
|
||||
c.Assert(content.Type.IsDir(), Equals, true)
|
||||
}
|
||||
@@ -187,7 +187,7 @@ func (s *TestSuite) TestBucketOperations(c *C) {
|
||||
s3c, err = S3New(conf)
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
for content := range s3c.List(globalContext, ListOptions{ShowDir: DirNone}) {
|
||||
for content := range s3c.List(globalContext, false, false, false, DirNone) {
|
||||
c.Assert(content.Err, IsNil)
|
||||
c.Assert(content.Type.IsDir(), Equals, true)
|
||||
}
|
||||
@@ -196,7 +196,7 @@ func (s *TestSuite) TestBucketOperations(c *C) {
|
||||
s3c, err = S3New(conf)
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
for content := range s3c.List(globalContext, ListOptions{ShowDir: DirNone}) {
|
||||
for content := range s3c.List(globalContext, false, false, false, DirNone) {
|
||||
c.Assert(content.Err, IsNil)
|
||||
c.Assert(content.Type.IsRegular(), Equals, true)
|
||||
}
|
||||
@@ -221,15 +221,13 @@ func (s *TestSuite) TestObjectOperations(c *C) {
|
||||
|
||||
var reader io.Reader
|
||||
reader = bytes.NewReader(object.data)
|
||||
n, err := s3c.Put(context.Background(), reader, int64(len(object.data)), nil, PutOptions{
|
||||
metadata: map[string]string{
|
||||
"Content-Type": "application/octet-stream",
|
||||
},
|
||||
})
|
||||
n, err := s3c.Put(context.Background(), reader, int64(len(object.data)), map[string]string{
|
||||
"Content-Type": "application/octet-stream",
|
||||
}, nil, nil, false, false, false)
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(n, Equals, int64(len(object.data)))
|
||||
|
||||
reader, err = s3c.Get(context.Background(), GetOptions{})
|
||||
reader, err = s3c.Get(context.Background(), nil)
|
||||
c.Assert(err, IsNil)
|
||||
var buffer bytes.Buffer
|
||||
{
|
||||
|
||||
+6
-20
@@ -23,7 +23,6 @@ import (
|
||||
"regexp"
|
||||
"runtime"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/minio/pkg/mimedb"
|
||||
@@ -185,7 +184,7 @@ func urlJoinPath(url1, url2 string) string {
|
||||
}
|
||||
|
||||
// url2Stat returns stat info for URL.
|
||||
func url2Stat(ctx context.Context, urlStr, versionID string, fileAttr bool, encKeyDB map[string][]prefixSSEPair, timeRef time.Time) (client Client, content *ClientContent, err *probe.Error) {
|
||||
func url2Stat(ctx context.Context, urlStr string, fileAttr bool, encKeyDB map[string][]prefixSSEPair) (client Client, content *ClientContent, err *probe.Error) {
|
||||
client, err = newClient(urlStr)
|
||||
if err != nil {
|
||||
return nil, nil, err.Trace(urlStr)
|
||||
@@ -193,29 +192,13 @@ func url2Stat(ctx context.Context, urlStr, versionID string, fileAttr bool, encK
|
||||
alias, _ := url2Alias(urlStr)
|
||||
sse := getSSE(urlStr, encKeyDB[alias])
|
||||
|
||||
content, err = client.Stat(ctx, StatOptions{preserve: fileAttr, sse: sse, timeRef: timeRef, versionID: versionID})
|
||||
content, err = client.Stat(ctx, false, fileAttr, sse)
|
||||
if err != nil {
|
||||
return nil, nil, err.Trace(urlStr)
|
||||
}
|
||||
return client, content, nil
|
||||
}
|
||||
|
||||
// firstURL2Stat returns the stat info of the first object having the specified prefix
|
||||
func firstURL2Stat(ctx context.Context, prefix string, timeRef time.Time) (client Client, content *ClientContent, err *probe.Error) {
|
||||
client, err = newClient(prefix)
|
||||
if err != nil {
|
||||
return nil, nil, err.Trace(prefix)
|
||||
}
|
||||
content = <-client.List(ctx, ListOptions{Recursive: true, TimeRef: timeRef, Count: 1})
|
||||
if content == nil {
|
||||
return nil, nil, probe.NewError(ObjectMissing{timeRef: timeRef}).Trace(prefix)
|
||||
}
|
||||
if content.Err != nil {
|
||||
return nil, nil, content.Err.Trace(prefix)
|
||||
}
|
||||
return client, content, nil
|
||||
}
|
||||
|
||||
// url2Alias separates alias and path from the URL. Aliased URL is of
|
||||
// the form alias/path/to/blah.
|
||||
func url2Alias(aliasedURL string) (alias, path string) {
|
||||
@@ -246,7 +229,10 @@ func isURLPrefixExists(urlPrefix string, incomplete bool) bool {
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
for entry := range clnt.List(globalContext, ListOptions{Recursive: false, Incomplete: incomplete, WithMetadata: false, ShowDir: DirNone}) {
|
||||
isRecursive := false
|
||||
isIncomplete := incomplete
|
||||
isFetchMeta := false
|
||||
for entry := range clnt.List(globalContext, isRecursive, isIncomplete, isFetchMeta, DirNone) {
|
||||
return entry.Err == nil
|
||||
}
|
||||
return false
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user