Compare commits
155
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
77f82e18b5 | ||
|
|
ed0b962588 | ||
|
|
7394ce0dd2 | ||
|
|
b01f0c7371 | ||
|
|
5bb5df85e2 | ||
|
|
ae1eab7d52 | ||
|
|
ee72571936 | ||
|
|
e5d2270535 | ||
|
|
2676e50bc1 | ||
|
|
f72d75db5a | ||
|
|
c305d62fd5 | ||
|
|
4e38f39e25 | ||
|
|
8576e735b1 | ||
|
|
9a180cece7 | ||
|
|
039be57dd2 | ||
|
|
3c9df3f2ea | ||
|
|
00fb114bce | ||
|
|
68f1d43f05 | ||
|
|
f71ad84bcf | ||
|
|
99c1b4365a | ||
|
|
18c1c94d85 | ||
|
|
b9f30231ca | ||
|
|
19d87ba475 | ||
|
|
bbfe579fef | ||
|
|
2c1e058767 | ||
|
|
0a686cf874 | ||
|
|
719f121225 | ||
|
|
b00526b153 | ||
|
|
391616f9cf | ||
|
|
ddda0fce2c | ||
|
|
0b4d69bc57 | ||
|
|
e929f89cee | ||
|
|
56f94fd375 | ||
|
|
2d305ce990 | ||
|
|
3296636c25 | ||
|
|
5349af0082 | ||
|
|
ceb07bee89 | ||
|
|
5ce725ba7d | ||
|
|
c652022dab | ||
|
|
d249b65941 | ||
|
|
b2d265dcc6 | ||
|
|
0f061900ee | ||
|
|
cf909e1063 | ||
|
|
c1d5d4cbb4 | ||
|
|
b3a00e0f8c | ||
|
|
06520070bb | ||
|
|
ce874fdc6a | ||
|
|
1e412f58a5 | ||
|
|
b0f40b4db7 | ||
|
|
10035268c4 | ||
|
|
9eb205cb62 | ||
|
|
0ba848a99e | ||
|
|
28909abaa4 | ||
|
|
383560b1c3 | ||
|
|
8585339d12 | ||
|
|
468ab39f41 | ||
|
|
217d92358b | ||
|
|
c32317ef80 | ||
|
|
089f833ce0 | ||
|
|
42b78ded3a | ||
|
|
147e8f5b3b | ||
|
|
e97f4324d5 | ||
|
|
859c5989a1 | ||
|
|
10c50368c5 | ||
|
|
bd925c01a1 | ||
|
|
030c8125eb | ||
|
|
6376279f15 | ||
|
|
5aee0b1c9e | ||
|
|
8d713ff927 | ||
|
|
318e707071 | ||
|
|
423ef1ba2a | ||
|
|
a4f20fe74c | ||
|
|
5cfac09600 | ||
|
|
b436cd2436 | ||
|
|
0019b7b83c | ||
|
|
cc8758c88d | ||
|
|
95e1f70eb5 | ||
|
|
b1a3941f22 | ||
|
|
147852cb37 | ||
|
|
bf7b5f620e | ||
|
|
f4dd5e4a07 | ||
|
|
19017536cc | ||
|
|
86907df91d | ||
|
|
1681e4497c | ||
|
|
35cb4b8177 | ||
|
|
bb4ff4951a | ||
|
|
308a8ea9d0 | ||
|
|
63eb4a4609 | ||
|
|
6ac18619cf | ||
|
|
95a03f54da | ||
|
|
9f4659884d | ||
|
|
a814b5deaf | ||
|
|
65aa514dfa | ||
|
|
d9b81b2956 | ||
|
|
2c4e3ad46b | ||
|
|
bad9b2c737 | ||
|
|
e20dea646f | ||
|
|
cf128de2cf | ||
|
|
07eeb10c06 | ||
|
|
ce0b434152 | ||
|
|
4616d11c20 | ||
|
|
609f32a4ff | ||
|
|
97fe232a9a | ||
|
|
a5a54b4429 | ||
|
|
be874766a7 | ||
|
|
3dac3d392f | ||
|
|
11ebe952ea | ||
|
|
37095dadcc | ||
|
|
41aca25f6c | ||
|
|
bbfe577d2e | ||
|
|
04c5116c9b | ||
|
|
f2d65b6c18 | ||
|
|
3092b6bf14 | ||
|
|
25ea06308f | ||
|
|
54268c4808 | ||
|
|
ba97441b5e | ||
|
|
efc60a8a90 | ||
|
|
a55d9a8d17 | ||
|
|
6801d70e55 | ||
|
|
2e10255b6d | ||
|
|
efa1b396f2 | ||
|
|
aca5c185fe | ||
|
|
690f3f8bb3 | ||
|
|
2c94b8d039 | ||
|
|
456709a2a4 | ||
|
|
479171e7be | ||
|
|
b34cd742cb | ||
|
|
21ab58a03f | ||
|
|
32b7b72193 | ||
|
|
e7d1e97852 | ||
|
|
d6886b33d2 | ||
|
|
487b874a2e | ||
|
|
58f15fca83 | ||
|
|
a56899e13c | ||
|
|
3cb570ff56 | ||
|
|
28d64f224a | ||
|
|
f0d2ad4708 | ||
|
|
6a06daa1de | ||
|
|
8ad22bb694 | ||
|
|
73e614aee9 | ||
|
|
58c42bc91b | ||
|
|
f6df01d750 | ||
|
|
ded36374e8 | ||
|
|
11034f9de1 | ||
|
|
4d498deb35 | ||
|
|
ddfd44cb35 | ||
|
|
ea33d018ca | ||
|
|
21d3ec0089 | ||
|
|
661e19b3b2 | ||
|
|
d6ff970125 | ||
|
|
26680ab77c | ||
|
|
7e4b64d12a | ||
|
|
74032bc16a | ||
|
|
bbdd9638f2 | ||
|
|
e0d2e95984 |
@@ -20,7 +20,7 @@ jobs:
|
||||
runs-on: ${{ matrix.os }}
|
||||
strategy:
|
||||
matrix:
|
||||
go-version: [1.21.x, 1.22.x]
|
||||
go-version: [1.25.x]
|
||||
os: [ubuntu-latest]
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
@@ -19,7 +19,7 @@ jobs:
|
||||
GO111MODULE: on
|
||||
strategy:
|
||||
matrix:
|
||||
go-version: [1.22.x]
|
||||
go-version: [1.25.x]
|
||||
os: [ubuntu-latest, macos-latest, windows-latest]
|
||||
steps:
|
||||
- name: Set up Go ${{ matrix.go-version }} on ${{ matrix.os }}
|
||||
@@ -69,7 +69,7 @@ jobs:
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@v2
|
||||
with:
|
||||
go-version: 1.22.x
|
||||
go-version: 1.24.x
|
||||
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v2
|
||||
@@ -77,6 +77,3 @@ jobs:
|
||||
- name: Test 386
|
||||
run: GOOS=linux GOARCH=386 go test -short ./...
|
||||
|
||||
- name: Staticcheck
|
||||
# Run with defaults, but allow errors with other formats ST1005
|
||||
run: go install honnef.co/go/tools/cmd/staticcheck@latest && make lint
|
||||
|
||||
@@ -16,8 +16,7 @@ jobs:
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: 1.22.x
|
||||
check-latest: true
|
||||
go-version: 1.25.x
|
||||
- name: Get official govulncheck
|
||||
run: go install golang.org/x/vuln/cmd/govulncheck@latest
|
||||
shell: bash
|
||||
|
||||
+2
-1
@@ -14,4 +14,5 @@ mc
|
||||
mc.RELEASE*
|
||||
mc.gz
|
||||
.DS_Store
|
||||
.vscode/
|
||||
.vscode/
|
||||
.bin/
|
||||
|
||||
+37
-27
@@ -1,32 +1,42 @@
|
||||
version: "2"
|
||||
linters:
|
||||
disable-all: true
|
||||
default: none
|
||||
enable:
|
||||
- typecheck
|
||||
- goimports
|
||||
- misspell
|
||||
- staticcheck
|
||||
- govet
|
||||
- revive
|
||||
- ineffassign
|
||||
- gomodguard
|
||||
- gofmt
|
||||
- govet
|
||||
- ineffassign
|
||||
- misspell
|
||||
- revive
|
||||
- staticcheck
|
||||
- unused
|
||||
settings:
|
||||
misspell:
|
||||
locale: US
|
||||
exclusions:
|
||||
generated: lax
|
||||
rules:
|
||||
- path: (.+)\.go$
|
||||
text: instead of using struct literal
|
||||
- path: (.+)\.go$
|
||||
text: should have a package comment
|
||||
- path: (.+)\.go$
|
||||
text: error strings should not be capitalized or end with punctuation or a newline
|
||||
- path: (.+)\.go$
|
||||
text: error strings should not end with punctuation or newlines
|
||||
- path: (.+)\.go$
|
||||
text: error strings should not be capitalized
|
||||
paths:
|
||||
- third_party$
|
||||
- builtin$
|
||||
- examples$
|
||||
formatters:
|
||||
enable:
|
||||
- gofmt
|
||||
- gofumpt
|
||||
|
||||
linters-settings:
|
||||
golint:
|
||||
min-confidence: 0
|
||||
|
||||
misspell:
|
||||
locale: US
|
||||
|
||||
# Choose whether or not to use the extra rules that are disabled
|
||||
# by default
|
||||
extra-rules: false
|
||||
|
||||
issues:
|
||||
exclude-use-default: false
|
||||
exclude:
|
||||
- instead of using struct literal
|
||||
- should have a package comment
|
||||
- error strings should not be capitalized or end with punctuation or a newline
|
||||
- goimports
|
||||
exclusions:
|
||||
generated: lax
|
||||
paths:
|
||||
- third_party$
|
||||
- builtin$
|
||||
- examples$
|
||||
|
||||
+2
-2
@@ -1,4 +1,4 @@
|
||||
FROM golang:1.21-alpine as build
|
||||
FROM golang:1.22-alpine as build
|
||||
|
||||
LABEL maintainer="MinIO Inc <dev@min.io>"
|
||||
|
||||
@@ -19,4 +19,4 @@ COPY --from=build /go/CREDITS /licenses/CREDITS
|
||||
COPY --from=build /go/LICENSE /licenses/LICENSE
|
||||
COPY --from=build /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/
|
||||
|
||||
ENTRYPOINT ["mc"]
|
||||
ENTRYPOINT ["mc"]
|
||||
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
FROM --platform=linux/amd64 registry.access.redhat.com/ubi9/ubi-minimal:latest as build
|
||||
FROM registry.access.redhat.com/ubi9/ubi-minimal:latest AS build
|
||||
|
||||
RUN microdnf update --nodocs --assumeyes && microdnf install ca-certificates --nodocs --assumeyes
|
||||
|
||||
|
||||
@@ -1,24 +0,0 @@
|
||||
FROM --platform=linux/amd64 registry.access.redhat.com/ubi9/ubi-minimal:latest as build
|
||||
|
||||
RUN microdnf update --nodocs --assumeyes && microdnf install ca-certificates --nodocs --assumeyes
|
||||
|
||||
FROM registry.access.redhat.com/ubi9/ubi-micro:latest
|
||||
|
||||
ARG TARGETARCH
|
||||
ARG RELEASE
|
||||
|
||||
LABEL maintainer="MinIO Inc <dev@min.io>"
|
||||
|
||||
# On RHEL the certificate bundle is located at:
|
||||
# - /etc/pki/tls/certs/ca-bundle.crt (RHEL 6)
|
||||
# - /etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem (RHEL 7)
|
||||
COPY --from=build /etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem /etc/pki/ca-trust/extracted/pem/
|
||||
|
||||
COPY CREDITS /licenses/CREDITS
|
||||
COPY LICENSE /licenses/LICENSE
|
||||
|
||||
ADD https://dl.minio.io/client/mc/release/linux-${TARGETARCH}/archive/mc.${RELEASE}.fips /usr/bin/mc
|
||||
|
||||
RUN chmod +x /usr/bin/mc
|
||||
|
||||
ENTRYPOINT ["mc"]
|
||||
@@ -1,4 +1,4 @@
|
||||
FROM --platform=linux/amd64 registry.access.redhat.com/ubi8/ubi-minimal:latest as build
|
||||
FROM registry.access.redhat.com/ubi8/ubi-minimal:latest AS build
|
||||
|
||||
RUN microdnf update --nodocs --assumeyes && microdnf install ca-certificates --nodocs --assumeyes
|
||||
|
||||
|
||||
@@ -2,12 +2,14 @@ PWD := $(shell pwd)
|
||||
GOPATH := $(shell go env GOPATH)
|
||||
LDFLAGS := $(shell go run buildscripts/gen-ldflags.go)
|
||||
|
||||
GOARCH := $(shell go env GOARCH)
|
||||
GOOS := $(shell go env GOOS)
|
||||
TARGET_GOARCH ?= $(shell go env GOARCH)
|
||||
TARGET_GOOS ?= $(shell go env GOOS)
|
||||
|
||||
VERSION ?= $(shell git describe --tags)
|
||||
TAG ?= "minio/mc:$(VERSION)"
|
||||
|
||||
GOLANGCI = $(GOPATH)/bin/golangci-lint
|
||||
|
||||
all: build
|
||||
|
||||
checks:
|
||||
@@ -16,8 +18,7 @@ checks:
|
||||
|
||||
getdeps:
|
||||
@mkdir -p ${GOPATH}/bin
|
||||
@echo "Installing golangci-lint" && curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(GOPATH)/bin
|
||||
@echo "Installing stringer" && go install -v golang.org/x/tools/cmd/stringer@latest
|
||||
@echo "Installing tools" && go install tool
|
||||
|
||||
crosscompile:
|
||||
@(env bash $(PWD)/buildscripts/cross-compile.sh)
|
||||
@@ -31,9 +32,13 @@ vet:
|
||||
@echo "Running $@"
|
||||
@GO111MODULE=on go vet github.com/minio/mc/...
|
||||
|
||||
lint-fix: getdeps ## runs golangci-lint suite of linters with automatic fixes
|
||||
@echo "Running $@ check"
|
||||
@$(GOLANGCI) run --build-tags kqueue --timeout=10m --config ./.golangci.yml --fix
|
||||
|
||||
lint: getdeps
|
||||
@echo "Running $@ check"
|
||||
@GO111MODULE=on ${GOPATH}/bin/golangci-lint run --timeout=5m --config ./.golangci.yml
|
||||
@$(GOLANGCI) run --build-tags kqueue --timeout=10m --config ./.golangci.yml
|
||||
|
||||
# Builds mc, runs the verifiers then runs the tests.
|
||||
check: test
|
||||
@@ -57,7 +62,7 @@ verify:
|
||||
# Builds mc locally.
|
||||
build: checks
|
||||
@echo "Building mc binary to './mc'"
|
||||
@GO111MODULE=on CGO_ENABLED=0 go build -trimpath -tags kqueue --ldflags "$(LDFLAGS)" -o $(PWD)/mc
|
||||
@GO111MODULE=on GOOS=$(TARGET_GOOS) GOARCH=$(TARGET_GOARCH) CGO_ENABLED=0 go build -trimpath -tags kqueue --ldflags "$(LDFLAGS)" -o $(PWD)/mc
|
||||
|
||||
hotfix-vars:
|
||||
$(eval LDFLAGS := $(shell MC_RELEASE="RELEASE" MC_HOTFIX="hotfix.$(shell git rev-parse --short HEAD)" go run buildscripts/gen-ldflags.go $(shell git describe --tags --abbrev=0 | \
|
||||
@@ -71,9 +76,9 @@ hotfix: hotfix-vars install ## builds mc binary with hotfix tags
|
||||
@sha256sum < ./mc.$(VERSION) | sed 's, -,mc.$(VERSION),g' > mc.$(VERSION).sha256sum
|
||||
|
||||
hotfix-push: hotfix
|
||||
@scp -q -r mc.$(VERSION)* minio@dl-0.min.io:~/releases/client/mc/hotfixes/linux-amd64/archive/
|
||||
@scp -q -r mc.$(VERSION)* minio@dl-1.min.io:~/releases/client/mc/hotfixes/linux-amd64/archive/
|
||||
@echo "Published new hotfix binaries at https://dl.min.io/client/mc/hotfixes/linux-amd64/archive/mc.$(VERSION)"
|
||||
@scp -q -r mc.$(VERSION)* minio@dl-0.min.io:~/releases/client/mc/hotfixes/$(TARGET_GOOS)-$(TARGET_GOARCH)/archive/
|
||||
@scp -q -r mc.$(VERSION)* minio@dl-1.min.io:~/releases/client/mc/hotfixes/$(TARGET_GOOS)-$(TARGET_GOARCH)/archive/
|
||||
@echo "Published new hotfix binaries at https://dl.min.io/client/mc/hotfixes/$(TARGET_GOOS)-$(TARGET_GOARCH)/archive/mc.$(VERSION)"
|
||||
|
||||
docker-hotfix-push: docker-hotfix
|
||||
@docker push -q $(TAG) && echo "Published new container $(TAG)"
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
[](https://slack.min.io) [](https://goreportcard.com/report/minio/mc) [](https://hub.docker.com/r/minio/mc/) [](https://github.com/minio/mc/blob/master/LICENSE)
|
||||
|
||||
# Documentation
|
||||
- [MC documentation](https://min.io/docs/minio/linux/reference/minio-mc.html)
|
||||
- [MC documentation](https://docs.min.io/community/minio-object-store/reference/minio-mc.html)
|
||||
|
||||
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).
|
||||
|
||||
@@ -121,7 +121,7 @@ mc.exe --help
|
||||
```
|
||||
|
||||
## Install from Source
|
||||
Source installation is only intended for developers and advanced users. If you do not have a working Golang environment, please follow [How to install Golang](https://golang.org/doc/install). Minimum version required is [go1.17](https://golang.org/dl/#stable)
|
||||
Source installation is only intended for developers and advanced users. If you do not have a working Golang environment, please follow [How to install Golang](https://golang.org/doc/install). Minimum version required is [go1.22](https://golang.org/dl/#stable)
|
||||
|
||||
```sh
|
||||
go install github.com/minio/mc@latest
|
||||
|
||||
+3
-3
@@ -165,9 +165,9 @@ cat cp events mb pipe rm share version
|
||||
```
|
||||
|
||||
## 了解更多
|
||||
- [MinIO Client完全指南](https://min.io/docs/minio/linux/reference/minio-mc.html?ref=gh)
|
||||
- [MinIO快速入门](https://min.io/docs/minio/linux/index.html#quickstart-for-linux?ref=gh)
|
||||
- [MinIO官方文档](https://min.io/docs/minio/linux/index.html?ref=gh)
|
||||
- [MinIO Client完全指南](https://docs.min.io/community/minio-object-store/reference/minio-mc.html?ref=gh)
|
||||
- [MinIO快速入门](https://docs.min.io/community/minio-object-store/operations/deployments/baremetal-deploy-minio-on-redhat-linux.html?ref=gh)
|
||||
- [MinIO官方文档](https://docs.min.io/community/minio-object-store/index.html?ref=gh)
|
||||
|
||||
## 贡献
|
||||
请遵守MinIO[贡献者指南](https://github.com/minio/mc/blob/master/docs/zh_CN/CONTRIBUTING.md)
|
||||
|
||||
+43
-12
@@ -18,11 +18,14 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/pkg/v3/console"
|
||||
|
||||
"github.com/cheggaaa/pb"
|
||||
json "github.com/minio/colorjson"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
@@ -56,14 +59,14 @@ func newAccounter(total int64) *accounter {
|
||||
}
|
||||
|
||||
// write calculate the final speed.
|
||||
func (a *accounter) write(current int64) float64 {
|
||||
func (a *accounter) write(current int64) (float64, time.Duration) {
|
||||
fromStart := time.Since(a.startTime)
|
||||
currentFromStart := current - a.startValue
|
||||
if currentFromStart > 0 {
|
||||
speed := float64(currentFromStart) / (float64(fromStart) / float64(time.Second))
|
||||
return speed
|
||||
return speed, fromStart
|
||||
}
|
||||
return 0.0
|
||||
return 0.0, 0
|
||||
}
|
||||
|
||||
// writer update new accounting data for a specified refreshRate.
|
||||
@@ -81,10 +84,11 @@ func (a *accounter) writer() {
|
||||
|
||||
// accountStat cantainer for current stats captured.
|
||||
type accountStat struct {
|
||||
Status string `json:"status"`
|
||||
Total int64 `json:"total"`
|
||||
Transferred int64 `json:"transferred"`
|
||||
Speed float64 `json:"speed"`
|
||||
Status string `json:"status"`
|
||||
Total int64 `json:"total"`
|
||||
Transferred int64 `json:"transferred"`
|
||||
Duration time.Duration `json:"duration"`
|
||||
Speed float64 `json:"speed"`
|
||||
}
|
||||
|
||||
func (c accountStat) JSON() string {
|
||||
@@ -96,15 +100,42 @@ func (c accountStat) JSON() string {
|
||||
}
|
||||
|
||||
func (c accountStat) String() string {
|
||||
dspOrder := []col{colGreen} // Header
|
||||
dspOrder = append(dspOrder, colGrey)
|
||||
var printColors []*color.Color
|
||||
for _, c := range dspOrder {
|
||||
printColors = append(printColors, getPrintCol(c))
|
||||
}
|
||||
|
||||
tbl := console.NewTable(printColors, []bool{false, false, false, false}, 0)
|
||||
|
||||
var builder strings.Builder
|
||||
cellText := make([][]string, 0, 2)
|
||||
cellText = append(cellText, []string{
|
||||
"Total",
|
||||
"Transferred",
|
||||
"Duration",
|
||||
"Speed",
|
||||
})
|
||||
|
||||
speedBox := pb.Format(int64(c.Speed)).To(pb.U_BYTES).String()
|
||||
if speedBox == "" {
|
||||
speedBox = "0 MB"
|
||||
} else {
|
||||
speedBox = speedBox + "/s"
|
||||
}
|
||||
message := fmt.Sprintf("Total: %s, Transferred: %s, Speed: %s", pb.Format(c.Total).To(pb.U_BYTES),
|
||||
pb.Format(c.Transferred).To(pb.U_BYTES), speedBox)
|
||||
return message
|
||||
|
||||
cellText = append(cellText, []string{
|
||||
pb.Format(c.Total).To(pb.U_BYTES).String(),
|
||||
pb.Format(c.Transferred).To(pb.U_BYTES).String(),
|
||||
pb.Format(int64(c.Duration)).To(pb.U_DURATION).String(),
|
||||
speedBox,
|
||||
})
|
||||
|
||||
e := tbl.PopulateTable(&builder, cellText)
|
||||
fatalIf(probe.NewError(e), "unable to populate the table")
|
||||
|
||||
return builder.String()
|
||||
}
|
||||
|
||||
// Stat provides current stats captured.
|
||||
@@ -114,7 +145,7 @@ func (a *accounter) Stat() accountStat {
|
||||
close(a.isFinished)
|
||||
acntStat.Total = a.total
|
||||
acntStat.Transferred = atomic.LoadInt64(&a.current)
|
||||
acntStat.Speed = a.write(atomic.LoadInt64(&a.current))
|
||||
acntStat.Speed, acntStat.Duration = a.write(atomic.LoadInt64(&a.current))
|
||||
})
|
||||
return acntStat
|
||||
}
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
// Copyright (c) 2015-2024 MinIO, Inc.
|
||||
//
|
||||
// This file is part of MinIO Object Storage stack
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"github.com/minio/cli"
|
||||
)
|
||||
|
||||
var adminAccesskeyCreateFlags = []cli.Flag{
|
||||
cli.StringFlag{
|
||||
Name: "access-key",
|
||||
Usage: "set an access key for the account",
|
||||
},
|
||||
cli.StringFlag{
|
||||
Name: "secret-key",
|
||||
Usage: "set a secret key for the account",
|
||||
},
|
||||
cli.StringFlag{
|
||||
Name: "policy",
|
||||
Usage: "path to a JSON policy file",
|
||||
},
|
||||
cli.StringFlag{
|
||||
Name: "name",
|
||||
Usage: "friendly name for the account",
|
||||
},
|
||||
cli.StringFlag{
|
||||
Name: "description",
|
||||
Usage: "description for the account",
|
||||
},
|
||||
cli.StringFlag{
|
||||
Name: "expiry-duration",
|
||||
Usage: "duration before the access key expires",
|
||||
},
|
||||
cli.StringFlag{
|
||||
Name: "expiry",
|
||||
Usage: "expiry date for the access key",
|
||||
},
|
||||
}
|
||||
|
||||
var adminAccesskeyCreateCmd = cli.Command{
|
||||
Name: "create",
|
||||
Usage: "create access key pairs for users",
|
||||
Action: mainAdminAccesskeyCreate,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: append(adminAccesskeyCreateFlags, globalFlags...),
|
||||
OnUsageError: onUsageError,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
{{.HelpName}} [FLAGS] [TARGET]
|
||||
|
||||
FLAGS:
|
||||
{{range .VisibleFlags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
1. Create a new access key pair with the same policy as the authenticated user
|
||||
{{.Prompt}} {{.HelpName}} myminio/
|
||||
|
||||
2. Create a new access key pair with custom access key and secret key
|
||||
{{.Prompt}} {{.HelpName}} myminio/ --access-key myaccesskey --secret-key mysecretkey
|
||||
|
||||
3. Create a new access key pair for user 'tester' that expires in 1 day
|
||||
{{.Prompt}} {{.HelpName}} myminio/ tester --expiry-duration 24h
|
||||
|
||||
4. Create a new access key pair for authenticated user that expires on 2025-01-01
|
||||
{{.Prompt}} {{.HelpName}} --expiry 2025-01-01
|
||||
|
||||
5. Create a new access key pair for user 'tester' with a custom policy
|
||||
{{.Prompt}} {{.HelpName}} myminio/ tester --policy /path/to/policy.json
|
||||
|
||||
6. Create a new access key pair for user 'tester' with a custom name and description
|
||||
{{.Prompt}} {{.HelpName}} myminio/ tester --name "Tester's Access Key" --description "Access key for tester"
|
||||
`,
|
||||
}
|
||||
|
||||
func mainAdminAccesskeyCreate(ctx *cli.Context) error {
|
||||
return commonAccesskeyCreate(ctx, false)
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
// Copyright (c) 2015-2024 MinIO, Inc.
|
||||
//
|
||||
// This file is part of MinIO Object Storage stack
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"github.com/minio/cli"
|
||||
)
|
||||
|
||||
var adminAccesskeyDisableCmd = cli.Command{
|
||||
Name: "disable",
|
||||
Usage: "disable an access key",
|
||||
Action: mainAdminAccesskeyDisable,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
OnUsageError: onUsageError,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
{{.HelpName}} [FLAGS] [TARGET]
|
||||
|
||||
FLAGS:
|
||||
{{range .VisibleFlags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
1. Disable access key
|
||||
{{.Prompt}} {{.HelpName}} myminio myaccesskey
|
||||
`,
|
||||
}
|
||||
|
||||
func mainAdminAccesskeyDisable(ctx *cli.Context) error {
|
||||
return enableDisableAccesskey(ctx, false)
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
// Copyright (c) 2015-2024 MinIO, Inc.
|
||||
//
|
||||
// This file is part of MinIO Object Storage stack
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"github.com/minio/cli"
|
||||
)
|
||||
|
||||
var adminAccesskeyEditFlags = []cli.Flag{
|
||||
cli.StringFlag{
|
||||
Name: "secret-key",
|
||||
Usage: "set a secret key for the account",
|
||||
},
|
||||
cli.StringFlag{
|
||||
Name: "policy",
|
||||
Usage: "path to a JSON policy file",
|
||||
},
|
||||
cli.StringFlag{
|
||||
Name: "name",
|
||||
Usage: "friendly name for the account",
|
||||
},
|
||||
cli.StringFlag{
|
||||
Name: "description",
|
||||
Usage: "description for the account",
|
||||
},
|
||||
cli.StringFlag{
|
||||
Name: "expiry-duration",
|
||||
Usage: "duration before the access key expires",
|
||||
},
|
||||
cli.StringFlag{
|
||||
Name: "expiry",
|
||||
Usage: "expiry date for the access key",
|
||||
},
|
||||
}
|
||||
|
||||
var adminAccesskeyEditCmd = cli.Command{
|
||||
Name: "edit",
|
||||
Usage: "edit existing access keys",
|
||||
Action: mainAdminAccesskeyEdit,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: append(adminAccesskeyEditFlags, globalFlags...),
|
||||
OnUsageError: onUsageError,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
{{.HelpName}} [FLAGS] [TARGET]
|
||||
|
||||
FLAGS:
|
||||
{{range .VisibleFlags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
1. Change the secret key for the access key "testkey"
|
||||
{{.Prompt}} {{.HelpName}} myminio/ testkey --secret-key 'xxxxxxx'
|
||||
2. Change the expiry duration for the access key "testkey"
|
||||
{{.Prompt}} {{.HelpName}} myminio/ testkey ---expiry-duration 24h
|
||||
`,
|
||||
}
|
||||
|
||||
func mainAdminAccesskeyEdit(ctx *cli.Context) error {
|
||||
return commonAccesskeyEdit(ctx)
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
// Copyright (c) 2015-2024 MinIO, Inc.
|
||||
//
|
||||
// This file is part of MinIO Object Storage stack
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"github.com/minio/cli"
|
||||
)
|
||||
|
||||
var adminAccesskeyEnableCmd = cli.Command{
|
||||
Name: "enable",
|
||||
Usage: "enable an access key",
|
||||
Action: mainAdminAccesskeyEnable,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
OnUsageError: onUsageError,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
{{.HelpName}} [FLAGS] [TARGET]
|
||||
|
||||
FLAGS:
|
||||
{{range .VisibleFlags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
1. Enable access key
|
||||
{{.Prompt}} {{.HelpName}} myminio myaccesskey
|
||||
`,
|
||||
}
|
||||
|
||||
func mainAdminAccesskeyEnable(ctx *cli.Context) error {
|
||||
return enableDisableAccesskey(ctx, true)
|
||||
}
|
||||
@@ -0,0 +1,202 @@
|
||||
// Copyright (c) 2015-2023 MinIO, Inc.
|
||||
//
|
||||
// This file is part of MinIO Object Storage stack
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/charmbracelet/lipgloss"
|
||||
humanize "github.com/dustin/go-humanize"
|
||||
"github.com/minio/cli"
|
||||
json "github.com/minio/colorjson"
|
||||
"github.com/minio/madmin-go/v3"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
)
|
||||
|
||||
var adminAccesskeyInfoCmd = cli.Command{
|
||||
Name: "info",
|
||||
Usage: "info about given access key pairs",
|
||||
Action: mainAdminAccesskeyInfo,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
OnUsageError: onUsageError,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
{{.HelpName}} [FLAGS] TARGET ACCESSKEY [ACCESSKEY...]
|
||||
|
||||
FLAGS:
|
||||
{{range .VisibleFlags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
1. Get info for the access key "testkey"
|
||||
{{.Prompt}} {{.HelpName}} local/ testkey
|
||||
2. Get info for the access keys "testkey" and "testkey2"
|
||||
{{.Prompt}} {{.HelpName}} local/ testkey testkey2
|
||||
`,
|
||||
}
|
||||
|
||||
type accesskeyMessage struct {
|
||||
op string
|
||||
Status string `json:"status"`
|
||||
AccessKey string `json:"accessKey"`
|
||||
SecretKey string `json:"secretKey,omitempty"`
|
||||
STS bool `json:"sts,omitempty"`
|
||||
ParentUser string `json:"parentUser,omitempty"`
|
||||
AccountStatus string `json:"accountStatus,omitempty"`
|
||||
ImpliedPolicy bool `json:"impliedPolicy,omitempty"`
|
||||
Policy json.RawMessage `json:"policy,omitempty"`
|
||||
Name string `json:"name,omitempty"`
|
||||
Description string `json:"description,omitempty"`
|
||||
Expiration *time.Time `json:"expiration,omitempty"`
|
||||
Provider string `json:"provider,omitempty"`
|
||||
ProviderInfo providerInfo `json:"providerInfo,omitempty"`
|
||||
}
|
||||
|
||||
func (m accesskeyMessage) String() string {
|
||||
labelStyle := lipgloss.NewStyle().Foreground(lipgloss.Color("#04B575")) // green
|
||||
o := strings.Builder{}
|
||||
switch m.op {
|
||||
case "info":
|
||||
expirationStr := "NONE"
|
||||
if m.Expiration != nil && !m.Expiration.IsZero() && !m.Expiration.Equal(timeSentinel) {
|
||||
expirationStr = humanize.Time(*m.Expiration)
|
||||
}
|
||||
policyStr := "embedded"
|
||||
if m.ImpliedPolicy {
|
||||
policyStr = "implied"
|
||||
}
|
||||
statusStr := "enabled"
|
||||
if m.AccountStatus == "off" {
|
||||
statusStr = "disabled"
|
||||
}
|
||||
stsStr := "false"
|
||||
if m.STS {
|
||||
stsStr = "true"
|
||||
}
|
||||
o.WriteString(iFmt(0, "%s %s\n", labelStyle.Render("Access Key:"), m.AccessKey))
|
||||
o.WriteString(iFmt(0, "%s %s\n", labelStyle.Render("Parent User:"), m.ParentUser))
|
||||
o.WriteString(iFmt(0, "%s %s\n", labelStyle.Render("Status:"), statusStr))
|
||||
o.WriteString(iFmt(0, "%s %s\n", labelStyle.Render("Policy:"), policyStr))
|
||||
o.WriteString(iFmt(0, "%s %s\n", labelStyle.Render("Name:"), m.Name))
|
||||
o.WriteString(iFmt(0, "%s %s\n", labelStyle.Render("Description:"), m.Description))
|
||||
o.WriteString(iFmt(0, "%s %s\n", labelStyle.Render("Expiration:"), expirationStr))
|
||||
o.WriteString(iFmt(0, "%s %s\n", labelStyle.Render("STS:"), stsStr))
|
||||
o.WriteString(iFmt(0, "%s %s\n", labelStyle.Render("Provider:"), m.Provider))
|
||||
if m.ProviderInfo != nil {
|
||||
o.WriteString(iFmt(0, "%s\n", labelStyle.Render("Provider Specific Info:")))
|
||||
o.WriteString(m.ProviderInfo.String())
|
||||
}
|
||||
case "create":
|
||||
expirationStr := "NONE"
|
||||
if m.Expiration != nil && !m.Expiration.IsZero() && !m.Expiration.Equal(timeSentinel) {
|
||||
expirationStr = m.Expiration.String()
|
||||
}
|
||||
o.WriteString(iFmt(0, "%s %s\n", labelStyle.Render("Access Key:"), m.AccessKey))
|
||||
o.WriteString(iFmt(0, "%s %s\n", labelStyle.Render("Secret Key:"), m.SecretKey))
|
||||
o.WriteString(iFmt(0, "%s %s\n", labelStyle.Render("Expiration:"), expirationStr))
|
||||
o.WriteString(iFmt(0, "%s %s\n", labelStyle.Render("Name:"), m.Name))
|
||||
o.WriteString(iFmt(0, "%s %s\n", labelStyle.Render("Description:"), m.Description))
|
||||
case "remove":
|
||||
o.WriteString(labelStyle.Render(iFmt(0, "Successfully removed access key `%s`.", m.AccessKey)))
|
||||
case "edit":
|
||||
o.WriteString(labelStyle.Render(iFmt(0, "Successfully edited access key `%s`.", m.AccessKey)))
|
||||
case "enable":
|
||||
o.WriteString(labelStyle.Render(iFmt(0, "Successfully enabled access key `%s`.", m.AccessKey)))
|
||||
case "disable":
|
||||
o.WriteString(labelStyle.Render(iFmt(0, "Successfully disabled access key `%s`.", m.AccessKey)))
|
||||
}
|
||||
return o.String()
|
||||
}
|
||||
|
||||
func (m accesskeyMessage) JSON() string {
|
||||
m.Status = "success"
|
||||
jsonMessageBytes, e := json.MarshalIndent(m, "", " ")
|
||||
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
|
||||
|
||||
return string(jsonMessageBytes)
|
||||
}
|
||||
|
||||
type providerInfo interface {
|
||||
String() string
|
||||
}
|
||||
|
||||
func mainAdminAccesskeyInfo(ctx *cli.Context) error {
|
||||
return commonAccesskeyInfo(ctx)
|
||||
}
|
||||
|
||||
func commonAccesskeyInfo(ctx *cli.Context) error {
|
||||
if len(ctx.Args()) < 2 {
|
||||
showCommandHelpAndExit(ctx, 1) // last argument is exit code
|
||||
}
|
||||
|
||||
args := ctx.Args()
|
||||
aliasedURL := args.Get(0)
|
||||
accessKeys := args.Tail()
|
||||
|
||||
// Create a new MinIO Admin Client
|
||||
client, err := newAdminClient(aliasedURL)
|
||||
fatalIf(err, "Unable to initialize admin connection.")
|
||||
|
||||
for _, accessKey := range accessKeys {
|
||||
// Assume service account by default
|
||||
res, e := client.InfoAccessKey(globalContext, accessKey)
|
||||
fatalIf(probe.NewError(e), "Unable to get info for access key.")
|
||||
m := accesskeyMessage{
|
||||
op: "info",
|
||||
AccessKey: accessKey,
|
||||
ParentUser: res.ParentUser,
|
||||
AccountStatus: res.AccountStatus,
|
||||
ImpliedPolicy: res.ImpliedPolicy,
|
||||
Policy: json.RawMessage(res.Policy),
|
||||
Name: res.Name,
|
||||
Description: res.Description,
|
||||
Expiration: nilExpiry(res.Expiration),
|
||||
Provider: res.UserProvider,
|
||||
}
|
||||
|
||||
switch res.UserProvider {
|
||||
case madmin.LDAPProvider:
|
||||
info := res.LDAPSpecificInfo
|
||||
m.ProviderInfo = ldapAccessKeyInfo{
|
||||
Username: info.Username,
|
||||
}
|
||||
case madmin.OpenIDProvider:
|
||||
info := res.OpenIDSpecificInfo
|
||||
m.ProviderInfo = openIDAccessKeyInfo{
|
||||
ConfigName: info.ConfigName,
|
||||
UserID: info.UserID,
|
||||
UserIDClaim: info.UserIDClaim,
|
||||
DisplayName: info.DisplayName,
|
||||
DisplayNameClaim: info.DisplayNameClaim,
|
||||
}
|
||||
}
|
||||
printMsg(m)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func nilExpiry(expiry *time.Time) *time.Time {
|
||||
if expiry != nil && expiry.Equal(timeSentinel) {
|
||||
return nil
|
||||
}
|
||||
return expiry
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
// Copyright (c) 2015-2024 MinIO, Inc.
|
||||
//
|
||||
// This file is part of MinIO Object Storage stack
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"github.com/charmbracelet/lipgloss"
|
||||
humanize "github.com/dustin/go-humanize"
|
||||
"github.com/minio/cli"
|
||||
json "github.com/minio/colorjson"
|
||||
"github.com/minio/madmin-go/v3"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
)
|
||||
|
||||
var adminAccesskeyListFlags = []cli.Flag{
|
||||
cli.BoolFlag{
|
||||
Name: "users-only",
|
||||
Usage: "only list user DNs",
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "temp-only",
|
||||
Usage: "only list temporary access keys",
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "svcacc-only",
|
||||
Usage: "only list service account access keys",
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "self",
|
||||
Usage: "list access keys for the authenticated user",
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "all",
|
||||
Usage: "list all access keys for all builtin users",
|
||||
},
|
||||
}
|
||||
|
||||
var adminAccesskeyListCmd = cli.Command{
|
||||
Name: "list",
|
||||
ShortName: "ls",
|
||||
Usage: "list access key pairs for builtin users",
|
||||
Action: mainAdminAccesskeyList,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: append(adminAccesskeyListFlags, globalFlags...),
|
||||
OnUsageError: onUsageError,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
{{.HelpName}} [FLAGS] TARGET [DN...]
|
||||
|
||||
FLAGS:
|
||||
{{range .VisibleFlags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
1. Get list of all builtin users and associated access keys in local server
|
||||
{{.Prompt}} {{.HelpName}} local/ --all
|
||||
|
||||
2. Get list of access keys for the authenticated user in local server
|
||||
{{.Prompt}} {{.HelpName}} local/ --self
|
||||
|
||||
3. Get list of builtin users in local server
|
||||
{{.Prompt}} {{.HelpName}} local/ --all --users-only
|
||||
|
||||
4. Get list of all builtin users and associated temporary access keys in play server (if admin)
|
||||
{{.Prompt}} {{.HelpName}} play/ --temp-only
|
||||
|
||||
5. Get list of access keys associated with user 'foobar'
|
||||
{{.Prompt}} {{.HelpName}} play/ foobar
|
||||
|
||||
6. Get list of access keys associated with users 'foobar' and 'tester'
|
||||
{{.Prompt}} {{.HelpName}} play/ foobar tester
|
||||
|
||||
7. Get all users and access keys if admin, else get authenticated user and associated access keys
|
||||
{{.Prompt}} {{.HelpName}} local/
|
||||
`,
|
||||
}
|
||||
|
||||
type userAccesskeyList struct {
|
||||
Status string `json:"status"`
|
||||
User string `json:"user"`
|
||||
STSKeys []madmin.ServiceAccountInfo `json:"stsKeys"`
|
||||
ServiceAccounts []madmin.ServiceAccountInfo `json:"svcaccs"`
|
||||
LDAP bool `json:"ldap,omitempty"`
|
||||
}
|
||||
|
||||
func (m userAccesskeyList) String() string {
|
||||
labelStyle := lipgloss.NewStyle().Foreground(lipgloss.Color("#04B575"))
|
||||
o := strings.Builder{}
|
||||
|
||||
userStr := "User"
|
||||
if m.LDAP {
|
||||
userStr = "DN"
|
||||
}
|
||||
o.WriteString(iFmt(0, "%s %s\n", labelStyle.Render(userStr+":"), m.User))
|
||||
if len(m.STSKeys) > 0 || len(m.ServiceAccounts) > 0 {
|
||||
o.WriteString(iFmt(2, "%s\n", labelStyle.Render("Access Keys:")))
|
||||
}
|
||||
for _, k := range m.STSKeys {
|
||||
expiration := "never"
|
||||
if nilExpiry(k.Expiration) != nil {
|
||||
expiration = humanize.Time(*k.Expiration)
|
||||
}
|
||||
o.WriteString(iFmt(4, "%s, expires: %s, sts: true\n", k.AccessKey, expiration))
|
||||
}
|
||||
for _, k := range m.ServiceAccounts {
|
||||
expiration := "never"
|
||||
if nilExpiry(k.Expiration) != nil {
|
||||
expiration = humanize.Time(*k.Expiration)
|
||||
}
|
||||
o.WriteString(iFmt(4, "%s, expires: %s, sts: false\n", k.AccessKey, expiration))
|
||||
}
|
||||
|
||||
return o.String()
|
||||
}
|
||||
|
||||
func (m userAccesskeyList) JSON() string {
|
||||
jsonMessageBytes, e := json.MarshalIndent(m, "", " ")
|
||||
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
|
||||
|
||||
return string(jsonMessageBytes)
|
||||
}
|
||||
|
||||
func mainAdminAccesskeyList(ctx *cli.Context) error {
|
||||
aliasedURL, tentativeAll, users, opts := commonAccesskeyList(ctx)
|
||||
|
||||
// Create a new MinIO Admin Client
|
||||
client, err := newAdminClient(aliasedURL)
|
||||
fatalIf(err, "Unable to initialize admin connection.")
|
||||
|
||||
accessKeysMap, e := client.ListAccessKeysBulk(globalContext, users, opts)
|
||||
if e != nil {
|
||||
if e.Error() == "Access Denied." && tentativeAll {
|
||||
// retry with self
|
||||
opts.All = false
|
||||
accessKeysMap, e = client.ListAccessKeysBulk(globalContext, users, opts)
|
||||
}
|
||||
fatalIf(probe.NewError(e), "Unable to list access keys.")
|
||||
}
|
||||
|
||||
for user, accessKeys := range accessKeysMap {
|
||||
m := userAccesskeyList{
|
||||
Status: "success",
|
||||
User: user,
|
||||
ServiceAccounts: accessKeys.ServiceAccounts,
|
||||
STSKeys: accessKeys.STSKeys,
|
||||
LDAP: false,
|
||||
}
|
||||
printMsg(m)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
// Copyright (c) 2015-2024 MinIO, Inc.
|
||||
//
|
||||
// This file is part of MinIO Object Storage stack
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"github.com/minio/cli"
|
||||
)
|
||||
|
||||
var adminAccesskeyRemoveCmd = cli.Command{
|
||||
Name: "remove",
|
||||
ShortName: "rm",
|
||||
Usage: "delete access key pairs for builtin users",
|
||||
Action: mainAdminAccesskeyRemove,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
OnUsageError: onUsageError,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
{{.HelpName}} [FLAGS] TARGET ACCESSKEY
|
||||
|
||||
FLAGS:
|
||||
{{range .VisibleFlags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
1. Remove the access key "testkey" from local server
|
||||
{{.Prompt}} {{.HelpName}} local/ testkey
|
||||
`,
|
||||
}
|
||||
|
||||
func mainAdminAccesskeyRemove(ctx *cli.Context) error {
|
||||
return commonAccesskeyRemove(ctx)
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
// Copyright (c) 2015-2025 MinIO, Inc.
|
||||
//
|
||||
// This file is part of MinIO Object Storage stack
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"github.com/minio/cli"
|
||||
json "github.com/minio/colorjson"
|
||||
"github.com/minio/madmin-go/v3"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
)
|
||||
|
||||
var adminAccesskeySTSRevokeFlags = []cli.Flag{
|
||||
cli.BoolFlag{
|
||||
Name: "all",
|
||||
Usage: "revoke all STS accounts for the specified user",
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "self",
|
||||
Usage: "revoke all STS accounts for the authenticated user",
|
||||
},
|
||||
cli.StringFlag{
|
||||
Name: "token-type",
|
||||
Usage: "specify the token type to revoke",
|
||||
},
|
||||
}
|
||||
|
||||
var adminAccesskeySTSRevokeCmd = cli.Command{
|
||||
Name: "sts-revoke",
|
||||
Usage: "revokes all STS accounts or specified types for the specified user",
|
||||
Action: mainAdminAccesskeySTSRevoke,
|
||||
OnUsageError: onUsageError,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: append(adminAccesskeySTSRevokeFlags, globalFlags...),
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
{{.HelpName}} ALIAS USER [--all | --token-type TOKEN_TYPE]
|
||||
|
||||
Exactly one of --all or --token-type must be specified.
|
||||
|
||||
FLAGS:
|
||||
{{range .VisibleFlags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
1. Revoke all STS accounts for user "user1"
|
||||
{{.Prompt}} {{.HelpName}} myminio user1 --all
|
||||
|
||||
2. Revoke STS accounts of a token type "app-1" for user "user1"
|
||||
{{.Prompt}} {{.HelpName}} myminio user1 --token-type app-1
|
||||
|
||||
3. Revoke all STS accounts for the authenticated user
|
||||
{{.Prompt}} {{.HelpName}} myminio --self
|
||||
|
||||
4. Revoke STS accounts of a token type "app-1" for the authenticated user
|
||||
{{.Prompt}} {{.HelpName}} myminio --self --token-type app-1
|
||||
`,
|
||||
}
|
||||
|
||||
type stsRevokeMessage struct {
|
||||
Status string `json:"status"`
|
||||
User string `json:"user"`
|
||||
TokenRevokeType string `json:"tokenRevokeType,omitempty"`
|
||||
}
|
||||
|
||||
func (m stsRevokeMessage) String() string {
|
||||
userString := "user " + m.User
|
||||
if m.User == "" {
|
||||
userString = "authenticated user"
|
||||
}
|
||||
if m.TokenRevokeType == "" {
|
||||
return "Successfully revoked all STS accounts for " + userString
|
||||
}
|
||||
return "Successfully revoked all STS accounts of type " + m.TokenRevokeType + " for " + userString
|
||||
}
|
||||
|
||||
func (m stsRevokeMessage) JSON() string {
|
||||
if m.Status == "" {
|
||||
m.Status = "success"
|
||||
}
|
||||
jsonMessageBytes, e := json.MarshalIndent(m, "", " ")
|
||||
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
|
||||
|
||||
return string(jsonMessageBytes)
|
||||
}
|
||||
|
||||
// checkSTSRevokeSyntax - validate all the passed arguments
|
||||
func checkSTSRevokeSyntax(ctx *cli.Context) {
|
||||
if len(ctx.Args()) > 2 || len(ctx.Args()) == 0 {
|
||||
showCommandHelpAndExit(ctx, 1)
|
||||
}
|
||||
|
||||
if !ctx.Bool("self") && ctx.Args().Get(1) == "" {
|
||||
fatalIf(errInvalidArgument().Trace(), "Must specify user or use --self flag.")
|
||||
}
|
||||
|
||||
if ctx.Bool("self") && ctx.Args().Get(1) != "" {
|
||||
fatalIf(errInvalidArgument().Trace(), "Cannot specify user with --self flag.")
|
||||
}
|
||||
|
||||
if (!ctx.Bool("all") && ctx.String("token-type") == "") || (ctx.Bool("all") && ctx.String("token-type") != "") {
|
||||
fatalIf(errDummy().Trace(), "Exactly one of --all or --token-type must be specified.")
|
||||
}
|
||||
}
|
||||
|
||||
// mainAdminAccesskeySTSRevoke is the handle for "mc admin accesskey sts-revoke" command.
|
||||
func mainAdminAccesskeySTSRevoke(ctx *cli.Context) error {
|
||||
checkSTSRevokeSyntax(ctx)
|
||||
|
||||
// Get the alias parameter from cli
|
||||
args := ctx.Args()
|
||||
aliasedURL := args.Get(0)
|
||||
user := args.Get(1) // will be empty if --self flag is set
|
||||
tokenRevokeType := ctx.String("token-type")
|
||||
fullRevoke := ctx.Bool("all")
|
||||
|
||||
// Create a new MinIO Admin Client
|
||||
client, err := newAdminClient(aliasedURL)
|
||||
fatalIf(err, "Unable to initialize admin connection.")
|
||||
|
||||
e := client.RevokeTokens(globalContext, madmin.RevokeTokensReq{
|
||||
User: user,
|
||||
TokenRevokeType: tokenRevokeType,
|
||||
FullRevoke: fullRevoke,
|
||||
})
|
||||
fatalIf(probe.NewError(e).Trace(args...), "Unable to revoke tokens for %s", user)
|
||||
|
||||
printMsg(stsRevokeMessage{
|
||||
User: user,
|
||||
TokenRevokeType: tokenRevokeType,
|
||||
})
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
// Copyright (c) 2015-2024 MinIO, Inc.
|
||||
//
|
||||
// This file is part of MinIO Object Storage stack
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package cmd
|
||||
|
||||
import "github.com/minio/cli"
|
||||
|
||||
var adminAccesskeySubcommands = []cli.Command{
|
||||
adminAccesskeyListCmd,
|
||||
adminAccesskeyRemoveCmd,
|
||||
adminAccesskeyInfoCmd,
|
||||
adminAccesskeyCreateCmd,
|
||||
adminAccesskeyEditCmd,
|
||||
adminAccesskeyEnableCmd,
|
||||
adminAccesskeyDisableCmd,
|
||||
adminAccesskeySTSRevokeCmd,
|
||||
}
|
||||
|
||||
var adminAccesskeyCmd = cli.Command{
|
||||
Name: "accesskey",
|
||||
Usage: "manage access keys defined in the MinIO server",
|
||||
Action: mainAdminAccesskey,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
Subcommands: adminAccesskeySubcommands,
|
||||
HideHelpCommand: true,
|
||||
}
|
||||
|
||||
func mainAdminAccesskey(ctx *cli.Context) error {
|
||||
commandNotFound(ctx, adminAccesskeySubcommands)
|
||||
return nil
|
||||
}
|
||||
@@ -121,7 +121,6 @@ func TestGetBandwidthInBytes(t *testing.T) {
|
||||
}
|
||||
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)
|
||||
|
||||
@@ -119,6 +119,11 @@ func mainClusterBucketExport(ctx *cli.Context) error {
|
||||
}
|
||||
fatalIf(probe.NewError(moveFile(tmpFile.Name(), downloadPath)), "Unable to rename downloaded data, file exists at %s", tmpFile.Name())
|
||||
|
||||
// Explicitly set permissions to 0o600 and override umask
|
||||
// to ensure that the file is not world-readable.
|
||||
e = os.Chmod(downloadPath, 0o600)
|
||||
fatalIf(probe.NewError(e), "Unable to set file permissions for "+downloadPath)
|
||||
|
||||
if !globalJSON {
|
||||
console.Infof("Bucket metadata successfully downloaded as %s\n", downloadPath)
|
||||
return nil
|
||||
|
||||
@@ -96,6 +96,7 @@ func mainClusterBucketImport(ctx *cli.Context) error {
|
||||
|
||||
f, e = os.Open(args.Get(1))
|
||||
fatalIf(probe.NewError(e).Trace(args...), "Unable to get bucket metadata")
|
||||
defer f.Close()
|
||||
|
||||
// Create a new MinIO Admin Client
|
||||
client, err := newAdminClient(aliasedURL)
|
||||
@@ -141,14 +142,15 @@ func statusTick(s madmin.MetaStatus) string {
|
||||
}
|
||||
|
||||
func (i importMetaMsg) String() string {
|
||||
m := i.BucketMetaImportErrs.Buckets
|
||||
m := i.Buckets
|
||||
totBuckets := len(m)
|
||||
totErrs := 0
|
||||
for _, st := range m {
|
||||
if st.ObjectLock.Err != "" || st.Versioning.Err != "" ||
|
||||
st.SSEConfig.Err != "" || st.Tagging.Err != "" ||
|
||||
st.Lifecycle.Err != "" || st.Quota.Err != "" ||
|
||||
st.Policy.Err != "" || st.Notification.Err != "" {
|
||||
st.Policy.Err != "" || st.Notification.Err != "" ||
|
||||
st.Cors.Err != "" || st.Err != "" {
|
||||
totErrs++
|
||||
}
|
||||
}
|
||||
@@ -168,7 +170,8 @@ func (i importMetaMsg) String() string {
|
||||
if st.ObjectLock.Err != "" || st.Versioning.Err != "" ||
|
||||
st.SSEConfig.Err != "" || st.Tagging.Err != "" ||
|
||||
st.Lifecycle.Err != "" || st.Quota.Err != "" ||
|
||||
st.Policy.Err != "" || st.Notification.Err != "" {
|
||||
st.Policy.Err != "" || st.Notification.Err != "" ||
|
||||
st.Cors.Err != "" || st.Err != "" {
|
||||
fmt.Fprintln(&b, printImportErrs(bucket, st))
|
||||
}
|
||||
}
|
||||
@@ -183,7 +186,7 @@ func (i importMetaMsg) JSON() string {
|
||||
// Disable escaping special chars to display XML tags correctly
|
||||
enc.SetEscapeHTML(false)
|
||||
|
||||
fatalIf(probe.NewError(enc.Encode(i.BucketMetaImportErrs.Buckets)), "Unable to marshal into JSON.")
|
||||
fatalIf(probe.NewError(enc.Encode(i.Buckets)), "Unable to marshal into JSON.")
|
||||
return buf.String()
|
||||
}
|
||||
|
||||
@@ -194,6 +197,10 @@ func printImportErrs(bucket string, r madmin.BucketStatus) string {
|
||||
key := fmt.Sprintf("%-10s: %s", "Name", bucket)
|
||||
fmt.Fprintln(&b, console.Colorize("Name", key))
|
||||
|
||||
if r.Err != "" {
|
||||
fmt.Fprintf(&b, "%2s%s %s", placeHolder, console.Colorize("errors", "Error: "), r.Err)
|
||||
fmt.Fprintln(&b)
|
||||
}
|
||||
if r.ObjectLock.IsSet {
|
||||
fmt.Fprintf(&b, "%2s%s %s", placeHolder, "Object lock: ", statusTick(r.ObjectLock))
|
||||
fmt.Fprintln(&b)
|
||||
@@ -227,5 +234,9 @@ func printImportErrs(bucket string, r madmin.BucketStatus) string {
|
||||
fmt.Fprintf(&b, "%2s%s %s", placeHolder, "Tagging: ", statusTick(r.Tagging))
|
||||
fmt.Fprintln(&b)
|
||||
}
|
||||
if r.Cors.IsSet {
|
||||
fmt.Fprintf(&b, "%2s%s %s", placeHolder, "CORS: ", statusTick(r.Cors))
|
||||
fmt.Fprintln(&b)
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
@@ -32,13 +32,23 @@ import (
|
||||
"github.com/minio/pkg/v3/console"
|
||||
)
|
||||
|
||||
// iam export specific flags.
|
||||
var (
|
||||
iamExportFlags = []cli.Flag{
|
||||
cli.StringFlag{
|
||||
Name: "output,o",
|
||||
Usage: "output iam export to a custom file path",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
var adminClusterIAMExportCmd = cli.Command{
|
||||
Name: "export",
|
||||
Usage: "exports IAM info to zipped file",
|
||||
Action: mainClusterIAMExport,
|
||||
OnUsageError: onUsageError,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
Flags: append(iamExportFlags, globalFlags...),
|
||||
HideHelpCommand: true,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
@@ -52,6 +62,9 @@ FLAGS:
|
||||
EXAMPLES:
|
||||
1. Download all IAM metadata for cluster into zip file.
|
||||
{{.Prompt}} {{.HelpName}} myminio
|
||||
|
||||
2. Download all IAM metadata to a custom file.
|
||||
{{.Prompt}} {{.HelpName}} myminio --output /tmp/myminio-iam.zip
|
||||
`,
|
||||
}
|
||||
|
||||
@@ -97,6 +110,9 @@ func mainClusterIAMExport(ctx *cli.Context) error {
|
||||
tmpFile.Close()
|
||||
|
||||
downloadPath := fmt.Sprintf("%s-iam-info.%s", aliasedURL, ext)
|
||||
if ctx.String("output") != "" {
|
||||
downloadPath = ctx.String("output")
|
||||
}
|
||||
fi, e := os.Stat(downloadPath)
|
||||
if e == nil && !fi.IsDir() {
|
||||
e = moveFile(downloadPath, downloadPath+"."+time.Now().Format(dateTimeFormatFilename))
|
||||
@@ -109,6 +125,11 @@ func mainClusterIAMExport(ctx *cli.Context) error {
|
||||
|
||||
fatalIf(probe.NewError(moveFile(tmpFile.Name(), downloadPath)), "Unable to rename downloaded data, file exists at %s", tmpFile.Name())
|
||||
|
||||
// Explicitly set permissions to 0o600 and override umask
|
||||
// to ensure that the file is not world-readable.
|
||||
e = os.Chmod(downloadPath, 0o600)
|
||||
fatalIf(probe.NewError(e), "Unable to set file permissions for "+downloadPath)
|
||||
|
||||
if !globalJSON {
|
||||
console.Infof("IAM info successfully downloaded as %s\n", downloadPath)
|
||||
return nil
|
||||
|
||||
@@ -23,9 +23,12 @@ import (
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/klauspost/compress/zip"
|
||||
"github.com/minio/cli"
|
||||
json "github.com/minio/colorjson"
|
||||
"github.com/minio/madmin-go/v3"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/pkg/v3/console"
|
||||
)
|
||||
@@ -54,6 +57,123 @@ EXAMPLES:
|
||||
`,
|
||||
}
|
||||
|
||||
type iamImportInfo madmin.ImportIAMResult
|
||||
|
||||
func (i iamImportInfo) JSON() string {
|
||||
bs, e := json.MarshalIndent(madmin.ImportIAMResult(i), "", " ")
|
||||
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
|
||||
return string(bs)
|
||||
}
|
||||
|
||||
func (i iamImportInfo) String() string {
|
||||
var messages []string
|
||||
info := madmin.ImportIAMResult(i)
|
||||
messages = append(messages, processIAMEntities(info.Skipped, "Skipped")...)
|
||||
messages = append(messages, processIAMEntities(info.Removed, "Removed")...)
|
||||
messages = append(messages, processIAMEntities(info.Added, "Added")...)
|
||||
messages = append(messages, processErrIAMEntities(info.Failed)...)
|
||||
return strings.Join(messages, "\n")
|
||||
}
|
||||
|
||||
func processIAMEntities(entities madmin.IAMEntities, action string) []string {
|
||||
var messages []string
|
||||
if len(entities.Policies) > 0 {
|
||||
messages = append(messages, fmt.Sprintf("%s policies: %v", action, strings.Join(entities.Policies, ", ")))
|
||||
}
|
||||
if len(entities.Users) > 0 {
|
||||
messages = append(messages, fmt.Sprintf("%s users: %v", action, strings.Join(entities.Users, ", ")))
|
||||
}
|
||||
if len(entities.Groups) > 0 {
|
||||
messages = append(messages, fmt.Sprintf("%s groups: %v", action, strings.Join(entities.Groups, ", ")))
|
||||
}
|
||||
if len(entities.ServiceAccounts) > 0 {
|
||||
messages = append(messages, fmt.Sprintf("%s service accounts: %v", action, strings.Join(entities.ServiceAccounts, ", ")))
|
||||
}
|
||||
var users []string
|
||||
for _, pol := range entities.UserPolicies {
|
||||
for name := range pol {
|
||||
users = append(users, name)
|
||||
}
|
||||
}
|
||||
if len(users) > 0 {
|
||||
messages = append(messages, fmt.Sprintf("%s policies for users: %v", action, strings.Join(users, ", ")))
|
||||
}
|
||||
var groups []string
|
||||
for _, pol := range entities.GroupPolicies {
|
||||
for name := range pol {
|
||||
groups = append(groups, name)
|
||||
}
|
||||
}
|
||||
if len(groups) > 0 {
|
||||
messages = append(messages, fmt.Sprintf("%s policies for groups: %v", action, strings.Join(groups, ", ")))
|
||||
}
|
||||
var stsarr []string
|
||||
for _, pol := range entities.STSPolicies {
|
||||
for name := range pol {
|
||||
stsarr = append(stsarr, name)
|
||||
}
|
||||
}
|
||||
if len(stsarr) > 0 {
|
||||
messages = append(messages, fmt.Sprintf("%s policies for sts: %v", action, strings.Join(stsarr, ", ")))
|
||||
}
|
||||
return messages
|
||||
}
|
||||
|
||||
func processErrIAMEntities(entities madmin.IAMErrEntities) []string {
|
||||
var messages []string
|
||||
|
||||
var policies []string
|
||||
for _, entry := range entities.Policies {
|
||||
policies = append(policies, entry.Name)
|
||||
}
|
||||
if len(policies) > 0 {
|
||||
messages = append(messages, fmt.Sprintf("Failed to add policies: %v", strings.Join(policies, ", ")))
|
||||
}
|
||||
var users []string
|
||||
for _, entry := range entities.Users {
|
||||
users = append(users, entry.Name)
|
||||
}
|
||||
if len(users) > 0 {
|
||||
messages = append(messages, fmt.Sprintf("Failed to add users: %v", strings.Join(users, ", ")))
|
||||
}
|
||||
var groups []string
|
||||
for _, entry := range entities.Groups {
|
||||
groups = append(groups, entry.Name)
|
||||
}
|
||||
if len(groups) > 0 {
|
||||
messages = append(messages, fmt.Sprintf("Failed to add groups: %v", strings.Join(groups, ", ")))
|
||||
}
|
||||
var sas []string
|
||||
for _, entry := range entities.ServiceAccounts {
|
||||
sas = append(sas, entry.Name)
|
||||
}
|
||||
if len(sas) > 0 {
|
||||
messages = append(messages, fmt.Sprintf("Failed to add service accounts: %v", strings.Join(sas, ", ")))
|
||||
}
|
||||
var polusers []string
|
||||
for _, pol := range entities.UserPolicies {
|
||||
polusers = append(polusers, pol.Name)
|
||||
}
|
||||
if len(polusers) > 0 {
|
||||
messages = append(messages, fmt.Sprintf("Failed to add policies for users: %v", strings.Join(polusers, ", ")))
|
||||
}
|
||||
var polgroups []string
|
||||
for _, pol := range entities.GroupPolicies {
|
||||
polgroups = append(polgroups, pol.Name)
|
||||
}
|
||||
if len(polgroups) > 0 {
|
||||
messages = append(messages, fmt.Sprintf("Failed to add policies for groups: %v", strings.Join(polgroups, ", ")))
|
||||
}
|
||||
var polsts []string
|
||||
for _, pol := range entities.STSPolicies {
|
||||
polsts = append(polsts, pol.Name)
|
||||
}
|
||||
if len(polsts) > 0 {
|
||||
messages = append(messages, fmt.Sprintf("Failed to add policies for sts: %v", strings.Join(polsts, ", ")))
|
||||
}
|
||||
return messages
|
||||
}
|
||||
|
||||
func checkIAMImportSyntax(ctx *cli.Context) {
|
||||
if len(ctx.Args()) != 2 {
|
||||
showCommandHelpAndExit(ctx, 1) // last argument is exit code
|
||||
@@ -87,6 +207,7 @@ func mainClusterIAMImport(ctx *cli.Context) error {
|
||||
|
||||
f, e = os.Open(args.Get(1))
|
||||
fatalIf(probe.NewError(e).Trace(args...), "Unable to get IAM info")
|
||||
defer f.Close()
|
||||
|
||||
// Create a new MinIO Admin Client
|
||||
client, err := newAdminClient(aliasedURL)
|
||||
@@ -95,11 +216,17 @@ func mainClusterIAMImport(ctx *cli.Context) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
e = client.ImportIAM(context.Background(), f)
|
||||
fatalIf(probe.NewError(e).Trace(aliasedURL), "Unable to import IAM info.")
|
||||
|
||||
if !globalJSON {
|
||||
console.Infof("IAM info imported to %s from %s\n", aliasedURL, args.Get(1))
|
||||
iamr, e := client.ImportIAMV2(context.Background(), f)
|
||||
if e != nil {
|
||||
f.Seek(0, 0)
|
||||
e = client.ImportIAM(context.Background(), f)
|
||||
fatalIf(probe.NewError(e).Trace(aliasedURL), "Unable to import IAM info.")
|
||||
if !globalJSON {
|
||||
console.Infof("IAM info imported to %s from %s\n", aliasedURL, args.Get(1))
|
||||
}
|
||||
} else {
|
||||
printMsg(iamImportInfo(iamr))
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -127,7 +127,7 @@ func mainAdminConfigHistory(ctx *cli.Context) error {
|
||||
client, err := newAdminClient(aliasedURL)
|
||||
fatalIf(err, "Unable to initialize admin connection.")
|
||||
|
||||
if ctx.IsSet("clear") {
|
||||
if ctx.Bool("clear") {
|
||||
fatalIf(probe.NewError(client.ClearConfigHistoryKV(globalContext, "all")), "Unable to clear server configuration.")
|
||||
|
||||
// Print
|
||||
|
||||
@@ -116,13 +116,13 @@ func mainAdminConfigReset(ctx *cli.Context) error {
|
||||
|
||||
if len(ctx.Args()) == 1 {
|
||||
// Call get config API
|
||||
hr, e := client.HelpConfigKV(globalContext, "", "", ctx.IsSet("env"))
|
||||
hr, e := client.HelpConfigKV(globalContext, "", "", ctx.Bool("env"))
|
||||
fatalIf(probe.NewError(e), "Unable to get help for the sub-system")
|
||||
|
||||
// Print
|
||||
printMsg(configHelpMessage{
|
||||
Value: hr,
|
||||
envOnly: ctx.IsSet("env"),
|
||||
envOnly: ctx.Bool("env"),
|
||||
})
|
||||
|
||||
return nil
|
||||
|
||||
@@ -112,13 +112,13 @@ 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"))
|
||||
hr, e := client.HelpConfigKV(globalContext, args.Get(1), args.Get(2), ctx.Bool("env"))
|
||||
fatalIf(probe.NewError(e), "Unable to get help for the sub-system")
|
||||
|
||||
// Print
|
||||
printMsg(configHelpMessage{
|
||||
Value: hr,
|
||||
envOnly: ctx.IsSet("env"),
|
||||
envOnly: ctx.Bool("env"),
|
||||
})
|
||||
|
||||
return nil
|
||||
|
||||
@@ -125,7 +125,7 @@ func mainAdminDecommissionStatus(ctx *cli.Context) error {
|
||||
}
|
||||
|
||||
dspOrder := []col{colGreen} // Header
|
||||
for i := 0; i < len(poolStatuses); i++ {
|
||||
for range poolStatuses {
|
||||
dspOrder = append(dspOrder, colGrey)
|
||||
}
|
||||
var printColors []*color.Color
|
||||
|
||||
@@ -18,6 +18,7 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/minio/madmin-go/v3"
|
||||
@@ -49,12 +50,52 @@ func (h hri) getObjectHCCChange() (b, a col, err error) {
|
||||
}
|
||||
a, err = getHColCode(surplusShardsAfterHeal, parityShards)
|
||||
if err != nil {
|
||||
err = fmt.Errorf("%w: surplusShardsBeforeHeal: %d, parityShards: %d",
|
||||
err = fmt.Errorf("%w: surplusShardsAfterHeal: %d, parityShards: %d",
|
||||
err, surplusShardsAfterHeal, parityShards)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// getBucketHCCChange - fetches health color code for bucket healing
|
||||
// this does not return a Grey color since it does not have any meaning
|
||||
// for a bucket healing. Return green if the bucket is found in a drive,
|
||||
// yellow for missing, and red for everything else, grey for weird situations
|
||||
func (h hri) getBucketHCCChange() (b, a col, err error) {
|
||||
if h.HealResultItem == nil {
|
||||
return colGrey, colGrey, errors.New("empty result")
|
||||
}
|
||||
|
||||
getColCode := func(drives []madmin.HealDriveInfo) (c col) {
|
||||
var missing, unavailable int
|
||||
for i := range drives {
|
||||
switch drives[i].State {
|
||||
case madmin.DriveStateOk:
|
||||
case madmin.DriveStateMissing:
|
||||
missing++
|
||||
default:
|
||||
unavailable++
|
||||
}
|
||||
}
|
||||
if unavailable > 0 {
|
||||
return colRed
|
||||
}
|
||||
if missing > 0 {
|
||||
return colYellow
|
||||
}
|
||||
return colGreen
|
||||
}
|
||||
|
||||
a, b = colGrey, colGrey
|
||||
|
||||
if len(h.Before.Drives) > 0 {
|
||||
b = getColCode(h.Before.Drives)
|
||||
}
|
||||
if len(h.After.Drives) > 0 {
|
||||
a = getColCode(h.After.Drives)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// getReplicatedFileHCCChange - fetches health color code for metadata
|
||||
// files that are replicated.
|
||||
func (h hri) getReplicatedFileHCCChange() (b, a col, err error) {
|
||||
|
||||
+26
-16
@@ -52,7 +52,7 @@ var (
|
||||
|
||||
func getHColCode(surplusShards, parityShards int) (c col, err error) {
|
||||
if parityShards < 1 || parityShards > 8 || surplusShards > parityShards {
|
||||
return c, fmt.Errorf("Invalid parity shard count/surplus shard count given")
|
||||
return c, errors.New("Invalid parity shard count/surplus shard count given")
|
||||
}
|
||||
if surplusShards < 0 {
|
||||
return colGrey, err
|
||||
@@ -63,7 +63,7 @@ func getHColCode(surplusShards, parityShards int) (c col, err error) {
|
||||
return hColOrder[index], err
|
||||
}
|
||||
}
|
||||
return c, fmt.Errorf("cannot get a heal color code")
|
||||
return c, errors.New("cannot get a heal color code")
|
||||
}
|
||||
|
||||
type uiData struct {
|
||||
@@ -127,7 +127,9 @@ func (ui *uiData) updateStats(i madmin.HealResultItem) error {
|
||||
var afterCol col
|
||||
h := newHRI(&i)
|
||||
switch h.Type {
|
||||
case madmin.HealItemMetadata, madmin.HealItemBucket:
|
||||
case madmin.HealItemBucket:
|
||||
_, afterCol, err = h.getBucketHCCChange()
|
||||
case madmin.HealItemMetadata, madmin.HealItemBucketMetadata:
|
||||
_, afterCol, err = h.getReplicatedFileHCCChange()
|
||||
default:
|
||||
_, afterCol, err = h.getObjectHCCChange()
|
||||
@@ -205,17 +207,24 @@ func (ui *uiData) printItemsQuietly(s *madmin.HealTaskStatus) (err error) {
|
||||
var b, a col
|
||||
for _, item := range s.Items {
|
||||
h := newHRI(&item)
|
||||
hrStr := h.getHealResultStr()
|
||||
switch h.Type {
|
||||
case madmin.HealItemMetadata, madmin.HealItemBucket:
|
||||
case madmin.HealItemBucket:
|
||||
b, a, err = h.getBucketHCCChange()
|
||||
case madmin.HealItemMetadata, madmin.HealItemBucketMetadata:
|
||||
b, a, err = h.getReplicatedFileHCCChange()
|
||||
default:
|
||||
b, a, err = h.getObjectHCCChange()
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
errMsg := err.Error()
|
||||
if h.Detail != "" {
|
||||
errMsg = h.Detail
|
||||
}
|
||||
console.PrintC("[ERROR] ** ", hrStr, " **", ": ", errMsg, "\n")
|
||||
continue
|
||||
}
|
||||
printColStr(b, a)
|
||||
hrStr := h.getHealResultStr()
|
||||
switch h.Type {
|
||||
case madmin.HealItemMetadata, madmin.HealItemBucketMetadata:
|
||||
console.PrintC(fmt.Sprintln("**", hrStr, "**"))
|
||||
@@ -240,6 +249,7 @@ func (ui *uiData) printItemsJSON(s *madmin.HealTaskStatus) (err error) {
|
||||
type healRec struct {
|
||||
Status string `json:"status"`
|
||||
Error string `json:"error,omitempty"`
|
||||
Detail string `json:"detail,omitempty"`
|
||||
Type string `json:"type"`
|
||||
Name string `json:"name"`
|
||||
Before struct {
|
||||
@@ -267,7 +277,9 @@ func (ui *uiData) printItemsJSON(s *madmin.HealTaskStatus) (err error) {
|
||||
var b, a col
|
||||
var err error
|
||||
switch h.Type {
|
||||
case madmin.HealItemMetadata, madmin.HealItemBucket:
|
||||
case madmin.HealItemBucket:
|
||||
b, a, err = h.getBucketHCCChange()
|
||||
case madmin.HealItemMetadata, madmin.HealItemBucketMetadata:
|
||||
b, a, err = h.getReplicatedFileHCCChange()
|
||||
default:
|
||||
if h.Type == madmin.HealItemObject {
|
||||
@@ -278,6 +290,7 @@ func (ui *uiData) printItemsJSON(s *madmin.HealTaskStatus) (err error) {
|
||||
if err != nil {
|
||||
r.Error = err.Error()
|
||||
}
|
||||
r.Detail = h.Detail
|
||||
r.Before.Color = strings.ToLower(string(b))
|
||||
r.After.Color = strings.ToLower(string(a))
|
||||
r.Before.Online, r.After.Online = h.GetOnlineCounts()
|
||||
@@ -369,7 +382,7 @@ func (ui *uiData) updateUI(s *madmin.HealTaskStatus) (err error) {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (ui *uiData) UpdateDisplay(s *madmin.HealTaskStatus) (err error) {
|
||||
func (ui *uiData) UpdateDisplay(s *madmin.HealTaskStatus) {
|
||||
// Update state
|
||||
ui.updateDuration(s)
|
||||
for _, i := range s.Items {
|
||||
@@ -379,13 +392,12 @@ func (ui *uiData) UpdateDisplay(s *madmin.HealTaskStatus) (err error) {
|
||||
// Update display
|
||||
switch {
|
||||
case globalJSON:
|
||||
err = ui.printItemsJSON(s)
|
||||
ui.printItemsJSON(s)
|
||||
case globalQuiet:
|
||||
err = ui.printItemsQuietly(s)
|
||||
ui.printItemsQuietly(s)
|
||||
default:
|
||||
err = ui.updateUI(s)
|
||||
ui.updateUI(s)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (ui *uiData) healResumeMsg(aliasedURL string) string {
|
||||
@@ -420,10 +432,8 @@ func (ui *uiData) DisplayAndFollowHealStatus(aliasedURL string) (res madmin.Heal
|
||||
console.RewindLines(8)
|
||||
}
|
||||
}
|
||||
err = ui.UpdateDisplay(&res)
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
|
||||
ui.UpdateDisplay(&res)
|
||||
|
||||
if res.Summary == "finished" {
|
||||
if globalJSON {
|
||||
|
||||
+112
-37
@@ -1,4 +1,4 @@
|
||||
// Copyright (c) 2015-2022 MinIO, Inc.
|
||||
// Copyright (c) 2015-2024 MinIO, Inc.
|
||||
//
|
||||
// This file is part of MinIO Object Storage stack
|
||||
//
|
||||
@@ -18,8 +18,11 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"fmt"
|
||||
"math"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
@@ -40,6 +43,16 @@ const (
|
||||
)
|
||||
|
||||
var adminHealFlags = []cli.Flag{
|
||||
cli.IntFlag{
|
||||
Name: "pool",
|
||||
Usage: "heal only the given pool",
|
||||
Hidden: true,
|
||||
},
|
||||
cli.IntFlag{
|
||||
Name: "set",
|
||||
Usage: "heal only the given set",
|
||||
Hidden: true,
|
||||
},
|
||||
cli.StringFlag{
|
||||
Name: "scan",
|
||||
Usage: "select the healing scan mode (normal/deep)",
|
||||
@@ -66,6 +79,10 @@ var adminHealFlags = []cli.Flag{
|
||||
Usage: "force stop a running heal sequence",
|
||||
Hidden: true,
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "force",
|
||||
Usage: "avoid showing a warning prompt",
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "remove",
|
||||
Usage: "remove dangling objects in heal sequence",
|
||||
@@ -85,6 +102,10 @@ var adminHealFlags = []cli.Flag{
|
||||
Name: "verbose, v",
|
||||
Usage: "show verbose information",
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "all-drives, a",
|
||||
Usage: "select all drives for verbose printing",
|
||||
},
|
||||
}
|
||||
|
||||
var adminHealCmd = cli.Command{
|
||||
@@ -152,8 +173,11 @@ type poolInfo struct {
|
||||
}
|
||||
|
||||
type setInfo struct {
|
||||
maxUsedSpace uint64
|
||||
totalDisks int
|
||||
totalDisks int
|
||||
|
||||
readyDisksCount int // disks online and not in healing state
|
||||
readyDisksUsedSpace uint64 // the total used space of ready disks
|
||||
|
||||
incapableDisks int
|
||||
}
|
||||
|
||||
@@ -208,11 +232,11 @@ func generateSetsStatus(disks []madmin.Disk) map[setIndex]setInfo {
|
||||
setSt = setInfo{}
|
||||
}
|
||||
setSt.totalDisks++
|
||||
if d.UsedSpace > setSt.maxUsedSpace {
|
||||
setSt.maxUsedSpace = d.UsedSpace
|
||||
}
|
||||
if d.State != "ok" || d.Healing {
|
||||
setSt.incapableDisks++
|
||||
} else {
|
||||
setSt.readyDisksCount++
|
||||
setSt.readyDisksUsedSpace += d.UsedSpace
|
||||
}
|
||||
m[idx] = setSt
|
||||
}
|
||||
@@ -317,6 +341,8 @@ type verboseBackgroundHealStatusMessage struct {
|
||||
Status string `json:"status"`
|
||||
HealInfo madmin.BgHealState
|
||||
|
||||
allDrives bool
|
||||
|
||||
// Specify storage class to show servers/disks tolerance
|
||||
ToleranceForSC string `json:"-"`
|
||||
}
|
||||
@@ -364,14 +390,16 @@ func (s verboseBackgroundHealStatusMessage) String() string {
|
||||
fmt.Fprintf(&msg, " %s: %s\n", endpoint, stateText)
|
||||
continue
|
||||
}
|
||||
var serverHeader strings.Builder
|
||||
var serverHeaderPrinted bool
|
||||
serverStatus := serversStatus[endpoint]
|
||||
switch {
|
||||
case showTolerance:
|
||||
serverHeader := " %s: (Tolerance: %d server(s))\n"
|
||||
fmt.Fprintf(&msg, serverHeader, endpoint, poolsInfo[serverStatus.pool].tolerance)
|
||||
hdr := " %s: (Tolerance: %d server(s))\n"
|
||||
fmt.Fprintf(&serverHeader, hdr, endpoint, poolsInfo[serverStatus.pool].tolerance)
|
||||
default:
|
||||
serverHeader := " %s:\n"
|
||||
fmt.Fprintf(&msg, serverHeader, endpoint)
|
||||
hdr := " %s:\n"
|
||||
fmt.Fprintf(&serverHeader, hdr, endpoint)
|
||||
}
|
||||
|
||||
for _, d := range serverStatus.disks {
|
||||
@@ -383,25 +411,49 @@ func (s verboseBackgroundHealStatusMessage) String() string {
|
||||
case d.State == "ok" && d.Healing:
|
||||
stateText = console.Colorize("DiskHealing", "HEALING")
|
||||
case d.State == "ok":
|
||||
if !s.allDrives {
|
||||
continue
|
||||
}
|
||||
stateText = console.Colorize("DiskOK", "OK")
|
||||
default:
|
||||
stateText = console.Colorize("DiskFailed", d.State)
|
||||
}
|
||||
fmt.Fprintf(&msg, " + %s : %s\n", d.DrivePath, stateText)
|
||||
if d.Healing && d.HealInfo != nil {
|
||||
now := time.Now().UTC()
|
||||
scanSpeed := float64(d.UsedSpace) / float64(now.Sub(d.HealInfo.Started))
|
||||
remainingTime := time.Duration(float64(setsStatus[setIndex{d.PoolIndex, d.SetIndex}].maxUsedSpace-d.UsedSpace) / scanSpeed)
|
||||
estimationText := humanize.RelTime(now, now.Add(remainingTime), "", "")
|
||||
fmt.Fprintf(&msg, " |__ Estimated: %s\n", estimationText)
|
||||
if !serverHeaderPrinted {
|
||||
serverHeaderPrinted = true
|
||||
fmt.Fprint(&msg, serverHeader.String())
|
||||
}
|
||||
fmt.Fprintf(&msg, " |__ Capacity: %s/%s\n", humanize.IBytes(d.UsedSpace), humanize.IBytes(d.TotalSpace))
|
||||
drivePath := d.DrivePath
|
||||
if drivePath == "" {
|
||||
if u, e := url.Parse(d.Endpoint); e == nil {
|
||||
drivePath = u.Path
|
||||
}
|
||||
}
|
||||
fmt.Fprintf(&msg, " + %s : %s\n", drivePath, stateText)
|
||||
|
||||
thisSet := setsStatus[setIndex{d.PoolIndex, d.SetIndex}]
|
||||
if d.Healing && d.HealInfo != nil && !d.HealInfo.Finished {
|
||||
refUsedSpace := uint64(math.MaxUint64)
|
||||
if thisSet.readyDisksCount > 0 { // to avoid crashing
|
||||
refUsedSpace = thisSet.readyDisksUsedSpace / uint64(thisSet.readyDisksCount)
|
||||
}
|
||||
if refUsedSpace < d.UsedSpace { // normalize
|
||||
refUsedSpace = d.UsedSpace
|
||||
}
|
||||
fmt.Fprintf(&msg, " |__ Progress: %d%%\n", 100*d.UsedSpace/refUsedSpace)
|
||||
fmt.Fprintf(&msg, " |__ Started: %s\n", humanize.Time(d.HealInfo.Started))
|
||||
if d.HealInfo.RetryAttempts > 0 {
|
||||
fmt.Fprintf(&msg, " |__ Retries: %d\n", d.HealInfo.RetryAttempts)
|
||||
}
|
||||
}
|
||||
fmt.Fprintf(&msg, " |__ Capacity: %s/%s\n", humanize.IBytes(d.UsedSpace), humanize.IBytes(d.TotalSpace))
|
||||
if showTolerance {
|
||||
fmt.Fprintf(&msg, " |__ Tolerance: %d drive(s)\n", parity-setsStatus[setIndex{d.PoolIndex, d.SetIndex}].incapableDisks)
|
||||
fmt.Fprintf(&msg, " |__ Tolerance: %d drive(s)\n", parity-thisSet.incapableDisks)
|
||||
}
|
||||
}
|
||||
|
||||
fmt.Fprintf(&msg, "\n")
|
||||
if serverHeaderPrinted {
|
||||
fmt.Fprintf(&msg, "\n")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -462,9 +514,6 @@ func (s shortBackgroundHealStatusMessage) String() string {
|
||||
// The addition of Elapsed time of each parallel healing operation
|
||||
// this is needed to calculate the rate of healing
|
||||
accumulatedElapsedTime time.Duration
|
||||
|
||||
// ETA of healing - it is the latest ETA of all drives currently healing
|
||||
healingRemaining time.Duration
|
||||
)
|
||||
|
||||
var problematicDisks int
|
||||
@@ -485,12 +534,19 @@ func (s shortBackgroundHealStatusMessage) String() string {
|
||||
continue
|
||||
}
|
||||
|
||||
if disk.HealInfo != nil {
|
||||
if disk.HealInfo != nil && !disk.HealInfo.Finished {
|
||||
missingInSet++
|
||||
|
||||
diskSet := setIndex{pool: disk.PoolIndex, set: disk.SetIndex}
|
||||
if maxUsedSpace := setsStatus[diskSet].maxUsedSpace; maxUsedSpace > 0 {
|
||||
if pct := float64(disk.UsedSpace) / float64(maxUsedSpace); pct < leastPct {
|
||||
thisSet := setsStatus[setIndex{pool: disk.PoolIndex, set: disk.SetIndex}]
|
||||
refUsedSpace := uint64(math.MaxUint64)
|
||||
if thisSet.readyDisksCount > 0 {
|
||||
refUsedSpace = thisSet.readyDisksUsedSpace / uint64(thisSet.readyDisksCount)
|
||||
}
|
||||
if refUsedSpace < disk.UsedSpace {
|
||||
refUsedSpace = disk.UsedSpace
|
||||
}
|
||||
if refUsedSpace > 0 {
|
||||
if pct := float64(disk.UsedSpace) / float64(refUsedSpace); pct < leastPct {
|
||||
leastPct = pct
|
||||
}
|
||||
} else {
|
||||
@@ -498,12 +554,6 @@ func (s shortBackgroundHealStatusMessage) String() string {
|
||||
leastPct = 0
|
||||
}
|
||||
|
||||
scanSpeed := float64(disk.UsedSpace) / float64(time.Since(disk.HealInfo.Started))
|
||||
remainingTime := time.Duration(float64(setsStatus[diskSet].maxUsedSpace-disk.UsedSpace) / scanSpeed)
|
||||
if remainingTime > healingRemaining {
|
||||
healingRemaining = remainingTime
|
||||
}
|
||||
|
||||
disk := disk
|
||||
if furthestHealingDisk == nil {
|
||||
furthestHealingDisk = &disk
|
||||
@@ -566,10 +616,6 @@ func (s shortBackgroundHealStatusMessage) String() string {
|
||||
healPrettyMsg += fmt.Sprintf("Heal rate: %d obj/s, %s/s\n", int64(itemsHealedPerSec), humanize.IBytes(uint64(bytesHealedPerSec)))
|
||||
}
|
||||
|
||||
// Estimation completion
|
||||
now := time.Now()
|
||||
healPrettyMsg += fmt.Sprintf("Estimated Completion: %s\n", humanize.RelTime(now, now.Add(healingRemaining), "", ""))
|
||||
|
||||
if problematicDisks > 0 {
|
||||
healPrettyMsg += "\n"
|
||||
healPrettyMsg += fmt.Sprintf("%d offline disk(s) found.", problematicDisks)
|
||||
@@ -649,6 +695,7 @@ func mainAdminHeal(ctx *cli.Context) error {
|
||||
printMsg(verboseBackgroundHealStatusMessage{
|
||||
Status: "success",
|
||||
HealInfo: bgHealStatus,
|
||||
allDrives: ctx.Bool("all-drives"),
|
||||
ToleranceForSC: strings.ToUpper(ctx.String("storage-class")),
|
||||
})
|
||||
} else {
|
||||
@@ -668,6 +715,24 @@ func mainAdminHeal(ctx *cli.Context) error {
|
||||
Recreate: ctx.Bool("rewrite"),
|
||||
}
|
||||
|
||||
if ctx.IsSet("pool") {
|
||||
p := ctx.Int("pool")
|
||||
if p < 1 {
|
||||
fatalIf(errInvalidArgument(), "--pool takes a non zero positive number.")
|
||||
}
|
||||
p--
|
||||
opts.Pool = &p
|
||||
}
|
||||
|
||||
if ctx.IsSet("set") {
|
||||
s := ctx.Int("set")
|
||||
if s < 1 {
|
||||
fatalIf(errInvalidArgument(), "--set takes a non zero positive number.")
|
||||
}
|
||||
s--
|
||||
opts.Set = &s
|
||||
}
|
||||
|
||||
forceStart := ctx.Bool("force-start")
|
||||
forceStop := ctx.Bool("force-stop")
|
||||
if forceStop {
|
||||
@@ -677,6 +742,16 @@ func mainAdminHeal(ctx *cli.Context) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
if opts.Recursive && opts.Pool == nil && opts.Set == nil && isTerminal() && !ctx.Bool("force") {
|
||||
fmt.Printf("You are about to scan and heal the whole namespace in all pools and sets, please confirm [y/N]: ")
|
||||
answer, e := bufio.NewReader(os.Stdin).ReadString('\n')
|
||||
fatalIf(probe.NewError(e), "Unable to parse user input.")
|
||||
if answer = strings.TrimSpace(strings.ToLower(answer)); answer != "y" && answer != "yes" {
|
||||
fmt.Println("Heal aborted!")
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
healStart, _, e := adminClnt.Heal(globalContext, bucket, prefix, opts, "", forceStart, false)
|
||||
fatalIf(probe.NewError(e), "Unable to start healing.")
|
||||
|
||||
|
||||
+16
-16
@@ -95,9 +95,11 @@ func clusterSummaryInfo(info madmin.InfoMessage) clusterInfo {
|
||||
}
|
||||
}
|
||||
|
||||
if disk.DiskIndex < (info.Backend.DrivesPerSet[disk.PoolIndex] - info.Backend.StandardSCParity) {
|
||||
pool.drivesTotalFreeSpace += disk.AvailableSpace
|
||||
pool.drivesTotalUsableSpace += disk.TotalSpace
|
||||
if len(info.Backend.DrivesPerSet) > 0 {
|
||||
if disk.DiskIndex < (info.Backend.DrivesPerSet[disk.PoolIndex] - info.Backend.StandardSCParity) {
|
||||
pool.drivesTotalFreeSpace += disk.AvailableSpace
|
||||
pool.drivesTotalUsableSpace += disk.TotalSpace
|
||||
}
|
||||
}
|
||||
|
||||
pool.endpoints.Add(srv.Endpoint)
|
||||
@@ -105,8 +107,6 @@ func clusterSummaryInfo(info madmin.InfoMessage) clusterInfo {
|
||||
}
|
||||
}
|
||||
|
||||
// This was already added in 2022 enough time has passed to remove
|
||||
// any other deprecated calculations
|
||||
for idx := range info.Backend.TotalSets {
|
||||
pool := summary[idx]
|
||||
if pool != nil {
|
||||
@@ -150,11 +150,6 @@ func (u clusterStruct) String() (msg string) {
|
||||
fatal(probe.NewError(errors.New("Unable to get service info")), "")
|
||||
}
|
||||
|
||||
// Validate such that we expect the server to be atleast from 2022
|
||||
if len(u.Info.Backend.TotalSets) == 0 || len(u.Info.Backend.DrivesPerSet) == 0 {
|
||||
fatal(probe.NewError(errors.New("Unable to display service info, server is too old")), "")
|
||||
}
|
||||
|
||||
// Initialization
|
||||
var totalOfflineNodes int
|
||||
|
||||
@@ -299,6 +294,7 @@ func (u clusterStruct) String() (msg string) {
|
||||
"Erasure sets",
|
||||
})
|
||||
|
||||
var printSummary bool
|
||||
// Keep the pool order while printing the output
|
||||
for poolIdx := 0; poolIdx < len(clusterSummary); poolIdx++ {
|
||||
summary := clusterSummary[poolIdx]
|
||||
@@ -308,12 +304,14 @@ func (u clusterStruct) String() (msg string) {
|
||||
totalSize := summary.drivesTotalUsableSpace
|
||||
usedCurrent := summary.drivesTotalUsableSpace - summary.drivesTotalFreeSpace
|
||||
var capacity string
|
||||
if totalSize == 0 {
|
||||
capacity = "0% (total: 0B)"
|
||||
} else {
|
||||
if totalSize > 0 {
|
||||
capacity = fmt.Sprintf("%.1f%% (total: %s)", 100*float64(usedCurrent)/float64(totalSize), humanize.IBytes(totalSize))
|
||||
}
|
||||
|
||||
if summary.drivesPerSet > 0 {
|
||||
printSummary = true
|
||||
}
|
||||
|
||||
cellText = append(cellText, []string{
|
||||
humanize.Ordinal(poolIdx + 1),
|
||||
capacity,
|
||||
@@ -322,10 +320,12 @@ func (u clusterStruct) String() (msg string) {
|
||||
})
|
||||
}
|
||||
|
||||
e := tbl.PopulateTable(&builder, cellText)
|
||||
fatalIf(probe.NewError(e), "unable to populate the table")
|
||||
if printSummary {
|
||||
e := tbl.PopulateTable(&builder, cellText)
|
||||
fatalIf(probe.NewError(e), "unable to populate the table")
|
||||
|
||||
msg += builder.String() + "\n"
|
||||
msg += builder.String() + "\n"
|
||||
}
|
||||
}
|
||||
|
||||
// Summary on used space, total no of buckets and
|
||||
|
||||
+3
-9
@@ -107,15 +107,6 @@ func (l logMessage) String() string {
|
||||
if l.NodeName != "" {
|
||||
hostStr = fmt.Sprintf("%s ", colorizedNodeName(l.NodeName))
|
||||
}
|
||||
log := l.LogInfo
|
||||
if log.ConsoleMsg != "" {
|
||||
if strings.HasPrefix(log.ConsoleMsg, "\n") {
|
||||
fmt.Fprintf(b, "%s\n", hostStr)
|
||||
log.ConsoleMsg = strings.TrimPrefix(log.ConsoleMsg, "\n")
|
||||
}
|
||||
fmt.Fprintf(b, "%s %s", hostStr, log.ConsoleMsg)
|
||||
return b.String()
|
||||
}
|
||||
if l.API != nil {
|
||||
apiString := "API: " + l.API.Name + "("
|
||||
if l.API.Args != nil && l.API.Args.Bucket != "" {
|
||||
@@ -142,6 +133,9 @@ func (l logMessage) String() string {
|
||||
if l.UserAgent != "" {
|
||||
fmt.Fprintf(b, "\n%s UserAgent: %s", hostStr, l.UserAgent)
|
||||
}
|
||||
if l.Message != "" {
|
||||
fmt.Fprintf(b, "\n%s Message: %s", hostStr, l.Message)
|
||||
}
|
||||
if l.Trace != nil {
|
||||
if l.Trace.Message != "" {
|
||||
fmt.Fprintf(b, "\n%s Error: %s", hostStr, console.Colorize("LogMessage", l.Trace.Message))
|
||||
|
||||
@@ -56,6 +56,7 @@ var adminCmdSubcommands = []cli.Command{
|
||||
adminClusterCmd,
|
||||
adminRebalanceCmd,
|
||||
adminLogsCmd,
|
||||
adminAccesskeyCmd,
|
||||
}
|
||||
|
||||
var adminCmd = cli.Command{
|
||||
|
||||
@@ -23,6 +23,10 @@ import (
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
)
|
||||
|
||||
const (
|
||||
errCodeChangeAlreadyApplied = "XMinioAdminPolicyChangeAlreadyApplied"
|
||||
)
|
||||
|
||||
var adminAttachPolicyFlags = []cli.Flag{
|
||||
cli.StringFlag{
|
||||
Name: "user, u",
|
||||
@@ -97,10 +101,13 @@ func userAttachOrDetachPolicy(ctx *cli.Context, attach bool) error {
|
||||
} else {
|
||||
res, e = client.DetachPolicy(globalContext, req)
|
||||
}
|
||||
fatalIf(probe.NewError(e), "Unable to make user/group policy association")
|
||||
|
||||
if e != nil && madmin.ToErrorResponse(e).Code != errCodeChangeAlreadyApplied {
|
||||
fatalIf(probe.NewError(e), "Unable to make user/group policy association")
|
||||
}
|
||||
|
||||
var emptyResp madmin.PolicyAssociationResp
|
||||
if res.UpdatedAt == emptyResp.UpdatedAt {
|
||||
if res.UpdatedAt.Equal(emptyResp.UpdatedAt) {
|
||||
// Older minio does not send a result, so we populate res manually to
|
||||
// simulate a result. TODO(aditya): remove this after newer minio is
|
||||
// released in a few months (Older API Deprecated in Jun 2023)
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// Copyright (c) 2015-2022 MinIO, Inc.
|
||||
// Copyright (c) 2015-2024 MinIO, Inc.
|
||||
//
|
||||
// This file is part of MinIO Object Storage stack
|
||||
//
|
||||
@@ -31,22 +31,15 @@ import (
|
||||
)
|
||||
|
||||
const (
|
||||
defaultJobName = "minio-job"
|
||||
nodeJobName = "minio-job-node"
|
||||
bucketJobName = "minio-job-bucket"
|
||||
defaultMetricsPath = "/minio/v2/metrics/cluster"
|
||||
nodeMetricsPath = "/minio/v2/metrics/node"
|
||||
bucketMetricsPath = "/minio/v2/metrics/bucket"
|
||||
resourceJobName = "minio-job-resource"
|
||||
resourceMetricsPath = "/minio/v2/metrics/resource"
|
||||
defaultJobName = "minio-job"
|
||||
metricsV2BasePath = "/minio/v2/metrics"
|
||||
)
|
||||
|
||||
var prometheusFlags = []cli.Flag{
|
||||
var prometheusFlags = append(metricsFlags,
|
||||
cli.BoolFlag{
|
||||
Name: "public",
|
||||
Usage: "disable bearer token generation for scrape_configs",
|
||||
},
|
||||
}
|
||||
})
|
||||
|
||||
var adminPrometheusGenerateCmd = cli.Command{
|
||||
Name: "generate",
|
||||
@@ -63,14 +56,56 @@ USAGE:
|
||||
{{.HelpName}} TARGET [METRIC-TYPE]
|
||||
|
||||
METRIC-TYPE:
|
||||
valid values are ['cluster', 'node', 'bucket']. Defaults to 'cluster' if not specified.
|
||||
valid values are
|
||||
api-version v2 ['cluster', 'node', 'bucket', 'resource']. defaults to 'cluster' if not specified.
|
||||
api-version v3 ["api", "system", "debug", "cluster", "ilm", "audit", "logger", "replication", "notification", "scanner"]. defaults to all if not specified.
|
||||
|
||||
FLAGS:
|
||||
{{range .VisibleFlags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
EXAMPLES (v3):
|
||||
1. Generate a default prometheus config.
|
||||
{{.Prompt}} {{.HelpName}} myminio
|
||||
{{.Prompt}} {{.HelpName}} play --api-version v3
|
||||
|
||||
2. Generate prometheus config for api metrics.
|
||||
{{.Prompt}} {{.HelpName}} play api --api-version v3
|
||||
|
||||
3. Generate prometheus config for api metrics of bucket 'mybucket'.
|
||||
{{.Prompt}} {{.HelpName}} play api --bucket mybucket --api-version v3
|
||||
|
||||
4. Generate prometheus config for system metrics.
|
||||
{{.Prompt}} {{.HelpName}} play system --api-version v3
|
||||
|
||||
5. Generate prometheus config for debug metrics.
|
||||
{{.Prompt}} {{.HelpName}} play debug --api-version v3
|
||||
|
||||
6. Generate prometheus config for cluster metrics.
|
||||
{{.Prompt}} {{.HelpName}} play cluster --api-version v3
|
||||
|
||||
7. Generate prometheus config for ilm metrics.
|
||||
{{.Prompt}} {{.HelpName}} play ilm --api-version v3
|
||||
|
||||
8. Generate prometheus config for audit metrics.
|
||||
{{.Prompt}} {{.HelpName}} play audit --api-version v3
|
||||
|
||||
9. Generate prometheus config for logger metrics.
|
||||
{{.Prompt}} {{.HelpName}} play logger --api-version v3
|
||||
|
||||
10. Generate prometheus config for replication metrics.
|
||||
{{.Prompt}} {{.HelpName}} play replication --api-version v3
|
||||
|
||||
11. Generate prometheus config for replication metrics of bucket 'mybucket'.
|
||||
{{.Prompt}} {{.HelpName}} play replication --bucket mybucket --api-version v3
|
||||
|
||||
12. Generate prometheus config for notification metrics.
|
||||
{{.Prompt}} {{.HelpName}} play notification --api-version v3
|
||||
|
||||
13. Generate prometheus config for scanner metrics.
|
||||
{{.Prompt}} {{.HelpName}} play scanner --api-version v3
|
||||
|
||||
EXAMPLES (v2):
|
||||
1. Generate a default prometheus config.
|
||||
{{.Prompt}} {{.HelpName}} play
|
||||
|
||||
2. Generate prometheus config for node metrics.
|
||||
{{.Prompt}} {{.HelpName}} play node
|
||||
@@ -80,6 +115,9 @@ EXAMPLES:
|
||||
|
||||
4. Generate prometheus config for resource metrics.
|
||||
{{.Prompt}} {{.HelpName}} play resource
|
||||
|
||||
5. Generate prometheus config for cluster metrics.
|
||||
{{.Prompt}} {{.HelpName}} play cluster
|
||||
`,
|
||||
}
|
||||
|
||||
@@ -164,66 +202,43 @@ func generatePrometheusConfig(ctx *cli.Context) error {
|
||||
}
|
||||
|
||||
metricsSubSystem := args.Get(1)
|
||||
var config PrometheusConfig
|
||||
switch metricsSubSystem {
|
||||
case "node":
|
||||
config = PrometheusConfig{
|
||||
ScrapeConfigs: []ScrapeConfig{
|
||||
{
|
||||
JobName: nodeJobName,
|
||||
MetricsPath: nodeMetricsPath,
|
||||
StaticConfigs: []StatConfig{
|
||||
{
|
||||
Targets: []string{""},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
apiVer := ctx.String("api-version")
|
||||
jobName := defaultJobName
|
||||
metricsPath := ""
|
||||
|
||||
switch apiVer {
|
||||
case "v2":
|
||||
if metricsSubSystem == "" {
|
||||
metricsSubSystem = "cluster"
|
||||
}
|
||||
case "bucket":
|
||||
config = PrometheusConfig{
|
||||
ScrapeConfigs: []ScrapeConfig{
|
||||
{
|
||||
JobName: bucketJobName,
|
||||
MetricsPath: bucketMetricsPath,
|
||||
StaticConfigs: []StatConfig{
|
||||
{
|
||||
Targets: []string{""},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
validateV2Args(ctx, metricsSubSystem)
|
||||
if metricsSubSystem != "cluster" {
|
||||
jobName = defaultJobName + "-" + metricsSubSystem
|
||||
}
|
||||
case "resource":
|
||||
config = PrometheusConfig{
|
||||
ScrapeConfigs: []ScrapeConfig{
|
||||
{
|
||||
JobName: resourceJobName,
|
||||
MetricsPath: resourceMetricsPath,
|
||||
StaticConfigs: []StatConfig{
|
||||
{
|
||||
Targets: []string{""},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
case "", "cluster":
|
||||
config = PrometheusConfig{
|
||||
ScrapeConfigs: []ScrapeConfig{
|
||||
{
|
||||
JobName: defaultJobName,
|
||||
MetricsPath: defaultMetricsPath,
|
||||
StaticConfigs: []StatConfig{
|
||||
{
|
||||
Targets: []string{""},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
metricsPath = metricsV2BasePath + "/" + metricsSubSystem
|
||||
case "v3":
|
||||
bucket := ctx.String("bucket")
|
||||
validateV3Args(metricsSubSystem, bucket)
|
||||
metricsPath = getMetricsV3Path(metricsSubSystem, bucket)
|
||||
if metricsSubSystem != "" {
|
||||
jobName = defaultJobName + "-" + metricsSubSystem
|
||||
}
|
||||
default:
|
||||
fatalIf(errInvalidArgument().Trace(), "invalid metric type '%v'", metricsSubSystem)
|
||||
fatalIf(errInvalidArgument().Trace(), "Invalid api version `"+apiVer+"`")
|
||||
}
|
||||
|
||||
config := PrometheusConfig{
|
||||
ScrapeConfigs: []ScrapeConfig{
|
||||
{
|
||||
JobName: jobName,
|
||||
MetricsPath: metricsPath,
|
||||
StaticConfigs: []StatConfig{
|
||||
{
|
||||
Targets: []string{""},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
if !ctx.Bool("public") {
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
// Copyright (c) 2015-2024 MinIO, Inc.
|
||||
//
|
||||
// This file is part of MinIO Object Storage stack
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/minio-go/v7/pkg/set"
|
||||
)
|
||||
|
||||
var (
|
||||
metricsV3Flags = []cli.Flag{
|
||||
cli.StringFlag{
|
||||
Name: "bucket",
|
||||
Usage: "bucket name to list metrics for. only applicable with api version v3 for metric type 'api, replication'",
|
||||
},
|
||||
}
|
||||
|
||||
metricsV3SubSystems = set.CreateStringSet("api", "system", "debug", "cluster",
|
||||
"ilm", "audit", "logger", "replication", "notification", "scanner")
|
||||
|
||||
bucketMetricsSubSystems = set.CreateStringSet("api", "replication")
|
||||
)
|
||||
|
||||
const metricsV3EndPointRoot = "/minio/metrics/v3"
|
||||
|
||||
func getMetricsV3Path(subsys string, bucket string) string {
|
||||
params := url.Values{}
|
||||
|
||||
metricsPath := metricsV3EndPointRoot
|
||||
if len(bucket) > 0 {
|
||||
metricsPath += "/bucket"
|
||||
}
|
||||
|
||||
if len(subsys) > 0 {
|
||||
metricsPath += "/" + subsys
|
||||
}
|
||||
|
||||
if len(bucket) > 0 {
|
||||
// bucket specific metrics endpoints have '/bucket' prefix and bucket name as suffix.
|
||||
// e.g. bucket api metrics: /bucket/api/mybucket
|
||||
metricsPath += "/" + bucket
|
||||
}
|
||||
|
||||
qparams := params.Encode()
|
||||
if len(qparams) > 0 {
|
||||
metricsPath += "?" + qparams
|
||||
}
|
||||
return metricsPath
|
||||
}
|
||||
|
||||
func validateV3Args(subsys string, bucket string) {
|
||||
if subsys != "" && !metricsV3SubSystems.Contains(subsys) {
|
||||
fatalIf(errInvalidArgument().Trace(),
|
||||
"invalid metric type `"+subsys+"`. valid values are `"+
|
||||
strings.Join(metricsV3SubSystems.ToSlice(), ", ")+"`")
|
||||
}
|
||||
|
||||
if len(bucket) > 0 {
|
||||
bms := strings.Join(bucketMetricsSubSystems.ToSlice(), ", ")
|
||||
if len(subsys) == 0 {
|
||||
fatalIf(errInvalidArgument().Trace(), fmt.Sprintf("metric type must be passed with --bucket. valid values are `%s`", bms))
|
||||
}
|
||||
|
||||
if !bucketMetricsSubSystems.Contains(subsys) {
|
||||
fatalIf(errInvalidArgument().Trace(), fmt.Sprintf("--bucket is applicable only for metric types `%s`", bms))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func printPrometheusMetricsV3(ctx *cli.Context, req prometheusMetricsReq) error {
|
||||
bucket := ctx.String("bucket")
|
||||
validateV3Args(req.subsystem, bucket)
|
||||
|
||||
metricsURL := req.aliasURL + getMetricsV3Path(req.subsystem, bucket)
|
||||
|
||||
resp, e := fetchMetrics(metricsURL, req.token)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode == http.StatusOK {
|
||||
printMsg(prometheusMetricsReader{Reader: resp.Body})
|
||||
return nil
|
||||
}
|
||||
|
||||
return errors.New(resp.Status)
|
||||
}
|
||||
+132
-41
@@ -1,4 +1,4 @@
|
||||
// Copyright (c) 2015-2022 MinIO, Inc.
|
||||
// Copyright (c) 2015-2024 MinIO, Inc.
|
||||
//
|
||||
// This file is part of MinIO Object Storage stack
|
||||
//
|
||||
@@ -22,49 +22,105 @@ import (
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/minio/cli"
|
||||
json "github.com/minio/colorjson"
|
||||
"github.com/minio/madmin-go/v3"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/minio-go/v7/pkg/set"
|
||||
)
|
||||
|
||||
var metricsFlags = append(metricsV3Flags,
|
||||
cli.StringFlag{
|
||||
Name: "api-version",
|
||||
Usage: "version of metrics api to use. valid values are ['v2', 'v3']. defaults to 'v2' if not specified.",
|
||||
Value: "v2",
|
||||
})
|
||||
|
||||
var metricsV2SubSystems = set.CreateStringSet("node", "bucket", "cluster", "resource")
|
||||
|
||||
var adminPrometheusMetricsCmd = cli.Command{
|
||||
Name: "metrics",
|
||||
Usage: "print cluster wide prometheus metrics",
|
||||
Usage: "print prometheus metrics",
|
||||
OnUsageError: onUsageError,
|
||||
Action: mainSupportMetrics,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
Flags: append(globalFlags, metricsFlags...),
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
USAGE:
|
||||
{{.HelpName}} TARGET [METRIC-TYPE]
|
||||
|
||||
METRIC-TYPE:
|
||||
valid values are ['cluster', 'node', 'bucket', 'resource']. Defaults to 'cluster' if not specified.
|
||||
valid values are
|
||||
api-version v2 ['cluster', 'node', 'bucket', 'resource']. defaults to 'cluster' if not specified.
|
||||
api-version v3 ["api", "system", "debug", "cluster", "ilm", "audit", "logger", "replication", "notification", "scanner"]. defaults to all if not specified.
|
||||
|
||||
FLAGS:
|
||||
{{range .VisibleFlags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
1. List of metrics reported cluster wide.
|
||||
EXAMPLES (v3):
|
||||
1. API metrics
|
||||
{{.Prompt}} {{.HelpName}} play api --api-version v3
|
||||
|
||||
2. API metrics for the bucket 'mybucket'
|
||||
{{.Prompt}} {{.HelpName}} play api --bucket mybucket --api-version v3
|
||||
|
||||
3. System metrics
|
||||
{{.Prompt}} {{.HelpName}} play system --api-version v3
|
||||
|
||||
4. Debug metrics
|
||||
{{.Prompt}} {{.HelpName}} play debug --api-version v3
|
||||
|
||||
5. Cluster metrics
|
||||
{{.Prompt}} {{.HelpName}} play cluster --api-version v3
|
||||
|
||||
6. ILM metrics
|
||||
{{.Prompt}} {{.HelpName}} play ilm --api-version v3
|
||||
|
||||
7. Audit metrics
|
||||
{{.Prompt}} {{.HelpName}} play audit --api-version v3
|
||||
|
||||
8. Logger metrics
|
||||
{{.Prompt}} {{.HelpName}} play logger --api-version v3
|
||||
|
||||
9. Replication metrics
|
||||
{{.Prompt}} {{.HelpName}} play replication --api-version v3
|
||||
|
||||
10. Replication metrics for the bucket 'mybucket'
|
||||
{{.Prompt}} {{.HelpName}} play replication --bucket mybucket --api-version v3
|
||||
|
||||
11. Notification metrics
|
||||
{{.Prompt}} {{.HelpName}} play notification --api-version v3
|
||||
|
||||
12. Scanner metrics
|
||||
{{.Prompt}} {{.HelpName}} play scanner --api-version v3
|
||||
|
||||
EXAMPLES (v2):
|
||||
1. Metrics reported cluster wide.
|
||||
{{.Prompt}} {{.HelpName}} play
|
||||
|
||||
2. List of metrics reported at node level.
|
||||
2. Metrics reported at node level.
|
||||
{{.Prompt}} {{.HelpName}} play node
|
||||
|
||||
3. List of metrics reported at bucket level.
|
||||
3. Metrics reported at bucket level.
|
||||
{{.Prompt}} {{.HelpName}} play bucket
|
||||
|
||||
4. List of resource metrics.
|
||||
4. Resource metrics.
|
||||
{{.Prompt}} {{.HelpName}} play resource
|
||||
`,
|
||||
}
|
||||
|
||||
const metricsEndPointRoot = "/minio/v2/metrics/"
|
||||
|
||||
type prometheusMetricsReq struct {
|
||||
aliasURL string
|
||||
token string
|
||||
subsystem string
|
||||
}
|
||||
|
||||
// checkSupportMetricsSyntax - validate arguments passed by a user
|
||||
func checkSupportMetricsSyntax(ctx *cli.Context) {
|
||||
if len(ctx.Args()) == 0 || len(ctx.Args()) > 2 {
|
||||
@@ -72,44 +128,42 @@ func checkSupportMetricsSyntax(ctx *cli.Context) {
|
||||
}
|
||||
}
|
||||
|
||||
func printPrometheusMetrics(ctx *cli.Context) error {
|
||||
// Get the alias parameter from cli
|
||||
args := ctx.Args()
|
||||
alias := cleanAlias(args.Get(0))
|
||||
|
||||
if !isValidAlias(alias) {
|
||||
fatalIf(errInvalidAlias(alias), "Invalid alias.")
|
||||
}
|
||||
hostConfig := mustGetHostConfig(alias)
|
||||
if hostConfig == nil {
|
||||
fatalIf(errInvalidAliasedURL(alias), "No such alias `"+alias+"` found.")
|
||||
return nil
|
||||
}
|
||||
|
||||
token, e := getPrometheusToken(hostConfig)
|
||||
func fetchMetrics(metricsURL string, token string) (*http.Response, error) {
|
||||
req, e := http.NewRequest(http.MethodGet, metricsURL, nil)
|
||||
if e != nil {
|
||||
return e
|
||||
return nil, e
|
||||
}
|
||||
metricsSubSystem := args.Get(1)
|
||||
switch metricsSubSystem {
|
||||
case "node", "bucket", "cluster", "resource":
|
||||
case "":
|
||||
metricsSubSystem = "cluster"
|
||||
default:
|
||||
fatalIf(errInvalidArgument().Trace(), "invalid metric type '%v'", metricsSubSystem)
|
||||
}
|
||||
|
||||
req, e := http.NewRequest(http.MethodGet, hostConfig.URL+metricsEndPointRoot+metricsSubSystem, nil)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
|
||||
if token != "" {
|
||||
req.Header.Add("Authorization", "Bearer "+token)
|
||||
}
|
||||
|
||||
client := httpClient(60 * time.Second)
|
||||
resp, e := client.Do(req)
|
||||
return client.Do(req)
|
||||
}
|
||||
|
||||
func validateV2Args(ctx *cli.Context, subsys string) {
|
||||
for _, flag := range metricsV3Flags {
|
||||
flagName := flag.GetName()
|
||||
if ctx.IsSet(flagName) {
|
||||
fatalIf(errInvalidArgument().Trace(), "Flag `"+flagName+"` is not supported with v2 metrics")
|
||||
}
|
||||
}
|
||||
|
||||
if !metricsV2SubSystems.Contains(subsys) {
|
||||
fatalIf(errInvalidArgument().Trace(),
|
||||
"invalid metric type `"+subsys+"`. valid values are `"+
|
||||
strings.Join(metricsV2SubSystems.ToSlice(), ", ")+"`")
|
||||
}
|
||||
}
|
||||
|
||||
func printPrometheusMetricsV2(ctx *cli.Context, req prometheusMetricsReq) error {
|
||||
subsys := req.subsystem
|
||||
if subsys == "" {
|
||||
subsys = "cluster"
|
||||
}
|
||||
validateV2Args(ctx, subsys)
|
||||
|
||||
resp, e := fetchMetrics(req.aliasURL+metricsEndPointRoot+subsys, req.token)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
@@ -151,7 +205,44 @@ type prometheusMetricsReader struct {
|
||||
func mainSupportMetrics(ctx *cli.Context) error {
|
||||
checkSupportMetricsSyntax(ctx)
|
||||
|
||||
fatalIf(probe.NewError(printPrometheusMetrics(ctx)), "Unable to list prometheus metrics.")
|
||||
// Get the alias parameter from cli
|
||||
args := ctx.Args()
|
||||
alias := cleanAlias(args.Get(0))
|
||||
|
||||
if !isValidAlias(alias) {
|
||||
fatalIf(errInvalidAlias(alias), "Invalid alias.")
|
||||
}
|
||||
|
||||
hostConfig := mustGetHostConfig(alias)
|
||||
if hostConfig == nil {
|
||||
fatalIf(errInvalidAliasedURL(alias), "No such alias `"+alias+"` found.")
|
||||
return nil
|
||||
}
|
||||
|
||||
token, e := getPrometheusToken(hostConfig)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
|
||||
metricsSubSystem := args.Get(1)
|
||||
apiVer := ctx.String("api-version")
|
||||
|
||||
metricsReq := prometheusMetricsReq{
|
||||
aliasURL: hostConfig.URL,
|
||||
token: token,
|
||||
subsystem: metricsSubSystem,
|
||||
}
|
||||
|
||||
switch apiVer {
|
||||
case "v2":
|
||||
err := printPrometheusMetricsV2(ctx, metricsReq)
|
||||
fatalIf(probe.NewError(err), "Unable to list prometheus metrics with api-version v2.")
|
||||
case "v3":
|
||||
err := printPrometheusMetricsV3(ctx, metricsReq)
|
||||
fatalIf(probe.NewError(err), "Unable to list prometheus metrics with api-version v3.")
|
||||
default:
|
||||
fatalIf(errInvalidArgument().Trace(), "Invalid api version `"+apiVer+"`")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -83,27 +83,27 @@ func (i srRemoveStatus) String() string {
|
||||
if i.RemoveAll {
|
||||
return console.Colorize("UserMessage", "All site(s) were removed successfully")
|
||||
}
|
||||
if i.ReplicateRemoveStatus.Status == madmin.ReplicateRemoveStatusSuccess {
|
||||
if i.Status == madmin.ReplicateRemoveStatusSuccess {
|
||||
return console.Colorize("UserMessage", fmt.Sprintf("Following site(s) %s were removed successfully", i.sites))
|
||||
}
|
||||
if len(i.sites) == 1 {
|
||||
return console.Colorize("UserMessage", fmt.Sprintf("Following site %s was removed partially, some operations failed:\nERROR: '%s'", i.sites, i.ReplicateRemoveStatus.ErrDetail))
|
||||
return console.Colorize("UserMessage", fmt.Sprintf("Following site %s was removed partially, some operations failed:\nERROR: '%s'", i.sites, i.ErrDetail))
|
||||
}
|
||||
return console.Colorize("UserMessage", fmt.Sprintf("Following site(s) %s were removed partially, some operations failed: \nERROR: '%s'", i.sites, i.ReplicateRemoveStatus.ErrDetail))
|
||||
return console.Colorize("UserMessage", fmt.Sprintf("Following site(s) %s were removed partially, some operations failed: \nERROR: '%s'", i.sites, i.ErrDetail))
|
||||
}
|
||||
|
||||
func checkAdminReplicateRemoveSyntax(ctx *cli.Context) {
|
||||
// Check argument count
|
||||
argsNr := len(ctx.Args())
|
||||
if ctx.IsSet("all") && argsNr > 1 {
|
||||
if ctx.Bool("all") && argsNr > 1 {
|
||||
fatalIf(errInvalidArgument().Trace(ctx.Args().Tail()...),
|
||||
"")
|
||||
}
|
||||
if argsNr < 2 && !ctx.IsSet("all") {
|
||||
if argsNr < 2 && !ctx.Bool("all") {
|
||||
fatalIf(errInvalidArgument().Trace(ctx.Args().Tail()...),
|
||||
"Need at least two arguments to remove command.")
|
||||
}
|
||||
if !ctx.IsSet("force") {
|
||||
if !ctx.Bool("force") {
|
||||
fatalIf(errDummy().Trace(),
|
||||
"Site removal requires --force flag. This operation is *IRREVERSIBLE*. Please review carefully before performing this *DANGEROUS* operation.")
|
||||
}
|
||||
|
||||
@@ -74,13 +74,12 @@ func (m resyncCancelMessage) String() string {
|
||||
}
|
||||
|
||||
func mainAdminReplicateResyncCancel(ctx *cli.Context) error {
|
||||
{
|
||||
// Check argument count
|
||||
argsNr := len(ctx.Args())
|
||||
if argsNr != 2 {
|
||||
cli.ShowCommandHelpAndExit(ctx, "cancel", 1) // last argument is exit code
|
||||
}
|
||||
// Check argument count
|
||||
argsNr := len(ctx.Args())
|
||||
if argsNr != 2 {
|
||||
showCommandHelpAndExit(ctx, 1) // last argument is exit code
|
||||
}
|
||||
|
||||
console.SetColor("ResyncMessage", color.New(color.FgGreen))
|
||||
|
||||
// Get the alias parameter from cli
|
||||
|
||||
@@ -21,10 +21,11 @@ import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/minio/madmin-go/v3"
|
||||
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/cli"
|
||||
json "github.com/minio/colorjson"
|
||||
"github.com/minio/madmin-go/v3"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/pkg/v3/console"
|
||||
)
|
||||
@@ -74,12 +75,10 @@ func (m resyncMessage) String() string {
|
||||
}
|
||||
|
||||
func mainAdminReplicateResyncStart(ctx *cli.Context) error {
|
||||
{
|
||||
// Check argument count
|
||||
argsNr := len(ctx.Args())
|
||||
if argsNr != 2 {
|
||||
cli.ShowCommandHelpAndExit(ctx, "start", 1) // last argument is exit code
|
||||
}
|
||||
// Check argument count
|
||||
argsNr := len(ctx.Args())
|
||||
if argsNr != 2 {
|
||||
showCommandHelpAndExit(ctx, 1) // last argument is exit code
|
||||
}
|
||||
|
||||
console.SetColor("ResyncMessage", color.New(color.FgGreen))
|
||||
|
||||
@@ -60,12 +60,10 @@ EXAMPLES:
|
||||
}
|
||||
|
||||
func mainAdminReplicationResyncStatus(ctx *cli.Context) error {
|
||||
{
|
||||
// Check argument count
|
||||
argsNr := len(ctx.Args())
|
||||
if argsNr != 2 {
|
||||
cli.ShowCommandHelpAndExit(ctx, "status", 1) // last argument is exit code
|
||||
}
|
||||
// Check argument count
|
||||
argsNr := len(ctx.Args())
|
||||
if argsNr != 2 {
|
||||
showCommandHelpAndExit(ctx, 1) // last argument is exit code
|
||||
}
|
||||
|
||||
console.SetColor("ResyncMessage", color.New(color.FgGreen))
|
||||
@@ -208,7 +206,7 @@ func (m *resyncMetricsUI) View() string {
|
||||
table.SetNoWhiteSpace(true)
|
||||
|
||||
var data [][]string
|
||||
addLine := func(prefix string, value interface{}) {
|
||||
addLine := func(prefix string, value any) {
|
||||
data = append(data, []string{
|
||||
prefix,
|
||||
whiteStyle.Render(fmt.Sprint(value)),
|
||||
|
||||
@@ -167,8 +167,8 @@ func (i srStatus) String() string {
|
||||
if i.opts.Buckets {
|
||||
messages = append(messages,
|
||||
console.Colorize("SummaryHdr", "Bucket replication status:"))
|
||||
switch {
|
||||
case i.MaxBuckets == 0:
|
||||
switch i.MaxBuckets {
|
||||
case 0:
|
||||
messages = append(messages, console.Colorize("Summary", "No Buckets present\n"))
|
||||
default:
|
||||
msg := console.Colorize(i.getTheme(len(info.BucketStats) == 0), fmt.Sprintf("%d/%d Buckets in sync", info.MaxBuckets-len(info.BucketStats), info.MaxBuckets)) + "\n"
|
||||
@@ -204,8 +204,8 @@ func (i srStatus) String() string {
|
||||
if i.opts.Policies {
|
||||
messages = append(messages,
|
||||
console.Colorize("SummaryHdr", "Policy replication status:"))
|
||||
switch {
|
||||
case i.MaxPolicies == 0:
|
||||
switch i.MaxPolicies {
|
||||
case 0:
|
||||
messages = append(messages, console.Colorize("Summary", "No Policies present\n"))
|
||||
default:
|
||||
msg := console.Colorize(i.getTheme(len(i.PolicyStats) == 0), fmt.Sprintf("%d/%d Policies in sync", info.MaxPolicies-len(info.PolicyStats), info.MaxPolicies)) + "\n"
|
||||
@@ -243,8 +243,8 @@ func (i srStatus) String() string {
|
||||
if i.opts.Users {
|
||||
messages = append(messages,
|
||||
console.Colorize("SummaryHdr", "User replication status:"))
|
||||
switch {
|
||||
case i.MaxUsers == 0:
|
||||
switch i.MaxUsers {
|
||||
case 0:
|
||||
messages = append(messages, console.Colorize("Summary", "No Users present\n"))
|
||||
default:
|
||||
msg := console.Colorize(i.getTheme(len(i.UserStats) == 0), fmt.Sprintf("%d/%d Users in sync", info.MaxUsers-len(i.UserStats), info.MaxUsers)) + "\n"
|
||||
@@ -284,8 +284,8 @@ func (i srStatus) String() string {
|
||||
if i.opts.Groups {
|
||||
messages = append(messages,
|
||||
console.Colorize("SummaryHdr", "Group replication status:"))
|
||||
switch {
|
||||
case i.MaxGroups == 0:
|
||||
switch i.MaxGroups {
|
||||
case 0:
|
||||
messages = append(messages, console.Colorize("Summary", "No Groups present\n"))
|
||||
default:
|
||||
msg := console.Colorize(i.getTheme(len(i.GroupStats) == 0), fmt.Sprintf("%d/%d Groups in sync", i.MaxGroups-len(i.GroupStats), i.MaxGroups)) + "\n"
|
||||
@@ -426,10 +426,7 @@ func (i srStatus) String() string {
|
||||
currDowntime = UTCNow().Sub(m.LastOnline)
|
||||
}
|
||||
// normalize because total downtime is calculated at server side at heartbeat interval, may be slightly behind
|
||||
totalDowntime := m.TotalDowntime
|
||||
if currDowntime > totalDowntime {
|
||||
totalDowntime = currDowntime
|
||||
}
|
||||
totalDowntime := max(currDowntime, m.TotalDowntime)
|
||||
var linkStatus string
|
||||
if m.Online {
|
||||
linkStatus = healthDot + fmt.Sprintf(" online (total downtime: %s)", timeDurationToHumanizedDuration(totalDowntime).String())
|
||||
@@ -478,7 +475,7 @@ func (i srStatus) getBucketStatusSummary(siteNames []string, nameIDMap map[strin
|
||||
var messages []string
|
||||
coloredDot := console.Colorize("Status", dot)
|
||||
var found bool
|
||||
for _, st := range i.SRStatusInfo.BucketStats[i.opts.EntityValue] {
|
||||
for _, st := range i.BucketStats[i.opts.EntityValue] {
|
||||
if st.HasBucket {
|
||||
found = true
|
||||
break
|
||||
@@ -518,7 +515,7 @@ func (i srStatus) getBucketStatusSummary(siteNames []string, nameIDMap map[strin
|
||||
rows := make([]string, len(rowLegend))
|
||||
for j, sname := range siteNames {
|
||||
dID := nameIDMap[sname]
|
||||
ss := i.SRStatusInfo.BucketStats[i.opts.EntityValue][dID]
|
||||
ss := i.BucketStats[i.opts.EntityValue][dID]
|
||||
var theme, msgStr string
|
||||
for r := range rowLegend {
|
||||
switch r {
|
||||
@@ -582,7 +579,7 @@ func (i srStatus) getPolicyStatusSummary(siteNames []string, nameIDMap map[strin
|
||||
var messages []string
|
||||
coloredDot := console.Colorize("Status", dot)
|
||||
var found bool
|
||||
for _, st := range i.SRStatusInfo.PolicyStats[i.opts.EntityValue] {
|
||||
for _, st := range i.PolicyStats[i.opts.EntityValue] {
|
||||
if st.HasPolicy {
|
||||
found = true
|
||||
break
|
||||
@@ -603,7 +600,7 @@ func (i srStatus) getPolicyStatusSummary(siteNames []string, nameIDMap map[strin
|
||||
rows := make([]string, len(rowLegend))
|
||||
for j, sname := range siteNames {
|
||||
dID := nameIDMap[sname]
|
||||
ss := i.SRStatusInfo.PolicyStats[i.opts.EntityValue][dID]
|
||||
ss := i.PolicyStats[i.opts.EntityValue][dID]
|
||||
var theme, msgStr string
|
||||
for r := range rowLegend {
|
||||
switch r {
|
||||
@@ -634,7 +631,7 @@ func (i srStatus) getUserStatusSummary(siteNames []string, nameIDMap map[string]
|
||||
var messages []string
|
||||
coloredDot := console.Colorize("Status", dot)
|
||||
var found bool
|
||||
for _, st := range i.SRStatusInfo.UserStats[i.opts.EntityValue] {
|
||||
for _, st := range i.UserStats[i.opts.EntityValue] {
|
||||
if st.HasUser {
|
||||
found = true
|
||||
break
|
||||
@@ -662,7 +659,7 @@ func (i srStatus) getUserStatusSummary(siteNames []string, nameIDMap map[string]
|
||||
rows := make([]string, len(rowLegend))
|
||||
for j, sname := range siteNames {
|
||||
dID := nameIDMap[sname]
|
||||
ss := i.SRStatusInfo.UserStats[i.opts.EntityValue][dID]
|
||||
ss := i.UserStats[i.opts.EntityValue][dID]
|
||||
var theme, msgStr string
|
||||
for r := range rowLegend {
|
||||
switch r {
|
||||
@@ -702,7 +699,7 @@ func (i srStatus) getGroupStatusSummary(siteNames []string, nameIDMap map[string
|
||||
rowLegend := []string{"Info", "Policy mapping"}
|
||||
detailFields := make([][]Field, len(rowLegend))
|
||||
var found bool
|
||||
for _, st := range i.SRStatusInfo.GroupStats[i.opts.EntityValue] {
|
||||
for _, st := range i.GroupStats[i.opts.EntityValue] {
|
||||
if st.HasGroup {
|
||||
found = true
|
||||
break
|
||||
@@ -728,7 +725,7 @@ func (i srStatus) getGroupStatusSummary(siteNames []string, nameIDMap map[string
|
||||
// b := i.opts.EntityValue
|
||||
for j, sname := range siteNames {
|
||||
dID := nameIDMap[sname]
|
||||
ss := i.SRStatusInfo.GroupStats[i.opts.EntityValue][dID]
|
||||
ss := i.GroupStats[i.opts.EntityValue][dID]
|
||||
// sm := i.SRStatusInfo.StatsSummary
|
||||
var theme, msgStr string
|
||||
for r := range rowLegend {
|
||||
@@ -767,7 +764,7 @@ func (i srStatus) getILMExpiryStatusSummary(siteNames []string, nameIDMap map[st
|
||||
var messages []string
|
||||
coloredDot := console.Colorize("Status", dot)
|
||||
var found bool
|
||||
for _, st := range i.SRStatusInfo.ILMExpiryStats[i.opts.EntityValue] {
|
||||
for _, st := range i.ILMExpiryStats[i.opts.EntityValue] {
|
||||
if st.HasILMExpiryRules {
|
||||
found = true
|
||||
break
|
||||
@@ -788,7 +785,7 @@ func (i srStatus) getILMExpiryStatusSummary(siteNames []string, nameIDMap map[st
|
||||
rows := make([]string, len(rowLegend))
|
||||
for j, sname := range siteNames {
|
||||
dID := nameIDMap[sname]
|
||||
ss := i.SRStatusInfo.ILMExpiryStats[i.opts.EntityValue][dID]
|
||||
ss := i.ILMExpiryStats[i.opts.EntityValue][dID]
|
||||
var theme, msgStr string
|
||||
for r := range rowLegend {
|
||||
switch r {
|
||||
@@ -817,17 +814,7 @@ func (i srStatus) getILMExpiryStatusSummary(siteNames []string, nameIDMap map[st
|
||||
|
||||
// Calculate srstatus options for command line flags
|
||||
func srStatusOpts(ctx *cli.Context) (opts madmin.SRStatusOptions) {
|
||||
if !(ctx.IsSet("buckets") ||
|
||||
ctx.IsSet("users") ||
|
||||
ctx.IsSet("groups") ||
|
||||
ctx.IsSet("policies") ||
|
||||
ctx.IsSet("ilm-expiry-rules") ||
|
||||
ctx.IsSet("bucket") ||
|
||||
ctx.IsSet("user") ||
|
||||
ctx.IsSet("group") ||
|
||||
ctx.IsSet("policy") ||
|
||||
ctx.IsSet("ilm-expiry-rule") ||
|
||||
ctx.IsSet("all")) || ctx.IsSet("all") {
|
||||
if (!ctx.IsSet("buckets") && !ctx.IsSet("users") && !ctx.IsSet("groups") && !ctx.IsSet("policies") && !ctx.IsSet("ilm-expiry-rules") && !ctx.IsSet("bucket") && !ctx.IsSet("user") && !ctx.IsSet("group") && !ctx.IsSet("policy") && !ctx.IsSet("ilm-expiry-rule") && !ctx.IsSet("all")) || ctx.IsSet("all") {
|
||||
opts.Buckets = true
|
||||
opts.Users = true
|
||||
opts.Groups = true
|
||||
|
||||
+148
-36
@@ -26,13 +26,16 @@ import (
|
||||
"io"
|
||||
"os"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/charmbracelet/bubbles/spinner"
|
||||
tea "github.com/charmbracelet/bubbletea"
|
||||
"github.com/charmbracelet/lipgloss"
|
||||
"github.com/dustin/go-humanize"
|
||||
"github.com/fatih/color"
|
||||
"github.com/klauspost/compress/zstd"
|
||||
"github.com/minio/cli"
|
||||
json "github.com/minio/colorjson"
|
||||
"github.com/minio/madmin-go/v3"
|
||||
@@ -62,9 +65,12 @@ var adminScannerInfoFlags = []cli.Flag{
|
||||
Value: -1,
|
||||
},
|
||||
cli.StringFlag{
|
||||
Name: "in",
|
||||
Hidden: true,
|
||||
Usage: "read previously saved json from file and replay",
|
||||
Name: "in",
|
||||
Usage: "read previously saved json from file and replay",
|
||||
},
|
||||
cli.StringFlag{
|
||||
Name: "bucket",
|
||||
Usage: "show scan stats about a given bucket",
|
||||
},
|
||||
}
|
||||
|
||||
@@ -103,10 +109,94 @@ func checkAdminScannerInfoSyntax(ctx *cli.Context) {
|
||||
}
|
||||
}
|
||||
|
||||
func mainAdminScannerInfo(ctx *cli.Context) error {
|
||||
checkAdminScannerInfoSyntax(ctx)
|
||||
// bucketScanMsg container for content message structure
|
||||
type bucketScanMsg struct {
|
||||
Status string `json:"status"`
|
||||
Stats []madmin.BucketScanInfo `json:"stats"`
|
||||
}
|
||||
|
||||
aliasedURL := ctx.Args().Get(0)
|
||||
func (b bucketScanMsg) String() string {
|
||||
var sb strings.Builder
|
||||
sb.WriteString("\n")
|
||||
|
||||
sort.Slice(b.Stats, func(i, j int) bool { return b.Stats[i].LastUpdate.Before(b.Stats[j].LastUpdate) })
|
||||
|
||||
pt := newPrettyTable(" | ",
|
||||
Field{"Pool", 5},
|
||||
Field{"Set", 5},
|
||||
Field{"LastUpdate", timeFieldMaxLen},
|
||||
)
|
||||
|
||||
sb.WriteString(console.Colorize("Headers", pt.buildRow("Pool", "Set", "Last Update")) + "\n")
|
||||
|
||||
now := time.Now().UTC()
|
||||
for i := range b.Stats {
|
||||
sb.WriteString(
|
||||
pt.buildRow(
|
||||
strconv.Itoa(b.Stats[i].Pool+1),
|
||||
strconv.Itoa(b.Stats[i].Set+1),
|
||||
humanize.RelTime(now, b.Stats[i].LastUpdate, "", "ago"),
|
||||
) + "\n")
|
||||
}
|
||||
|
||||
var (
|
||||
earliestESScan time.Time // the earliest ES that completed a bucket scan
|
||||
latestESScan time.Time // the last ES that completed a bucket scan
|
||||
fullScan = true
|
||||
)
|
||||
|
||||
// Look for a bucket full scan inforation only if all
|
||||
// erasure sets completed at least 16 cycles
|
||||
for _, st := range b.Stats {
|
||||
if len(st.Completed) < 16 {
|
||||
fullScan = false
|
||||
break
|
||||
}
|
||||
if earliestESScan.IsZero() {
|
||||
// First stats
|
||||
earliestESScan = st.Completed[0]
|
||||
latestESScan = st.Completed[len(st.Completed)-1]
|
||||
continue
|
||||
}
|
||||
if earliestESScan.Before(st.Completed[0]) {
|
||||
earliestESScan = st.Completed[0]
|
||||
}
|
||||
if latestESScan.After(st.Completed[len(st.Completed)-1]) {
|
||||
latestESScan = st.Completed[len(st.Completed)-1]
|
||||
}
|
||||
}
|
||||
|
||||
sb.WriteString("\n")
|
||||
|
||||
if fullScan {
|
||||
took := latestESScan.Sub(earliestESScan)
|
||||
sb.WriteString(
|
||||
fmt.Sprintf(
|
||||
"%s %s (took %s)\n",
|
||||
console.Colorize("FullScan", "Full bucket scan: "),
|
||||
humanize.RelTime(now, latestESScan, "", "ago"),
|
||||
fmt.Sprintf("%dd%dh%dm", int(took.Hours()/24), int(took.Hours())%24, int(took.Minutes())%60)),
|
||||
)
|
||||
}
|
||||
|
||||
sb.WriteString("\n")
|
||||
|
||||
return sb.String()
|
||||
}
|
||||
|
||||
func (b bucketScanMsg) JSON() string {
|
||||
b.Status = "success"
|
||||
jsonMessageBytes, e := json.MarshalIndent(b, "", " ")
|
||||
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
|
||||
|
||||
return string(jsonMessageBytes)
|
||||
}
|
||||
|
||||
func mainAdminScannerInfo(ctx *cli.Context) error {
|
||||
console.SetColor("Headers", color.New(color.Bold, color.FgHiGreen))
|
||||
console.SetColor("FullScan", color.New(color.Bold, color.FgHiGreen))
|
||||
|
||||
checkAdminScannerInfoSyntax(ctx)
|
||||
|
||||
ui := tea.NewProgram(initScannerMetricsUI(ctx.Int("max-paths")))
|
||||
ctxt, cancel := context.WithCancel(globalContext)
|
||||
@@ -117,12 +207,20 @@ func mainAdminScannerInfo(ctx *cli.Context) error {
|
||||
go func() {
|
||||
if _, e := ui.Run(); e != nil {
|
||||
cancel()
|
||||
fatalIf(probe.NewError(e).Trace(aliasedURL), "Unable to fetch scanner metrics")
|
||||
fatalIf(probe.NewError(e), "Unable to fetch scanner metrics")
|
||||
}
|
||||
}()
|
||||
f, e := os.Open(inFile)
|
||||
fatalIf(probe.NewError(e).Trace(aliasedURL), "Unable to open input")
|
||||
sc := bufio.NewReader(f)
|
||||
fatalIf(probe.NewError(e), "Unable to open input")
|
||||
defer f.Close()
|
||||
in := io.Reader(f)
|
||||
if strings.HasSuffix(inFile, ".zst") {
|
||||
zr, e := zstd.NewReader(in)
|
||||
fatalIf(probe.NewError(e), "Unable to open input")
|
||||
defer zr.Close()
|
||||
in = zr
|
||||
}
|
||||
sc := bufio.NewReader(in)
|
||||
var lastTime time.Time
|
||||
for {
|
||||
b, e := sc.ReadBytes('\n')
|
||||
@@ -148,9 +246,17 @@ func mainAdminScannerInfo(ctx *cli.Context) error {
|
||||
}
|
||||
|
||||
// Create a new MinIO Admin Client
|
||||
aliasedURL := ctx.Args().Get(0)
|
||||
client, err := newAdminClient(aliasedURL)
|
||||
fatalIf(err.Trace(aliasedURL), "Unable to initialize admin client.")
|
||||
|
||||
if bucket := ctx.String("bucket"); bucket != "" {
|
||||
bucketStats, err := client.BucketScanInfo(globalContext, bucket)
|
||||
fatalIf(probe.NewError(err).Trace(aliasedURL), "Unable to get bucket stats.")
|
||||
printMsg(bucketScanMsg{Stats: bucketStats})
|
||||
return nil
|
||||
}
|
||||
|
||||
opts := madmin.MetricsOptions{
|
||||
Type: madmin.MetricsScanner,
|
||||
N: ctx.Int("n"),
|
||||
@@ -291,7 +397,7 @@ func (m *scannerMetricsUI) View() string {
|
||||
writtenRows++
|
||||
}
|
||||
_ = addRow
|
||||
addRowF := func(format string, vals ...interface{}) {
|
||||
addRowF := func(format string, vals ...any) {
|
||||
s := fmt.Sprintf(format, vals...)
|
||||
table.Append([]string{s})
|
||||
writtenRows++
|
||||
@@ -305,37 +411,43 @@ func (m *scannerMetricsUI) View() string {
|
||||
|
||||
title := metricsTitle
|
||||
ui := metricsUint64
|
||||
const wantCycles = 16
|
||||
addRow("")
|
||||
if len(sc.CyclesCompletedAt) < 2 {
|
||||
addRow("Last full scan time: Unknown (not enough data)")
|
||||
|
||||
if sc.CurrentCycle == 0 && sc.CurrentStarted.IsZero() && sc.CyclesCompletedAt == nil {
|
||||
addRowF(" "+title("Scanning:")+" %d bucket(s)", sc.OngoingBuckets)
|
||||
} else {
|
||||
addRow("Overall Statistics")
|
||||
addRow("------------------")
|
||||
sort.Slice(sc.CyclesCompletedAt, func(i, j int) bool {
|
||||
return sc.CyclesCompletedAt[i].After(sc.CyclesCompletedAt[j])
|
||||
})
|
||||
if len(sc.CyclesCompletedAt) >= wantCycles {
|
||||
sinceLast := sc.CyclesCompletedAt[0].Sub(sc.CyclesCompletedAt[wantCycles-1])
|
||||
perMonth := float64(30*24*time.Hour) / float64(sinceLast)
|
||||
cycleTime := console.Colorize("metrics-number", fmt.Sprintf("%dd%dh%dm", int(sinceLast.Hours()/24), int(sinceLast.Hours())%24, int(sinceLast.Minutes())%60))
|
||||
perms := console.Colorize("metrics-number", fmt.Sprintf("%.02f", perMonth))
|
||||
addRowF(title("Last full scan time:")+" %s; Estimated %s/month", cycleTime, perms)
|
||||
const wantCycles = 16
|
||||
if len(sc.CyclesCompletedAt) < 2 {
|
||||
addRow("Last full scan time: Unknown (not enough data)")
|
||||
} else {
|
||||
sinceLast := sc.CyclesCompletedAt[0].Sub(sc.CyclesCompletedAt[1]) * time.Duration(wantCycles)
|
||||
perMonth := float64(30*24*time.Hour) / float64(sinceLast)
|
||||
cycleTime := console.Colorize("metrics-number", fmt.Sprintf("%dd%dh%dm", int(sinceLast.Hours()/24), int(sinceLast.Hours())%24, int(sinceLast.Minutes())%60))
|
||||
perms := console.Colorize("metrics-number", fmt.Sprintf("%.02f", perMonth))
|
||||
addRowF(title("Est. full scan time:")+" %s; Estimated %s/month", cycleTime, perms)
|
||||
addRow("Overall Statistics")
|
||||
addRow("------------------")
|
||||
sort.Slice(sc.CyclesCompletedAt, func(i, j int) bool {
|
||||
return sc.CyclesCompletedAt[i].After(sc.CyclesCompletedAt[j])
|
||||
})
|
||||
if len(sc.CyclesCompletedAt) >= wantCycles {
|
||||
sinceLast := sc.CyclesCompletedAt[0].Sub(sc.CyclesCompletedAt[wantCycles-1])
|
||||
perMonth := float64(30*24*time.Hour) / float64(sinceLast)
|
||||
cycleTime := console.Colorize("metrics-number", fmt.Sprintf("%dd%dh%dm", int(sinceLast.Hours()/24), int(sinceLast.Hours())%24, int(sinceLast.Minutes())%60))
|
||||
perms := console.Colorize("metrics-number", fmt.Sprintf("%.02f", perMonth))
|
||||
addRowF(title("Last full scan time:")+" %s; Estimated %s/month", cycleTime, perms)
|
||||
} else {
|
||||
sinceLast := sc.CyclesCompletedAt[0].Sub(sc.CyclesCompletedAt[1]) * time.Duration(wantCycles)
|
||||
perMonth := float64(30*24*time.Hour) / float64(sinceLast)
|
||||
cycleTime := console.Colorize("metrics-number", fmt.Sprintf("%dd%dh%dm", int(sinceLast.Hours()/24), int(sinceLast.Hours())%24, int(sinceLast.Minutes())%60))
|
||||
perms := console.Colorize("metrics-number", fmt.Sprintf("%.02f", perMonth))
|
||||
addRowF(title("Est. full scan time:")+" %s; Estimated %s/month", cycleTime, perms)
|
||||
}
|
||||
}
|
||||
if sc.CurrentCycle > 0 {
|
||||
addRowF(title("Current cycle:")+" %s; Started: %v", ui(sc.CurrentCycle), console.Colorize("metrics-date", sc.CurrentStarted))
|
||||
} else {
|
||||
addRowF("%s", title("Current cycle:")+" (between cycles)")
|
||||
}
|
||||
}
|
||||
if sc.CurrentCycle > 0 {
|
||||
addRowF(title("Current cycle:")+" %s; Started: %v", ui(sc.CurrentCycle), console.Colorize("metrics-date", sc.CurrentStarted))
|
||||
addRowF(title("Active drives:")+" %s", ui(uint64(len(sc.ActivePaths))))
|
||||
} else {
|
||||
addRowF(title("Current cycle:") + " (between cycles)")
|
||||
addRowF(title("Active drives:")+" %s", ui(uint64(len(sc.ActivePaths))))
|
||||
}
|
||||
|
||||
addRowF(title("Active drives:")+" %s", ui(uint64(len(sc.ActivePaths))))
|
||||
|
||||
getRate := func(x madmin.TimedAction) string {
|
||||
if x.AccTime > 0 {
|
||||
return fmt.Sprintf("; Rate: %v/day", ui(uint64(float64(24*time.Hour)/(float64(time.Minute)/float64(x.Count)))))
|
||||
|
||||
+244
-112
@@ -1,4 +1,4 @@
|
||||
// Copyright (c) 2015-2022 MinIO, Inc.
|
||||
// Copyright (c) 2015-2024 MinIO, Inc.
|
||||
//
|
||||
// This file is part of MinIO Object Storage stack
|
||||
//
|
||||
@@ -21,11 +21,13 @@ import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/charmbracelet/bubbles/spinner"
|
||||
tea "github.com/charmbracelet/bubbletea"
|
||||
"github.com/charmbracelet/lipgloss"
|
||||
"github.com/fatih/color"
|
||||
"github.com/jedib0t/go-pretty/v6/table"
|
||||
"github.com/jedib0t/go-pretty/v6/text"
|
||||
"github.com/minio/cli"
|
||||
json "github.com/minio/colorjson"
|
||||
"github.com/minio/madmin-go/v3"
|
||||
@@ -38,6 +40,10 @@ var serviceRestartFlag = []cli.Flag{
|
||||
Name: "dry-run",
|
||||
Usage: "do not attempt a restart, however verify the peer status",
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "wait, w",
|
||||
Usage: "wait for background initializations to complete",
|
||||
},
|
||||
}
|
||||
|
||||
var adminServiceRestartCmd = cli.Command{
|
||||
@@ -62,70 +68,154 @@ EXAMPLES:
|
||||
`,
|
||||
}
|
||||
|
||||
// serviceRestartCommand is container for service restart command success and failure messages.
|
||||
type serviceRestartCommand struct {
|
||||
Status string `json:"status"`
|
||||
ServerURL string `json:"serverURL"`
|
||||
Result madmin.ServiceActionResult `json:"result"`
|
||||
TimeTaken time.Duration `json:"timeTaken"`
|
||||
type serviceRestartUI struct {
|
||||
current atomic.Value
|
||||
tbl *console.Table
|
||||
meter spinner.Model
|
||||
quitting bool
|
||||
}
|
||||
|
||||
// String colorized service restart command message.
|
||||
func (s serviceRestartCommand) String() string {
|
||||
var s1 strings.Builder
|
||||
s1.WriteString("Restart command successfully acknowledged by `" + s.ServerURL + "` in " + timeDurationToHumanizedDuration(s.TimeTaken).StringShort() + ". Type Ctrl-C to quit or wait to follow the status of the restart process.")
|
||||
func (m *serviceRestartUI) add(msg serviceRestartMessage) {
|
||||
m.current.Store(msg)
|
||||
}
|
||||
|
||||
if len(s.Result.Results) > 0 {
|
||||
s1.WriteString("\n")
|
||||
var rows []table.Row
|
||||
for _, peerRes := range s.Result.Results {
|
||||
errStr := tickCell
|
||||
if peerRes.Err != "" {
|
||||
errStr = peerRes.Err
|
||||
} else if len(peerRes.WaitingDrives) > 0 {
|
||||
errStr = fmt.Sprintf("%d drives are waiting for I/O and are offline, manual restart of OS is recommended", len(peerRes.WaitingDrives))
|
||||
}
|
||||
rows = append(rows, table.Row{peerRes.Host, errStr})
|
||||
func (m *serviceRestartUI) Init() tea.Cmd {
|
||||
return m.meter.Tick
|
||||
}
|
||||
|
||||
func (m *serviceRestartUI) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
||||
if m.quitting {
|
||||
return m, tea.Quit
|
||||
}
|
||||
switch msg := msg.(type) {
|
||||
case tea.KeyMsg:
|
||||
switch msg.String() {
|
||||
case "q", "esc", "ctrl+c":
|
||||
m.quitting = true
|
||||
return m, tea.Quit
|
||||
default:
|
||||
return m, nil
|
||||
}
|
||||
case spinner.TickMsg:
|
||||
var cmd tea.Cmd
|
||||
m.meter, cmd = m.meter.Update(msg)
|
||||
return m, cmd
|
||||
}
|
||||
return m, nil
|
||||
}
|
||||
|
||||
t := table.NewWriter()
|
||||
t.SetOutputMirror(&s1)
|
||||
t.SetColumnConfigs([]table.ColumnConfig{{Align: text.AlignCenter}})
|
||||
func (m *serviceRestartUI) View() string {
|
||||
var s strings.Builder
|
||||
|
||||
t.AppendHeader(table.Row{"Host", "Status"})
|
||||
t.AppendRows(rows)
|
||||
t.SetStyle(table.StyleLight)
|
||||
t.Render()
|
||||
msgI := m.current.Load()
|
||||
if msgI == nil {
|
||||
s.WriteString("(waiting for data)")
|
||||
return s.String()
|
||||
}
|
||||
|
||||
return console.Colorize("ServiceRestart", s1.String())
|
||||
s.WriteString(fmt.Sprintf("Service status: %s ", m.meter.View()))
|
||||
|
||||
msg := msgI.(serviceRestartMessage)
|
||||
state := msg.State
|
||||
switch state {
|
||||
case restarting:
|
||||
// Actually still restarting, no response yet from the server.
|
||||
s.WriteString("[RESTARTING]\n")
|
||||
case waiting:
|
||||
// Waiting on background initializations such as IAM and bucket metadata
|
||||
s.WriteString(console.Colorize("ServiceInitializing", "[WAITING]"))
|
||||
s.WriteString("\n")
|
||||
case done:
|
||||
m.quitting = true
|
||||
|
||||
// Finished restarting and optionally waiting for the background initializations to complete.
|
||||
s.WriteString(console.Colorize("ServiceRestarted", "[DONE]"))
|
||||
s.WriteString("\n")
|
||||
var (
|
||||
totalNodes = len(msg.Result.Results)
|
||||
totalOfflineNodes int
|
||||
totalHungNodes int
|
||||
)
|
||||
|
||||
for _, peerRes := range msg.Result.Results {
|
||||
if peerRes.Err != "" {
|
||||
totalOfflineNodes++
|
||||
} else if len(peerRes.WaitingDrives) > 0 {
|
||||
totalHungNodes++
|
||||
}
|
||||
}
|
||||
|
||||
s.WriteString("Summary:\n")
|
||||
|
||||
var cellText [][]string
|
||||
cellText = append(cellText, []string{
|
||||
"Servers:",
|
||||
fmt.Sprintf("%d online, %d offline, %d hung", totalNodes-(totalOfflineNodes+totalHungNodes), totalOfflineNodes, totalHungNodes),
|
||||
})
|
||||
|
||||
cellText = append(cellText, []string{
|
||||
"Restart Time:",
|
||||
msg.RestartDuration.String(),
|
||||
})
|
||||
|
||||
if msg.WaitingDuration > 0 {
|
||||
cellText = append(cellText, []string{
|
||||
"Background Init Time:",
|
||||
msg.WaitingDuration.String(),
|
||||
})
|
||||
}
|
||||
|
||||
fatalIf(probe.NewError(m.tbl.PopulateTable(&s, cellText)), "unable to populate the table")
|
||||
}
|
||||
|
||||
return s.String()
|
||||
}
|
||||
|
||||
func initServiceRestartUI(rowCount int, currentCh chan serviceRestartMessage) *serviceRestartUI {
|
||||
var printColors []*color.Color
|
||||
for range rowCount {
|
||||
printColors = append(printColors, getPrintCol(colGreen))
|
||||
}
|
||||
|
||||
tbl := console.NewTable(printColors, []bool{false, false}, 4)
|
||||
|
||||
meter := spinner.New()
|
||||
meter.Spinner = spinner.Meter
|
||||
meter.Style = lipgloss.NewStyle().Foreground(lipgloss.Color("205"))
|
||||
|
||||
svcUI := &serviceRestartUI{tbl: tbl, meter: meter}
|
||||
go func() {
|
||||
for msg := range currentCh {
|
||||
if msg.Status != "" {
|
||||
svcUI.add(msg)
|
||||
}
|
||||
}
|
||||
}()
|
||||
return svcUI
|
||||
}
|
||||
|
||||
const (
|
||||
restarting = iota
|
||||
waiting
|
||||
done
|
||||
)
|
||||
|
||||
// serviceRestartMessage is container for service restart command success and failure messages.
|
||||
type serviceRestartMessage struct {
|
||||
Status string `json:"status"`
|
||||
ServerURL string `json:"serverURL"`
|
||||
Result madmin.ServiceActionResult `json:"result"`
|
||||
RestartDuration time.Duration `json:"restartDuration"`
|
||||
WaitingDuration time.Duration `json:"waitingDuration"`
|
||||
TimeTaken time.Duration `json:"timeTaken"` // deprecated use "restartDuration" instead.
|
||||
State int `json:"state"`
|
||||
}
|
||||
|
||||
func (s serviceRestartMessage) String() string {
|
||||
return s.JSON()
|
||||
}
|
||||
|
||||
// JSON jsonified service restart command message.
|
||||
func (s serviceRestartCommand) JSON() string {
|
||||
serviceRestartJSONBytes, e := json.MarshalIndent(s, "", " ")
|
||||
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
|
||||
|
||||
return string(serviceRestartJSONBytes)
|
||||
}
|
||||
|
||||
// serviceRestartMessage is container for service restart success and failure messages.
|
||||
type serviceRestartMessage struct {
|
||||
Status string `json:"status"`
|
||||
ServerURL string `json:"serverURL"`
|
||||
TimeTaken time.Duration `json:"timeTaken"`
|
||||
Err error `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
// String colorized service restart message.
|
||||
func (s serviceRestartMessage) String() string {
|
||||
if s.Err == nil {
|
||||
return console.Colorize("ServiceRestart", fmt.Sprintf("\nEstablished quorum on `%s` successfully in %s", s.ServerURL, timeDurationToHumanizedDuration(s.TimeTaken).StringShort()))
|
||||
}
|
||||
return console.Colorize("FailedServiceRestart", "Failed to restart `"+s.ServerURL+"`. error: "+s.Err.Error())
|
||||
}
|
||||
|
||||
// JSON jsonified service restart message.
|
||||
func (s serviceRestartMessage) JSON() string {
|
||||
serviceRestartJSONBytes, e := json.MarshalIndent(s, "", " ")
|
||||
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
|
||||
@@ -150,7 +240,7 @@ func mainAdminServiceRestart(ctx *cli.Context) error {
|
||||
// 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("ServiceRestarted", color.New(color.FgGreen, color.Bold))
|
||||
console.SetColor("FailedServiceRestart", color.New(color.FgRed, color.Bold))
|
||||
|
||||
// Get the alias parameter from cli
|
||||
@@ -160,68 +250,110 @@ func mainAdminServiceRestart(ctx *cli.Context) error {
|
||||
client, err := newAdminClient(aliasedURL)
|
||||
fatalIf(err, "Unable to initialize admin connection.")
|
||||
|
||||
t := time.Now()
|
||||
// Restart the specified MinIO server
|
||||
result, e := client.ServiceAction(ctxt, madmin.ServiceActionOpts{
|
||||
Action: madmin.ServiceActionRestart,
|
||||
DryRun: ctx.Bool("dry-run"),
|
||||
})
|
||||
if e != nil {
|
||||
// Attempt an older API server might be old
|
||||
e = client.ServiceRestart(ctxt)
|
||||
rowCount := 2
|
||||
toWait := ctx.Bool("wait")
|
||||
if toWait {
|
||||
rowCount = 3
|
||||
}
|
||||
fatalIf(probe.NewError(e), "Unable to restart the server.")
|
||||
|
||||
// Success..
|
||||
printMsg(serviceRestartCommand{Status: "success", ServerURL: aliasedURL, Result: result, TimeTaken: time.Since(t)})
|
||||
ch := make(chan serviceRestartMessage, 1)
|
||||
|
||||
// Start pinging the service until it is ready
|
||||
svcUI := initServiceRestartUI(rowCount, ch)
|
||||
go func() {
|
||||
t := time.Now()
|
||||
|
||||
anonClient, err := newAnonymousClient(aliasedURL)
|
||||
fatalIf(err.Trace(aliasedURL), "Could not ping `"+aliasedURL+"`.")
|
||||
// Restart the specified MinIO server
|
||||
result, e := client.ServiceAction(ctxt, madmin.ServiceActionOpts{
|
||||
Action: madmin.ServiceActionRestart,
|
||||
DryRun: ctx.Bool("dry-run"),
|
||||
})
|
||||
if e != nil {
|
||||
// Attempt an older API server might be old
|
||||
// nolint:staticcheck
|
||||
// we need this fallback
|
||||
e = client.ServiceRestart(ctxt)
|
||||
}
|
||||
fatalIf(probe.NewError(e), "Unable to restart the server.")
|
||||
|
||||
coloring := color.New(color.FgRed)
|
||||
mark := "..."
|
||||
timeTaken := time.Since(t)
|
||||
restart := restarting
|
||||
if !toWait {
|
||||
restart = done
|
||||
}
|
||||
|
||||
// Print restart progress
|
||||
printProgress := func() {
|
||||
if !globalQuiet && !globalJSON {
|
||||
coloring.Printf(mark)
|
||||
ch <- serviceRestartMessage{
|
||||
Status: "success",
|
||||
ServerURL: aliasedURL,
|
||||
Result: result,
|
||||
RestartDuration: timeTaken,
|
||||
TimeTaken: timeTaken,
|
||||
State: restart,
|
||||
}
|
||||
|
||||
if toWait {
|
||||
sleepInterval := 500 * time.Millisecond
|
||||
go func() {
|
||||
defer close(ch)
|
||||
|
||||
wt := time.Now()
|
||||
|
||||
// Start pinging the service until it is ready
|
||||
anonClient, err := newAnonymousClient(aliasedURL)
|
||||
fatalIf(err.Trace(aliasedURL), "unable to initialize anonymous client for`"+aliasedURL+"`.")
|
||||
|
||||
for {
|
||||
healthCtx, healthCancel := context.WithTimeout(ctxt, 2*time.Second)
|
||||
|
||||
// Fetch the health status of the specified MinIO server
|
||||
healthResult, healthErr := anonClient.Healthy(healthCtx, madmin.HealthOpts{})
|
||||
healthCancel()
|
||||
|
||||
switch {
|
||||
case healthErr == nil && healthResult.Healthy:
|
||||
ch <- serviceRestartMessage{
|
||||
Status: "success",
|
||||
ServerURL: aliasedURL,
|
||||
Result: result,
|
||||
RestartDuration: timeTaken,
|
||||
TimeTaken: timeTaken,
|
||||
WaitingDuration: time.Since(wt),
|
||||
State: done,
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
ch <- serviceRestartMessage{
|
||||
Status: "success",
|
||||
ServerURL: aliasedURL,
|
||||
Result: result,
|
||||
WaitingDuration: time.Since(wt),
|
||||
RestartDuration: timeTaken,
|
||||
TimeTaken: timeTaken,
|
||||
State: waiting,
|
||||
}
|
||||
|
||||
time.Sleep(sleepInterval)
|
||||
}
|
||||
}()
|
||||
} else {
|
||||
close(ch)
|
||||
}
|
||||
}()
|
||||
|
||||
if !globalJSON {
|
||||
ui := tea.NewProgram(svcUI)
|
||||
if _, e := ui.Run(); e != nil {
|
||||
cancel()
|
||||
fatalIf(probe.NewError(e).Trace(aliasedURL), "Unable to initialize service restart UI")
|
||||
}
|
||||
} else {
|
||||
for msg := range ch {
|
||||
printMsg(msg)
|
||||
if msg.State == done {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
printProgress()
|
||||
mark = "."
|
||||
|
||||
t = time.Now()
|
||||
for {
|
||||
healthCtx, healthCancel := context.WithTimeout(ctxt, 2*time.Second)
|
||||
|
||||
// Fetch the health status of the specified MinIO server
|
||||
healthResult, healthErr := anonClient.Healthy(healthCtx, madmin.HealthOpts{})
|
||||
healthCancel()
|
||||
|
||||
switch {
|
||||
case healthErr == nil && healthResult.Healthy:
|
||||
printMsg(serviceRestartMessage{
|
||||
Status: "success",
|
||||
ServerURL: aliasedURL,
|
||||
TimeTaken: time.Since(t),
|
||||
})
|
||||
return nil
|
||||
case healthErr == nil && !healthResult.Healthy:
|
||||
coloring = color.New(color.FgYellow)
|
||||
mark = "!"
|
||||
fallthrough
|
||||
default:
|
||||
printProgress()
|
||||
}
|
||||
|
||||
select {
|
||||
case <-ctxt.Done():
|
||||
return ctxt.Err()
|
||||
default:
|
||||
time.Sleep(500 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -18,6 +18,8 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/cli"
|
||||
json "github.com/minio/colorjson"
|
||||
@@ -74,7 +76,7 @@ func checkAdminServiceUnfreezeSyntax(ctx *cli.Context) {
|
||||
}
|
||||
|
||||
func mainAdminServiceUnfreeze(ctx *cli.Context) error {
|
||||
// Validate serivce unfreeze syntax.
|
||||
// Validate service unfreeze syntax.
|
||||
checkAdminServiceUnfreezeSyntax(ctx)
|
||||
|
||||
// Set color.
|
||||
@@ -88,8 +90,19 @@ func mainAdminServiceUnfreeze(ctx *cli.Context) error {
|
||||
client, err := newAdminClient(aliasedURL)
|
||||
fatalIf(err, "Unable to initialize admin connection.")
|
||||
|
||||
ctxt, cancel := context.WithCancel(globalContext)
|
||||
defer cancel()
|
||||
|
||||
// Unfreeze the specified MinIO server
|
||||
fatalIf(probe.NewError(client.ServiceUnfreeze(globalContext)), "Unable to unfreeze the server.")
|
||||
e := client.ServiceUnfreezeV2(ctxt)
|
||||
if e != nil {
|
||||
// Attempt an older API server might be old
|
||||
// nolint:staticcheck
|
||||
// we need this fallback
|
||||
e = client.ServiceUnfreeze(ctxt)
|
||||
}
|
||||
// Unfreeze the specified MinIO server
|
||||
fatalIf(probe.NewError(e), "Unable to unfreeze the server.")
|
||||
|
||||
// Success..
|
||||
printMsg(serviceUnfreezeCommand{Status: "success", ServerURL: aliasedURL})
|
||||
|
||||
@@ -28,7 +28,7 @@ var adminServiceSubcommands = []cli.Command{
|
||||
|
||||
var adminServiceCmd = cli.Command{
|
||||
Name: "service",
|
||||
Usage: "restart, stop and unfreeze a MinIO cluster",
|
||||
Usage: "restart or unfreeze a MinIO cluster",
|
||||
Action: mainAdminService,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
|
||||
+97
-24
@@ -18,12 +18,15 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"hash/fnv"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"path"
|
||||
"sort"
|
||||
"strings"
|
||||
@@ -33,6 +36,7 @@ import (
|
||||
tea "github.com/charmbracelet/bubbletea"
|
||||
"github.com/dustin/go-humanize"
|
||||
"github.com/fatih/color"
|
||||
"github.com/klauspost/compress/zstd"
|
||||
"github.com/minio/cli"
|
||||
json "github.com/minio/colorjson"
|
||||
"github.com/minio/madmin-go/v3"
|
||||
@@ -92,7 +96,7 @@ var adminTraceFlags = []cli.Flag{
|
||||
cli.IntFlag{
|
||||
Name: "stats-n",
|
||||
Usage: "maximum number of stat entries",
|
||||
Value: 30,
|
||||
Value: 20,
|
||||
Hidden: true,
|
||||
},
|
||||
cli.BoolFlag{
|
||||
@@ -111,6 +115,10 @@ var adminTraceFlags = []cli.Flag{
|
||||
Name: "filter-size",
|
||||
Usage: "filter size, use with filter (see UNITS)",
|
||||
},
|
||||
cli.StringFlag{
|
||||
Name: "in",
|
||||
Usage: "read previously saved json from file and replay",
|
||||
},
|
||||
}
|
||||
|
||||
// traceCallTypes contains all call types and flags to apply when selected.
|
||||
@@ -239,7 +247,7 @@ const traceTimeFormat = "2006-01-02T15:04:05.000"
|
||||
var colors = []color.Attribute{color.FgCyan, color.FgWhite, color.FgYellow, color.FgGreen}
|
||||
|
||||
func checkAdminTraceSyntax(ctx *cli.Context) {
|
||||
if len(ctx.Args()) != 1 {
|
||||
if len(ctx.Args()) != 1 && len(ctx.String("in")) == 0 {
|
||||
showCommandHelpAndExit(ctx, 1) // last argument is exit code
|
||||
}
|
||||
filterFlag := ctx.Bool("filter-request") || ctx.Bool("filter-response")
|
||||
@@ -403,12 +411,10 @@ func (opts matchOpts) matches(traceInfo madmin.ServiceTraceInfo) bool {
|
||||
}
|
||||
}
|
||||
|
||||
if opts.requestSize > 0 && traceInfo.Trace.HTTP.CallStats.InputBytes < int(opts.requestSize) {
|
||||
return false
|
||||
}
|
||||
|
||||
if opts.responseSize > 0 && traceInfo.Trace.HTTP.CallStats.OutputBytes < int(opts.responseSize) {
|
||||
return false
|
||||
if traceInfo.Trace.HTTP != nil {
|
||||
if (opts.requestSize > 0 && traceInfo.Trace.HTTP.CallStats.InputBytes < int(opts.requestSize)) || (opts.responseSize > 0 && traceInfo.Trace.HTTP.CallStats.OutputBytes < int(opts.responseSize)) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
return true
|
||||
@@ -489,7 +495,6 @@ func mainAdminTrace(ctx *cli.Context) error {
|
||||
|
||||
verbose := ctx.Bool("verbose")
|
||||
stats := ctx.Bool("stats")
|
||||
aliasedURL := ctx.Args().Get(0)
|
||||
|
||||
console.SetColor("Stat", color.New(color.FgYellow))
|
||||
|
||||
@@ -510,26 +515,81 @@ func mainAdminTrace(ctx *cli.Context) error {
|
||||
for _, c := range colors {
|
||||
console.SetColor(fmt.Sprintf("Node%d", c), color.New(c))
|
||||
}
|
||||
// Create a new MinIO Admin Client
|
||||
client, err := newAdminClient(aliasedURL)
|
||||
if err != nil {
|
||||
fatalIf(err.Trace(aliasedURL), "Unable to initialize admin client.")
|
||||
return nil
|
||||
}
|
||||
|
||||
var traceCh <-chan madmin.ServiceTraceInfo
|
||||
|
||||
ctxt, cancel := context.WithCancel(globalContext)
|
||||
defer cancel()
|
||||
|
||||
opts, e := tracingOpts(ctx, ctx.StringSlice("call"))
|
||||
fatalIf(probe.NewError(e), "Unable to start tracing")
|
||||
if inFile := ctx.String("in"); inFile != "" {
|
||||
stats = true
|
||||
ch := make(chan madmin.ServiceTraceInfo, 1000)
|
||||
traceCh = ch
|
||||
go func() {
|
||||
f, e := os.Open(inFile)
|
||||
fatalIf(probe.NewError(e), "Unable to open input")
|
||||
defer f.Close()
|
||||
in := io.Reader(f)
|
||||
if strings.HasSuffix(inFile, ".zst") {
|
||||
zr, e := zstd.NewReader(in)
|
||||
fatalIf(probe.NewError(e), "Unable to open input")
|
||||
defer zr.Close()
|
||||
in = zr
|
||||
}
|
||||
sc := bufio.NewReader(in)
|
||||
for ctxt.Err() == nil {
|
||||
b, e := sc.ReadBytes('\n')
|
||||
if e == io.EOF {
|
||||
break
|
||||
}
|
||||
var t shortTraceMsg
|
||||
e = json.Unmarshal(b, &t)
|
||||
if e != nil || t.Type == "Bootstrap" {
|
||||
// Ignore bootstrap, since their times skews averages.
|
||||
continue
|
||||
}
|
||||
ch <- madmin.ServiceTraceInfo{
|
||||
Trace: madmin.TraceInfo{
|
||||
TraceType: t.trcType, // TODO: Grab from string, once we can.
|
||||
NodeName: t.Host,
|
||||
FuncName: t.FuncName,
|
||||
Time: t.Time,
|
||||
Path: t.Path,
|
||||
Duration: t.Duration,
|
||||
Bytes: t.Size,
|
||||
Message: t.StatusMsg,
|
||||
Error: t.Error,
|
||||
Custom: t.Extra,
|
||||
HTTP: nil,
|
||||
HealResult: nil,
|
||||
},
|
||||
Err: nil,
|
||||
}
|
||||
}
|
||||
close(ch)
|
||||
select {}
|
||||
}()
|
||||
} else {
|
||||
// Create a new MinIO Admin Client
|
||||
aliasedURL := ctx.Args().Get(0)
|
||||
|
||||
client, err := newAdminClient(aliasedURL)
|
||||
if err != nil {
|
||||
fatalIf(err.Trace(aliasedURL), "Unable to initialize admin client.")
|
||||
return nil
|
||||
}
|
||||
|
||||
opts, e := tracingOpts(ctx, ctx.StringSlice("call"))
|
||||
fatalIf(probe.NewError(e), "Unable to start tracing")
|
||||
|
||||
// Start listening on all trace activity.
|
||||
traceCh = client.ServiceTrace(ctxt, opts)
|
||||
}
|
||||
|
||||
mopts := matchingOpts(ctx)
|
||||
|
||||
// Start listening on all trace activity.
|
||||
traceCh := client.ServiceTrace(ctxt, opts)
|
||||
if stats {
|
||||
filteredTraces := make(chan madmin.ServiceTraceInfo, 1)
|
||||
ui := tea.NewProgram(initTraceStatsUI(ctx.Int("stats-n"), filteredTraces))
|
||||
ui := tea.NewProgram(initTraceStatsUI(ctx.Bool("all"), ctx.Int("stats-n"), filteredTraces))
|
||||
var te error
|
||||
go func() {
|
||||
for t := range traceCh {
|
||||
@@ -542,12 +602,14 @@ func mainAdminTrace(ctx *cli.Context) error {
|
||||
filteredTraces <- t
|
||||
}
|
||||
}
|
||||
ui.Send(tea.Quit())
|
||||
}()
|
||||
if _, e := ui.Run(); e != nil {
|
||||
cancel()
|
||||
if te != nil {
|
||||
e = te
|
||||
}
|
||||
aliasedURL := ctx.Args().Get(0)
|
||||
fatalIf(probe.NewError(e).Trace(aliasedURL), "Unable to fetch http trace statistics")
|
||||
}
|
||||
return nil
|
||||
@@ -915,9 +977,10 @@ type statItem struct {
|
||||
}
|
||||
|
||||
type statTrace struct {
|
||||
Calls map[string]statItem `json:"calls"`
|
||||
Started time.Time
|
||||
mu sync.Mutex
|
||||
Calls map[string]statItem `json:"calls"`
|
||||
Oldest time.Time
|
||||
Latest time.Time
|
||||
mu sync.Mutex
|
||||
}
|
||||
|
||||
func (s *statTrace) JSON() string {
|
||||
@@ -942,6 +1005,16 @@ func (s *statTrace) add(t madmin.ServiceTraceInfo) {
|
||||
id := t.Trace.FuncName
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if t.Trace.TraceType != madmin.TraceBootstrap {
|
||||
// We can't use bootstrap to find start/end
|
||||
ended := t.Trace.Time.Add(t.Trace.Duration)
|
||||
if s.Oldest.IsZero() {
|
||||
s.Oldest = ended
|
||||
}
|
||||
if ended.After(s.Latest) {
|
||||
s.Latest = ended
|
||||
}
|
||||
}
|
||||
got := s.Calls[id]
|
||||
if got.Name == "" {
|
||||
got.Name = id
|
||||
|
||||
@@ -244,7 +244,7 @@ func generateCredentials() (accessKey, secretKey string, err *probe.Error) {
|
||||
if e != nil {
|
||||
return "", "", probe.NewError(e)
|
||||
}
|
||||
for i := 0; i < accessKeyMaxLen; i++ {
|
||||
for i := range accessKeyMaxLen {
|
||||
keyBytes[i] = alphaNumericTable[keyBytes[i]%alphaNumericTableLen]
|
||||
}
|
||||
accessKey = string(keyBytes)
|
||||
|
||||
+49
-37
@@ -20,10 +20,13 @@ package cmd
|
||||
import (
|
||||
"fmt"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/pkg/v3/console"
|
||||
"github.com/minio/pkg/v3/env"
|
||||
|
||||
"github.com/fatih/color"
|
||||
)
|
||||
|
||||
var aliasListCmd = cli.Command{
|
||||
@@ -75,6 +78,7 @@ func mainAliasList(ctx *cli.Context, deprecated bool) error {
|
||||
console.SetColor("SecretKey", color.New(color.FgCyan))
|
||||
console.SetColor("API", color.New(color.FgBlue))
|
||||
console.SetColor("Path", color.New(color.FgCyan))
|
||||
console.SetColor("Src", color.New(color.FgCyan))
|
||||
|
||||
alias := cleanAlias(ctx.Args().Get(0))
|
||||
|
||||
@@ -115,51 +119,59 @@ func (d byAlias) Len() int { return len(d) }
|
||||
func (d byAlias) Swap(i, j int) { d[i], d[j] = d[j], d[i] }
|
||||
func (d byAlias) Less(i, j int) bool { return d[i].Alias < d[j].Alias }
|
||||
|
||||
func buildAliasMessage(alias string, deprecated bool, aliasCfg *aliasConfigV10) aliasMessage {
|
||||
aliasMsg := aliasMessage{
|
||||
prettyPrint: false,
|
||||
Alias: alias,
|
||||
URL: aliasCfg.URL,
|
||||
AccessKey: aliasCfg.AccessKey,
|
||||
SecretKey: aliasCfg.SecretKey,
|
||||
API: aliasCfg.API,
|
||||
Src: aliasCfg.Src,
|
||||
}
|
||||
|
||||
if deprecated {
|
||||
aliasMsg.Lookup = aliasCfg.Path
|
||||
} else {
|
||||
aliasMsg.Path = aliasCfg.Path
|
||||
}
|
||||
return aliasMsg
|
||||
}
|
||||
|
||||
// listAliases - list one or all aliases
|
||||
func listAliases(alias string, deprecated bool) (aliases []aliasMessage) {
|
||||
conf, err := loadMcConfig()
|
||||
fatalIf(err.Trace(globalMCConfigVersion), "Unable to load config version `"+globalMCConfigVersion+"`.")
|
||||
|
||||
// If specific alias is requested, look for it and print.
|
||||
if alias != "" {
|
||||
if v, ok := conf.Aliases[alias]; ok {
|
||||
aliasMsg := aliasMessage{
|
||||
prettyPrint: false,
|
||||
Alias: alias,
|
||||
URL: v.URL,
|
||||
AccessKey: v.AccessKey,
|
||||
SecretKey: v.SecretKey,
|
||||
API: v.API,
|
||||
}
|
||||
|
||||
if deprecated {
|
||||
aliasMsg.Lookup = v.Path
|
||||
} else {
|
||||
aliasMsg.Path = v.Path
|
||||
}
|
||||
|
||||
return []aliasMessage{aliasMsg}
|
||||
aliasCfg := mustGetHostConfig(alias)
|
||||
if aliasCfg != nil {
|
||||
return []aliasMessage{buildAliasMessage(alias, deprecated, aliasCfg)}
|
||||
}
|
||||
|
||||
fatalIf(errInvalidAliasedURL(alias), "No such alias `"+alias+"` found.")
|
||||
}
|
||||
|
||||
// list alias from the environment variable.
|
||||
for _, envK := range env.List(mcEnvHostPrefix) {
|
||||
aliasCfg, _ := expandAliasFromEnv(env.Get(envK, ""))
|
||||
if aliasCfg == nil {
|
||||
continue
|
||||
}
|
||||
alias := strings.ReplaceAll(envK, mcEnvHostPrefix, "")
|
||||
aliases = append(aliases, buildAliasMessage(alias, deprecated, aliasCfg))
|
||||
}
|
||||
|
||||
// list alias from the customized configuration.
|
||||
for s, aliasCfg := range aliasToConfigMap {
|
||||
aliases = append(aliases, buildAliasMessage(s, deprecated, aliasCfg))
|
||||
}
|
||||
|
||||
// list alias from the default configuration.
|
||||
conf, err := loadMcConfig()
|
||||
fatalIf(err.Trace(globalMCConfigVersion), "Unable to load config version `"+globalMCConfigVersion+"`.")
|
||||
|
||||
for k, v := range conf.Aliases {
|
||||
aliasMsg := aliasMessage{
|
||||
prettyPrint: true,
|
||||
Alias: k,
|
||||
URL: v.URL,
|
||||
AccessKey: v.AccessKey,
|
||||
SecretKey: v.SecretKey,
|
||||
API: v.API,
|
||||
}
|
||||
|
||||
if deprecated {
|
||||
aliasMsg.Lookup = v.Path
|
||||
} else {
|
||||
aliasMsg.Path = v.Path
|
||||
}
|
||||
|
||||
aliases = append(aliases, aliasMsg)
|
||||
v.Src = mustGetMcConfigPath()
|
||||
aliases = append(aliases, buildAliasMessage(k, deprecated, &v))
|
||||
}
|
||||
|
||||
// Sort by alias names lexically.
|
||||
|
||||
+3
-1
@@ -73,6 +73,7 @@ type aliasMessage struct {
|
||||
SecretKey string `json:"secretKey,omitempty"`
|
||||
API string `json:"api,omitempty"`
|
||||
Path string `json:"path,omitempty"`
|
||||
Src string `json:"src,omitempty"`
|
||||
// Deprecated field, replaced by Path
|
||||
Lookup string `json:"lookup,omitempty"`
|
||||
}
|
||||
@@ -91,13 +92,14 @@ func (h aliasMessage) String() string {
|
||||
Row{"SecretKey", "SecretKey"},
|
||||
Row{"API", "API"},
|
||||
Row{"Path", "Path"},
|
||||
Row{"Src", "Src"},
|
||||
)
|
||||
// Handle deprecated lookup
|
||||
path := h.Path
|
||||
if path == "" {
|
||||
path = h.Lookup
|
||||
}
|
||||
return t.buildRecord(h.Alias, h.URL, h.AccessKey, h.SecretKey, h.API, path)
|
||||
return t.buildRecord(h.Alias, h.URL, h.AccessKey, h.SecretKey, h.API, path, h.Src)
|
||||
case "remove":
|
||||
return console.Colorize("AliasMessage", "Removed `"+h.Alias+"` successfully.")
|
||||
case "add": // add is deprecated
|
||||
|
||||
+6
-9
@@ -24,7 +24,6 @@ import (
|
||||
"crypto/x509"
|
||||
"fmt"
|
||||
"math/rand"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
@@ -149,7 +148,7 @@ func checkAliasSetSyntax(ctx *cli.Context, accessKey, secretKey string, deprecat
|
||||
}
|
||||
} else {
|
||||
if !isValidPath(path) {
|
||||
fatalIf(errInvalidArgument().Trace(bucketLookup),
|
||||
fatalIf(errInvalidArgument().Trace(path),
|
||||
"Unrecognized path value. Valid options are `[auto, on, off]`.")
|
||||
}
|
||||
}
|
||||
@@ -373,25 +372,23 @@ func configurePeerCertificate(s3Config *Config, peerCert *x509.Certificate) {
|
||||
globalRootCAs.AddCert(peerCert)
|
||||
}
|
||||
tr = &http.Transport{
|
||||
Proxy: http.ProxyFromEnvironment,
|
||||
DialContext: (&net.Dialer{
|
||||
Timeout: 10 * time.Second,
|
||||
KeepAlive: 15 * time.Second,
|
||||
}).DialContext,
|
||||
Proxy: http.ProxyFromEnvironment,
|
||||
DialContext: newCustomDialContext(&Config{}),
|
||||
DialTLSContext: newCustomDialTLSContext(&tls.Config{RootCAs: globalRootCAs}),
|
||||
MaxIdleConnsPerHost: 256,
|
||||
IdleConnTimeout: 90 * time.Second,
|
||||
TLSHandshakeTimeout: 10 * time.Second,
|
||||
ExpectContinueTimeout: 10 * time.Second,
|
||||
DisableCompression: true,
|
||||
TLSClientConfig: &tls.Config{RootCAs: globalRootCAs},
|
||||
}
|
||||
case tr.TLSClientConfig == nil || tr.TLSClientConfig.RootCAs == nil:
|
||||
if globalRootCAs != nil {
|
||||
globalRootCAs.AddCert(peerCert)
|
||||
}
|
||||
tr.TLSClientConfig = &tls.Config{RootCAs: globalRootCAs}
|
||||
tr.DialTLSContext = newCustomDialTLSContext(&tls.Config{RootCAs: globalRootCAs})
|
||||
default:
|
||||
tr.TLSClientConfig.RootCAs.AddCert(peerCert)
|
||||
tr.DialTLSContext = newCustomDialTLSContext(tr.TLSClientConfig)
|
||||
}
|
||||
s3Config.Transport = tr
|
||||
}
|
||||
|
||||
@@ -116,11 +116,11 @@ func (s anonymousRules) JSON() string {
|
||||
|
||||
// anonymousMessage is container for anonymous command on bucket success and failure messages.
|
||||
type anonymousMessage struct {
|
||||
Operation string `json:"operation"`
|
||||
Status string `json:"status"`
|
||||
Bucket string `json:"bucket"`
|
||||
Perms accessPerms `json:"permission"`
|
||||
Anonymous map[string]interface{} `json:"anonymous,omitempty"`
|
||||
Operation string `json:"operation"`
|
||||
Status string `json:"status"`
|
||||
Bucket string `json:"bucket"`
|
||||
Perms accessPerms `json:"permission"`
|
||||
Anonymous map[string]any `json:"anonymous,omitempty"`
|
||||
}
|
||||
|
||||
// String colorized access message.
|
||||
@@ -406,7 +406,7 @@ func runAnonymousLinksCmd(args cli.Args, recursive bool) {
|
||||
|
||||
// Encode public URL
|
||||
u, e := url.Parse(content.URL.String())
|
||||
errorIf(probe.NewError(e), "Unable to parse url `"+content.URL.String()+"`.")
|
||||
errorIf(probe.NewError(e), "Unable to parse url `%s`.", content.URL)
|
||||
publicURL := u.String()
|
||||
|
||||
// Construct the message to be displayed to the user
|
||||
@@ -464,7 +464,7 @@ func runAnonymousCmd(args cli.Args) {
|
||||
"Unable to "+operation+" anonymous `"+string(perms)+"` for `"+targetURL+"`.")
|
||||
}
|
||||
}
|
||||
anonymousJSON := map[string]interface{}{}
|
||||
anonymousJSON := map[string]any{}
|
||||
if anonymousStr != "" {
|
||||
e := json.Unmarshal([]byte(anonymousStr), &anonymousJSON)
|
||||
fatalIf(probe.NewError(e), "Unable to unmarshal custom anonymous file.")
|
||||
|
||||
@@ -369,6 +369,15 @@ var completeCmds = map[string]complete.Predictor{
|
||||
"/idp/openid/enable": aliasCompleter,
|
||||
"/idp/openid/disable": aliasCompleter,
|
||||
|
||||
"/idp/openid/accesskey/list": aliasCompleter,
|
||||
"/idp/openid/accesskey/ls": aliasCompleter,
|
||||
"/idp/openid/accesskey/info": aliasCompleter,
|
||||
"/idp/openid/accesskey/remove": aliasCompleter,
|
||||
"/idp/openid/accesskey/rm": aliasCompleter,
|
||||
"/idp/openid/accesskey/edit": aliasCompleter,
|
||||
"/idp/openid/accesskey/enable": aliasCompleter,
|
||||
"/idp/openid/accesskey/disable": aliasCompleter,
|
||||
|
||||
"/idp/ldap/add": aliasCompleter,
|
||||
"/idp/ldap/update": aliasCompleter,
|
||||
"/idp/ldap/remove": aliasCompleter,
|
||||
@@ -388,6 +397,21 @@ var completeCmds = map[string]complete.Predictor{
|
||||
"/idp/ldap/accesskey/remove": aliasCompleter,
|
||||
"/idp/ldap/accesskey/rm": aliasCompleter,
|
||||
"/idp/ldap/accesskey/info": aliasCompleter,
|
||||
"/idp/ldap/accesskey/edit": aliasCompleter,
|
||||
"/idp/ldap/accesskey/enable": aliasCompleter,
|
||||
"/idp/ldap/accesskey/disable": aliasCompleter,
|
||||
"/idp/ldap/accesskey/sts-revoke": aliasCompleter,
|
||||
|
||||
"/admin/accesskey/create": aliasCompleter,
|
||||
"/admin/accesskey/list": aliasCompleter,
|
||||
"/admin/accesskey/ls": aliasCompleter,
|
||||
"/admin/accesskey/remove": aliasCompleter,
|
||||
"/admin/accesskey/rm": aliasCompleter,
|
||||
"/admin/accesskey/info": aliasCompleter,
|
||||
"/admin/accesskey/edit": aliasCompleter,
|
||||
"/admin/accesskey/enable": aliasCompleter,
|
||||
"/admin/accesskey/disable": aliasCompleter,
|
||||
"/admin/accesskey/sts-revoke": aliasCompleter,
|
||||
|
||||
"/admin/policy/info": aliasCompleter,
|
||||
"/admin/policy/update": aliasCompleter,
|
||||
@@ -489,6 +513,7 @@ var completeCmds = map[string]complete.Predictor{
|
||||
"/support/top/drive": aliasCompleter,
|
||||
"/support/top/disk": aliasCompleter,
|
||||
"/support/top/net": aliasCompleter,
|
||||
"/support/top/rpc": aliasCompleter,
|
||||
"/support/upload": aliasCompleter,
|
||||
|
||||
"/license/register": aliasCompleter,
|
||||
@@ -511,6 +536,10 @@ var completeCmds = map[string]complete.Predictor{
|
||||
"/quota/clear": aliasCompleter,
|
||||
"/put": complete.PredictOr(s3Completer, fsCompleter),
|
||||
"/get": complete.PredictOr(s3Completer, fsCompleter),
|
||||
|
||||
"/cors/set": s3Complete{deepLevel: 2},
|
||||
"/cors/get": s3Complete{deepLevel: 2},
|
||||
"/cors/remove": s3Complete{deepLevel: 2},
|
||||
}
|
||||
|
||||
// flagsToCompleteFlags transforms a cli.Flag to complete.Flags
|
||||
|
||||
+47
-12
@@ -19,9 +19,9 @@ package cmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/minio/cli"
|
||||
json "github.com/minio/colorjson"
|
||||
"github.com/minio/madmin-go/v3"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
)
|
||||
@@ -40,26 +40,22 @@ USAGE:
|
||||
{{.HelpName}} TARGET JOBTYPE
|
||||
|
||||
JOBTYPE:
|
||||
` + supportedJobTypes() + `
|
||||
- replicate
|
||||
- keyrotate
|
||||
- expire
|
||||
Use the special value "list" to request server to list supported job types.
|
||||
|
||||
FLAGS:
|
||||
{{range .VisibleFlags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
1. Generate a new batch 'replication' job definition:
|
||||
{{.Prompt}} {{.HelpName}} myminio replicate > replication.yaml
|
||||
2. List all supported job types:
|
||||
{{.Prompt}} {{.HelpName}} myminio list
|
||||
`,
|
||||
}
|
||||
|
||||
func supportedJobTypes() string {
|
||||
var builder strings.Builder
|
||||
for _, jobType := range madmin.SupportedJobTypes {
|
||||
builder.WriteString(" - ")
|
||||
builder.WriteString(string(jobType))
|
||||
builder.WriteString("\n")
|
||||
}
|
||||
return builder.String()
|
||||
}
|
||||
|
||||
// checkBatchGenerateSyntax - validate all the passed arguments
|
||||
func checkBatchGenerateSyntax(ctx *cli.Context) {
|
||||
if len(ctx.Args()) != 2 {
|
||||
@@ -80,6 +76,45 @@ func mainBatchGenerate(ctx *cli.Context) error {
|
||||
adminClient, err := newAdminClient(aliasedURL)
|
||||
fatalIf(err, "Unable to initialize admin connection.")
|
||||
|
||||
if jobType == "list" {
|
||||
supportedJobTypes, apiUnavailable, e := adminClient.GetSupportedBatchJobTypes(globalContext)
|
||||
if e != nil {
|
||||
fatalIf(probe.NewError(e), "Unable to list supported job types")
|
||||
}
|
||||
if apiUnavailable {
|
||||
// Fallback to default supported jobs.
|
||||
supportedJobTypes = madmin.SupportedJobTypes
|
||||
}
|
||||
|
||||
if globalJSON {
|
||||
j, err := json.Marshal(supportedJobTypes)
|
||||
if err != nil {
|
||||
fatalIf(probe.NewError(err), "Unable to marshal supported job types")
|
||||
}
|
||||
fmt.Println(string(j))
|
||||
} else {
|
||||
for _, jobType := range supportedJobTypes {
|
||||
fmt.Println(jobType)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Try GenerateV2 API.
|
||||
template, apiUnavailable, e := adminClient.GenerateBatchJobV2(globalContext, madmin.GenerateBatchJobOpts{
|
||||
Type: madmin.BatchJobType(jobType),
|
||||
})
|
||||
if e != nil {
|
||||
fatalIf(probe.NewError(e), "Unable to generate template for %s", args.Get(1))
|
||||
}
|
||||
|
||||
// Check if server supports GenerateV2 API.
|
||||
if !apiUnavailable {
|
||||
fmt.Println(template)
|
||||
return nil
|
||||
}
|
||||
|
||||
// As API is not supported we fallback to returning the static job template.
|
||||
var found bool
|
||||
for _, job := range madmin.SupportedJobTypes {
|
||||
if jobType == string(job) {
|
||||
|
||||
+61
-3
@@ -66,6 +66,7 @@ EXAMPLES:
|
||||
type batchListMessage struct {
|
||||
Status string `json:"status"`
|
||||
Jobs []madmin.BatchJobResult `json:"jobs"`
|
||||
Admin *madmin.AdminClient `json:"-"` // Add AdminClient to fetch job status
|
||||
}
|
||||
|
||||
// String colorized batchList message
|
||||
@@ -90,15 +91,35 @@ func (c batchListMessage) String() string {
|
||||
table.SetTablePadding("\t") // pad with tabs
|
||||
table.SetNoWhiteSpace(true)
|
||||
|
||||
table.SetHeader([]string{"ID", "TYPE", "USER", "STARTED"})
|
||||
data := make([][]string, 0, 4)
|
||||
// Add a new "STATUS" column to the table header
|
||||
table.SetHeader([]string{"ID", "TYPE", "USER", "STARTED", "STATUS"})
|
||||
data := make([][]string, 0, 5)
|
||||
|
||||
// Fetch the status for the batch job using BatchJobStatus API
|
||||
for _, job := range c.Jobs {
|
||||
jobStatus := "unknown"
|
||||
jobMetric, err := c.Admin.BatchJobStatus(context.Background(), job.ID)
|
||||
|
||||
// Output error if the API call fails, but continue processing remaining jobs
|
||||
if err != nil {
|
||||
println("Failed to fetch job status for Job ID:", job.ID, "Error:", err.Error())
|
||||
} else {
|
||||
if jobMetric.LastMetric.Complete && !jobMetric.LastMetric.Failed {
|
||||
jobStatus = "completed"
|
||||
} else if !jobMetric.LastMetric.Complete && !jobMetric.LastMetric.Failed {
|
||||
jobStatus = "in-progress"
|
||||
} else if jobMetric.LastMetric.Failed {
|
||||
jobStatus = "failed"
|
||||
}
|
||||
}
|
||||
|
||||
// Add jobStatus details to the data table
|
||||
data = append(data, []string{
|
||||
job.ID,
|
||||
string(job.Type),
|
||||
job.User,
|
||||
humanize.Time(job.Started),
|
||||
jobStatus,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -111,7 +132,43 @@ func (c batchListMessage) String() string {
|
||||
// JSON jsonified batchList message
|
||||
func (c batchListMessage) JSON() string {
|
||||
c.Status = "success"
|
||||
batchListMessageBytes, e := json.MarshalIndent(c, "", " ")
|
||||
|
||||
// Create a temporary slice to hold jobs with derived statuses
|
||||
jobsWithStatus := make([]map[string]interface{}, len(c.Jobs))
|
||||
|
||||
// Fetch the status for the batch job using BatchJobStatus API
|
||||
for i, job := range c.Jobs {
|
||||
jobStatus := "unknown"
|
||||
jobMetric, err := c.Admin.BatchJobStatus(context.Background(), job.ID)
|
||||
|
||||
// Output error if the API call fails, but continue processing remaining jobs
|
||||
if err != nil {
|
||||
println("Failed to fetch job status for Job ID:", job.ID, "Error:", err.Error())
|
||||
} else {
|
||||
if jobMetric.LastMetric.Complete && !jobMetric.LastMetric.Failed {
|
||||
jobStatus = "completed"
|
||||
} else if !jobMetric.LastMetric.Complete && !jobMetric.LastMetric.Failed {
|
||||
jobStatus = "in-progress"
|
||||
} else if jobMetric.LastMetric.Failed {
|
||||
jobStatus = "failed"
|
||||
}
|
||||
}
|
||||
|
||||
// Add the job details along with the derived status
|
||||
jobsWithStatus[i] = map[string]interface{}{
|
||||
"id": job.ID,
|
||||
"type": job.Type,
|
||||
"user": job.User,
|
||||
"started": job.Started,
|
||||
"status": jobStatus,
|
||||
}
|
||||
}
|
||||
|
||||
// Marshal the updated jobs into JSON
|
||||
batchListMessageBytes, e := json.MarshalIndent(map[string]interface{}{
|
||||
"status": c.Status,
|
||||
"jobs": jobsWithStatus,
|
||||
}, "", " ")
|
||||
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
|
||||
|
||||
return string(batchListMessageBytes)
|
||||
@@ -147,6 +204,7 @@ func mainBatchList(ctx *cli.Context) error {
|
||||
printMsg(batchListMessage{
|
||||
Status: "success",
|
||||
Jobs: res.Jobs,
|
||||
Admin: adminClient, // Pass the adminClient for status lookups
|
||||
})
|
||||
return nil
|
||||
}
|
||||
|
||||
+120
-63
@@ -12,6 +12,7 @@ import (
|
||||
"github.com/charmbracelet/lipgloss"
|
||||
"github.com/dustin/go-humanize"
|
||||
"github.com/minio/cli"
|
||||
json "github.com/minio/colorjson"
|
||||
"github.com/minio/madmin-go/v3"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/pkg/v3/console"
|
||||
@@ -41,6 +42,24 @@ EXAMPLES:
|
||||
`,
|
||||
}
|
||||
|
||||
// batchJobStatusMessage container for batch job status messages
|
||||
type batchJobStatusMessage struct {
|
||||
Status string `json:"status"`
|
||||
Metric madmin.JobMetric `json:"metric"`
|
||||
}
|
||||
|
||||
// JSON jsonified batchJobStatusMessage message
|
||||
func (c batchJobStatusMessage) JSON() string {
|
||||
batchJobStatusMessageBytes, e := json.MarshalIndent(c, "", " ")
|
||||
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
|
||||
|
||||
return string(batchJobStatusMessageBytes)
|
||||
}
|
||||
|
||||
func (c batchJobStatusMessage) String() string {
|
||||
return c.JSON()
|
||||
}
|
||||
|
||||
// checkBatchStatusSyntax - validate all the passed arguments
|
||||
func checkBatchStatusSyntax(ctx *cli.Context) {
|
||||
if len(ctx.Args()) != 2 {
|
||||
@@ -72,38 +91,69 @@ func mainBatchStatus(ctx *cli.Context) error {
|
||||
fatalIf(probe.NewError(e), "Unable to lookup job status")
|
||||
|
||||
ui := tea.NewProgram(initBatchJobMetricsUI(jobID))
|
||||
go func() {
|
||||
opts := madmin.MetricsOptions{
|
||||
Type: madmin.MetricsBatchJobs,
|
||||
ByJobID: jobID,
|
||||
Interval: time.Second,
|
||||
}
|
||||
e := client.Metrics(ctxt, opts, func(metrics madmin.RealtimeMetrics) {
|
||||
if nosuchJob {
|
||||
go func() {
|
||||
res, e := client.BatchJobStatus(ctxt, jobID)
|
||||
fatalIf(probe.NewError(e), "Unable to lookup job status")
|
||||
if globalJSON {
|
||||
if metrics.Aggregated.BatchJobs == nil {
|
||||
cancel()
|
||||
return
|
||||
}
|
||||
|
||||
job, ok := metrics.Aggregated.BatchJobs.Jobs[jobID]
|
||||
if !ok {
|
||||
cancel()
|
||||
return
|
||||
}
|
||||
|
||||
printMsg(metricsMessage{RealtimeMetrics: metrics})
|
||||
if job.Complete || job.Failed {
|
||||
printMsg(batchJobStatusMessage{
|
||||
Status: "success",
|
||||
Metric: res.LastMetric,
|
||||
})
|
||||
if res.LastMetric.Complete || res.LastMetric.Failed {
|
||||
cancel()
|
||||
return
|
||||
}
|
||||
} else {
|
||||
ui.Send(metrics)
|
||||
ui.Send(res.LastMetric)
|
||||
}
|
||||
})
|
||||
if e != nil && !errors.Is(e, context.Canceled) {
|
||||
fatalIf(probe.NewError(e).Trace(ctx.Args()...), "Unable to get current batch status")
|
||||
}
|
||||
}()
|
||||
}()
|
||||
} else {
|
||||
go func() {
|
||||
opts := madmin.MetricsOptions{
|
||||
Type: madmin.MetricsBatchJobs,
|
||||
ByJobID: jobID,
|
||||
Interval: time.Second,
|
||||
}
|
||||
e := client.Metrics(ctxt, opts, func(metrics madmin.RealtimeMetrics) {
|
||||
if globalJSON {
|
||||
if metrics.Aggregated.BatchJobs == nil {
|
||||
cancel()
|
||||
return
|
||||
}
|
||||
|
||||
job, ok := metrics.Aggregated.BatchJobs.Jobs[jobID]
|
||||
if !ok {
|
||||
cancel()
|
||||
return
|
||||
}
|
||||
|
||||
m := batchJobStatusMessage{
|
||||
Status: "in-progress",
|
||||
Metric: job,
|
||||
}
|
||||
switch {
|
||||
case job.Complete:
|
||||
m.Status = "complete"
|
||||
case job.Failed:
|
||||
m.Status = "failed"
|
||||
default:
|
||||
// leave as is with in-progress
|
||||
}
|
||||
printMsg(m)
|
||||
if job.Complete || job.Failed {
|
||||
cancel()
|
||||
return
|
||||
}
|
||||
} else {
|
||||
ui.Send(metrics.Aggregated.BatchJobs.Jobs[jobID])
|
||||
}
|
||||
})
|
||||
if e != nil && !errors.Is(e, context.Canceled) {
|
||||
fatalIf(probe.NewError(e).Trace(ctx.Args()...), "Unable to get current batch status")
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
if !globalJSON {
|
||||
if _, e := ui.Run(); e != nil {
|
||||
@@ -128,7 +178,7 @@ func initBatchJobMetricsUI(jobID string) *batchJobMetricsUI {
|
||||
}
|
||||
|
||||
type batchJobMetricsUI struct {
|
||||
current madmin.JobMetric
|
||||
metric madmin.JobMetric
|
||||
spinner spinner.Model
|
||||
quitting bool
|
||||
jobID string
|
||||
@@ -148,21 +198,9 @@ func (m *batchJobMetricsUI) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
||||
default:
|
||||
return m, nil
|
||||
}
|
||||
case madmin.RealtimeMetrics:
|
||||
metrics := msg
|
||||
if metrics.Aggregated.BatchJobs == nil {
|
||||
m.quitting = true
|
||||
return m, tea.Quit
|
||||
}
|
||||
|
||||
job, ok := metrics.Aggregated.BatchJobs.Jobs[m.jobID]
|
||||
if !ok {
|
||||
m.quitting = true
|
||||
return m, tea.Quit
|
||||
}
|
||||
|
||||
m.current = job
|
||||
if job.Complete || job.Failed {
|
||||
case madmin.JobMetric:
|
||||
m.metric = msg
|
||||
if msg.Complete || msg.Failed {
|
||||
m.quitting = true
|
||||
return m, tea.Quit
|
||||
}
|
||||
@@ -194,7 +232,7 @@ func (m *batchJobMetricsUI) View() string {
|
||||
table.SetNoWhiteSpace(true)
|
||||
|
||||
var data [][]string
|
||||
addLine := func(prefix string, value interface{}) {
|
||||
addLine := func(prefix string, value any) {
|
||||
data = append(data, []string{
|
||||
prefix,
|
||||
whiteStyle.Render(fmt.Sprint(value)),
|
||||
@@ -204,42 +242,61 @@ func (m *batchJobMetricsUI) View() string {
|
||||
if !m.quitting {
|
||||
s.WriteString(m.spinner.View())
|
||||
} else {
|
||||
if m.current.Complete {
|
||||
if m.metric.Complete {
|
||||
s.WriteString(m.spinner.Style.Render((tickCell + tickCell + tickCell)))
|
||||
} else if m.current.Failed {
|
||||
} else if m.metric.Failed {
|
||||
s.WriteString(m.spinner.Style.Render((crossTickCell + crossTickCell + crossTickCell)))
|
||||
}
|
||||
}
|
||||
s.WriteString("\n")
|
||||
|
||||
switch m.current.JobType {
|
||||
switch m.metric.JobType {
|
||||
case string(madmin.BatchJobReplicate):
|
||||
accElapsedTime := m.current.LastUpdate.Sub(m.current.StartTime)
|
||||
accElapsedTime := m.metric.LastUpdate.Sub(m.metric.StartTime)
|
||||
|
||||
addLine("JobType: ", m.current.JobType)
|
||||
addLine("Objects: ", m.current.Replicate.Objects)
|
||||
addLine("Versions: ", m.current.Replicate.Objects)
|
||||
addLine("FailedObjects: ", m.current.Replicate.ObjectsFailed)
|
||||
addLine("JobType: ", m.metric.JobType)
|
||||
addLine("Objects: ", m.metric.Replicate.Objects)
|
||||
addLine("Versions: ", m.metric.Replicate.Objects)
|
||||
addLine("FailedObjects: ", m.metric.Replicate.ObjectsFailed)
|
||||
addLine("DeleteMarker: ", m.metric.Replicate.DeleteMarkers)
|
||||
addLine("FailedDeleteMarker: ", m.metric.Replicate.DeleteMarkersFailed)
|
||||
if accElapsedTime > 0 {
|
||||
bytesTransferredPerSec := float64(m.current.Replicate.BytesTransferred) / accElapsedTime.Seconds()
|
||||
objectsPerSec := float64(int64(time.Second)*m.current.Replicate.Objects) / float64(accElapsedTime)
|
||||
bytesTransferredPerSec := float64(m.metric.Replicate.BytesTransferred) / accElapsedTime.Seconds()
|
||||
objectsPerSec := float64(int64(time.Second)*m.metric.Replicate.Objects) / float64(accElapsedTime)
|
||||
addLine("Throughput: ", fmt.Sprintf("%s/s", humanize.IBytes(uint64(bytesTransferredPerSec))))
|
||||
addLine("IOPs: ", fmt.Sprintf("%.2f objs/s", objectsPerSec))
|
||||
}
|
||||
addLine("Transferred: ", humanize.IBytes(uint64(m.current.Replicate.BytesTransferred)))
|
||||
addLine("Elapsed: ", accElapsedTime.String())
|
||||
addLine("CurrObjName: ", m.current.Replicate.Object)
|
||||
addLine("Transferred: ", humanize.IBytes(uint64(m.metric.Replicate.BytesTransferred)))
|
||||
addLine("Elapsed: ", accElapsedTime.Round(time.Second).String())
|
||||
addLine("CurrObjName: ", m.metric.Replicate.Object)
|
||||
case string(madmin.BatchJobExpire):
|
||||
addLine("JobType: ", m.current.JobType)
|
||||
addLine("Objects: ", m.current.Expired.Objects)
|
||||
addLine("FailedObjects: ", m.current.Expired.ObjectsFailed)
|
||||
addLine("CurrObjName: ", m.current.Expired.Object)
|
||||
addLine("JobType: ", m.metric.JobType)
|
||||
addLine("Objects: ", m.metric.Expired.Objects)
|
||||
addLine("FailedObjects: ", m.metric.Expired.ObjectsFailed)
|
||||
addLine("DeleteMarker: ", m.metric.Expired.DeleteMarkers)
|
||||
addLine("FailedDeleteMarker: ", m.metric.Expired.DeleteMarkersFailed)
|
||||
addLine("CurrObjName: ", m.metric.Expired.Object)
|
||||
|
||||
if !m.current.LastUpdate.IsZero() {
|
||||
accElapsedTime := m.current.LastUpdate.Sub(m.current.StartTime)
|
||||
if !m.metric.LastUpdate.IsZero() {
|
||||
accElapsedTime := m.metric.LastUpdate.Sub(m.metric.StartTime)
|
||||
addLine("Elapsed: ", accElapsedTime.String())
|
||||
}
|
||||
|
||||
case string(madmin.BatchJobCatalog):
|
||||
addLine("JobType: ", m.metric.JobType)
|
||||
addLine("ObjectsScannedCount: ", m.metric.Catalog.ObjectsScannedCount)
|
||||
addLine("ObjectsMatchedCount: ", m.metric.Catalog.ObjectsMatchedCount)
|
||||
lastScanned := fmt.Sprintf("%s/%s", m.metric.Catalog.LastBucketScanned, m.metric.Catalog.LastObjectScanned)
|
||||
addLine("LastScanned: ", lastScanned)
|
||||
lastMatched := fmt.Sprintf("%s/%s", m.metric.Catalog.LastBucketMatched, m.metric.Catalog.LastObjectMatched)
|
||||
addLine("LastMatched: ", lastMatched)
|
||||
accElapsedTime := m.metric.LastUpdate.Sub(m.metric.StartTime)
|
||||
addLine("RecordsWrittenCount: ", m.metric.Catalog.RecordsWrittenCount)
|
||||
addLine("OutputObjectsCount: ", m.metric.Catalog.OutputObjectsCount)
|
||||
addLine("Elapsed: ", accElapsedTime.Round(time.Second).String())
|
||||
addLine("Scan Speed: ", fmt.Sprintf("%f objects/s", float64(m.metric.Catalog.ObjectsScannedCount)/accElapsedTime.Seconds()))
|
||||
if m.metric.Catalog.ErrorMsg != "" {
|
||||
addLine("Error: ", m.metric.Catalog.ErrorMsg)
|
||||
}
|
||||
}
|
||||
|
||||
table.AppendBulk(data)
|
||||
|
||||
+15
-6
@@ -55,6 +55,10 @@ var catFlags = []cli.Flag{
|
||||
Name: "tail",
|
||||
Usage: "tail number of bytes at ending of file",
|
||||
},
|
||||
cli.IntFlag{
|
||||
Name: "part-number",
|
||||
Usage: "download only a specific part number",
|
||||
},
|
||||
}
|
||||
|
||||
// Display contents of a file.
|
||||
@@ -162,6 +166,7 @@ type catOpts struct {
|
||||
timeRef time.Time
|
||||
startO int64
|
||||
tailO int64
|
||||
partN int
|
||||
isZip bool
|
||||
stdinMode bool
|
||||
}
|
||||
@@ -197,6 +202,7 @@ func parseCatSyntax(ctx *cli.Context) catOpts {
|
||||
o.isZip = ctx.Bool("zip")
|
||||
o.startO = ctx.Int64("offset")
|
||||
o.tailO = ctx.Int64("tail")
|
||||
o.partN = ctx.Int("part-number")
|
||||
if o.tailO != 0 && o.startO != 0 {
|
||||
fatalIf(errInvalidArgument().Trace(), "You cannot specify both --tail and --offset")
|
||||
}
|
||||
@@ -209,6 +215,9 @@ func parseCatSyntax(ctx *cli.Context) catOpts {
|
||||
if o.stdinMode && (o.isZip || o.startO != 0 || o.tailO != 0) {
|
||||
fatalIf(errInvalidArgument().Trace(), "You cannot use --zip --tail or --offset with stdin")
|
||||
}
|
||||
if (o.tailO != 0 || o.startO != 0) && o.partN > 0 {
|
||||
fatalIf(errInvalidArgument().Trace(), "You cannot use --part-number with --tail or --offset")
|
||||
}
|
||||
|
||||
return o
|
||||
}
|
||||
@@ -242,13 +251,10 @@ func catURL(ctx context.Context, sourceURL string, encKeyDB map[string][]prefixS
|
||||
versionID = content.VersionID
|
||||
}
|
||||
if o.tailO > 0 && content.Size > 0 {
|
||||
o.startO = content.Size - o.tailO
|
||||
if o.startO < 0 {
|
||||
o.startO = max(content.Size-o.tailO,
|
||||
// Return all.
|
||||
o.startO = 0
|
||||
}
|
||||
0)
|
||||
}
|
||||
|
||||
if client.GetURL().Type == objectStorage {
|
||||
size = content.Size - o.startO
|
||||
if size < 0 {
|
||||
@@ -256,10 +262,13 @@ func catURL(ctx context.Context, sourceURL string, encKeyDB map[string][]prefixS
|
||||
return err.Trace(sourceURL)
|
||||
}
|
||||
}
|
||||
if o.partN != 0 {
|
||||
size = int64(-1)
|
||||
}
|
||||
} else {
|
||||
return err.Trace(sourceURL)
|
||||
}
|
||||
gopts := GetOptions{VersionID: versionID, Zip: o.isZip, RangeStart: o.startO}
|
||||
gopts := GetOptions{VersionID: versionID, Zip: o.isZip, RangeStart: o.startO, PartNumber: o.partN}
|
||||
if reader, err = getSourceStreamFromURL(ctx, sourceURL, encKeyDB, getSourceOpts{
|
||||
GetOptions: gopts,
|
||||
preserve: false,
|
||||
|
||||
+10
-24
@@ -20,7 +20,6 @@ package cmd
|
||||
import (
|
||||
"crypto/tls"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"sync"
|
||||
@@ -58,9 +57,9 @@ func NewAdminFactory() func(config *Config) (*madmin.AdminClient, *probe.Error)
|
||||
var found bool
|
||||
if api, found = clientCache[confSum]; !found {
|
||||
|
||||
transport := getTransportForConfig(config, true)
|
||||
transport := config.getTransport()
|
||||
|
||||
credsChain, err := getCredentialsChainForConfig(config, transport)
|
||||
credsChain, err := config.getCredsChain()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -138,10 +137,7 @@ func newAnonymousClient(aliasedURL string) (*madmin.AnonymousClient, *probe.Erro
|
||||
}
|
||||
|
||||
// By default enable HTTPs.
|
||||
useTLS := true
|
||||
if targetURL.Scheme == "http" {
|
||||
useTLS = false
|
||||
}
|
||||
useTLS := targetURL.Scheme != "http"
|
||||
|
||||
// Construct an anonymous client
|
||||
anonClient, e := madmin.NewAnonymousClient(targetURL.Host, useTLS)
|
||||
@@ -149,29 +145,19 @@ func newAnonymousClient(aliasedURL string) (*madmin.AnonymousClient, *probe.Erro
|
||||
return nil, probe.NewError(e)
|
||||
}
|
||||
|
||||
// Keep TLS config.
|
||||
tlsConfig := &tls.Config{
|
||||
RootCAs: globalRootCAs,
|
||||
// Can't use SSLv3 because of POODLE and BEAST
|
||||
// Can't use TLSv1.0 because of POODLE and BEAST using CBC cipher
|
||||
// Can't use TLSv1.1 because of RC4 cipher usage
|
||||
MinVersion: tls.VersionTLS12,
|
||||
}
|
||||
if globalInsecure {
|
||||
tlsConfig.InsecureSkipVerify = true
|
||||
}
|
||||
// Set custom transport
|
||||
var transport http.RoundTripper = &http.Transport{
|
||||
Proxy: ieproxy.GetProxyFunc(),
|
||||
DialContext: (&net.Dialer{
|
||||
Timeout: 10 * time.Second,
|
||||
KeepAlive: 15 * time.Second,
|
||||
}).DialContext,
|
||||
Proxy: ieproxy.GetProxyFunc(),
|
||||
DialContext: newCustomDialContext(&Config{}),
|
||||
DialTLSContext: newCustomDialTLSContext(&tls.Config{
|
||||
RootCAs: globalRootCAs,
|
||||
MinVersion: tls.VersionTLS12,
|
||||
InsecureSkipVerify: globalInsecure,
|
||||
}),
|
||||
MaxIdleConnsPerHost: 256,
|
||||
IdleConnTimeout: 90 * time.Second,
|
||||
TLSHandshakeTimeout: 10 * time.Second,
|
||||
ExpectContinueTimeout: 10 * time.Second,
|
||||
TLSClientConfig: tlsConfig,
|
||||
// Set this value so that the underlying transport round-tripper
|
||||
// doesn't try to auto decode the body of objects with
|
||||
// content-encoding set to `gzip`.
|
||||
|
||||
@@ -35,8 +35,8 @@ func (h adminPolicyHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
switch {
|
||||
case r.Method == "PUT":
|
||||
switch r.Method {
|
||||
case "PUT":
|
||||
length, e := strconv.Atoi(r.Header.Get("Content-Length"))
|
||||
if e != nil {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
|
||||
+85
-10
@@ -22,6 +22,7 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"maps"
|
||||
"os"
|
||||
"path"
|
||||
"path/filepath"
|
||||
@@ -32,6 +33,8 @@ import (
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"github.com/pkg/xattr"
|
||||
"github.com/rjeczalik/notify"
|
||||
|
||||
@@ -40,6 +43,7 @@ import (
|
||||
"github.com/minio/mc/pkg/hookreader"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/minio-go/v7"
|
||||
"github.com/minio/minio-go/v7/pkg/cors"
|
||||
"github.com/minio/minio-go/v7/pkg/encrypt"
|
||||
"github.com/minio/minio-go/v7/pkg/lifecycle"
|
||||
"github.com/minio/minio-go/v7/pkg/notification"
|
||||
@@ -300,8 +304,12 @@ func (f *fsClient) put(_ context.Context, reader io.Reader, size int64, progress
|
||||
|
||||
objectPath := f.PathURL.Path
|
||||
|
||||
// Write to a temporary file "object.part.minio" before commit.
|
||||
objectPartPath := objectPath + partSuffix
|
||||
if err := checkPathLength(objectPath); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
// Write to a temporary file "objectpath/uuid" before commit.
|
||||
objectPartPath := filepath.Join(filepath.Dir(objectPath), uuid.NewString())
|
||||
|
||||
// We cannot resume this operation, then we
|
||||
// should remove any partial download if any.
|
||||
@@ -392,6 +400,49 @@ func (f *fsClient) Put(ctx context.Context, reader io.Reader, size int64, progre
|
||||
return f.put(ctx, reader, size, progress, opts)
|
||||
}
|
||||
|
||||
// checkPathLength - returns error if given path name length more than 255
|
||||
func checkPathLength(pathName string) *probe.Error {
|
||||
// Apple OS X path length is limited to 1016
|
||||
if runtime.GOOS == "darwin" && len(pathName) > 1016 {
|
||||
return probe.NewError(errors.New("file name too long"))
|
||||
}
|
||||
|
||||
// Disallow more than 32,767 characters on windows, there
|
||||
// are no known name_max limits on Windows.
|
||||
// Refer: https://learn.microsoft.com/en-us/windows/win32/fileio/maximum-file-path-limitation?tabs=registry
|
||||
if runtime.GOOS == "windows" && len(pathName) > 32767 {
|
||||
return probe.NewError(errors.New("file name too long"))
|
||||
}
|
||||
|
||||
// On Unix we reject paths if they are just '.', '..' or '/'
|
||||
if pathName == "." || pathName == ".." || pathName == "/" {
|
||||
return probe.NewError(errors.New("file access denied"))
|
||||
}
|
||||
|
||||
// Check each path segment length is > 255 on all Unix
|
||||
// platforms, look for this value as NAME_MAX in
|
||||
// /usr/include/linux/limits.h
|
||||
var count int64
|
||||
for _, p := range pathName {
|
||||
switch p {
|
||||
case '/':
|
||||
count = 0 // Reset
|
||||
case '\\':
|
||||
if runtime.GOOS == "windows" {
|
||||
count = 0
|
||||
} else {
|
||||
count++
|
||||
}
|
||||
default:
|
||||
count++
|
||||
}
|
||||
if count > 255 {
|
||||
return probe.NewError(errors.New("file name too long"))
|
||||
}
|
||||
} // Success.
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *fsClient) putN(_ context.Context, reader io.Reader, size int64, progress io.Reader, opts PutOptions) (int64, *probe.Error) {
|
||||
// ContentType is not handled on purpose.
|
||||
// For filesystem this is a redundant information.
|
||||
@@ -414,8 +465,12 @@ func (f *fsClient) putN(_ context.Context, reader io.Reader, size int64, progres
|
||||
|
||||
objectPath := f.PathURL.Path
|
||||
|
||||
// Write to a temporary file "object.part.minio" before commit.
|
||||
objectPartPath := objectPath + partSuffix
|
||||
if err := checkPathLength(objectPath); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
// Write to a temporary file ""objectpath/uuid"" before commit.
|
||||
objectPartPath := filepath.Join(filepath.Dir(objectPath), uuid.NewString())
|
||||
|
||||
// We cannot resume this operation, then we
|
||||
// should remove any partial download if any.
|
||||
@@ -580,9 +635,7 @@ func (f *fsClient) Get(_ context.Context, opts GetOptions) (io.ReadCloser, *Clie
|
||||
if pErr != nil {
|
||||
return nil, content, nil
|
||||
}
|
||||
for k, v := range metaData {
|
||||
content.Metadata[k] = v
|
||||
}
|
||||
maps.Copy(content.Metadata, metaData)
|
||||
content.Metadata[metadataKey] = fileAttr
|
||||
}
|
||||
|
||||
@@ -1307,9 +1360,7 @@ func (f *fsClient) Stat(_ context.Context, opts StatOptions) (content *ClientCon
|
||||
if pErr != nil {
|
||||
return content, nil
|
||||
}
|
||||
for k, v := range metaData {
|
||||
content.Metadata[k] = v
|
||||
}
|
||||
maps.Copy(content.Metadata, metaData)
|
||||
content.Metadata[metadataKey] = fileAttr
|
||||
}
|
||||
|
||||
@@ -1507,3 +1558,27 @@ func (f *fsClient) GetPart(_ context.Context, _ int) (io.ReadCloser, *probe.Erro
|
||||
APIType: "filesystem",
|
||||
})
|
||||
}
|
||||
|
||||
// GetBucketCors - not implemented
|
||||
func (f *fsClient) GetBucketCors(_ context.Context) (*cors.Config, *probe.Error) {
|
||||
return nil, probe.NewError(APINotImplemented{
|
||||
API: "GetBucketCors",
|
||||
APIType: "filesystem",
|
||||
})
|
||||
}
|
||||
|
||||
// SetBucketCors - not implemented
|
||||
func (f *fsClient) SetBucketCors(_ context.Context, _ []byte) *probe.Error {
|
||||
return probe.NewError(APINotImplemented{
|
||||
API: "SetBucketCors",
|
||||
APIType: "filesystem",
|
||||
})
|
||||
}
|
||||
|
||||
// DeleteBucketCors - not implemented
|
||||
func (f *fsClient) DeleteBucketCors(_ context.Context) *probe.Error {
|
||||
return probe.NewError(APINotImplemented{
|
||||
API: "DeleteBucketCors",
|
||||
APIType: "filesystem",
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
//go:build darwin
|
||||
// +build darwin
|
||||
|
||||
// Copyright (c) 2015-2021 MinIO, Inc.
|
||||
//
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
//go:build linux
|
||||
// +build linux
|
||||
|
||||
// Copyright (c) 2015-2021 MinIO, Inc.
|
||||
//
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
//go:build solaris || openbsd
|
||||
// +build solaris openbsd
|
||||
|
||||
// Copyright (c) 2015-2021 MinIO, Inc.
|
||||
//
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
//go:build windows
|
||||
// +build windows
|
||||
|
||||
// Copyright (c) 2015-2021 MinIO, Inc.
|
||||
//
|
||||
@@ -56,6 +55,6 @@ func IsDeleteEvent(event notify.Event) bool {
|
||||
|
||||
// getAllXattrs returns the extended attributes for a file if supported
|
||||
// by the OS
|
||||
func getAllXattrs(path string) (map[string]string, error) {
|
||||
func getAllXattrs(_ string) (map[string]string, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
@@ -38,6 +38,7 @@ func newTraceV4() httptracer.HTTPTracer {
|
||||
// Request - Trace HTTP Request
|
||||
func (t traceV4) Request(req *http.Request) (err error) {
|
||||
origAuth := req.Header.Get("Authorization")
|
||||
sseKey := req.Header.Get("X-Amz-Server-Side-Encryption-Customer-Key")
|
||||
|
||||
printTrace := func() error {
|
||||
reqTrace, rerr := httputil.DumpRequestOut(req, false) // Only display header
|
||||
@@ -47,6 +48,11 @@ func (t traceV4) Request(req *http.Request) (err error) {
|
||||
return rerr
|
||||
}
|
||||
|
||||
if strings.TrimSpace(sseKey) != "" {
|
||||
// Stripe out SSE-C key from: X-Amz-Server-Side-Encryption-Customer-Key=<key>
|
||||
req.Header.Set("X-Amz-Server-Side-Encryption-Customer-Key", "**REDACTED**")
|
||||
}
|
||||
|
||||
if strings.TrimSpace(origAuth) != "" {
|
||||
// Authorization (S3 v4 signature) Format:
|
||||
// Authorization: AWS4-HMAC-SHA256 Credential=AKIAJNACEGBGMXBHLEZA/20150524/us-east-1/s3/aws4_request, SignedHeaders=host;x-amz-content-sha256;x-amz-date, Signature=bbfaa693c626021bcb5f911cd898a1a30206c1fad6bad1e0eb89e282173bd24c
|
||||
|
||||
+149
-127
@@ -26,7 +26,7 @@ import (
|
||||
"fmt"
|
||||
"hash/fnv"
|
||||
"io"
|
||||
"math/rand"
|
||||
"maps"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
@@ -37,9 +37,10 @@ import (
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/klauspost/compress/gzhttp"
|
||||
"github.com/minio/minio-go/v7/pkg/cors"
|
||||
"github.com/minio/pkg/v3/env"
|
||||
|
||||
"github.com/minio/minio-go/v7"
|
||||
@@ -55,8 +56,6 @@ import (
|
||||
"github.com/minio/pkg/v3/mimedb"
|
||||
|
||||
"github.com/minio/mc/pkg/deadlineconn"
|
||||
"github.com/minio/mc/pkg/httptracer"
|
||||
"github.com/minio/mc/pkg/limiter"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
)
|
||||
|
||||
@@ -106,6 +105,14 @@ func newCustomDialContext(c *Config) dialContext {
|
||||
KeepAlive: 15 * time.Second,
|
||||
}
|
||||
|
||||
if ip, ok := globalResolvers[addr]; ok {
|
||||
if _, port, err := net.SplitHostPort(addr); err == nil {
|
||||
addr = net.JoinHostPort(ip.String(), port)
|
||||
} else {
|
||||
addr = ip.String()
|
||||
}
|
||||
}
|
||||
|
||||
conn, err := dialer.DialContext(ctx, network, addr)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -119,6 +126,31 @@ func newCustomDialContext(c *Config) dialContext {
|
||||
}
|
||||
}
|
||||
|
||||
// newCustomDialTLSContext setups a custom TLS dialer for any external communication and proxies.
|
||||
func newCustomDialTLSContext(tlsConf *tls.Config) dialContext {
|
||||
return func(ctx context.Context, network, addr string) (net.Conn, error) {
|
||||
dialer := &tls.Dialer{
|
||||
NetDialer: &net.Dialer{
|
||||
Timeout: 10 * time.Second,
|
||||
KeepAlive: 15 * time.Second,
|
||||
},
|
||||
Config: tlsConf,
|
||||
}
|
||||
|
||||
if ip, ok := globalResolvers[addr]; ok {
|
||||
dialer.Config = dialer.Config.Clone()
|
||||
if host, port, err := net.SplitHostPort(addr); err == nil {
|
||||
dialer.Config.ServerName = host // Set SNI
|
||||
addr = net.JoinHostPort(ip.String(), port)
|
||||
} else {
|
||||
dialer.Config.ServerName = addr // Set SNI
|
||||
addr = ip.String()
|
||||
}
|
||||
}
|
||||
return dialer.DialContext(ctx, network, addr)
|
||||
}
|
||||
}
|
||||
|
||||
var timeSentinel = time.Unix(0, 0).UTC()
|
||||
|
||||
// getConfigHash returns the Hash for che *Config
|
||||
@@ -147,120 +179,35 @@ func isHostTLS(config *Config) bool {
|
||||
return useTLS
|
||||
}
|
||||
|
||||
// getTransportForConfig returns a corresponding *http.Transport for the *Config
|
||||
// set withS3v2 bool to true to add traceV2 tracer.
|
||||
func getTransportForConfig(config *Config, withS3v2 bool) http.RoundTripper {
|
||||
var transport http.RoundTripper
|
||||
|
||||
useTLS := isHostTLS(config)
|
||||
|
||||
if config.Transport != nil {
|
||||
transport = config.Transport
|
||||
} else {
|
||||
tr := &http.Transport{
|
||||
Proxy: http.ProxyFromEnvironment,
|
||||
DialContext: newCustomDialContext(config),
|
||||
MaxIdleConnsPerHost: 1024,
|
||||
WriteBufferSize: 32 << 10, // 32KiB moving up from 4KiB default
|
||||
ReadBufferSize: 32 << 10, // 32KiB moving up from 4KiB default
|
||||
IdleConnTimeout: 90 * time.Second,
|
||||
TLSHandshakeTimeout: 10 * time.Second,
|
||||
ExpectContinueTimeout: 10 * time.Second,
|
||||
// Set this value so that the underlying transport round-tripper
|
||||
// doesn't try to auto decode the body of objects with
|
||||
// content-encoding set to `gzip`.
|
||||
//
|
||||
// Refer:
|
||||
// https://golang.org/src/net/http/transport.go?h=roundTrip#L1843
|
||||
DisableCompression: true,
|
||||
}
|
||||
if useTLS {
|
||||
// Keep TLS config.
|
||||
tlsConfig := &tls.Config{
|
||||
RootCAs: globalRootCAs,
|
||||
// Can't use SSLv3 because of POODLE and BEAST
|
||||
// Can't use TLSv1.0 because of POODLE and BEAST using CBC cipher
|
||||
// Can't use TLSv1.1 because of RC4 cipher usage
|
||||
MinVersion: tls.VersionTLS12,
|
||||
}
|
||||
if config.Insecure {
|
||||
tlsConfig.InsecureSkipVerify = true
|
||||
}
|
||||
tr.TLSClientConfig = tlsConfig
|
||||
|
||||
// Because we create a custom TLSClientConfig, we have to opt-in to HTTP/2.
|
||||
// See https://github.com/golang/go/issues/14275
|
||||
//
|
||||
// TODO: Enable http2.0 when upstream issues related to HTTP/2 are fixed.
|
||||
//
|
||||
// if e = http2.ConfigureTransport(tr); e != nil {
|
||||
// return nil, probe.NewError(e)
|
||||
// }
|
||||
}
|
||||
transport = tr
|
||||
}
|
||||
|
||||
transport = limiter.New(config.UploadLimit, config.DownloadLimit, transport)
|
||||
|
||||
if config.Debug {
|
||||
if strings.EqualFold(config.Signature, "S3v4") {
|
||||
transport = httptracer.GetNewTraceTransport(newTraceV4(), transport)
|
||||
} else if strings.EqualFold(config.Signature, "S3v2") && withS3v2 {
|
||||
transport = httptracer.GetNewTraceTransport(newTraceV2(), transport)
|
||||
}
|
||||
}
|
||||
transport = gzhttp.Transport(transport)
|
||||
return transport
|
||||
type notifyExpiringTLS struct {
|
||||
transport http.RoundTripper
|
||||
}
|
||||
|
||||
// getCredentialsChainForConfig returns an []credentials.Provider array for the config
|
||||
// and the STS configuration (if present)
|
||||
func getCredentialsChainForConfig(config *Config, transport http.RoundTripper) ([]credentials.Provider, *probe.Error) {
|
||||
var credsChain []credentials.Provider
|
||||
// if an STS endpoint is set, we will add that to the chain
|
||||
if stsEndpoint := env.Get("MC_STS_ENDPOINT_"+config.Alias, ""); stsEndpoint != "" {
|
||||
// set AWS_WEB_IDENTITY_TOKEN_FILE is MC_WEB_IDENTITY_TOKEN_FILE is set
|
||||
if val := env.Get("MC_WEB_IDENTITY_TOKEN_FILE_"+config.Alias, ""); val != "" {
|
||||
os.Setenv("AWS_WEB_IDENTITY_TOKEN_FILE", val)
|
||||
if val := env.Get("MC_ROLE_ARN_"+config.Alias, ""); val != "" {
|
||||
os.Setenv("AWS_ROLE_ARN", val)
|
||||
}
|
||||
if val := env.Get("MC_ROLE_SESSION_NAME_"+config.Alias, randString(32, rand.NewSource(time.Now().UnixNano()), "mc-session-name-")); val != "" {
|
||||
os.Setenv("AWS_ROLE_SESSION_NAME", val)
|
||||
}
|
||||
}
|
||||
var globalExpiringCerts sync.Map
|
||||
|
||||
stsEndpointURL, err := url.Parse(stsEndpoint)
|
||||
if err != nil {
|
||||
return nil, probe.NewError(fmt.Errorf("Error parsing sts endpoint: %v", err))
|
||||
}
|
||||
credsSts := &credentials.IAM{
|
||||
Client: &http.Client{
|
||||
Transport: transport,
|
||||
},
|
||||
Endpoint: stsEndpointURL.String(),
|
||||
}
|
||||
credsChain = append(credsChain, credsSts)
|
||||
func (n notifyExpiringTLS) RoundTrip(req *http.Request) (res *http.Response, err error) {
|
||||
if n.transport == nil {
|
||||
return nil, errors.New("invalid transport")
|
||||
}
|
||||
|
||||
signType := credentials.SignatureV4
|
||||
if strings.EqualFold(config.Signature, "s3v2") {
|
||||
signType = credentials.SignatureV2
|
||||
res, err = n.transport.RoundTrip(req)
|
||||
if err != nil || res.TLS == nil || len(res.TLS.PeerCertificates) == 0 {
|
||||
return res, err
|
||||
}
|
||||
|
||||
// Credentials
|
||||
creds := &credentials.Static{
|
||||
Value: credentials.Value{
|
||||
AccessKeyID: config.AccessKey,
|
||||
SecretAccessKey: config.SecretKey,
|
||||
SessionToken: config.SessionToken,
|
||||
SignerType: signType,
|
||||
},
|
||||
cert := res.TLS.PeerCertificates[0] // leaf certificate
|
||||
validityDur := cert.NotAfter.Sub(cert.NotBefore)
|
||||
// Warn if less than 10% of time left and it is less than 28 days.
|
||||
if time.Until(cert.NotAfter) < time.Duration(min(0.1*float64(validityDur), 28*24*float64(time.Hour))) {
|
||||
globalExpiringCerts.Store(req.Host, cert.NotAfter)
|
||||
}
|
||||
credsChain = append(credsChain, creds)
|
||||
return credsChain, nil
|
||||
|
||||
return res, err
|
||||
}
|
||||
|
||||
// useTrailingHeaders will enable trailing headers on S3 clients.
|
||||
var useTrailingHeaders atomic.Bool
|
||||
|
||||
// newFactory encloses New function with client cache.
|
||||
func newFactory() func(config *Config) (Client, *probe.Error) {
|
||||
clientCache := make(map[uint32]*minio.Client)
|
||||
@@ -300,9 +247,9 @@ func newFactory() func(config *Config) (Client, *probe.Error) {
|
||||
var found bool
|
||||
if api, found = clientCache[confSum]; !found {
|
||||
|
||||
transport := getTransportForConfig(config, true)
|
||||
transport := config.getTransport()
|
||||
|
||||
credsChain, err := getCredentialsChainForConfig(config, transport)
|
||||
credsChain, err := config.getCredsChain()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -310,11 +257,12 @@ func newFactory() func(config *Config) (Client, *probe.Error) {
|
||||
var e error
|
||||
|
||||
options := minio.Options{
|
||||
Creds: credentials.NewChainCredentials(credsChain),
|
||||
Secure: useTLS,
|
||||
Region: env.Get("MC_REGION", env.Get("AWS_REGION", "")),
|
||||
BucketLookup: config.Lookup,
|
||||
Transport: transport,
|
||||
Creds: credentials.NewChainCredentials(credsChain),
|
||||
Secure: useTLS,
|
||||
Region: env.Get("MC_REGION", env.Get("AWS_REGION", "")),
|
||||
BucketLookup: config.Lookup,
|
||||
Transport: transport,
|
||||
TrailingHeaders: useTrailingHeaders.Load(),
|
||||
}
|
||||
|
||||
api, e = minio.New(hostName, &options)
|
||||
@@ -940,6 +888,7 @@ func (c *S3Client) Get(ctx context.Context, opts GetOptions) (io.ReadCloser, *Cl
|
||||
o := minio.GetObjectOptions{
|
||||
ServerSideEncryption: opts.SSE,
|
||||
VersionID: opts.VersionID,
|
||||
PartNumber: opts.PartNumber,
|
||||
}
|
||||
if opts.Zip {
|
||||
o.Set("x-minio-extract", "true")
|
||||
@@ -950,6 +899,9 @@ func (c *S3Client) Get(ctx context.Context, opts GetOptions) (io.ReadCloser, *Cl
|
||||
return nil, nil, probe.NewError(err)
|
||||
}
|
||||
}
|
||||
if opts.Preserve {
|
||||
o.Set("X-Amz-Tagging-Directive", "ACCESS")
|
||||
}
|
||||
// Disallow automatic decompression for some objects with content-encoding set.
|
||||
o.Set("Accept-Encoding", "identity")
|
||||
|
||||
@@ -985,9 +937,7 @@ func (c *S3Client) Copy(ctx context.Context, source string, opts CopyOptions, pr
|
||||
}
|
||||
|
||||
metadata := make(map[string]string, len(opts.metadata))
|
||||
for k, v := range opts.metadata {
|
||||
metadata[k] = v
|
||||
}
|
||||
maps.Copy(metadata, opts.metadata)
|
||||
|
||||
delete(metadata, "X-Amz-Storage-Class")
|
||||
if opts.storageClass != "" {
|
||||
@@ -1073,9 +1023,7 @@ func (c *S3Client) Put(ctx context.Context, reader io.Reader, size int64, progre
|
||||
}
|
||||
|
||||
metadata := make(map[string]string, len(putOpts.metadata))
|
||||
for k, v := range putOpts.metadata {
|
||||
metadata[k] = v
|
||||
}
|
||||
maps.Copy(metadata, putOpts.metadata)
|
||||
|
||||
// Do not copy storage class, it needs to be specified in putOpts
|
||||
delete(metadata, "X-Amz-Storage-Class")
|
||||
@@ -1135,6 +1083,8 @@ func (c *S3Client) Put(ctx context.Context, reader io.Reader, size int64, progre
|
||||
}
|
||||
}
|
||||
|
||||
disableSha256 := putOpts.checksum.IsSet() // pre-emptively disable sha256 payload, if checksum is set.
|
||||
|
||||
opts := minio.PutObjectOptions{
|
||||
UserMetadata: metadata,
|
||||
UserTags: tagsMap,
|
||||
@@ -1147,7 +1097,9 @@ func (c *S3Client) Put(ctx context.Context, reader io.Reader, size int64, progre
|
||||
StorageClass: strings.ToUpper(putOpts.storageClass),
|
||||
ServerSideEncryption: putOpts.sse,
|
||||
SendContentMd5: putOpts.md5,
|
||||
Checksum: putOpts.checksum,
|
||||
DisableMultipart: putOpts.disableMultipart,
|
||||
DisableContentSha256: disableSha256,
|
||||
PartSize: putOpts.multipartSize,
|
||||
NumThreads: putOpts.multipartThreads,
|
||||
ConcurrentStreamParts: putOpts.concurrentStream, // if enabled honors NumThreads for piped() uploads
|
||||
@@ -1680,7 +1632,10 @@ func (c *S3Client) Stat(ctx context.Context, opts StatOptions) (*ClientContent,
|
||||
}
|
||||
|
||||
if path == "" {
|
||||
content, err := c.bucketStat(ctx, BucketStatOptions{bucket: bucket, ignoreBucketExists: opts.ignoreBucketExists})
|
||||
content, err := c.bucketStat(ctx, BucketStatOptions{
|
||||
bucket: bucket,
|
||||
ignoreBucketExists: opts.ignoreBucketExists,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err.Trace(bucket)
|
||||
}
|
||||
@@ -1707,21 +1662,32 @@ func (c *S3Client) Stat(ctx context.Context, opts StatOptions) (*ClientContent,
|
||||
if opts.isZip {
|
||||
o.Set("x-minio-extract", "true")
|
||||
}
|
||||
|
||||
o.Set("x-amz-checksum-mode", "ENABLED")
|
||||
ctnt, err := c.getObjectStat(ctx, bucket, path, o)
|
||||
if err == nil {
|
||||
return ctnt, nil
|
||||
}
|
||||
|
||||
// Ignore object missing error but return for other errors
|
||||
if !errors.As(err.ToGoError(), &ObjectMissing{}) && !errors.As(err.ToGoError(), &ObjectIsDeleteMarker{}) {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// when versionID is specified we do not have to perform List() operation
|
||||
// when headOnly is specified we do not have to perform List() operation
|
||||
if (opts.versionID != "" || opts.headOnly) && errors.As(err.ToGoError(), &ObjectMissing{}) || errors.As(err.ToGoError(), &ObjectIsDeleteMarker{}) {
|
||||
return nil, probe.NewError(ObjectMissing{opts.timeRef})
|
||||
}
|
||||
|
||||
// The object is not found, look for a directory marker or a prefix
|
||||
path += string(c.targetURL.Separator)
|
||||
}
|
||||
|
||||
nonRecursive := false
|
||||
maxKeys := 1
|
||||
for objectStat := range c.listObjectWrapper(ctx, bucket, path, nonRecursive, opts.timeRef, opts.includeVersions, opts.includeVersions, false, maxKeys, opts.isZip) {
|
||||
for objectStat := range c.listObjectWrapper(ctx, bucket, path, nonRecursive, opts.timeRef,
|
||||
opts.includeVersions, opts.includeVersions, false, maxKeys, opts.isZip) {
|
||||
if objectStat.Err != nil {
|
||||
return nil, probe.NewError(objectStat.Err)
|
||||
}
|
||||
@@ -2291,9 +2257,7 @@ func (c *S3Client) objectInfo2ClientContent(bucket string, entry minio.ObjectInf
|
||||
content.Tags = entry.UserTags
|
||||
|
||||
content.ReplicationStatus = entry.ReplicationStatus
|
||||
for k, v := range entry.UserMetadata {
|
||||
content.UserMetadata[k] = v
|
||||
}
|
||||
maps.Copy(content.UserMetadata, entry.UserMetadata)
|
||||
for k := range entry.Metadata {
|
||||
content.Metadata[k] = entry.Metadata.Get(k)
|
||||
}
|
||||
@@ -2320,7 +2284,16 @@ func (c *S3Client) objectInfo2ClientContent(bucket string, entry minio.ObjectInf
|
||||
} else {
|
||||
content.Type = os.FileMode(0o664)
|
||||
}
|
||||
|
||||
setChecksum := func(k, v string) {
|
||||
if v != "" {
|
||||
content.Checksum = map[string]string{k: v}
|
||||
}
|
||||
}
|
||||
setChecksum("CRC32", entry.ChecksumCRC32)
|
||||
setChecksum("CRC32C", entry.ChecksumCRC32C)
|
||||
setChecksum("SHA1", entry.ChecksumSHA1)
|
||||
setChecksum("SHA256", entry.ChecksumSHA256)
|
||||
setChecksum("CRC64NVME", entry.ChecksumCRC64NVME)
|
||||
return content
|
||||
}
|
||||
|
||||
@@ -3051,3 +3024,52 @@ func (c *S3Client) GetPart(ctx context.Context, part int) (io.ReadCloser, *probe
|
||||
}
|
||||
return reader, nil
|
||||
}
|
||||
|
||||
// SetBucketCors - Set bucket cors configuration.
|
||||
func (c *S3Client) SetBucketCors(ctx context.Context, corsXML []byte) *probe.Error {
|
||||
bucketName, _ := c.url2BucketAndObject()
|
||||
if bucketName == "" {
|
||||
return probe.NewError(BucketNameEmpty{})
|
||||
}
|
||||
|
||||
corsCfg, err := cors.ParseBucketCorsConfig(bytes.NewReader(corsXML))
|
||||
if err != nil {
|
||||
return probe.NewError(err)
|
||||
}
|
||||
|
||||
err = c.api.SetBucketCors(ctx, bucketName, corsCfg)
|
||||
if err != nil {
|
||||
return probe.NewError(err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetBucketCors - Get bucket cors configuration.
|
||||
func (c *S3Client) GetBucketCors(ctx context.Context) (*cors.Config, *probe.Error) {
|
||||
bucketName, _ := c.url2BucketAndObject()
|
||||
if bucketName == "" {
|
||||
return nil, probe.NewError(BucketNameEmpty{})
|
||||
}
|
||||
|
||||
corsCfg, err := c.api.GetBucketCors(ctx, bucketName)
|
||||
if err != nil {
|
||||
return nil, probe.NewError(err)
|
||||
}
|
||||
|
||||
return corsCfg, nil
|
||||
}
|
||||
|
||||
// DeleteBucketCors - Delete bucket cors configuration.
|
||||
func (c *S3Client) DeleteBucketCors(ctx context.Context) *probe.Error {
|
||||
bucketName, _ := c.url2BucketAndObject()
|
||||
if bucketName == "" {
|
||||
return probe.NewError(BucketNameEmpty{})
|
||||
}
|
||||
|
||||
err := c.api.SetBucketCors(ctx, bucketName, nil)
|
||||
if err != nil {
|
||||
return probe.NewError(err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
+24
-25
@@ -26,7 +26,7 @@ import (
|
||||
"net/http/httptest"
|
||||
"strconv"
|
||||
|
||||
minio "github.com/minio/minio-go/v7"
|
||||
"github.com/minio/minio-go/v7"
|
||||
checkv1 "gopkg.in/check.v1"
|
||||
)
|
||||
|
||||
@@ -35,8 +35,8 @@ type bucketHandler struct {
|
||||
}
|
||||
|
||||
func (h bucketHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
switch {
|
||||
case r.Method == "GET":
|
||||
switch r.Method {
|
||||
case "GET":
|
||||
// Handler for incoming getBucketLocation request.
|
||||
if _, ok := r.URL.Query()["location"]; ok {
|
||||
response := []byte("<LocationConstraint xmlns=\"http://doc.s3.amazonaws.com/2006-03-01\"></LocationConstraint>")
|
||||
@@ -44,28 +44,28 @@ func (h bucketHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
w.Write(response)
|
||||
return
|
||||
}
|
||||
switch {
|
||||
case r.URL.Path == "/":
|
||||
switch r.URL.Path {
|
||||
case "/":
|
||||
// Handler for incoming ListBuckets request.
|
||||
response := []byte("<ListAllMyBucketsResult xmlns=\"http://doc.s3.amazonaws.com/2006-03-01\"><Buckets><Bucket><Name>bucket</Name><CreationDate>2015-05-20T23:05:09.230Z</CreationDate></Bucket></Buckets><Owner><ID>minio</ID><DisplayName>minio</DisplayName></Owner></ListAllMyBucketsResult>")
|
||||
w.Header().Set("Content-Length", strconv.Itoa(len(response)))
|
||||
w.Write(response)
|
||||
case r.URL.Path == "/bucket/":
|
||||
case "/bucket/":
|
||||
// Handler for incoming ListObjects request.
|
||||
response := []byte("<ListBucketResult xmlns=\"http://doc.s3.amazonaws.com/2006-03-01\"><Contents><ETag>259d04a13802ae09c7e41be50ccc6baa</ETag><Key>object</Key><LastModified>2015-05-21T18:24:21.097Z</LastModified><Size>22061</Size><Owner><ID>minio</ID><DisplayName>minio</DisplayName></Owner><StorageClass>STANDARD</StorageClass></Contents><Delimiter></Delimiter><EncodingType></EncodingType><IsTruncated>false</IsTruncated><Marker></Marker><MaxKeys>1000</MaxKeys><Name>testbucket</Name><NextMarker></NextMarker><Prefix></Prefix></ListBucketResult>")
|
||||
w.Header().Set("Content-Length", strconv.Itoa(len(response)))
|
||||
w.Write(response)
|
||||
}
|
||||
case r.Method == "PUT":
|
||||
switch {
|
||||
case r.URL.Path == h.resource:
|
||||
case "PUT":
|
||||
switch r.URL.Path {
|
||||
case h.resource:
|
||||
w.WriteHeader(http.StatusOK)
|
||||
default:
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
}
|
||||
case r.Method == "HEAD":
|
||||
switch {
|
||||
case r.URL.Path == h.resource:
|
||||
case "HEAD":
|
||||
switch r.URL.Path {
|
||||
case h.resource:
|
||||
w.WriteHeader(http.StatusOK)
|
||||
default:
|
||||
w.WriteHeader(http.StatusForbidden)
|
||||
@@ -85,8 +85,8 @@ func (h objectHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
switch {
|
||||
case r.Method == http.MethodPut:
|
||||
switch r.Method {
|
||||
case http.MethodPut:
|
||||
// Handler for PUT object request.
|
||||
length, e := strconv.Atoi(r.Header.Get("Content-Length"))
|
||||
if e != nil {
|
||||
@@ -100,7 +100,7 @@ func (h objectHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
w.Header().Set("ETag", "9af2f8218b150c351ad802c6f3d66abe")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
case r.Method == http.MethodHead:
|
||||
case http.MethodHead:
|
||||
// Handler for Stat object request.
|
||||
if r.URL.Path != h.resource {
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
@@ -110,7 +110,7 @@ func (h objectHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Last-Modified", UTCNow().Format(http.TimeFormat))
|
||||
w.Header().Set("ETag", "9af2f8218b150c351ad802c6f3d66abe")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
case r.Method == http.MethodPost:
|
||||
case http.MethodPost:
|
||||
// Handler for multipart upload request.
|
||||
if _, ok := r.URL.Query()["uploads"]; ok {
|
||||
if r.URL.Path == h.resource {
|
||||
@@ -132,7 +132,7 @@ func (h objectHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
case r.Method == http.MethodGet:
|
||||
case http.MethodGet:
|
||||
// Handler for get bucket location request.
|
||||
if _, ok := r.URL.Query()["location"]; ok {
|
||||
response := []byte("<LocationConstraint xmlns=\"http://doc.s3.amazonaws.com/2006-03-01\"></LocationConstraint>")
|
||||
@@ -171,8 +171,8 @@ func (h stsHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
switch {
|
||||
case r.Method == http.MethodPost:
|
||||
switch r.Method {
|
||||
case http.MethodPost:
|
||||
token := r.Form.Get("WebIdentityToken")
|
||||
if token == string(h.jwt) {
|
||||
response := []byte("<AssumeRoleWithWebIdentityResponse xmlns=\"https://sts.amazonaws.com/doc/2011-06-15/\"><AssumeRoleWithWebIdentityResult><AssumedRoleUser><Arn></Arn><AssumeRoleId></AssumeRoleId></AssumedRoleUser><Credentials><AccessKeyId>7NL5BR739GUQ0ZOD4JNB</AccessKeyId><SecretAccessKey>A2mxZSxPnHNhSduedUHczsXZpVSSssOLpDruUmTV</SecretAccessKey><Expiration>0001-01-01T00:00:00Z</Expiration><SessionToken>eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJhY2Nlc3NLZXkiOiI3Tkw1QlI3MzlHVVEwWk9ENEpOQiIsImV4cCI6MTY5OTYwMzMwNiwicGFyZW50IjoibWluaW8iLCJzZXNzaW9uUG9saWN5IjoiZXlKV1pYSnphVzl1SWpvaU1qQXhNaTB4TUMweE55SXNJbE4wWVhSbGJXVnVkQ0k2VzNzaVJXWm1aV04wSWpvaVFXeHNiM2NpTENKQlkzUnBiMjRpT2xzaVlXUnRhVzQ2S2lKZGZTeDdJa1ZtWm1WamRDSTZJa0ZzYkc5M0lpd2lRV04wYVc5dUlqcGJJbXR0Y3pvcUlsMTlMSHNpUldabVpXTjBJam9pUVd4c2IzY2lMQ0pCWTNScGIyNGlPbHNpY3pNNktpSmRMQ0pTWlhOdmRYSmpaU0k2V3lKaGNtNDZZWGR6T25Nek9qbzZLaUpkZlYxOSJ9.uuE_x7PO8QoPfUk9KzUELoAqxihIknZAvJLl5aYJjwpSjJYFTPLp6EvuyJX2hc18s9HzeiJ-vU0dPzsy50dXmg</SessionToken></Credentials></AssumeRoleWithWebIdentityResult><ResponseMetadata></ResponseMetadata></AssumeRoleWithWebIdentityResponse>")
|
||||
@@ -181,13 +181,12 @@ func (h stsHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Server", "MinIO")
|
||||
w.Write(response)
|
||||
return
|
||||
} else {
|
||||
response := []byte("<ErrorResponse xmlns=\"https://sts.amazonaws.com/doc/2011-06-15/\"><Error><Type></Type><Code>AccessDenied</Code><Message>Access denied: Invalid Token</Message></Error><RequestId></RequestId></ErrorResponse>")
|
||||
w.Header().Set("Content-Length", strconv.Itoa(len(response)))
|
||||
w.Header().Set("Content-Type", "application/xml")
|
||||
w.Write(response)
|
||||
return
|
||||
}
|
||||
response := []byte("<ErrorResponse xmlns=\"https://sts.amazonaws.com/doc/2011-06-15/\"><Error><Type></Type><Code>AccessDenied</Code><Message>Access denied: Invalid Token</Message></Error><RequestId></RequestId></ErrorResponse>")
|
||||
w.Header().Set("Content-Length", strconv.Itoa(len(response)))
|
||||
w.Header().Set("Content-Type", "application/xml")
|
||||
w.Write(response)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -65,8 +65,7 @@ func TestSTSS3Operation(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
var reader io.Reader
|
||||
reader = bytes.NewReader(object.data)
|
||||
var reader io.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",
|
||||
|
||||
+44
-1
@@ -50,6 +50,7 @@ type url2StatOptions struct {
|
||||
encKeyDB map[string][]prefixSSEPair
|
||||
timeRef time.Time
|
||||
isZip bool
|
||||
headOnly bool
|
||||
ignoreBucketExistsCheck bool
|
||||
}
|
||||
|
||||
@@ -204,7 +205,15 @@ func url2Stat(ctx context.Context, opts url2StatOptions) (client Client, content
|
||||
alias, _ := url2Alias(opts.urlStr)
|
||||
sse := getSSE(opts.urlStr, opts.encKeyDB[alias])
|
||||
|
||||
content, err = client.Stat(ctx, StatOptions{preserve: opts.fileAttr, sse: sse, timeRef: opts.timeRef, versionID: opts.versionID, isZip: opts.isZip, ignoreBucketExists: opts.ignoreBucketExistsCheck})
|
||||
content, err = client.Stat(ctx, StatOptions{
|
||||
preserve: opts.fileAttr,
|
||||
sse: sse,
|
||||
timeRef: opts.timeRef,
|
||||
versionID: opts.versionID,
|
||||
isZip: opts.isZip,
|
||||
ignoreBucketExists: opts.ignoreBucketExistsCheck,
|
||||
headOnly: opts.headOnly,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, nil, err.Trace(opts.urlStr)
|
||||
}
|
||||
@@ -258,3 +267,37 @@ func guessURLContentType(urlStr string) string {
|
||||
contentType := mimedb.TypeByExtension(filepath.Ext(url.Path))
|
||||
return contentType
|
||||
}
|
||||
|
||||
// urlParts - split URL into parts.
|
||||
func urlParts(urlStr string) []string {
|
||||
// Convert '/' on windows to filepath.Separator.
|
||||
urlStr = filepath.FromSlash(urlStr)
|
||||
|
||||
if runtime.GOOS == "windows" {
|
||||
// Remove '/' prefix before alias if any to support '\\home' alias
|
||||
// style under Windows
|
||||
urlStr = strings.TrimPrefix(urlStr, string(filepath.Separator))
|
||||
}
|
||||
|
||||
// Remove everything after alias (i.e. after '/').
|
||||
return strings.Split(urlStr, string(filepath.Separator))
|
||||
}
|
||||
|
||||
// isURLPrefix - check if source and destination be subdirectories of each other
|
||||
func isURLPrefix(src string, dest string) bool {
|
||||
srcURLParts := urlParts(src)
|
||||
dstURLParts := urlParts(dest)
|
||||
minIndex := min(len(srcURLParts), len(dstURLParts))
|
||||
isPrefix := true
|
||||
for i := range minIndex {
|
||||
// if one of the URLs ends with '/' and other does not
|
||||
if (i == minIndex-1) && (dstURLParts[i] == "" || srcURLParts[i] == "" || dstURLParts[i] == "*" || srcURLParts[i] == "*") {
|
||||
continue
|
||||
}
|
||||
if srcURLParts[i] != dstURLParts[i] {
|
||||
isPrefix = false
|
||||
break
|
||||
}
|
||||
}
|
||||
return isPrefix
|
||||
}
|
||||
|
||||
+35
-1
@@ -17,7 +17,11 @@
|
||||
|
||||
package cmd
|
||||
|
||||
import checkv1 "gopkg.in/check.v1"
|
||||
import (
|
||||
"testing"
|
||||
|
||||
checkv1 "gopkg.in/check.v1"
|
||||
)
|
||||
|
||||
// TestURL - tests url parsing and fields.
|
||||
func (s *TestSuite) TestURL(c *checkv1.C) {
|
||||
@@ -52,3 +56,33 @@ func (s *TestSuite) TestURLJoinPath(c *checkv1.C) {
|
||||
url = urlJoinPath(url1, url2)
|
||||
c.Assert(url, checkv1.Equals, "http://s3.mycompany.io/dev/mybucket/bin/")
|
||||
}
|
||||
|
||||
func Test_isURLPrefix(t *testing.T) {
|
||||
type args struct {
|
||||
src string
|
||||
dest string
|
||||
}
|
||||
tests := []struct {
|
||||
name string
|
||||
args args
|
||||
want bool
|
||||
}{
|
||||
{"test1", args{"s3/test", "s3/test/test"}, true},
|
||||
{"test2", args{"s3/test/", "s3/test/test"}, true},
|
||||
{"test3", args{"s3/test/test", "s3/test/"}, true},
|
||||
{"test4", args{"s3/test/test", "s3/test/test.123"}, false},
|
||||
{"test5", args{"s3/test/", "s3/test/test/test/test"}, true},
|
||||
{"test6", args{"s3/test/*", "s3/test/test/"}, true},
|
||||
{"test7", args{"s3/test/*", "s3/test1/test/"}, false},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if got := isURLPrefix(tt.args.src, tt.args.dest); got != tt.want {
|
||||
t.Errorf("isURLPrefix() = %v, want %v", got, tt.want)
|
||||
}
|
||||
if got := isURLPrefix(tt.args.dest, tt.args.src); got != tt.want {
|
||||
t.Errorf("isURLPrefix() = %v, want %v", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
+171
-2
@@ -19,16 +19,28 @@ package cmd
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"fmt"
|
||||
"io"
|
||||
"maps"
|
||||
"math/rand"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/klauspost/compress/gzhttp"
|
||||
"github.com/minio/mc/pkg/httptracer"
|
||||
"github.com/minio/mc/pkg/limiter"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/minio-go/v7"
|
||||
"github.com/minio/minio-go/v7/pkg/cors"
|
||||
"github.com/minio/minio-go/v7/pkg/credentials"
|
||||
"github.com/minio/minio-go/v7/pkg/encrypt"
|
||||
"github.com/minio/minio-go/v7/pkg/lifecycle"
|
||||
"github.com/minio/minio-go/v7/pkg/replication"
|
||||
"github.com/minio/pkg/v3/env"
|
||||
)
|
||||
|
||||
// DirOpt - list directory option.
|
||||
@@ -49,6 +61,7 @@ type GetOptions struct {
|
||||
VersionID string
|
||||
Zip bool
|
||||
RangeStart int64
|
||||
PartNumber int
|
||||
Preserve bool
|
||||
}
|
||||
|
||||
@@ -63,6 +76,7 @@ type PutOptions struct {
|
||||
multipartThreads uint
|
||||
concurrentStream bool
|
||||
ifNotExists bool
|
||||
checksum minio.ChecksumType
|
||||
}
|
||||
|
||||
// StatOptions holds options of the HEAD operation
|
||||
@@ -75,6 +89,7 @@ type StatOptions struct {
|
||||
includeVersions bool
|
||||
isZip bool
|
||||
ignoreBucketExists bool
|
||||
headOnly bool
|
||||
}
|
||||
|
||||
// BucketStatOptions - bucket stat.
|
||||
@@ -123,8 +138,8 @@ type Client interface {
|
||||
GetObjectLockConfig(ctx context.Context) (status string, mode minio.RetentionMode, validity uint64, unit minio.ValidityUnit, perr *probe.Error)
|
||||
|
||||
// Access policy operations.
|
||||
GetAccess(ctx context.Context) (access, policyJSON string, error *probe.Error)
|
||||
GetAccessRules(ctx context.Context) (policyRules map[string]string, error *probe.Error)
|
||||
GetAccess(ctx context.Context) (access, policyJSON string, err *probe.Error)
|
||||
GetAccessRules(ctx context.Context) (policyRules map[string]string, err *probe.Error)
|
||||
SetAccess(ctx context.Context, access string, isJSON bool) *probe.Error
|
||||
|
||||
// I/O operations
|
||||
@@ -189,6 +204,11 @@ type Client interface {
|
||||
// OD operations
|
||||
GetPart(ctx context.Context, part int) (io.ReadCloser, *probe.Error)
|
||||
PutPart(ctx context.Context, reader io.Reader, size int64, progress io.Reader, opts PutOptions) (n int64, err *probe.Error)
|
||||
|
||||
// Cors operations
|
||||
GetBucketCors(ctx context.Context) (*cors.Config, *probe.Error)
|
||||
SetBucketCors(ctx context.Context, corsXML []byte) *probe.Error
|
||||
DeleteBucketCors(ctx context.Context) *probe.Error
|
||||
}
|
||||
|
||||
// ClientContent - Content container for content metadata
|
||||
@@ -202,6 +222,7 @@ type ClientContent struct {
|
||||
Metadata map[string]string
|
||||
Tags map[string]string
|
||||
UserMetadata map[string]string
|
||||
Checksum map[string]string
|
||||
ETag string
|
||||
Expires time.Time
|
||||
|
||||
@@ -244,9 +265,157 @@ type Config struct {
|
||||
Transport http.RoundTripper
|
||||
}
|
||||
|
||||
// getCredsChain returns an []credentials.Provider array for the config
|
||||
// and the STS configuration (if present)
|
||||
func (config *Config) getCredsChain() ([]credentials.Provider, *probe.Error) {
|
||||
var credsChain []credentials.Provider
|
||||
// if an STS endpoint is set, we will add that to the chain
|
||||
if stsEndpoint := env.Get("MC_STS_ENDPOINT_"+config.Alias, ""); stsEndpoint != "" {
|
||||
// set AWS_WEB_IDENTITY_TOKEN_FILE is MC_WEB_IDENTITY_TOKEN_FILE is set
|
||||
if val := env.Get("MC_WEB_IDENTITY_TOKEN_FILE_"+config.Alias, ""); val != "" {
|
||||
os.Setenv("AWS_WEB_IDENTITY_TOKEN_FILE", val)
|
||||
if val := env.Get("MC_ROLE_ARN_"+config.Alias, ""); val != "" {
|
||||
os.Setenv("AWS_ROLE_ARN", val)
|
||||
}
|
||||
if val := env.Get("MC_ROLE_SESSION_NAME_"+config.Alias, randString(32, rand.NewSource(time.Now().UnixNano()), "mc-session-name-")); val != "" {
|
||||
os.Setenv("AWS_ROLE_SESSION_NAME", val)
|
||||
}
|
||||
}
|
||||
stsEndpointURL, err := url.Parse(stsEndpoint)
|
||||
if err != nil {
|
||||
return nil, probe.NewError(fmt.Errorf("Error parsing sts endpoint: %w", err))
|
||||
}
|
||||
credsSts := &credentials.IAM{
|
||||
Client: &http.Client{
|
||||
Transport: config.getTransport(),
|
||||
},
|
||||
Endpoint: stsEndpointURL.String(),
|
||||
}
|
||||
credsChain = append(credsChain, credsSts)
|
||||
}
|
||||
|
||||
signType := credentials.SignatureV4
|
||||
if strings.EqualFold(config.Signature, "s3v2") {
|
||||
signType = credentials.SignatureV2
|
||||
}
|
||||
|
||||
// Credentials
|
||||
creds := &credentials.Static{
|
||||
Value: credentials.Value{
|
||||
AccessKeyID: config.AccessKey,
|
||||
SecretAccessKey: config.SecretKey,
|
||||
SessionToken: config.SessionToken,
|
||||
SignerType: signType,
|
||||
},
|
||||
}
|
||||
credsChain = append(credsChain, creds)
|
||||
return credsChain, nil
|
||||
}
|
||||
|
||||
// getTransport returns a corresponding *http.Transport for the *Config
|
||||
// set withS3v2 bool to true to add traceV2 tracer.
|
||||
func (config *Config) getTransport() http.RoundTripper {
|
||||
if config.Transport == nil {
|
||||
config.initTransport(true)
|
||||
}
|
||||
return config.Transport
|
||||
}
|
||||
|
||||
func (config *Config) isTLS() bool {
|
||||
if stsEndpoint := env.Get("MC_STS_ENDPOINT_"+config.Alias, ""); stsEndpoint != "" {
|
||||
stsEndpointURL, err := url.Parse(stsEndpoint)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
return isHostTLS(config) || stsEndpointURL.Scheme == "https"
|
||||
}
|
||||
return isHostTLS(config)
|
||||
}
|
||||
|
||||
func (config *Config) initTransport(withS3v2 bool) {
|
||||
var transport http.RoundTripper
|
||||
|
||||
useTLS := config.isTLS()
|
||||
|
||||
if config.Transport != nil {
|
||||
transport = config.Transport
|
||||
} else {
|
||||
tr := &http.Transport{
|
||||
Proxy: http.ProxyFromEnvironment,
|
||||
DialContext: newCustomDialContext(config),
|
||||
MaxIdleConnsPerHost: 1024,
|
||||
WriteBufferSize: 32 << 10, // 32KiB moving up from 4KiB default
|
||||
ReadBufferSize: 32 << 10, // 32KiB moving up from 4KiB default
|
||||
IdleConnTimeout: 90 * time.Second,
|
||||
TLSHandshakeTimeout: 10 * time.Second,
|
||||
ExpectContinueTimeout: 10 * time.Second,
|
||||
// Set this value so that the underlying transport round-tripper
|
||||
// doesn't try to auto decode the body of objects with
|
||||
// content-encoding set to `gzip`.
|
||||
//
|
||||
// Refer:
|
||||
// https://golang.org/src/net/http/transport.go?h=roundTrip#L1843
|
||||
DisableCompression: true,
|
||||
}
|
||||
if useTLS {
|
||||
tr.DialTLSContext = newCustomDialTLSContext(&tls.Config{
|
||||
RootCAs: globalRootCAs,
|
||||
MinVersion: tls.VersionTLS12,
|
||||
InsecureSkipVerify: config.Insecure,
|
||||
})
|
||||
|
||||
// Because we create a custom TLSClientConfig, we have to opt-in to HTTP/2.
|
||||
// See https://github.com/golang/go/issues/14275
|
||||
//
|
||||
// TODO: Enable http2.0 when upstream issues related to HTTP/2 are fixed.
|
||||
//
|
||||
// if e = http2.ConfigureTransport(tr); e != nil {
|
||||
// return nil, probe.NewError(e)
|
||||
// }
|
||||
}
|
||||
|
||||
if len(globalCustomHeader) > 0 {
|
||||
transport = &headerTransport{
|
||||
RoundTripper: tr,
|
||||
customHeader: globalCustomHeader.Clone(),
|
||||
}
|
||||
} else {
|
||||
transport = tr
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
transport = limiter.New(config.UploadLimit, config.DownloadLimit, transport)
|
||||
|
||||
if config.Debug {
|
||||
if strings.EqualFold(config.Signature, "S3v4") {
|
||||
transport = httptracer.GetNewTraceTransport(newTraceV4(), transport)
|
||||
} else if strings.EqualFold(config.Signature, "S3v2") && withS3v2 {
|
||||
transport = httptracer.GetNewTraceTransport(newTraceV2(), transport)
|
||||
}
|
||||
} else {
|
||||
if !globalJSONLine && !globalJSON {
|
||||
transport = notifyExpiringTLS{transport: transport}
|
||||
}
|
||||
}
|
||||
|
||||
transport = gzhttp.Transport(transport)
|
||||
config.Transport = transport
|
||||
}
|
||||
|
||||
// SelectObjectOpts - opts entered for select API
|
||||
type SelectObjectOpts struct {
|
||||
InputSerOpts map[string]map[string]string
|
||||
OutputSerOpts map[string]map[string]string
|
||||
CompressionType minio.SelectCompressionType
|
||||
}
|
||||
|
||||
type headerTransport struct {
|
||||
http.RoundTripper
|
||||
customHeader http.Header
|
||||
}
|
||||
|
||||
func (h *headerTransport) RoundTrip(request *http.Request) (*http.Response, error) {
|
||||
maps.Copy(request.Header, h.customHeader)
|
||||
return h.RoundTripper.RoundTrip(request)
|
||||
}
|
||||
|
||||
+20
-16
@@ -21,10 +21,12 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"maps"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
@@ -35,6 +37,7 @@ import (
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/minio-go/v7"
|
||||
"github.com/minio/minio-go/v7/pkg/encrypt"
|
||||
"github.com/minio/minio-go/v7/pkg/tags"
|
||||
"github.com/minio/pkg/v3/env"
|
||||
)
|
||||
|
||||
@@ -134,15 +137,12 @@ func isReadAt(reader io.Reader) (ok bool) {
|
||||
// which happen to also be io.ReaderAt compatible
|
||||
// we need to add special conditions for them to
|
||||
// be ignored by this function.
|
||||
for _, f := range []string{
|
||||
if slices.Contains([]string{
|
||||
"/dev/stdin",
|
||||
"/dev/stdout",
|
||||
"/dev/stderr",
|
||||
} {
|
||||
if f == v.Name() {
|
||||
ok = false
|
||||
break
|
||||
}
|
||||
}, v.Name()) {
|
||||
ok = false
|
||||
}
|
||||
}
|
||||
return
|
||||
@@ -353,16 +353,14 @@ func uploadSourceToTargetURL(ctx context.Context, uploadOpts uploadSourceToTarge
|
||||
}
|
||||
|
||||
// Optimize for server side copy if the host is same.
|
||||
if sourceAlias == targetAlias && !uploadOpts.isZip {
|
||||
if sourceAlias == targetAlias && !uploadOpts.isZip && !uploadOpts.urls.checksum.IsSet() {
|
||||
// preserve new metadata and save existing ones.
|
||||
if uploadOpts.preserve {
|
||||
currentMetadata, err := getAllMetadata(ctx, sourceAlias, sourceURL.String(), srcSSE, uploadOpts.urls)
|
||||
if err != nil {
|
||||
return uploadOpts.urls.WithError(err.Trace(sourceURL.String()))
|
||||
}
|
||||
for k, v := range currentMetadata {
|
||||
metadata[k] = v
|
||||
}
|
||||
maps.Copy(metadata, currentMetadata)
|
||||
}
|
||||
|
||||
// Get metadata from target content as well
|
||||
@@ -400,9 +398,7 @@ func uploadSourceToTargetURL(ctx context.Context, uploadOpts uploadSourceToTarge
|
||||
if err != nil {
|
||||
return uploadOpts.urls.WithError(err.Trace(sourceURL.String()))
|
||||
}
|
||||
for k, v := range currentMetadata {
|
||||
metadata[k] = v
|
||||
}
|
||||
maps.Copy(metadata, currentMetadata)
|
||||
}
|
||||
|
||||
// Get metadata from target content as well
|
||||
@@ -446,9 +442,7 @@ func uploadSourceToTargetURL(ctx context.Context, uploadOpts uploadSourceToTarge
|
||||
}
|
||||
|
||||
metadata := make(map[string]string, len(content.Metadata))
|
||||
for k, v := range content.Metadata {
|
||||
metadata[k] = v
|
||||
}
|
||||
maps.Copy(metadata, content.Metadata)
|
||||
|
||||
// Get metadata from target content as well
|
||||
for k, v := range uploadOpts.urls.TargetContent.Metadata {
|
||||
@@ -460,6 +454,15 @@ func uploadSourceToTargetURL(ctx context.Context, uploadOpts uploadSourceToTarge
|
||||
metadata[http.CanonicalHeaderKey(k)] = v
|
||||
}
|
||||
|
||||
if content.Tags != nil {
|
||||
tags, err := tags.NewTags(content.Tags, true)
|
||||
if err != nil {
|
||||
return uploadOpts.urls.WithError(probe.NewError(err))
|
||||
}
|
||||
metadata["X-Amz-Tagging"] = tags.String()
|
||||
delete(metadata, "X-Amz-Tagging-Count")
|
||||
}
|
||||
|
||||
var e error
|
||||
var multipartSize uint64
|
||||
var multipartThreads int
|
||||
@@ -495,6 +498,7 @@ func uploadSourceToTargetURL(ctx context.Context, uploadOpts uploadSourceToTarge
|
||||
multipartSize: multipartSize,
|
||||
multipartThreads: uint(multipartThreads),
|
||||
ifNotExists: uploadOpts.ifNotExists,
|
||||
checksum: uploadOpts.urls.checksum,
|
||||
}
|
||||
|
||||
if isReadAt(reader) || length == 0 {
|
||||
|
||||
@@ -1,101 +0,0 @@
|
||||
// Copyright (c) 2015-2022 MinIO, Inc.
|
||||
//
|
||||
// This file is part of MinIO Object Storage stack
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package cmd
|
||||
|
||||
import "github.com/minio/cli"
|
||||
|
||||
var configCmd = cli.Command{
|
||||
Name: "config",
|
||||
Usage: "configure MinIO client",
|
||||
Action: func(ctx *cli.Context) error {
|
||||
cli.ShowCommandHelp(ctx, ctx.Args().First())
|
||||
return nil
|
||||
},
|
||||
Hidden: true,
|
||||
Before: setGlobalsFromContext,
|
||||
HideHelpCommand: true,
|
||||
Flags: globalFlags,
|
||||
Subcommands: []cli.Command{
|
||||
configHostCmd,
|
||||
},
|
||||
}
|
||||
|
||||
var configHostCmd = cli.Command{
|
||||
Name: "host",
|
||||
Usage: "add, remove and list hosts in configuration file",
|
||||
Action: func(ctx *cli.Context) error {
|
||||
cli.ShowCommandHelp(ctx, ctx.Args().First())
|
||||
return nil
|
||||
},
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
Subcommands: []cli.Command{
|
||||
configHostAddCmd,
|
||||
configHostRemoveCmd,
|
||||
configHostListCmd,
|
||||
},
|
||||
HideHelpCommand: true,
|
||||
}
|
||||
|
||||
var configHostAddFlags = []cli.Flag{
|
||||
cli.StringFlag{
|
||||
Name: "lookup",
|
||||
Value: "auto",
|
||||
Usage: "bucket lookup supported by the server. Valid options are '[dns, path, auto]'",
|
||||
},
|
||||
cli.StringFlag{
|
||||
Name: "api",
|
||||
Usage: "API signature. Valid options are '[S3v4, S3v2]'",
|
||||
},
|
||||
}
|
||||
|
||||
var configHostAddCmd = cli.Command{
|
||||
Name: "add",
|
||||
ShortName: "a",
|
||||
Usage: "add a new host to configuration file",
|
||||
Action: func(cli *cli.Context) error {
|
||||
return mainAliasSet(cli, true)
|
||||
},
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: append(configHostAddFlags, globalFlags...),
|
||||
HideHelpCommand: true,
|
||||
}
|
||||
|
||||
var configHostListCmd = cli.Command{
|
||||
Name: "list",
|
||||
ShortName: "ls",
|
||||
Usage: "list hosts in configuration file",
|
||||
Action: func(cli *cli.Context) error {
|
||||
return mainAliasList(cli, true)
|
||||
},
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
HideHelpCommand: true,
|
||||
}
|
||||
|
||||
var configHostRemoveCmd = cli.Command{
|
||||
Name: "remove",
|
||||
ShortName: "rm",
|
||||
Usage: "remove a host from configuration file",
|
||||
Action: func(cli *cli.Context) error {
|
||||
return mainAliasRemove(cli)
|
||||
},
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
HideHelpCommand: true,
|
||||
}
|
||||
+3
-6
@@ -19,6 +19,7 @@ package cmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"maps"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
@@ -94,9 +95,7 @@ func fixConfigV3() {
|
||||
|
||||
cfgV3 := newConfigV3()
|
||||
isMutated := false
|
||||
for k, v := range brokenMcCfgV3.Data().(*brokenConfigV3).Aliases {
|
||||
cfgV3.Aliases[k] = v
|
||||
}
|
||||
maps.Copy(cfgV3.Aliases, brokenMcCfgV3.Data().(*brokenConfigV3).Aliases)
|
||||
|
||||
for host, brokenHostCfgV3 := range brokenMcCfgV3.Data().(*brokenConfigV3).Hosts {
|
||||
|
||||
@@ -144,9 +143,7 @@ func fixConfigV6ForHosts() {
|
||||
isMutated := false
|
||||
|
||||
// Copy aliases.
|
||||
for k, v := range brokenMcCfgV6.Data().(*configV6).Aliases {
|
||||
newCfgV6.Aliases[k] = v
|
||||
}
|
||||
maps.Copy(newCfgV6.Aliases, brokenMcCfgV6.Data().(*configV6).Aliases)
|
||||
|
||||
url := &ClientURL{}
|
||||
// Copy hosts.
|
||||
|
||||
+11
-21
@@ -19,6 +19,7 @@ package cmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"maps"
|
||||
"strings"
|
||||
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
@@ -70,9 +71,7 @@ func migrateConfigV1ToV101() {
|
||||
cfgV101 := newConfigV101()
|
||||
|
||||
// Copy aliases.
|
||||
for k, v := range mcCfgV1.Data().(*configV1).Aliases {
|
||||
cfgV101.Aliases[k] = v
|
||||
}
|
||||
maps.Copy(cfgV101.Aliases, mcCfgV1.Data().(*configV1).Aliases)
|
||||
|
||||
// Copy hosts.
|
||||
for k, hostCfgV1 := range mcCfgV1.Data().(*configV1).Hosts {
|
||||
@@ -128,9 +127,7 @@ func migrateConfigV101ToV2() {
|
||||
cfgV2 := newConfigV2()
|
||||
|
||||
// Copy aliases.
|
||||
for k, v := range mcCfgV101.Data().(*configV101).Aliases {
|
||||
cfgV2.Aliases[k] = v
|
||||
}
|
||||
maps.Copy(cfgV2.Aliases, mcCfgV101.Data().(*configV101).Aliases)
|
||||
|
||||
// Copy hosts.
|
||||
for k, hostCfgV101 := range mcCfgV101.Data().(*configV101).Hosts {
|
||||
@@ -166,9 +163,7 @@ func migrateConfigV2ToV3() {
|
||||
cfgV3 := newConfigV3()
|
||||
|
||||
// Copy aliases.
|
||||
for k, v := range mcCfgV2.Data().(*configV2).Aliases {
|
||||
cfgV3.Aliases[k] = v
|
||||
}
|
||||
maps.Copy(cfgV3.Aliases, mcCfgV2.Data().(*configV2).Aliases)
|
||||
|
||||
// Copy hosts.
|
||||
for k, hostCfgV2 := range mcCfgV2.Data().(*configV2).Hosts {
|
||||
@@ -203,9 +198,7 @@ func migrateConfigV3ToV4() {
|
||||
fatalIf(probe.NewError(e), "Unable to load mc config V3.")
|
||||
|
||||
cfgV4 := newConfigV4()
|
||||
for k, v := range mcCfgV3.Data().(*configV3).Aliases {
|
||||
cfgV4.Aliases[k] = v
|
||||
}
|
||||
maps.Copy(cfgV4.Aliases, mcCfgV3.Data().(*configV3).Aliases)
|
||||
// New hostConfig has API signature. All older entries were V4
|
||||
// only. So it is safe to assume V4 as default for all older
|
||||
// entries.
|
||||
@@ -244,9 +237,7 @@ func migrateConfigV4ToV5() {
|
||||
fatalIf(probe.NewError(e), "Unable to load mc config V4.")
|
||||
|
||||
cfgV5 := newConfigV5()
|
||||
for k, v := range mcCfgV4.Data().(*configV4).Aliases {
|
||||
cfgV5.Aliases[k] = v
|
||||
}
|
||||
maps.Copy(cfgV5.Aliases, mcCfgV4.Data().(*configV4).Aliases)
|
||||
for host, hostCfgV4 := range mcCfgV4.Data().(*configV4).Hosts {
|
||||
cfgV5.Hosts[host] = hostConfigV5{
|
||||
AccessKeyID: hostCfgV4.AccessKeyID,
|
||||
@@ -286,9 +277,7 @@ func migrateConfigV5ToV6() {
|
||||
// Add new Google Cloud Storage alias.
|
||||
cfgV6.Aliases["gcs"] = "https://storage.googleapis.com"
|
||||
|
||||
for k, v := range mcCfgV5.Data().(*configV5).Aliases {
|
||||
cfgV6.Aliases[k] = v
|
||||
}
|
||||
maps.Copy(cfgV6.Aliases, mcCfgV5.Data().(*configV5).Aliases)
|
||||
|
||||
// Add defaults.
|
||||
cfgV6.Hosts["*s3*amazonaws.com"] = hostConfigV6{
|
||||
@@ -366,7 +355,8 @@ func migrateConfigV6ToV7() {
|
||||
continue
|
||||
}
|
||||
}
|
||||
if host == "https://s3.amazonaws.com" {
|
||||
switch host {
|
||||
case "https://s3.amazonaws.com":
|
||||
// Only one entry can exist for "s3" domain.
|
||||
cfgV7.Hosts["s3"] = hostConfigV7{
|
||||
URL: host,
|
||||
@@ -374,7 +364,7 @@ func migrateConfigV6ToV7() {
|
||||
SecretKey: hostCfgV6.SecretAccessKey,
|
||||
API: hostCfgV6.API,
|
||||
}
|
||||
} else if host == "https://storage.googleapis.com" {
|
||||
case "https://storage.googleapis.com":
|
||||
// Only one entry can exist for "gcs" domain.
|
||||
cfgV7.Hosts["gcs"] = hostConfigV7{
|
||||
URL: host,
|
||||
@@ -382,7 +372,7 @@ func migrateConfigV6ToV7() {
|
||||
SecretKey: hostCfgV6.SecretAccessKey,
|
||||
API: hostCfgV6.API,
|
||||
}
|
||||
} else {
|
||||
default:
|
||||
// Assign a generic "cloud1", cloud2..." key
|
||||
// for all other entries that has valid keys set.
|
||||
alias := fmt.Sprintf("cloud%d", aliasIndex)
|
||||
|
||||
+6
-13
@@ -17,7 +17,10 @@
|
||||
|
||||
package cmd
|
||||
|
||||
import "strings"
|
||||
import (
|
||||
"slices"
|
||||
"strings"
|
||||
)
|
||||
|
||||
var validAPIs = []string{"S3v4", "S3v2"}
|
||||
|
||||
@@ -73,21 +76,11 @@ func isValidAPI(api string) (ok bool) {
|
||||
// isValidLookup - validates if bucket lookup is of valid type
|
||||
func isValidLookup(lookup string) (ok bool) {
|
||||
l := strings.ToLower(strings.TrimSpace(lookup))
|
||||
for _, v := range []string{"dns", "path", "auto"} {
|
||||
if l == v {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
return slices.Contains([]string{"dns", "path", "auto"}, l)
|
||||
}
|
||||
|
||||
// isValidPath - validates the alias path config
|
||||
func isValidPath(path string) (ok bool) {
|
||||
l := strings.ToLower(strings.TrimSpace(path))
|
||||
for _, v := range []string{"on", "off", "auto"} {
|
||||
if l == v {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
return slices.Contains([]string{"on", "off", "auto"}, l)
|
||||
}
|
||||
|
||||
@@ -46,6 +46,7 @@ type aliasConfigV10 struct {
|
||||
Path string `json:"path"`
|
||||
License string `json:"license,omitempty"`
|
||||
APIKey string `json:"apiKey,omitempty"`
|
||||
Src string `json:"src,omitempty"`
|
||||
}
|
||||
|
||||
// configV10 config version.
|
||||
|
||||
+17
-8
@@ -185,6 +185,7 @@ func getAliasConfig(alias string) (*aliasConfigV10, *probe.Error) {
|
||||
// if host is exact return quickly.
|
||||
if _, ok := mcCfg.Aliases[alias]; ok {
|
||||
hostCfg := mcCfg.Aliases[alias]
|
||||
hostCfg.Src = mustGetMcConfigPath()
|
||||
return &hostCfg, nil
|
||||
}
|
||||
|
||||
@@ -194,15 +195,18 @@ func getAliasConfig(alias string) (*aliasConfigV10, *probe.Error) {
|
||||
|
||||
// mustGetHostConfig retrieves host specific configuration such as access keys, signature type.
|
||||
func mustGetHostConfig(alias string) *aliasConfigV10 {
|
||||
aliasCfg, _ := getAliasConfig(alias)
|
||||
// look for it in the environment variable first.
|
||||
aliasCfg, _ := expandAliasFromEnv(env.Get(mcEnvHostPrefix+alias, ""))
|
||||
|
||||
// If alias is not found,
|
||||
// look for it in the environment variable.
|
||||
if aliasCfg == nil {
|
||||
aliasCfg, _ = expandAliasFromEnv(env.Get(mcEnvHostPrefix+alias, ""))
|
||||
}
|
||||
// look for it in the customized configuration.
|
||||
if aliasCfg == nil {
|
||||
aliasCfg = aliasToConfigMap[alias]
|
||||
}
|
||||
|
||||
if aliasCfg == nil {
|
||||
aliasCfg, _ = getAliasConfig(alias)
|
||||
}
|
||||
return aliasCfg
|
||||
}
|
||||
|
||||
@@ -244,9 +248,12 @@ func parseEnvURLStr(envURL string) (*url.URL, string, string, string, *probe.Err
|
||||
return nil, "", "", "", probe.NewError(e)
|
||||
}
|
||||
// Look for if URL has invalid values and return error.
|
||||
if !((u.Scheme == "http" || u.Scheme == "https") &&
|
||||
(u.Path == "/" || u.Path == "") && u.Opaque == "" &&
|
||||
!u.ForceQuery && u.RawQuery == "" && u.Fragment == "") {
|
||||
if (u.Scheme != "http" && u.Scheme != "https") ||
|
||||
(u.Path != "/" && u.Path != "") ||
|
||||
u.Opaque != "" ||
|
||||
u.ForceQuery ||
|
||||
u.RawQuery != "" ||
|
||||
u.Fragment != "" {
|
||||
return nil, "", "", "", errInvalidArgument().Trace(u.String())
|
||||
}
|
||||
if accessKey == "" && secretKey == "" {
|
||||
@@ -286,6 +293,7 @@ func readAliasesFromFile(envConfigFile string) *probe.Error {
|
||||
if err != nil {
|
||||
return err.Trace(envLine)
|
||||
}
|
||||
aliasConfig.Src = envConfigFile
|
||||
aliasToConfigMap[alias] = aliasConfig
|
||||
}
|
||||
if e := scanner.Err(); e != nil {
|
||||
@@ -306,6 +314,7 @@ func expandAliasFromEnv(envURL string) (*aliasConfigV10, *probe.Error) {
|
||||
AccessKey: accessKey,
|
||||
SecretKey: secretKey,
|
||||
SessionToken: sessionToken,
|
||||
Src: "env",
|
||||
}, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
// Copyright (c) 2015-2024 MinIO, Inc.
|
||||
//
|
||||
// This file is part of MinIO Object Storage stack
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/pkg/v3/console"
|
||||
)
|
||||
|
||||
var corsGetCmd = cli.Command{
|
||||
Name: "get",
|
||||
Usage: "get a bucket CORS configuration",
|
||||
Action: mainCorsGet,
|
||||
OnUsageError: onUsageError,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
{{.HelpName}} ALIAS/BUCKET
|
||||
|
||||
FLAGS:
|
||||
{{range .VisibleFlags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
1. Get the CORS configuration for the bucket 'mybucket':
|
||||
{{.Prompt}} {{.HelpName}} myminio/mybucket
|
||||
`,
|
||||
}
|
||||
|
||||
// checkCorsGetSyntax - validate all the passed arguments
|
||||
func checkCorsGetSyntax(ctx *cli.Context) {
|
||||
if len(ctx.Args()) != 1 {
|
||||
showCommandHelpAndExit(ctx, 1) // last argument is exit code
|
||||
}
|
||||
}
|
||||
|
||||
// mainCorsGet is the handle for "mc cors get" command.
|
||||
func mainCorsGet(ctx *cli.Context) error {
|
||||
checkCorsGetSyntax(ctx)
|
||||
|
||||
console.SetColor("CorsMessage", color.New(color.FgGreen))
|
||||
console.SetColor("CorsNotFound", color.New(color.FgYellow))
|
||||
|
||||
// args[0] is the ALIAS/BUCKET argument.
|
||||
args := ctx.Args()
|
||||
urlStr := args.Get(0)
|
||||
|
||||
client, err := newClient(urlStr)
|
||||
fatalIf(err.Trace(urlStr), "Unable to initialize client for "+urlStr)
|
||||
|
||||
corsCfg, err := client.GetBucketCors(globalContext)
|
||||
fatalIf(err.Trace(urlStr), "Unable to get bucket CORS configuration for "+urlStr)
|
||||
|
||||
status := "success"
|
||||
if corsCfg == nil {
|
||||
status = "not found"
|
||||
}
|
||||
|
||||
printMsg(corsMessage{
|
||||
op: "get",
|
||||
Status: status,
|
||||
CorsCfg: corsCfg,
|
||||
})
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
// Copyright (c) 2015-2024 MinIO, Inc.
|
||||
//
|
||||
// This file is part of MinIO Object Storage stack
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package cmd
|
||||
|
||||
import "github.com/minio/cli"
|
||||
|
||||
var corsSubcommands = []cli.Command{
|
||||
corsSetCmd,
|
||||
corsGetCmd,
|
||||
corsRemoveCmd,
|
||||
}
|
||||
|
||||
var corsCmd = cli.Command{
|
||||
Name: "cors",
|
||||
Usage: "manage bucket CORS configuration",
|
||||
Action: mainCors,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
Subcommands: corsSubcommands,
|
||||
}
|
||||
|
||||
func mainCors(ctx *cli.Context) error {
|
||||
commandNotFound(ctx, corsSubcommands)
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
// Copyright (c) 2015-2024 MinIO, Inc.
|
||||
//
|
||||
// This file is part of MinIO Object Storage stack
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/pkg/v3/console"
|
||||
)
|
||||
|
||||
var corsRemoveCmd = cli.Command{
|
||||
Name: "remove",
|
||||
Usage: "remove a bucket CORS configuration",
|
||||
Action: mainCorsRemove,
|
||||
OnUsageError: onUsageError,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
{{.HelpName}} ALIAS/BUCKET
|
||||
|
||||
FLAGS:
|
||||
{{range .VisibleFlags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
1. Remove the CORS configuration for the bucket 'mybucket':
|
||||
{{.Prompt}} {{.HelpName}} myminio/mybucket
|
||||
`,
|
||||
}
|
||||
|
||||
// checkCorsRemoveSyntax - validate all the passed arguments
|
||||
func checkCorsRemoveSyntax(ctx *cli.Context) {
|
||||
if len(ctx.Args()) != 1 {
|
||||
showCommandHelpAndExit(ctx, 1) // last argument is exit code
|
||||
}
|
||||
}
|
||||
|
||||
// mainCorsRemove is the handle for "mc cors remove" command.
|
||||
func mainCorsRemove(ctx *cli.Context) error {
|
||||
checkCorsRemoveSyntax(ctx)
|
||||
|
||||
console.SetColor("CorsMessage", color.New(color.FgGreen))
|
||||
|
||||
// args[0] is the ALIAS/BUCKET argument.
|
||||
args := ctx.Args()
|
||||
urlStr := args.Get(0)
|
||||
|
||||
client, err := newClient(urlStr)
|
||||
fatalIf(err.Trace(urlStr), "Unable to initialize client for "+urlStr)
|
||||
|
||||
err = client.DeleteBucketCors(globalContext)
|
||||
fatalIf(err.Trace(urlStr), "Unable to remove bucket CORS configuration for "+urlStr)
|
||||
|
||||
printMsg(corsMessage{
|
||||
op: "remove",
|
||||
Status: "success",
|
||||
})
|
||||
|
||||
return nil
|
||||
}
|
||||
+131
@@ -0,0 +1,131 @@
|
||||
// Copyright (c) 2015-2024 MinIO, Inc.
|
||||
//
|
||||
// This file is part of MinIO Object Storage stack
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"io"
|
||||
"os"
|
||||
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/cli"
|
||||
json "github.com/minio/colorjson"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/minio-go/v7/pkg/cors"
|
||||
"github.com/minio/pkg/v3/console"
|
||||
)
|
||||
|
||||
var corsSetCmd = cli.Command{
|
||||
Name: "set",
|
||||
Usage: "set a bucket CORS configuration",
|
||||
Action: mainCorsSet,
|
||||
OnUsageError: onUsageError,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
{{.HelpName}} ALIAS/BUCKET CORSFILE
|
||||
|
||||
CORSFILE:
|
||||
Path to the XML file containing the CORS configuration.
|
||||
|
||||
FLAGS:
|
||||
{{range .VisibleFlags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
1. Set the CORS configuration for the bucket 'mybucket':
|
||||
{{.Prompt}} {{.HelpName}} myminio/mybucket /path/to/cors.xml
|
||||
|
||||
2. Set the CORS configuration for the bucket 'mybucket' using stdin:
|
||||
{{.Prompt}} {{.HelpName}} myminio/mybucket -
|
||||
`,
|
||||
}
|
||||
|
||||
// corsMessage container for output message.
|
||||
type corsMessage struct {
|
||||
op string
|
||||
Status string `json:"status"`
|
||||
Message string `json:"message,omitempty"`
|
||||
CorsCfg *cors.Config `json:"cors,omitempty"`
|
||||
}
|
||||
|
||||
func (c corsMessage) String() string {
|
||||
switch c.op {
|
||||
case "get":
|
||||
if c.CorsCfg == nil {
|
||||
return console.Colorize("CorsNotFound", "No bucket CORS configuration found.")
|
||||
}
|
||||
corsXML, e := c.CorsCfg.ToXML()
|
||||
fatalIf(probe.NewError(e), "Unable to marshal to XML.")
|
||||
return string(corsXML)
|
||||
case "set":
|
||||
return console.Colorize("CorsMessage", "Set bucket CORS config successfully.")
|
||||
case "remove":
|
||||
return console.Colorize("CorsMessage", "Removed bucket CORS config successfully.")
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (c corsMessage) JSON() string {
|
||||
jsonBytes, e := json.MarshalIndent(&c, "", " ")
|
||||
fatalIf(probe.NewError(e), "Unable to marshal to JSON.")
|
||||
|
||||
return string(jsonBytes)
|
||||
}
|
||||
|
||||
// checkCorsSetSyntax - validate all the passed arguments
|
||||
func checkCorsSetSyntax(ctx *cli.Context) {
|
||||
if len(ctx.Args()) != 2 {
|
||||
showCommandHelpAndExit(ctx, 1) // last argument is exit code
|
||||
}
|
||||
}
|
||||
|
||||
// mainCorsSet is the handle for "mc cors set" command.
|
||||
func mainCorsSet(ctx *cli.Context) error {
|
||||
checkCorsSetSyntax(ctx)
|
||||
|
||||
console.SetColor("CorsMessage", color.New(color.FgGreen))
|
||||
|
||||
// args[0] is the ALIAS/BUCKET argument.
|
||||
args := ctx.Args()
|
||||
urlStr := args.Get(0)
|
||||
|
||||
// args[1] is the CORSFILE which is a local file, or in the case of "-", stdin.
|
||||
var e error
|
||||
in := os.Stdin
|
||||
if f := args.Get(1); f != "-" {
|
||||
in, e = os.Open(f)
|
||||
fatalIf(probe.NewError(e).Trace(args...), "Unable to open bucket CORS configuration file.")
|
||||
defer in.Close()
|
||||
}
|
||||
corsXML, e := io.ReadAll(in)
|
||||
fatalIf(probe.NewError(e).Trace(args...), "Unable to read bucket CORS configuration file.")
|
||||
|
||||
client, err := newClient(urlStr)
|
||||
fatalIf(err.Trace(urlStr), "Unable to initialize client for "+urlStr)
|
||||
|
||||
fatalIf(client.SetBucketCors(globalContext, corsXML), "Unable to set bucket CORS configuration for "+urlStr)
|
||||
|
||||
printMsg(corsMessage{
|
||||
op: "set",
|
||||
Status: "success",
|
||||
})
|
||||
|
||||
return nil
|
||||
}
|
||||
+28
-17
@@ -22,6 +22,7 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"maps"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
@@ -29,6 +30,7 @@ import (
|
||||
"github.com/minio/cli"
|
||||
json "github.com/minio/colorjson"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/minio-go/v7"
|
||||
"github.com/minio/pkg/v3/console"
|
||||
)
|
||||
|
||||
@@ -72,8 +74,9 @@ var (
|
||||
Usage: "disable multipart upload feature",
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "md5",
|
||||
Usage: "force all upload(s) to calculate md5sum checksum",
|
||||
Name: "md5",
|
||||
Usage: "force all upload(s) to calculate md5sum checksum",
|
||||
Hidden: true,
|
||||
},
|
||||
cli.StringFlag{
|
||||
Name: "tags",
|
||||
@@ -95,6 +98,11 @@ var (
|
||||
Name: "zip",
|
||||
Usage: "Extract from remote zip file (MinIO server source only)",
|
||||
},
|
||||
cli.IntFlag{
|
||||
Name: "max-workers",
|
||||
Usage: "maximum number of concurrent copies (default: autodetect)",
|
||||
},
|
||||
checksumFlag,
|
||||
}
|
||||
)
|
||||
|
||||
@@ -155,7 +163,7 @@ EXAMPLES:
|
||||
{{.Prompt}} {{.HelpName}} --recursive 'workdir/documents/May 2014/' s3/miniocloud
|
||||
|
||||
09. Copy a folder with encrypted objects recursively from Amazon S3 to MinIO cloud storage using s3 encryption.
|
||||
{{.Prompt}} {{.HelpName}} --recursive --enc-s3 "s3/documents/=my-aws-key" --enc-s3 "myminio/documents/=my-minio-key" s3/documents/ myminio/documents/
|
||||
{{.Prompt}} {{.HelpName}} --recursive --enc-s3 "s3/documents" --enc-s3 "myminio/documents" s3/documents/ myminio/documents/
|
||||
|
||||
10. Copy a folder with encrypted objects recursively from Amazon S3 to MinIO cloud storage.
|
||||
{{.Prompt}} {{.HelpName}} --recursive --enc-c "s3/documents/=MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTIzNDU2Nzg5MDA" --enc-c "myminio/documents/=MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTIzNDU2Nzg5BBB" s3/documents/ myminio/documents/
|
||||
@@ -276,7 +284,7 @@ func doCopy(ctx context.Context, copyOpts doCopyOpts) URLs {
|
||||
// doCopyFake - Perform a fake copy to update the progress bar appropriately.
|
||||
func doCopyFake(cpURLs URLs, pg Progress) URLs {
|
||||
if progressReader, ok := pg.(*progressBar); ok {
|
||||
progressReader.ProgressBar.Add64(cpURLs.SourceContent.Size)
|
||||
progressReader.Add64(cpURLs.SourceContent.Size)
|
||||
}
|
||||
|
||||
return cpURLs
|
||||
@@ -315,7 +323,6 @@ func doCopySession(ctx context.Context, cancelCopy context.CancelFunc, cli *cli.
|
||||
} else {
|
||||
pg = newAccounter(totalBytes)
|
||||
}
|
||||
|
||||
sourceURLs := cli.Args()[:len(cli.Args())-1]
|
||||
targetURL := cli.Args()[len(cli.Args())-1] // Last one is target
|
||||
|
||||
@@ -327,6 +334,11 @@ func doCopySession(ctx context.Context, cancelCopy context.CancelFunc, cli *cli.
|
||||
newerThan := cli.String("newer-than")
|
||||
rewind := cli.String("rewind")
|
||||
versionID := cli.String("version-id")
|
||||
md5, checksum := parseChecksum(cli)
|
||||
if withLock {
|
||||
// The Content-MD5 header is required for any request to upload an object with a retention period configured using Amazon S3 Object Lock.
|
||||
md5, checksum = true, minio.ChecksumNone
|
||||
}
|
||||
|
||||
go func() {
|
||||
totalBytes := int64(0)
|
||||
@@ -359,7 +371,7 @@ func doCopySession(ctx context.Context, cancelCopy context.CancelFunc, cli *cli.
|
||||
|
||||
quitCh := make(chan struct{})
|
||||
statusCh := make(chan URLs)
|
||||
parallel := newParallelManager(statusCh)
|
||||
parallel := newParallelManager(statusCh, cli.Int("max-workers"))
|
||||
|
||||
go func() {
|
||||
gracefulStop := func() {
|
||||
@@ -415,12 +427,11 @@ func doCopySession(ctx context.Context, cancelCopy context.CancelFunc, cli *cli.
|
||||
isZip := cli.Bool("zip")
|
||||
if cli.String("attr") != "" {
|
||||
userMetaMap, _ := getMetaDataEntry(cli.String("attr"))
|
||||
for metadataKey, metaDataVal := range userMetaMap {
|
||||
cpURLs.TargetContent.UserMetadata[metadataKey] = metaDataVal
|
||||
}
|
||||
maps.Copy(cpURLs.TargetContent.UserMetadata, userMetaMap)
|
||||
}
|
||||
|
||||
cpURLs.MD5 = cli.Bool("md5") || withLock
|
||||
cpURLs.MD5 = md5
|
||||
cpURLs.checksum = checksum
|
||||
cpURLs.DisableMultipart = cli.Bool("disable-multipart")
|
||||
|
||||
// Verify if previously copied, notify progress bar.
|
||||
@@ -477,7 +488,7 @@ loop:
|
||||
console.Eraseline()
|
||||
}
|
||||
errorIf(cpURLs.Error.Trace(cpURLs.SourceContent.URL.String()),
|
||||
fmt.Sprintf("Failed to copy `%s`.", cpURLs.SourceContent.URL.String()))
|
||||
"Failed to copy `%s`.", cpURLs.SourceContent.URL)
|
||||
if isErrIgnored(cpURLs.Error) {
|
||||
cpAllFilesErr = false
|
||||
continue loop
|
||||
@@ -485,13 +496,13 @@ loop:
|
||||
|
||||
errSeen = true
|
||||
if progressReader, pgok := pg.(*progressBar); pgok {
|
||||
if progressReader.ProgressBar.Get() > 0 {
|
||||
if progressReader.Get() > 0 {
|
||||
writeContSize := (int)(cpURLs.SourceContent.Size)
|
||||
totalPGSize := (int)(progressReader.ProgressBar.Total)
|
||||
written := (int)(progressReader.ProgressBar.Get())
|
||||
totalPGSize := (int)(progressReader.Total)
|
||||
written := (int)(progressReader.Get())
|
||||
if totalPGSize > writeContSize && written > writeContSize {
|
||||
progressReader.ProgressBar.Set((written - writeContSize))
|
||||
progressReader.ProgressBar.Update()
|
||||
progressReader.Set((written - writeContSize))
|
||||
progressReader.Update()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -506,7 +517,7 @@ loop:
|
||||
if !globalQuiet && !globalJSON {
|
||||
console.Eraseline()
|
||||
}
|
||||
} else if progressReader.ProgressBar.Get() > 0 {
|
||||
} else if progressReader.Get() > 0 {
|
||||
progressReader.Finish()
|
||||
}
|
||||
} else {
|
||||
|
||||
+14
-11
@@ -48,11 +48,12 @@ func getMetaDataEntry(metadataString string) (map[string]string, *probe.Error) {
|
||||
var key, value strings.Builder
|
||||
|
||||
writeRune := func(ch rune, pt pToken) {
|
||||
if pt == KEY {
|
||||
switch pt {
|
||||
case KEY:
|
||||
key.WriteRune(ch)
|
||||
} else if pt == VALUE {
|
||||
case VALUE:
|
||||
value.WriteRune(ch)
|
||||
} else {
|
||||
default:
|
||||
panic("Invalid parser token type")
|
||||
}
|
||||
}
|
||||
@@ -73,26 +74,28 @@ func getMetaDataEntry(metadataString string) (map[string]string, *probe.Error) {
|
||||
}
|
||||
|
||||
if ch == '"' {
|
||||
if ps == DQSTRING {
|
||||
switch ps {
|
||||
case DQSTRING:
|
||||
ps = NORMAL
|
||||
} else if ps == QSTRING {
|
||||
case QSTRING:
|
||||
writeRune(ch, pt)
|
||||
} else if ps == NORMAL {
|
||||
case NORMAL:
|
||||
ps = DQSTRING
|
||||
} else {
|
||||
default:
|
||||
break
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
if ch == '\'' {
|
||||
if ps == QSTRING {
|
||||
switch ps {
|
||||
case QSTRING:
|
||||
ps = NORMAL
|
||||
} else if ps == DQSTRING {
|
||||
case DQSTRING:
|
||||
writeRune(ch, pt)
|
||||
} else if ps == NORMAL {
|
||||
case NORMAL:
|
||||
ps = QSTRING
|
||||
} else {
|
||||
default:
|
||||
break
|
||||
}
|
||||
continue
|
||||
|
||||
@@ -28,6 +28,7 @@ func checkCopySyntax(cliCtx *cli.Context) {
|
||||
if len(cliCtx.Args()) < 2 {
|
||||
showCommandHelpAndExit(cliCtx, 1) // last argument is exit code.
|
||||
}
|
||||
parseChecksum(cliCtx)
|
||||
|
||||
// extract URLs.
|
||||
URLs := cliCtx.Args()
|
||||
|
||||
+1
-1
@@ -336,7 +336,7 @@ func prepareCopyURLs(ctx context.Context, o prepareCopyURLsOpts) chan URLs {
|
||||
defer close(copyURLsCh)
|
||||
copyURLsContent, err := guessCopyURLType(ctx, o)
|
||||
if err != nil {
|
||||
copyURLsCh <- URLs{Error: errUnableToGuess().Trace(o.sourceURLs...)}
|
||||
copyURLsCh <- URLs{Error: errUnableToGuess(err.Cause.Error()).Trace(o.sourceURLs...)}
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -184,7 +184,7 @@ func doDiffMain(ctx context.Context, firstURL, secondURL string) error {
|
||||
}
|
||||
|
||||
// Diff first and second urls.
|
||||
for diffMsg := range objectDifference(ctx, firstClient, secondClient, true) {
|
||||
for diffMsg := range bucketObjectDifference(ctx, firstClient, secondClient) {
|
||||
if diffMsg.Error != nil {
|
||||
errorIf(diffMsg.Error, "Unable to calculate objects difference.")
|
||||
// Ignore error and proceed to next object.
|
||||
|
||||
+34
-17
@@ -161,17 +161,23 @@ func metadataEqual(m1, m2 map[string]string) bool {
|
||||
return true
|
||||
}
|
||||
|
||||
func objectDifference(ctx context.Context, sourceClnt, targetClnt Client, isMetadata bool) (diffCh chan diffMessage) {
|
||||
sourceURL := sourceClnt.GetURL().String()
|
||||
sourceCh := sourceClnt.List(ctx, ListOptions{Recursive: true, WithMetadata: isMetadata, ShowDir: DirNone})
|
||||
|
||||
targetURL := targetClnt.GetURL().String()
|
||||
targetCh := targetClnt.List(ctx, ListOptions{Recursive: true, WithMetadata: isMetadata, ShowDir: DirNone})
|
||||
|
||||
return difference(sourceURL, sourceCh, targetURL, targetCh, isMetadata, false)
|
||||
func bucketObjectDifference(ctx context.Context, sourceClnt, targetClnt Client) (diffCh chan diffMessage) {
|
||||
return objectDifference(ctx, sourceClnt, targetClnt, mirrorOptions{
|
||||
isMetadata: false,
|
||||
})
|
||||
}
|
||||
|
||||
func bucketDifference(ctx context.Context, sourceClnt, targetClnt Client) (diffCh chan diffMessage) {
|
||||
func objectDifference(ctx context.Context, sourceClnt, targetClnt Client, opts mirrorOptions) (diffCh chan diffMessage) {
|
||||
sourceURL := sourceClnt.GetURL().String()
|
||||
sourceCh := sourceClnt.List(ctx, ListOptions{Recursive: true, WithMetadata: opts.isMetadata, ShowDir: DirNone})
|
||||
|
||||
targetURL := targetClnt.GetURL().String()
|
||||
targetCh := targetClnt.List(ctx, ListOptions{Recursive: true, WithMetadata: opts.isMetadata, ShowDir: DirNone})
|
||||
|
||||
return difference(sourceURL, sourceCh, targetURL, targetCh, opts, false)
|
||||
}
|
||||
|
||||
func bucketDifference(ctx context.Context, sourceClnt, targetClnt Client, opts mirrorOptions) (diffCh chan diffMessage) {
|
||||
sourceURL := sourceClnt.GetURL().String()
|
||||
sourceCh := make(chan *ClientContent)
|
||||
|
||||
@@ -215,11 +221,16 @@ func bucketDifference(ctx context.Context, sourceClnt, targetClnt Client) (diffC
|
||||
}
|
||||
}()
|
||||
|
||||
return difference(sourceURL, sourceCh, targetURL, targetCh, false, false)
|
||||
return difference(sourceURL, sourceCh, targetURL, targetCh, opts, false)
|
||||
}
|
||||
|
||||
func differenceInternal(sourceURL string, srcCh <-chan *ClientContent, targetURL string, tgtCh <-chan *ClientContent,
|
||||
cmpMetadata, returnSimilar bool, diffCh chan<- diffMessage,
|
||||
func differenceInternal(sourceURL string,
|
||||
srcCh <-chan *ClientContent,
|
||||
targetURL string,
|
||||
tgtCh <-chan *ClientContent,
|
||||
opts mirrorOptions,
|
||||
returnSimilar bool,
|
||||
diffCh chan<- diffMessage,
|
||||
) *probe.Error {
|
||||
// Pop first entries from the source and targets
|
||||
srcCtnt, srcOk := <-srcCh
|
||||
@@ -232,8 +243,14 @@ func differenceInternal(sourceURL string, srcCh <-chan *ClientContent, targetURL
|
||||
tgtEOF = !tgtOk
|
||||
|
||||
// No objects from source AND target: Finish
|
||||
if srcEOF && tgtEOF {
|
||||
break
|
||||
if opts.sourceListingOnly {
|
||||
if srcEOF {
|
||||
break
|
||||
}
|
||||
} else {
|
||||
if srcEOF && tgtEOF {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if !srcEOF && srcCtnt.Err != nil {
|
||||
@@ -332,7 +349,7 @@ func differenceInternal(sourceURL string, srcCh <-chan *ClientContent, targetURL
|
||||
firstContent: srcCtnt,
|
||||
secondContent: tgtCtnt,
|
||||
}
|
||||
} else if cmpMetadata &&
|
||||
} else if opts.isMetadata &&
|
||||
!metadataEqual(srcCtnt.UserMetadata, tgtCtnt.UserMetadata) &&
|
||||
!metadataEqual(srcCtnt.Metadata, tgtCtnt.Metadata) {
|
||||
|
||||
@@ -375,13 +392,13 @@ func differenceInternal(sourceURL string, srcCh <-chan *ClientContent, targetURL
|
||||
|
||||
// objectDifference function finds the difference between all objects
|
||||
// recursively in sorted order from source and target.
|
||||
func difference(sourceURL string, sourceCh <-chan *ClientContent, targetURL string, targetCh <-chan *ClientContent, cmpMetadata, returnSimilar bool) (diffCh chan diffMessage) {
|
||||
func difference(sourceURL string, sourceCh <-chan *ClientContent, targetURL string, targetCh <-chan *ClientContent, opts mirrorOptions, returnSimilar bool) (diffCh chan diffMessage) {
|
||||
diffCh = make(chan diffMessage, 10000)
|
||||
|
||||
go func() {
|
||||
defer close(diffCh)
|
||||
|
||||
err := differenceInternal(sourceURL, sourceCh, targetURL, targetCh, cmpMetadata, returnSimilar, diffCh)
|
||||
err := differenceInternal(sourceURL, sourceCh, targetURL, targetCh, opts, returnSimilar, diffCh)
|
||||
if err != nil {
|
||||
// handle this specifically for filesystem related errors.
|
||||
switch v := err.ToGoError().(type) {
|
||||
|
||||
+2
-2
@@ -128,7 +128,7 @@ func du(ctx context.Context, urlStr string, timeRef time.Time, withVersions bool
|
||||
|
||||
clnt, pErr := newClientFromAlias(targetAlias, targetURL)
|
||||
if pErr != nil {
|
||||
errorIf(pErr.Trace(urlStr), "Failed to summarize disk usage `"+urlStr+"`.")
|
||||
errorIf(pErr.Trace(urlStr), "Failed to summarize disk usage `%s`.", urlStr)
|
||||
return 0, 0, exitStatus(globalErrorExitStatus) // End of journey.
|
||||
}
|
||||
|
||||
@@ -156,7 +156,7 @@ func du(ctx context.Context, urlStr string, timeRef time.Time, withVersions bool
|
||||
errorIf(content.Err.Trace(clnt.GetURL().String()), "Unable to list folder.")
|
||||
continue
|
||||
}
|
||||
errorIf(content.Err.Trace(urlStr), "Failed to find disk usage of `"+urlStr+"` recursively.")
|
||||
errorIf(content.Err.Trace(urlStr), "Failed to find disk usage of `%s` recursively.", urlStr)
|
||||
return 0, 0, exitStatus(globalErrorExitStatus)
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -125,7 +125,7 @@ func ParseDuration(s string) (Duration, error) {
|
||||
var err error
|
||||
|
||||
// The next character must be [0-9.]
|
||||
if !(s[0] == '.' || '0' <= s[0] && s[0] <= '9') {
|
||||
if s[0] != '.' && ('0' > s[0] || s[0] > '9') {
|
||||
return 0, errors.New("invalid duration " + orig)
|
||||
}
|
||||
// Consume [0-9]*
|
||||
|
||||
@@ -22,6 +22,7 @@ import (
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
@@ -60,6 +61,7 @@ func (p byPrefixLength) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
|
||||
|
||||
// get SSE Key if object prefix matches with given resource.
|
||||
func getSSE(resource string, encKeys []prefixSSEPair) encrypt.ServerSide {
|
||||
resource = filepath.ToSlash(resource)
|
||||
for _, k := range encKeys {
|
||||
if strings.HasPrefix(resource, k.Prefix) {
|
||||
return k.SSE
|
||||
@@ -168,7 +170,7 @@ func validateAndParseKey(ctx *cli.Context, key string, keyType sseKeyType) (SSEP
|
||||
}
|
||||
|
||||
func validateOverLappingSSEKeys(keyMap []prefixSSEPair) (err *probe.Error) {
|
||||
for i := 0; i < len(keyMap); i++ {
|
||||
for i := range keyMap {
|
||||
for j := i + 1; j < len(keyMap); j++ {
|
||||
if strings.HasPrefix(keyMap[i].Prefix, keyMap[j].Prefix) ||
|
||||
strings.HasPrefix(keyMap[j].Prefix, keyMap[i].Prefix) {
|
||||
|
||||
+3
-3
@@ -46,14 +46,14 @@ type errorMessage struct {
|
||||
}
|
||||
|
||||
// fatalIf wrapper function which takes error and selectively prints stack frames if available on debug
|
||||
func fatalIf(err *probe.Error, msg string, data ...interface{}) {
|
||||
func fatalIf(err *probe.Error, msg string, data ...any) {
|
||||
if err == nil {
|
||||
return
|
||||
}
|
||||
fatal(err, msg, data...)
|
||||
}
|
||||
|
||||
func fatal(err *probe.Error, msg string, data ...interface{}) {
|
||||
func fatal(err *probe.Error, msg string, data ...any) {
|
||||
if globalJSON {
|
||||
errorMsg := errorMessage{
|
||||
Message: msg,
|
||||
@@ -128,7 +128,7 @@ func exitStatus(status int) error {
|
||||
}
|
||||
|
||||
// errorIf synonymous with fatalIf but doesn't exit on error != nil
|
||||
func errorIf(err *probe.Error, msg string, data ...interface{}) {
|
||||
func errorIf(err *probe.Error, msg string, data ...any) {
|
||||
if err == nil {
|
||||
return
|
||||
}
|
||||
|
||||
+10
-7
@@ -36,6 +36,7 @@ import (
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/pkg/v3/console"
|
||||
"golang.org/x/text/unicode/norm"
|
||||
|
||||
// golang does not support flat keys for path matching, find does
|
||||
"github.com/minio/pkg/v3/wildcard"
|
||||
@@ -49,9 +50,9 @@ type findMessage struct {
|
||||
// String calls tells the console what to print and how to print it.
|
||||
func (f findMessage) String() string {
|
||||
var msg string
|
||||
msg += f.contentMessage.Key
|
||||
msg += f.Key
|
||||
if f.VersionID != "" {
|
||||
msg += " (" + f.contentMessage.VersionID + ")"
|
||||
msg += " (" + f.VersionID + ")"
|
||||
}
|
||||
return console.Colorize("Find", msg)
|
||||
}
|
||||
@@ -117,7 +118,7 @@ func getExitStatus(err error) int {
|
||||
return 0
|
||||
}
|
||||
if pe, ok := err.(*exec.ExitError); ok {
|
||||
if es, ok := pe.ProcessState.Sys().(syscall.WaitStatus); ok {
|
||||
if es, ok := pe.Sys().(syscall.WaitStatus); ok {
|
||||
return es.ExitStatus()
|
||||
}
|
||||
}
|
||||
@@ -273,7 +274,7 @@ func doFind(ctxCtx context.Context, ctx *findContext) error {
|
||||
|
||||
lstOptions := ListOptions{
|
||||
WithOlderVersions: ctx.withVersions,
|
||||
WithDeleteMarkers: false,
|
||||
WithDeleteMarkers: ctx.withVersions,
|
||||
Recursive: true,
|
||||
ShowDir: DirFirst,
|
||||
WithMetadata: len(ctx.matchMeta) > 0 || len(ctx.matchTags) > 0,
|
||||
@@ -486,8 +487,10 @@ func getRegexMap(cliCtx *cli.Context, key string) map[string]*regexp.Regexp {
|
||||
reMap[split[0]] = nil
|
||||
continue
|
||||
}
|
||||
// Normalize character encoding.
|
||||
norm := norm.NFC.String(split[1])
|
||||
var err error
|
||||
reMap[split[0]], err = regexp.Compile(split[1])
|
||||
reMap[split[0]], err = regexp.Compile(norm)
|
||||
if err != nil {
|
||||
fatalIf(probe.NewError(err), fmt.Sprintf("Unable to compile metadata regex for %s=%s", split[0], split[1]))
|
||||
}
|
||||
@@ -507,7 +510,7 @@ func matchRegexMaps(m map[string]*regexp.Regexp, v map[string]string) bool {
|
||||
continue
|
||||
}
|
||||
val, ok := v[k]
|
||||
if !ok || !reg.MatchString(val) {
|
||||
if !ok || !reg.MatchString(norm.NFC.String(val)) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
@@ -529,7 +532,7 @@ func matchMetadataRegexMaps(m map[string]*regexp.Regexp, v map[string]string) bo
|
||||
if !ok {
|
||||
val, ok = v[http.CanonicalHeaderKey(fmt.Sprintf("X-Amz-Meta-%s", k))]
|
||||
}
|
||||
if !ok || !reg.MatchString(val) {
|
||||
if !ok || !reg.MatchString(norm.NFC.String(val)) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
@@ -18,9 +18,14 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/minio-go/v7"
|
||||
)
|
||||
|
||||
const envPrefix = "MC_"
|
||||
@@ -59,6 +64,11 @@ var globalFlags = []cli.Flag{
|
||||
Usage: "enable debug output",
|
||||
EnvVar: envPrefix + "DEBUG",
|
||||
},
|
||||
cli.StringSliceFlag{
|
||||
Name: "resolve",
|
||||
Usage: "resolves HOST[:PORT] to an IP address. Example: minio.local:9000=10.10.75.1",
|
||||
EnvVar: envPrefix + "RESOLVE",
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "insecure",
|
||||
Usage: "disable SSL certificate verification",
|
||||
@@ -86,6 +96,10 @@ var globalFlags = []cli.Flag{
|
||||
Hidden: true,
|
||||
Value: 10 * time.Minute,
|
||||
},
|
||||
cli.StringSliceFlag{
|
||||
Name: "custom-header,H",
|
||||
Usage: "add custom HTTP header to the request. 'key:value' format.",
|
||||
},
|
||||
}
|
||||
|
||||
// bundled encryption flags
|
||||
@@ -111,3 +125,44 @@ var encS3Flag = cli.StringSliceFlag{
|
||||
Usage: "encrypt/decrypt objects using server-side default keys and configurations. (multiple keys can be provided).",
|
||||
EnvVar: envPrefix + "ENC_S3",
|
||||
}
|
||||
|
||||
var checksumFlag = cli.StringFlag{
|
||||
Name: "checksum",
|
||||
Usage: "Add checksum to uploaded object. Values: CRC64NVME, CRC32, CRC32C, SHA1 or SHA256. Requires server trailing headers (AWS, MinIO)",
|
||||
Value: "",
|
||||
}
|
||||
|
||||
func parseChecksum(ctx *cli.Context) (useMD5 bool, ct minio.ChecksumType) {
|
||||
useMD5 = ctx.Bool("md5")
|
||||
if cs := ctx.String("checksum"); cs != "" {
|
||||
switch strings.ToUpper(cs) {
|
||||
case "CRC32":
|
||||
ct = minio.ChecksumCRC32
|
||||
case "CRC32C":
|
||||
ct = minio.ChecksumCRC32C
|
||||
case "CRC32-FO":
|
||||
ct = minio.ChecksumFullObjectCRC32
|
||||
case "CRC32C-FO":
|
||||
ct = minio.ChecksumFullObjectCRC32C
|
||||
case "SHA1":
|
||||
ct = minio.ChecksumSHA1
|
||||
case "SHA256":
|
||||
ct = minio.ChecksumSHA256
|
||||
case "CRC64N", "CRC64NVME":
|
||||
ct = minio.ChecksumCRC64NVME
|
||||
case "MD5":
|
||||
useMD5 = true
|
||||
default:
|
||||
err := fmt.Errorf("unknown checksum type: %s. Should be one of CRC64NVME, MD5, CRC32, CRC32C, SHA1 or SHA256", cs)
|
||||
fatalIf(probe.NewError(err), "")
|
||||
}
|
||||
if ct.IsSet() {
|
||||
useTrailingHeaders.Store(true)
|
||||
if useMD5 {
|
||||
err := errors.New("cannot combine MD5 with checksum")
|
||||
fatalIf(probe.NewError(err), "")
|
||||
}
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
//go:build !windows
|
||||
// +build !windows
|
||||
|
||||
// Copyright (c) 2015-2021 MinIO, Inc.
|
||||
//
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user