Compare commits
88
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 |
@@ -20,7 +20,7 @@ jobs:
|
||||
runs-on: ${{ matrix.os }}
|
||||
strategy:
|
||||
matrix:
|
||||
go-version: [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,7 +16,7 @@ jobs:
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: 1.22.5
|
||||
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$
|
||||
|
||||
@@ -1,24 +0,0 @@
|
||||
FROM 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"]
|
||||
@@ -2,14 +2,13 @@ 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_DIR = .bin/golangci/$(GOLANGCI_VERSION)
|
||||
GOLANGCI = $(GOLANGCI_DIR)/golangci-lint
|
||||
GOLANGCI = $(GOPATH)/bin/golangci-lint
|
||||
|
||||
all: build
|
||||
|
||||
@@ -19,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 $(GOLANGCI_DIR)
|
||||
@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)
|
||||
@@ -64,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 | \
|
||||
@@ -78,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).
|
||||
|
||||
|
||||
+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
|
||||
}
|
||||
|
||||
@@ -18,7 +18,15 @@
|
||||
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{
|
||||
@@ -45,6 +53,150 @@ EXAMPLES:
|
||||
`,
|
||||
}
|
||||
|
||||
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,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
|
||||
}
|
||||
@@ -27,6 +27,7 @@ var adminAccesskeySubcommands = []cli.Command{
|
||||
adminAccesskeyEditCmd,
|
||||
adminAccesskeyEnableCmd,
|
||||
adminAccesskeyDisableCmd,
|
||||
adminAccesskeySTSRevokeCmd,
|
||||
}
|
||||
|
||||
var adminAccesskeyCmd = cli.Command{
|
||||
|
||||
@@ -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,7 +142,7 @@ 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 {
|
||||
@@ -185,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()
|
||||
}
|
||||
|
||||
|
||||
@@ -125,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
|
||||
|
||||
@@ -207,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)
|
||||
|
||||
@@ -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 {
|
||||
|
||||
+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))
|
||||
|
||||
@@ -107,7 +107,7 @@ func userAttachOrDetachPolicy(ctx *cli.Context, attach bool) error {
|
||||
}
|
||||
|
||||
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)
|
||||
|
||||
@@ -83,13 +83,13 @@ 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) {
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -35,6 +35,7 @@ import (
|
||||
"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"
|
||||
@@ -211,7 +212,15 @@ func mainAdminScannerInfo(ctx *cli.Context) error {
|
||||
}()
|
||||
f, e := os.Open(inFile)
|
||||
fatalIf(probe.NewError(e), "Unable to open input")
|
||||
sc := bufio.NewReader(f)
|
||||
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')
|
||||
@@ -388,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++
|
||||
@@ -433,7 +442,7 @@ func (m *scannerMetricsUI) View() string {
|
||||
if sc.CurrentCycle > 0 {
|
||||
addRowF(title("Current cycle:")+" %s; Started: %v", ui(sc.CurrentCycle), console.Colorize("metrics-date", sc.CurrentStarted))
|
||||
} else {
|
||||
addRowF(title("Current cycle:") + " (between cycles)")
|
||||
addRowF("%s", title("Current cycle:")+" (between cycles)")
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -173,7 +173,7 @@ func (m *serviceRestartUI) View() string {
|
||||
|
||||
func initServiceRestartUI(rowCount int, currentCh chan serviceRestartMessage) *serviceRestartUI {
|
||||
var printColors []*color.Color
|
||||
for i := 0; i < rowCount; i++ {
|
||||
for range rowCount {
|
||||
printColors = append(printColors, getPrintCol(colGreen))
|
||||
}
|
||||
|
||||
@@ -269,6 +269,8 @@ func mainAdminServiceRestart(ctx *cli.Context) error {
|
||||
})
|
||||
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.")
|
||||
|
||||
@@ -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})
|
||||
|
||||
+96
-23
@@ -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,23 +515,78 @@ 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.Bool("all"), ctx.Int("stats-n"), filteredTraces))
|
||||
@@ -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)
|
||||
|
||||
+1
-1
@@ -148,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]`.")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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.
|
||||
@@ -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.")
|
||||
|
||||
+20
-9
@@ -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,
|
||||
@@ -391,16 +400,18 @@ var completeCmds = map[string]complete.Predictor{
|
||||
"/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/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,
|
||||
|
||||
+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
|
||||
}
|
||||
|
||||
+21
-2
@@ -232,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)),
|
||||
@@ -258,6 +258,8 @@ func (m *batchJobMetricsUI) View() string {
|
||||
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.metric.Replicate.BytesTransferred) / accElapsedTime.Seconds()
|
||||
objectsPerSec := float64(int64(time.Second)*m.metric.Replicate.Objects) / float64(accElapsedTime)
|
||||
@@ -271,13 +273,30 @@ func (m *batchJobMetricsUI) View() string {
|
||||
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.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)
|
||||
|
||||
+2
-4
@@ -251,11 +251,9 @@ 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
|
||||
|
||||
+1
-4
@@ -137,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)
|
||||
|
||||
@@ -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)
|
||||
|
||||
+60
-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"
|
||||
|
||||
@@ -301,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.
|
||||
@@ -393,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.
|
||||
@@ -415,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.
|
||||
@@ -581,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
|
||||
}
|
||||
|
||||
@@ -1308,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
|
||||
}
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
+15
-10
@@ -26,6 +26,7 @@ import (
|
||||
"fmt"
|
||||
"hash/fnv"
|
||||
"io"
|
||||
"maps"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
@@ -898,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")
|
||||
|
||||
@@ -933,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 != "" {
|
||||
@@ -1021,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")
|
||||
@@ -1083,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,
|
||||
@@ -1097,6 +1099,7 @@ func (c *S3Client) Put(ctx context.Context, reader io.Reader, size int64, progre
|
||||
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
|
||||
@@ -1659,18 +1662,21 @@ 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
|
||||
if opts.versionID != "" && errors.As(err.ToGoError(), &ObjectMissing{}) || errors.As(err.ToGoError(), &ObjectIsDeleteMarker{}) {
|
||||
// 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})
|
||||
}
|
||||
|
||||
@@ -2251,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)
|
||||
}
|
||||
@@ -2289,6 +2293,7 @@ func (c *S3Client) objectInfo2ClientContent(bucket string, entry minio.ObjectInf
|
||||
setChecksum("CRC32C", entry.ChecksumCRC32C)
|
||||
setChecksum("SHA1", entry.ChecksumSHA1)
|
||||
setChecksum("SHA256", entry.ChecksumSHA256)
|
||||
setChecksum("CRC64NVME", entry.ChecksumCRC64NVME)
|
||||
return content
|
||||
}
|
||||
|
||||
|
||||
+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",
|
||||
|
||||
@@ -212,6 +212,7 @@ func url2Stat(ctx context.Context, opts url2StatOptions) (client Client, content
|
||||
versionID: opts.versionID,
|
||||
isZip: opts.isZip,
|
||||
ignoreBucketExists: opts.ignoreBucketExistsCheck,
|
||||
headOnly: opts.headOnly,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, nil, err.Trace(opts.urlStr)
|
||||
@@ -266,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)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
+24
-3
@@ -22,6 +22,7 @@ import (
|
||||
"crypto/tls"
|
||||
"fmt"
|
||||
"io"
|
||||
"maps"
|
||||
"math/rand"
|
||||
"net/http"
|
||||
"net/url"
|
||||
@@ -88,6 +89,7 @@ type StatOptions struct {
|
||||
includeVersions bool
|
||||
isZip bool
|
||||
ignoreBucketExists bool
|
||||
headOnly bool
|
||||
}
|
||||
|
||||
// BucketStatOptions - bucket stat.
|
||||
@@ -136,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
|
||||
@@ -371,7 +373,16 @@ func (config *Config) initTransport(withS3v2 bool) {
|
||||
// return nil, probe.NewError(e)
|
||||
// }
|
||||
}
|
||||
transport = tr
|
||||
|
||||
if len(globalCustomHeader) > 0 {
|
||||
transport = &headerTransport{
|
||||
RoundTripper: tr,
|
||||
customHeader: globalCustomHeader.Clone(),
|
||||
}
|
||||
} else {
|
||||
transport = tr
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
transport = limiter.New(config.UploadLimit, config.DownloadLimit, transport)
|
||||
@@ -398,3 +409,13 @@ type SelectObjectOpts struct {
|
||||
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)
|
||||
}
|
||||
|
||||
+18
-15
@@ -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
|
||||
@@ -360,9 +360,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
|
||||
@@ -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
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
+6
-3
@@ -248,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 == "" {
|
||||
|
||||
+14
-11
@@ -22,6 +22,7 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"maps"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
@@ -97,6 +98,10 @@ 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,
|
||||
}
|
||||
)
|
||||
@@ -279,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
|
||||
@@ -366,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() {
|
||||
@@ -422,9 +427,7 @@ 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 = md5
|
||||
@@ -493,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()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -514,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
|
||||
|
||||
+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) {
|
||||
|
||||
+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
|
||||
}
|
||||
|
||||
+4
-4
@@ -50,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)
|
||||
}
|
||||
@@ -118,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()
|
||||
}
|
||||
}
|
||||
@@ -274,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,
|
||||
|
||||
+12
-2
@@ -96,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
|
||||
@@ -124,7 +128,7 @@ var encS3Flag = cli.StringSliceFlag{
|
||||
|
||||
var checksumFlag = cli.StringFlag{
|
||||
Name: "checksum",
|
||||
Usage: "Add checksum to uploaded object. Values: MD5, CRC32, CRC32C, SHA1 or SHA256. Requires server trailing headers (AWS, MinIO)",
|
||||
Usage: "Add checksum to uploaded object. Values: CRC64NVME, CRC32, CRC32C, SHA1 or SHA256. Requires server trailing headers (AWS, MinIO)",
|
||||
Value: "",
|
||||
}
|
||||
|
||||
@@ -136,14 +140,20 @@ func parseChecksum(ctx *cli.Context) (useMD5 bool, ct minio.ChecksumType) {
|
||||
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 MD5, CRC32, CRC32C, SHA1 or SHA256", cs)
|
||||
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() {
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
//go:build !windows
|
||||
// +build !windows
|
||||
|
||||
// Copyright (c) 2015-2021 MinIO, Inc.
|
||||
//
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
//go:build windows
|
||||
// +build windows
|
||||
|
||||
// Copyright (c) 2015-2021 MinIO, Inc.
|
||||
//
|
||||
|
||||
+1
-1
@@ -92,7 +92,7 @@ func guessGetURLType(ctx context.Context, o prepareCopyURLsOpts) (*copyURLsConte
|
||||
return cc, probe.NewError(fmt.Errorf("Please set a full path for s3 resource."))
|
||||
}
|
||||
cc.sourceContent = s3clnt.objectInfo2ClientContent(bucket, minio.ObjectInfo{
|
||||
Key: path,
|
||||
Key: path, VersionID: o.versionID,
|
||||
})
|
||||
|
||||
client, err = newClient(o.targetURL)
|
||||
|
||||
@@ -23,6 +23,7 @@ import (
|
||||
"crypto/x509"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/netip"
|
||||
"net/url"
|
||||
"os"
|
||||
@@ -36,6 +37,7 @@ import (
|
||||
"github.com/minio/madmin-go/v3"
|
||||
"github.com/minio/pkg/v3/console"
|
||||
"github.com/muesli/termenv"
|
||||
"golang.org/x/net/http/httpguts"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -80,6 +82,9 @@ var (
|
||||
// GlobalDevMode is set to true if the program is running in development mode
|
||||
GlobalDevMode = false
|
||||
|
||||
// GlobalTrapSignals is set to true if need to trap the registered signals and cancel the global context.
|
||||
GlobalTrapSignals = true
|
||||
|
||||
// GlobalSubnetProxyURL is the proxy to be used for communication with subnet
|
||||
GlobalSubnetProxyURL *url.URL
|
||||
|
||||
@@ -90,6 +95,8 @@ var (
|
||||
globalLimitDownload uint64
|
||||
|
||||
globalContext, globalCancel = context.WithCancel(context.Background())
|
||||
|
||||
globalCustomHeader http.Header
|
||||
)
|
||||
|
||||
var (
|
||||
@@ -200,5 +207,23 @@ func setGlobalsFromContext(ctx *cli.Context) error {
|
||||
globalResolvers[host] = addr
|
||||
}
|
||||
}
|
||||
|
||||
customHeaders := ctx.StringSlice("custom-header")
|
||||
if len(customHeaders) > 0 {
|
||||
globalCustomHeader = make(http.Header)
|
||||
for _, header := range customHeaders {
|
||||
i := strings.IndexByte(header, ':')
|
||||
if i <= 0 {
|
||||
return fmt.Errorf("invalid custom header entry %s", header)
|
||||
}
|
||||
h := strings.TrimSpace(header[:i])
|
||||
hv := strings.TrimSpace(header[i+1:])
|
||||
if !httpguts.ValidHeaderFieldName(h) || !httpguts.ValidHeaderFieldValue(hv) {
|
||||
return fmt.Errorf("invalid custom header entry %s", header)
|
||||
}
|
||||
globalCustomHeader.Add(h, hv)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
+7
-3
@@ -22,6 +22,7 @@ import (
|
||||
"compress/bzip2"
|
||||
"compress/gzip"
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"os"
|
||||
"strings"
|
||||
@@ -142,9 +143,12 @@ func headOut(r io.Reader, nlines int64) *probe.Error {
|
||||
}
|
||||
|
||||
for nlines > 0 {
|
||||
line, _, e := br.ReadLine()
|
||||
if e != nil {
|
||||
return probe.NewError(e)
|
||||
line, _, err := br.ReadLine()
|
||||
if err != nil && !errors.Is(err, io.EOF) {
|
||||
return probe.NewError(err)
|
||||
}
|
||||
if errors.Is(err, io.EOF) {
|
||||
break
|
||||
}
|
||||
if _, e := stdout.Write(line); e != nil {
|
||||
switch e := e.(type) {
|
||||
|
||||
+1
-1
@@ -95,7 +95,7 @@ type SwInfoV1 struct {
|
||||
// MinioHealthInfoV1 - Health info of the MinIO cluster
|
||||
type MinioHealthInfoV1 struct {
|
||||
Info madmin.InfoMessage `json:"info,omitempty"`
|
||||
Config interface{} `json:"config,omitempty"`
|
||||
Config any `json:"config,omitempty"`
|
||||
ProcInfo []madmin.ServerProcInfo `json:"procinfos,omitempty"`
|
||||
Error string `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
@@ -20,8 +20,10 @@ package cmd
|
||||
import (
|
||||
"bufio"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"slices"
|
||||
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/cli"
|
||||
@@ -32,12 +34,23 @@ import (
|
||||
"golang.org/x/term"
|
||||
)
|
||||
|
||||
var idpLdapAccesskeyCreateWithLoginFlags = []cli.Flag{
|
||||
cli.StringFlag{
|
||||
Name: "ldap-username",
|
||||
Usage: "username to login as (prompt if empty)",
|
||||
},
|
||||
cli.StringFlag{
|
||||
Name: "ldap-password",
|
||||
Usage: "password for ldap-user (prompt if empty)",
|
||||
},
|
||||
}
|
||||
|
||||
var idpLdapAccesskeyCreateWithLoginCmd = cli.Command{
|
||||
Name: "create-with-login",
|
||||
Usage: "login using LDAP credentials to generate access key pair",
|
||||
Action: mainIDPLdapAccesskeyCreateWithLogin,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: append(idpLdapAccesskeyCreateFlags, globalFlags...),
|
||||
Flags: slices.Concat(idpLdapAccesskeyCreateWithLoginFlags, idpLdapAccesskeyCreateFlags, globalFlags),
|
||||
OnUsageError: onUsageError,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
@@ -73,7 +86,7 @@ func mainIDPLdapAccesskeyCreateWithLogin(ctx *cli.Context) error {
|
||||
res, e := client.AddServiceAccountLDAP(globalContext, opts)
|
||||
fatalIf(probe.NewError(e), "unable to add service account")
|
||||
|
||||
m := ldapAccesskeyMessage{
|
||||
m := accesskeyMessage{
|
||||
op: "create",
|
||||
Status: "success",
|
||||
AccessKey: res.AccessKey,
|
||||
@@ -96,21 +109,29 @@ func loginLDAPAccesskey(ctx *cli.Context) (*madmin.AdminClient, madmin.AddServic
|
||||
console.SetColor(cred, color.New(color.FgYellow, color.Italic))
|
||||
reader := bufio.NewReader(os.Stdin)
|
||||
|
||||
fmt.Printf("%s", console.Colorize(cred, "Enter LDAP Username: "))
|
||||
value, _, e := reader.ReadLine()
|
||||
fatalIf(probe.NewError(e), "unable to read username")
|
||||
username := string(value)
|
||||
username := ctx.String("ldap-username")
|
||||
if username == "" {
|
||||
fmt.Printf("%s", console.Colorize(cred, "Enter LDAP Username: "))
|
||||
value, _, e := reader.ReadLine()
|
||||
fatalIf(probe.NewError(e), "unable to read username")
|
||||
username = string(value)
|
||||
}
|
||||
|
||||
fmt.Printf("%s", console.Colorize(cred, "Enter LDAP Password: "))
|
||||
bytePassword, e := term.ReadPassword(int(os.Stdin.Fd()))
|
||||
fatalIf(probe.NewError(e), "unable to read password")
|
||||
fmt.Printf("\n")
|
||||
password := string(bytePassword)
|
||||
password := ctx.String("ldap-password")
|
||||
if password == "" {
|
||||
fmt.Printf("%s", console.Colorize(cred, "Enter LDAP Password: "))
|
||||
bytePassword, e := term.ReadPassword(int(os.Stdin.Fd()))
|
||||
fatalIf(probe.NewError(e), "unable to read password")
|
||||
fmt.Printf("\n")
|
||||
password = string(bytePassword)
|
||||
}
|
||||
|
||||
stsCreds, e := credentials.NewLDAPIdentity(urlStr, username, password)
|
||||
fatalIf(probe.NewError(e), "unable to initialize LDAP identity")
|
||||
|
||||
tempCreds, e := stsCreds.Get()
|
||||
tempCreds, e := stsCreds.GetWithContext(&credentials.CredContext{
|
||||
Client: http.DefaultClient,
|
||||
})
|
||||
fatalIf(probe.NewError(e), "unable to create a temporary account from LDAP identity")
|
||||
|
||||
client, e := madmin.NewWithOptions(u.Host, &madmin.Options{
|
||||
|
||||
@@ -127,7 +127,7 @@ func commonAccesskeyCreate(ctx *cli.Context, ldap bool) error {
|
||||
}
|
||||
fatalIf(probe.NewError(e), "Unable to add service account.")
|
||||
|
||||
m := ldapAccesskeyMessage{
|
||||
m := accesskeyMessage{
|
||||
op: "create",
|
||||
Status: "success",
|
||||
AccessKey: res.AccessKey,
|
||||
|
||||
@@ -101,7 +101,7 @@ func commonAccesskeyEdit(ctx *cli.Context) error {
|
||||
e := client.UpdateServiceAccount(globalContext, accessKey, opts)
|
||||
fatalIf(probe.NewError(e), "Unable to edit service account.")
|
||||
|
||||
m := ldapAccesskeyMessage{
|
||||
m := accesskeyMessage{
|
||||
op: "edit",
|
||||
Status: "success",
|
||||
AccessKey: accessKey,
|
||||
|
||||
@@ -73,7 +73,7 @@ func enableDisableAccesskey(ctx *cli.Context, enable bool) error {
|
||||
})
|
||||
fatalIf(probe.NewError(e), "Unable to add service account.")
|
||||
|
||||
m := ldapAccesskeyMessage{
|
||||
m := accesskeyMessage{
|
||||
op: op,
|
||||
Status: "success",
|
||||
AccessKey: accessKey,
|
||||
|
||||
@@ -19,13 +19,9 @@ 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/mc/pkg/probe"
|
||||
)
|
||||
|
||||
var idpLdapAccesskeyInfoCmd = cli.Command{
|
||||
@@ -52,137 +48,18 @@ EXAMPLES:
|
||||
`,
|
||||
}
|
||||
|
||||
type ldapAccesskeyMessage struct {
|
||||
op string
|
||||
Status string `json:"status"`
|
||||
AccessKey string `json:"accessKey"`
|
||||
SecretKey string `json:"secretKey,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"`
|
||||
type ldapAccessKeyInfo struct {
|
||||
Username string `json:"username,omitempty"`
|
||||
}
|
||||
|
||||
func (m ldapAccesskeyMessage) String() string {
|
||||
func (l ldapAccessKeyInfo) 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"
|
||||
}
|
||||
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))
|
||||
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)))
|
||||
}
|
||||
o.WriteString(labelStyle.Render("Username: "))
|
||||
o.WriteString(l.Username)
|
||||
return o.String()
|
||||
}
|
||||
|
||||
func (m ldapAccesskeyMessage) JSON() string {
|
||||
jsonMessageBytes, e := json.MarshalIndent(m, "", " ")
|
||||
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
|
||||
|
||||
return string(jsonMessageBytes)
|
||||
}
|
||||
|
||||
func mainIDPLdapAccesskeyInfo(ctx *cli.Context) error {
|
||||
return commonAccesskeyInfo(ctx)
|
||||
}
|
||||
|
||||
// currently no difference between ldap and builtin accesskey info
|
||||
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.InfoServiceAccount(globalContext, accessKey)
|
||||
if e != nil {
|
||||
// If not a service account must be sts
|
||||
tempRes, e := client.TemporaryAccountInfo(globalContext, accessKey)
|
||||
if e != nil {
|
||||
errorIf(probe.NewError(e), "Unable to retrieve access key %s info.", accessKey)
|
||||
} else {
|
||||
m := ldapAccesskeyMessage{
|
||||
op: "info",
|
||||
AccessKey: accessKey,
|
||||
Status: "success",
|
||||
ParentUser: tempRes.ParentUser,
|
||||
AccountStatus: tempRes.AccountStatus,
|
||||
ImpliedPolicy: tempRes.ImpliedPolicy,
|
||||
Policy: json.RawMessage(tempRes.Policy),
|
||||
Name: tempRes.Name,
|
||||
Description: tempRes.Description,
|
||||
Expiration: nilExpiry(tempRes.Expiration),
|
||||
}
|
||||
printMsg(m)
|
||||
}
|
||||
} else {
|
||||
m := ldapAccesskeyMessage{
|
||||
op: "info",
|
||||
AccessKey: accessKey,
|
||||
Status: "success",
|
||||
ParentUser: res.ParentUser,
|
||||
AccountStatus: res.AccountStatus,
|
||||
ImpliedPolicy: res.ImpliedPolicy,
|
||||
Policy: json.RawMessage(res.Policy),
|
||||
Name: res.Name,
|
||||
Description: res.Description,
|
||||
Expiration: nilExpiry(res.Expiration),
|
||||
}
|
||||
printMsg(m)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func nilExpiry(expiry *time.Time) *time.Time {
|
||||
if expiry != nil && expiry.Equal(timeSentinel) {
|
||||
return nil
|
||||
}
|
||||
return expiry
|
||||
}
|
||||
|
||||
@@ -19,6 +19,7 @@ package cmd
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"strings"
|
||||
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/madmin-go/v3"
|
||||
@@ -129,18 +130,24 @@ func commonAccesskeyList(ctx *cli.Context) (aliasedURL string, tentativeAll bool
|
||||
svcaccOnly := ctx.Bool("svcacc-only")
|
||||
selfFlag := ctx.Bool("self")
|
||||
opts.All = ctx.Bool("all")
|
||||
opts.AllConfigs = ctx.Bool("all-configs")
|
||||
|
||||
args := ctx.Args()
|
||||
aliasedURL = args.Get(0)
|
||||
users = args.Tail()
|
||||
|
||||
aliasedURL, cfgName, _ := strings.Cut(aliasedURL, ":")
|
||||
if cfgName != "" {
|
||||
opts.ConfigName = cfgName
|
||||
}
|
||||
|
||||
var e error
|
||||
if (usersOnly && svcaccOnly) || (usersOnly && stsOnly) || (svcaccOnly && stsOnly) {
|
||||
e = errors.New("only one of --users-only, --temp-only, or --permanent-only can be specified")
|
||||
} else if selfFlag && opts.All {
|
||||
e = errors.New("only one of --self or --all can be specified")
|
||||
} else if (selfFlag || opts.All) && len(users) > 0 {
|
||||
e = errors.New("user DNs cannot be specified with --self or --all")
|
||||
e = errors.New("users cannot be specified with --self or --all")
|
||||
}
|
||||
fatalIf(probe.NewError(e), "Invalid flags.")
|
||||
|
||||
|
||||
@@ -66,7 +66,7 @@ func commonAccesskeyRemove(ctx *cli.Context) error {
|
||||
e := client.DeleteServiceAccount(globalContext, accessKey)
|
||||
fatalIf(probe.NewError(e), "Unable to remove service account.")
|
||||
|
||||
m := ldapAccesskeyMessage{
|
||||
m := accesskeyMessage{
|
||||
op: "remove",
|
||||
Status: "success",
|
||||
AccessKey: accessKey,
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
// 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"
|
||||
"github.com/minio/madmin-go/v3"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
)
|
||||
|
||||
var idpLdapAccesskeySTSRevokeCmd = cli.Command{
|
||||
Name: "sts-revoke",
|
||||
Usage: "revokes all STS accounts or specified types for the specified user",
|
||||
Action: mainIdpLdapAccesskeySTSRevoke,
|
||||
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 LDAP user 'bobfisher'
|
||||
{{.Prompt}} {{.HelpName}} myminio uid=bobfisher,ou=people,ou=hwengg,dc=min,dc=io --all
|
||||
|
||||
2. Revoke all STS accounts for LDAP user 'bobfisher' (alt)
|
||||
{{.Prompt}} {{.HelpName}} myminio bobfisher --all
|
||||
|
||||
3. Revoke STS accounts of a token type 'app-1' for user 'user1'
|
||||
{{.Prompt}} {{.HelpName}} myminio user1 --token-type app-1
|
||||
|
||||
4. Revoke all STS accounts for the authenticated user (must be LDAP service account)
|
||||
{{.Prompt}} {{.HelpName}} myminio --self
|
||||
|
||||
5. Revoke STS accounts of a token type 'app-1' for the authenticated user (must be LDAP service account)
|
||||
{{.Prompt}} {{.HelpName}} myminio --self --token-type app-1
|
||||
`,
|
||||
}
|
||||
|
||||
// mainIdpLdapAccesskeySTSRevoke is the handle for "mc idp ldap accesskey sts-revoke" command.
|
||||
func mainIdpLdapAccesskeySTSRevoke(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
|
||||
}
|
||||
@@ -28,6 +28,7 @@ var idpLdapAccesskeySubcommands = []cli.Command{
|
||||
idpLdapAccesskeyEditCmd,
|
||||
idpLdapAccesskeyEnableCmd,
|
||||
idpLdapAccesskeyDisableCmd,
|
||||
idpLdapAccesskeySTSRevokeCmd,
|
||||
}
|
||||
|
||||
var idpLdapAccesskeyCmd = cli.Command{
|
||||
|
||||
@@ -185,7 +185,7 @@ func mainIDPLDAPRemove(ctx *cli.Context) error {
|
||||
showCommandHelpAndExit(ctx, 1)
|
||||
}
|
||||
|
||||
var cfgName string = madmin.Default
|
||||
cfgName := madmin.Default
|
||||
return idpRemove(ctx, false, cfgName)
|
||||
}
|
||||
|
||||
@@ -247,7 +247,7 @@ func mainIDPLDAPInfo(ctx *cli.Context) error {
|
||||
showCommandHelpAndExit(ctx, 1)
|
||||
}
|
||||
|
||||
var cfgName string = madmin.Default
|
||||
cfgName := madmin.Default
|
||||
return idpInfo(ctx, false, cfgName)
|
||||
}
|
||||
|
||||
|
||||
@@ -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 idpOpenidAccesskeyDisableCmd = cli.Command{
|
||||
Name: "disable",
|
||||
Usage: "disable an access key",
|
||||
Action: mainIDPOpenIDAccesskeyDisable,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
OnUsageError: onUsageError,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
{{.HelpName}} [FLAGS] [TARGET]
|
||||
|
||||
FLAGS:
|
||||
{{range .VisibleFlags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
1. Disable LDAP access key
|
||||
{{.Prompt}} {{.HelpName}} myminio myaccesskey
|
||||
`,
|
||||
}
|
||||
|
||||
func mainIDPOpenIDAccesskeyDisable(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 idpOpenIDAccesskeyEditFlags = []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 idpOpenidAccesskeyEditCmd = cli.Command{
|
||||
Name: "edit",
|
||||
Usage: "edit existing access keys for OpenID",
|
||||
Action: mainIDPOpenIDAccesskeyEdit,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: append(idpOpenIDAccesskeyEditFlags, 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 mainIDPOpenIDAccesskeyEdit(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 idpOpenidAccesskeyEnableCmd = cli.Command{
|
||||
Name: "enable",
|
||||
Usage: "enable an access key",
|
||||
Action: mainIDPOpenIDAccesskeyEnable,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
OnUsageError: onUsageError,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
{{.HelpName}} [FLAGS] [TARGET]
|
||||
|
||||
FLAGS:
|
||||
{{range .VisibleFlags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
1. Enable LDAP access key
|
||||
{{.Prompt}} {{.HelpName}} myminio myaccesskey
|
||||
`,
|
||||
}
|
||||
|
||||
func mainIDPOpenIDAccesskeyEnable(ctx *cli.Context) error {
|
||||
return enableDisableAccesskey(ctx, true)
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
// 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 (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/charmbracelet/lipgloss"
|
||||
"github.com/minio/cli"
|
||||
)
|
||||
|
||||
var idpOpenidAccesskeyInfoCmd = cli.Command{
|
||||
Name: "info",
|
||||
Usage: "info about given access key pairs for OpenID",
|
||||
Action: mainIDPOpenIDAccesskeyInfo,
|
||||
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 openIDAccessKeyInfo struct {
|
||||
ConfigName string `json:"configName"`
|
||||
UserID string `json:"userID"`
|
||||
UserIDClaim string `json:"userIDClaim"`
|
||||
DisplayName string `json:"displayName,omitempty"`
|
||||
DisplayNameClaim string `json:"displayNameClaim,omitempty"`
|
||||
}
|
||||
|
||||
func (l openIDAccessKeyInfo) String() string {
|
||||
labelStyle := lipgloss.NewStyle().Foreground(lipgloss.Color("#04B575")) // green
|
||||
o := strings.Builder{}
|
||||
if l.ConfigName == "_" {
|
||||
l.ConfigName = "_ (default)"
|
||||
}
|
||||
o.WriteString(iFmt(2, "%s %s\n", labelStyle.Render("Config:"), l.ConfigName))
|
||||
if l.DisplayNameClaim != "" {
|
||||
dispNameLabel := fmt.Sprintf("Display Name (%s):", l.DisplayNameClaim)
|
||||
o.WriteString(iFmt(2, "%s %s\n", labelStyle.Render(dispNameLabel), l.DisplayName))
|
||||
}
|
||||
uidLabel := fmt.Sprintf("User ID (%s):", l.UserIDClaim)
|
||||
o.WriteString(iFmt(2, "%s %s\n", labelStyle.Render(uidLabel), l.UserID))
|
||||
return o.String()
|
||||
}
|
||||
|
||||
func mainIDPOpenIDAccesskeyInfo(ctx *cli.Context) error {
|
||||
return commonAccesskeyInfo(ctx)
|
||||
}
|
||||
@@ -0,0 +1,169 @@
|
||||
// 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 (
|
||||
"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 idpOpenIDAccesskeyListFlags = []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 OpenID users",
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "all-configs",
|
||||
Usage: "list access keys for all OpenID configurations",
|
||||
},
|
||||
}
|
||||
|
||||
var idpOpenidAccesskeyListCmd = cli.Command{
|
||||
Name: "list",
|
||||
ShortName: "ls",
|
||||
Usage: "list access key pairs for OpenID",
|
||||
Action: mainIDPOpenIDAccesskeyList,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: append(idpOpenIDAccesskeyListFlags, globalFlags...),
|
||||
OnUsageError: onUsageError,
|
||||
CustomHelpTemplate: `NAME:
|
||||
{{.HelpName}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
{{.HelpName}} [FLAGS] TARGET[:CFGNAME] [USER/ID...]
|
||||
|
||||
FLAGS:
|
||||
{{range .VisibleFlags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
1. Get list of all OpenID users and associated access keys in local server (if admin)
|
||||
{{.Prompt}} {{.HelpName}} local/
|
||||
|
||||
2. Get list of OpenID users in local server (if admin)
|
||||
{{.Prompt}} {{.HelpName}} local/ --users-only
|
||||
|
||||
3. Get list of all users and associated temporary access keys in play server (if admin)
|
||||
{{.Prompt}} {{.HelpName}} play/ --temp-only
|
||||
|
||||
4. Get list of access keys associated with internal name 'openidinternalname'
|
||||
{{.Prompt}} {{.HelpName}} play/ openidinternalname
|
||||
|
||||
5. Get list of access keys associated with ID claim 'openidsub' (default claim is sub)
|
||||
{{.Prompt}} {{.HelpName}} play/ openidsub
|
||||
|
||||
7. Get authenticated user and associated access keys in local server (if not admin)
|
||||
{{.Prompt}} {{.HelpName}} local/
|
||||
`,
|
||||
}
|
||||
|
||||
type openIDAccesskeyList struct {
|
||||
Status string `json:"status"`
|
||||
ConfigName string `json:"configName"`
|
||||
Users []madmin.OpenIDUserAccessKeys `json:"users"`
|
||||
}
|
||||
|
||||
func (m openIDAccesskeyList) String() string {
|
||||
labelStyle := lipgloss.NewStyle().Foreground(lipgloss.Color("#04B575"))
|
||||
o := strings.Builder{}
|
||||
|
||||
o.WriteString(iFmt(0, "%s %s\n", labelStyle.Render("Config Name:"), m.ConfigName))
|
||||
userStr := "User ID"
|
||||
for _, user := range m.Users {
|
||||
o.WriteString(iFmt(2, "%s %s\n", labelStyle.Render(userStr+":"), user.MinioAccessKey))
|
||||
o.WriteString(iFmt(2, "%s %s\n", labelStyle.Render("ID:"), user.ID))
|
||||
if user.ReadableName != "" {
|
||||
o.WriteString(iFmt(2, "%s %s\n", labelStyle.Render("Readable Name:"), user.ReadableName))
|
||||
}
|
||||
if len(user.STSKeys) > 0 || len(user.ServiceAccounts) > 0 {
|
||||
o.WriteString(iFmt(4, "%s\n", labelStyle.Render("Access Keys:")))
|
||||
}
|
||||
for _, k := range user.STSKeys {
|
||||
expiration := "never"
|
||||
if nilExpiry(k.Expiration) != nil {
|
||||
expiration = humanize.Time(*k.Expiration)
|
||||
}
|
||||
o.WriteString(iFmt(6, "%s, expires: %s, sts: true\n", k.AccessKey, expiration))
|
||||
}
|
||||
for _, k := range user.ServiceAccounts {
|
||||
expiration := "never"
|
||||
if nilExpiry(k.Expiration) != nil {
|
||||
expiration = humanize.Time(*k.Expiration)
|
||||
}
|
||||
o.WriteString(iFmt(6, "%s, expires: %s, sts: false\n", k.AccessKey, expiration))
|
||||
}
|
||||
}
|
||||
|
||||
return o.String()
|
||||
}
|
||||
|
||||
func (m openIDAccesskeyList) JSON() string {
|
||||
jsonMessageBytes, e := json.MarshalIndent(m, "", " ")
|
||||
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
|
||||
|
||||
return string(jsonMessageBytes)
|
||||
}
|
||||
|
||||
func mainIDPOpenIDAccesskeyList(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.")
|
||||
|
||||
accessKeys, e := client.ListAccessKeysOpenIDBulk(globalContext, users, opts)
|
||||
if e != nil {
|
||||
if e.Error() == "Access Denied." && tentativeAll {
|
||||
// retry with self
|
||||
opts.All = false
|
||||
accessKeys, e = client.ListAccessKeysOpenIDBulk(globalContext, users, opts)
|
||||
}
|
||||
fatalIf(probe.NewError(e), "Unable to list access keys.")
|
||||
}
|
||||
|
||||
for _, cfg := range accessKeys {
|
||||
m := openIDAccesskeyList{
|
||||
Status: "success",
|
||||
ConfigName: cfg.ConfigName,
|
||||
Users: cfg.Users,
|
||||
}
|
||||
printMsg(m)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
// 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 (
|
||||
"github.com/minio/cli"
|
||||
)
|
||||
|
||||
var idpOpenidAccesskeyRemoveCmd = cli.Command{
|
||||
Name: "remove",
|
||||
ShortName: "rm",
|
||||
Usage: "delete access key pairs for OpenID",
|
||||
Action: mainIDPOpenIDAccesskeyRemove,
|
||||
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 mainIDPOpenIDAccesskeyRemove(ctx *cli.Context) error {
|
||||
return commonAccesskeyRemove(ctx)
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
// 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 "github.com/minio/cli"
|
||||
|
||||
var idpOpenidAccesskeySubcommands = []cli.Command{
|
||||
idpOpenidAccesskeyListCmd,
|
||||
idpOpenidAccesskeyRemoveCmd,
|
||||
idpOpenidAccesskeyInfoCmd,
|
||||
idpOpenidAccesskeyEditCmd,
|
||||
idpOpenidAccesskeyEnableCmd,
|
||||
idpOpenidAccesskeyDisableCmd,
|
||||
}
|
||||
|
||||
var idpOpenIDAccesskeyCmd = cli.Command{
|
||||
Name: "accesskey",
|
||||
Usage: "manage OpenID access key pairs",
|
||||
Action: mainIDPOpenIDAccesskey,
|
||||
Before: setGlobalsFromContext,
|
||||
Flags: globalFlags,
|
||||
Subcommands: idpOpenidAccesskeySubcommands,
|
||||
HideHelpCommand: true,
|
||||
}
|
||||
|
||||
func mainIDPOpenIDAccesskey(ctx *cli.Context) error {
|
||||
commandNotFound(ctx, idpOpenidAccesskeySubcommands)
|
||||
return nil
|
||||
}
|
||||
@@ -416,12 +416,16 @@ func (i idpConfig) String() string {
|
||||
return "Not configured."
|
||||
}
|
||||
|
||||
enableStr := "on"
|
||||
// Determine required width for key column.
|
||||
fieldColWidth := 0
|
||||
for _, kv := range i.Info {
|
||||
if fieldColWidth < len(kv.Key) {
|
||||
fieldColWidth = len(kv.Key)
|
||||
}
|
||||
if kv.Key == "enable" {
|
||||
enableStr = kv.Value
|
||||
}
|
||||
}
|
||||
// Add 1 for the colon-suffix in each entry.
|
||||
fieldColWidth++
|
||||
@@ -439,7 +443,14 @@ func (i idpConfig) String() string {
|
||||
PaddingLeft(1)
|
||||
|
||||
var lines []string
|
||||
lines = append(lines, fmt.Sprintf("%s%s",
|
||||
fieldColStyle.Render("enable:"),
|
||||
valueColStyle.Render(enableStr),
|
||||
))
|
||||
for _, kv := range i.Info {
|
||||
if kv.Key == "enable" {
|
||||
continue
|
||||
}
|
||||
envStr := ""
|
||||
if kv.IsCfg && kv.IsEnv {
|
||||
envStr = " (environment)"
|
||||
@@ -509,7 +520,7 @@ func idpEnableDisable(ctx *cli.Context, isOpenID, enable bool) error {
|
||||
idpType = madmin.OpenidIDPCfg
|
||||
}
|
||||
|
||||
configBody := "enable=on"
|
||||
configBody := "enable="
|
||||
if !enable {
|
||||
configBody = "enable=off"
|
||||
}
|
||||
|
||||
@@ -28,6 +28,7 @@ var (
|
||||
idpOpenidInfoCmd,
|
||||
idpOpenidEnableCmd,
|
||||
idpOpenidDisableCmd,
|
||||
idpOpenIDAccesskeyCmd,
|
||||
// TODO: idpOpenidPolicyCmd,
|
||||
}
|
||||
idpOpenidCmd = cli.Command{
|
||||
|
||||
+1
-1
@@ -224,7 +224,7 @@ func checkRestoreStatus(ctx context.Context, targetAlias, targetURL, targetVersi
|
||||
var dotCycle = 0
|
||||
|
||||
// Clear and print text in the same line
|
||||
func printStatus(msg string, args ...interface{}) {
|
||||
func printStatus(msg string, args ...any) {
|
||||
if globalJSON {
|
||||
return
|
||||
}
|
||||
|
||||
+22
-1
@@ -27,6 +27,7 @@ import (
|
||||
"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"
|
||||
)
|
||||
|
||||
@@ -180,13 +181,33 @@ func mainAdminTierInfo(ctx *cli.Context) error {
|
||||
NumbersStyle = lipgloss.NewStyle().Align(lipgloss.Right)
|
||||
)
|
||||
tableData := tierInfos(tInfos)
|
||||
filteredData := table.NewFilter(tableData).
|
||||
var filteredData table.Data
|
||||
filteredData = table.NewFilter(tableData).
|
||||
Filter(func(row int) bool {
|
||||
if tier == "" {
|
||||
return true
|
||||
}
|
||||
return tableData.At(row, 0) == tier
|
||||
})
|
||||
|
||||
if filteredData.Rows() == 0 {
|
||||
// check if that tier name is valid
|
||||
// if valid will show that with empty data
|
||||
tiers, e := client.ListTiers(globalContext)
|
||||
fatalIf(probe.NewError(e).Trace(args...), "Unable to list configured remote tier targets")
|
||||
for _, t := range tiers {
|
||||
if t.Name == tier {
|
||||
filteredData = tierInfos([]madmin.TierInfo{
|
||||
{
|
||||
Name: tier,
|
||||
Type: t.Type.String(),
|
||||
},
|
||||
})
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
tbl := table.New().
|
||||
Border(lipgloss.NormalBorder()).
|
||||
Headers(tableData.Headers()...).
|
||||
|
||||
@@ -28,6 +28,7 @@ import (
|
||||
json "github.com/minio/colorjson"
|
||||
madmin "github.com/minio/madmin-go/v3"
|
||||
"github.com/minio/mc/pkg/probe"
|
||||
"github.com/minio/pkg/v3/console"
|
||||
)
|
||||
|
||||
var adminTierListCmd = cli.Command{
|
||||
@@ -109,6 +110,11 @@ func mainAdminTierList(ctx *cli.Context) error {
|
||||
tiers, e := client.ListTiers(globalContext)
|
||||
fatalIf(probe.NewError(e).Trace(args...), "Unable to list configured remote tier targets")
|
||||
|
||||
if len(tiers) == 0 {
|
||||
console.Infoln("No remote tier targets found for alias '" + aliasedURL + "'. Use `mc ilm tier add` to configure one.")
|
||||
return nil
|
||||
}
|
||||
|
||||
if globalJSON {
|
||||
printMsg(&tierListMessage{
|
||||
Status: "success",
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user