Compare commits
53
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 |
@@ -20,7 +20,7 @@ jobs:
|
||||
runs-on: ${{ matrix.os }}
|
||||
strategy:
|
||||
matrix:
|
||||
go-version: [1.23.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.23.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.23.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.23.6
|
||||
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"]
|
||||
@@ -8,8 +8,7 @@ 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)
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -142,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 {
|
||||
@@ -186,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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -87,11 +87,11 @@ func (h hri) getBucketHCCChange() (b, a col, err error) {
|
||||
|
||||
a, b = colGrey, colGrey
|
||||
|
||||
if len(h.HealResultItem.Before.Drives) > 0 {
|
||||
b = getColCode(h.HealResultItem.Before.Drives)
|
||||
if len(h.Before.Drives) > 0 {
|
||||
b = getColCode(h.Before.Drives)
|
||||
}
|
||||
if len(h.HealResultItem.After.Drives) > 0 {
|
||||
a = getColCode(h.HealResultItem.After.Drives)
|
||||
if len(h.After.Drives) > 0 {
|
||||
a = getColCode(h.After.Drives)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
@@ -398,7 +398,6 @@ func (ui *uiData) UpdateDisplay(s *madmin.HealTaskStatus) {
|
||||
default:
|
||||
ui.updateUI(s)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (ui *uiData) healResumeMsg(aliasedURL string) string {
|
||||
|
||||
+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
|
||||
|
||||
@@ -397,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++
|
||||
@@ -442,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))
|
||||
}
|
||||
|
||||
|
||||
+4
-6
@@ -411,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
|
||||
|
||||
@@ -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)
|
||||
|
||||
+3
-6
@@ -22,6 +22,7 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"maps"
|
||||
"os"
|
||||
"path"
|
||||
"path/filepath"
|
||||
@@ -634,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
|
||||
}
|
||||
|
||||
@@ -1361,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.
|
||||
//
|
||||
|
||||
@@ -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
|
||||
|
||||
+7
-9
@@ -26,6 +26,7 @@ import (
|
||||
"fmt"
|
||||
"hash/fnv"
|
||||
"io"
|
||||
"maps"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
@@ -936,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 != "" {
|
||||
@@ -1024,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")
|
||||
@@ -1086,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,
|
||||
@@ -1100,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
|
||||
@@ -2257,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)
|
||||
}
|
||||
|
||||
+18
-18
@@ -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>")
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -267,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)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
+2
-3
@@ -22,6 +22,7 @@ import (
|
||||
"crypto/tls"
|
||||
"fmt"
|
||||
"io"
|
||||
"maps"
|
||||
"math/rand"
|
||||
"net/http"
|
||||
"net/url"
|
||||
@@ -415,8 +416,6 @@ type headerTransport struct {
|
||||
}
|
||||
|
||||
func (h *headerTransport) RoundTrip(request *http.Request) (*http.Response, error) {
|
||||
for k, v := range h.customHeader {
|
||||
request.Header[k] = v
|
||||
}
|
||||
maps.Copy(request.Header, h.customHeader)
|
||||
return h.RoundTripper.RoundTrip(request)
|
||||
}
|
||||
|
||||
+11
-19
@@ -21,11 +21,12 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"maps"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
@@ -36,7 +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/s3utils"
|
||||
"github.com/minio/minio-go/v7/pkg/tags"
|
||||
"github.com/minio/pkg/v3/env"
|
||||
)
|
||||
|
||||
@@ -136,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
|
||||
@@ -362,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
|
||||
@@ -402,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
|
||||
@@ -448,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 {
|
||||
@@ -463,11 +455,11 @@ func uploadSourceToTargetURL(ctx context.Context, uploadOpts uploadSourceToTarge
|
||||
}
|
||||
|
||||
if content.Tags != nil {
|
||||
tags, err := url.PathUnescape(s3utils.TagEncode(content.Tags))
|
||||
tags, err := tags.NewTags(content.Tags, true)
|
||||
if err != nil {
|
||||
return uploadOpts.urls.WithError(probe.NewError(err))
|
||||
}
|
||||
metadata["X-Amz-Tagging"] = tags
|
||||
metadata["X-Amz-Tagging"] = tags.String()
|
||||
delete(metadata, "X-Amz-Tagging-Count")
|
||||
}
|
||||
|
||||
|
||||
@@ -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
@@ -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
|
||||
}
|
||||
|
||||
+3
-3
@@ -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()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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.
|
||||
//
|
||||
|
||||
@@ -82,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
|
||||
|
||||
|
||||
+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"`
|
||||
}
|
||||
|
||||
@@ -23,6 +23,7 @@ import (
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"slices"
|
||||
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/cli"
|
||||
@@ -33,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}}
|
||||
@@ -74,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,
|
||||
@@ -97,16 +109,22 @@ 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")
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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",
|
||||
|
||||
+12
-1
@@ -113,6 +113,13 @@ func validateExpiration(rule lifecycle.Rule) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateTransition(rule lifecycle.Rule) error {
|
||||
if !rule.Transition.IsDaysNull() && !rule.Transition.IsDateNull() {
|
||||
return errors.New("only one parameter under Transition can be specified")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateNoncurrentExpiration(rule lifecycle.Rule) error {
|
||||
days := rule.NoncurrentVersionExpiration.NoncurrentDays
|
||||
if days < 0 {
|
||||
@@ -162,6 +169,9 @@ func validateILMRule(rule lifecycle.Rule) *probe.Error {
|
||||
if e := validateExpiration(rule); e != nil {
|
||||
return probe.NewError(e)
|
||||
}
|
||||
if e := validateTransition(rule); e != nil {
|
||||
return probe.NewError(e)
|
||||
}
|
||||
if e := validateTranExpCurdate(rule); e != nil {
|
||||
return probe.NewError(e)
|
||||
}
|
||||
@@ -206,7 +216,8 @@ func parseTransition(storageClass, transitionDateStr, transitionDaysStr *string)
|
||||
return lifecycle.Transition{}, err
|
||||
}
|
||||
transition.Date = transitionDate
|
||||
} else if transitionDaysStr != nil {
|
||||
}
|
||||
if transitionDaysStr != nil {
|
||||
transitionDays, err := parseTransitionDays(*transitionDaysStr)
|
||||
if err != nil {
|
||||
return lifecycle.Transition{}, err
|
||||
|
||||
+2
-2
@@ -64,7 +64,7 @@ func getExpirationDays(rule lifecycle.Rule) int {
|
||||
if rule.Expiration.Days > 0 {
|
||||
return int(rule.Expiration.Days)
|
||||
}
|
||||
if !rule.Expiration.Date.Time.IsZero() {
|
||||
if !rule.Expiration.Date.IsZero() {
|
||||
return int(time.Until(rule.Expiration.Date.Time).Hours() / 24)
|
||||
}
|
||||
|
||||
@@ -75,7 +75,7 @@ func getExpirationDays(rule lifecycle.Rule) int {
|
||||
// time.Now().UTC() for the given rule.
|
||||
func getTransitionDays(rule lifecycle.Rule) int {
|
||||
if !rule.Transition.Date.IsZero() {
|
||||
return int(time.Now().UTC().Sub(rule.Transition.Date.Time).Hours() / 24)
|
||||
return int(time.Until(rule.Transition.Date.Time).Hours() / 24)
|
||||
}
|
||||
|
||||
return int(rule.Transition.Days)
|
||||
|
||||
+1
-2
@@ -421,7 +421,6 @@ var appCmds = []cli.Command{
|
||||
batchCmd,
|
||||
cpCmd,
|
||||
catCmd,
|
||||
configCmd,
|
||||
corsCmd,
|
||||
diffCmd,
|
||||
duCmd,
|
||||
@@ -513,7 +512,7 @@ func registerApp(name string) *cli.App {
|
||||
app.EnableBashCompletion = true
|
||||
app.OnUsageError = onUsageError
|
||||
app.After = func(*cli.Context) error {
|
||||
globalExpiringCerts.Range(func(k, v interface{}) bool {
|
||||
globalExpiringCerts.Range(func(k, v any) bool {
|
||||
host := k.(string)
|
||||
expires := v.(time.Time)
|
||||
fmt.Fprintf(os.Stderr, "\n")
|
||||
|
||||
+48
-22
@@ -25,6 +25,7 @@ import (
|
||||
"path"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
@@ -144,6 +145,10 @@ var (
|
||||
Name: "skip-errors",
|
||||
Usage: "skip any errors when mirroring",
|
||||
},
|
||||
cli.IntFlag{
|
||||
Name: "max-workers",
|
||||
Usage: "maximum number of concurrent copies (default: autodetect)",
|
||||
},
|
||||
checksumFlag,
|
||||
}
|
||||
)
|
||||
@@ -297,8 +302,13 @@ func (m mirrorMessage) String() string {
|
||||
if m.EventTime != "" {
|
||||
msg = console.Colorize("Time", fmt.Sprintf("[%s] ", m.EventTime))
|
||||
}
|
||||
if m.EventType == notification.ObjectRemovedDelete {
|
||||
switch m.EventType {
|
||||
case notification.ObjectRemovedDelete:
|
||||
return msg + "Removed " + console.Colorize("Removed", fmt.Sprintf("`%s`", m.Target))
|
||||
case notification.ObjectRemovedDeleteMarkerCreated:
|
||||
return msg + "Removed (Delete Marker)" + console.Colorize("Removed", fmt.Sprintf("`%s`", m.Target))
|
||||
case notification.ILMDelMarkerExpirationDelete:
|
||||
return msg + "Removed (ILM)" + console.Colorize("Removed", fmt.Sprintf("`%s`", m.Target))
|
||||
}
|
||||
if m.EventTime == "" {
|
||||
return console.Colorize("Mirror", fmt.Sprintf("`%s` -> `%s`", m.Source, m.Target))
|
||||
@@ -647,10 +657,11 @@ func (mj *mirrorJob) watchMirrorEvents(ctx context.Context, events []EventInfo)
|
||||
}
|
||||
}
|
||||
eventPath := event.Path
|
||||
if runtime.GOOS == "darwin" {
|
||||
switch runtime.GOOS {
|
||||
case "darwin":
|
||||
// Strip the prefixes in the event path. Happens in darwin OS only
|
||||
eventPath = eventPath[strings.Index(eventPath, sourceURLFull):]
|
||||
} else if runtime.GOOS == "windows" {
|
||||
case "windows":
|
||||
// Shared folder as source URL and if event path is an absolute path.
|
||||
eventPath = getEventPathURLWin(mj.sourceURL, eventPath)
|
||||
}
|
||||
@@ -672,11 +683,8 @@ func (mj *mirrorJob) watchMirrorEvents(ctx context.Context, events []EventInfo)
|
||||
sc, ok := event.UserMetadata["x-amz-storage-class"]
|
||||
if ok {
|
||||
var found bool
|
||||
for _, esc := range mj.opts.excludeStorageClasses {
|
||||
if esc == sc {
|
||||
found = true
|
||||
break
|
||||
}
|
||||
if slices.Contains(mj.opts.excludeStorageClasses, sc) {
|
||||
found = true
|
||||
}
|
||||
if found {
|
||||
continue
|
||||
@@ -722,7 +730,9 @@ func (mj *mirrorJob) watchMirrorEvents(ctx context.Context, events []EventInfo)
|
||||
mj.parallel.queueTask(func() URLs {
|
||||
return mj.doMirrorWatch(ctx, targetPath, tgtSSE, mirrorURL, event)
|
||||
}, mirrorURL.SourceContent.Size)
|
||||
} else if event.Type == notification.ObjectRemovedDelete {
|
||||
} else if event.Type == notification.ObjectRemovedDelete ||
|
||||
event.Type == notification.ObjectRemovedDeleteMarkerCreated ||
|
||||
event.Type == notification.ILMDelMarkerExpirationDelete {
|
||||
if targetAlias != "" && strings.Contains(event.UserAgent, uaMirrorAppName+":"+targetAlias) {
|
||||
// Ignore delete cascading delete events if cyclical.
|
||||
continue
|
||||
@@ -739,7 +749,7 @@ func (mj *mirrorJob) watchMirrorEvents(ctx context.Context, events []EventInfo)
|
||||
}
|
||||
mirrorURL.TotalCount = mj.status.GetCounts()
|
||||
mirrorURL.TotalSize = mj.status.Get()
|
||||
if mirrorURL.TargetContent != nil && (mj.opts.isRemove || mj.opts.activeActive) {
|
||||
if mirrorURL.TargetContent != nil && (mj.opts.isRemove || mj.opts.activeActive || mj.opts.isWatch) {
|
||||
mj.parallel.queueTask(func() URLs {
|
||||
return mj.doRemove(ctx, mirrorURL, event)
|
||||
}, 0)
|
||||
@@ -861,8 +871,10 @@ func (mj *mirrorJob) mirror(ctx context.Context) bool {
|
||||
var wg sync.WaitGroup
|
||||
ctx, cancel := context.WithCancel(ctx)
|
||||
|
||||
doneCh := make(chan struct{})
|
||||
|
||||
// Starts watcher loop for watching for new events.
|
||||
if mj.opts.isWatch {
|
||||
if mj.opts.isWatch || mj.opts.activeActive {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
@@ -883,9 +895,12 @@ func (mj *mirrorJob) mirror(ctx context.Context) bool {
|
||||
wg.Wait()
|
||||
mj.parallel.stopAndWait()
|
||||
close(mj.statusCh)
|
||||
close(doneCh)
|
||||
}()
|
||||
|
||||
return mj.monitorMirrorStatus(cancel)
|
||||
ret := mj.monitorMirrorStatus(cancel)
|
||||
<-doneCh
|
||||
return ret
|
||||
}
|
||||
|
||||
func newMirrorJob(srcURL, dstURL string, opts mirrorOptions) *mirrorJob {
|
||||
@@ -899,7 +914,7 @@ func newMirrorJob(srcURL, dstURL string, opts mirrorOptions) *mirrorJob {
|
||||
watcher: NewWatcher(UTCNow()),
|
||||
}
|
||||
|
||||
mj.parallel = newParallelManager(mj.statusCh)
|
||||
mj.parallel = newParallelManager(mj.statusCh, opts.maxWorkers)
|
||||
|
||||
// we'll define the status to use here,
|
||||
// do we want the quiet status? or the progressbar
|
||||
@@ -987,7 +1002,8 @@ func runMirror(ctx context.Context, srcURL, dstURL string, cli *cli.Context, enc
|
||||
isOverwrite = cli.Bool("overwrite")
|
||||
}
|
||||
|
||||
isWatch := cli.Bool("watch") || cli.Bool("multi-master") || cli.Bool("active-active")
|
||||
isWatch := cli.Bool("watch") || cli.Bool("multi-master")
|
||||
isActiveActive := cli.Bool("active-active")
|
||||
isRemove := cli.Bool("remove")
|
||||
md5, checksum := parseChecksum(cli)
|
||||
|
||||
@@ -1015,7 +1031,8 @@ func runMirror(ctx context.Context, srcURL, dstURL string, cli *cli.Context, enc
|
||||
storageClass: cli.String("storage-class"),
|
||||
userMetadata: userMetadata,
|
||||
encKeyDB: encKeyDB,
|
||||
activeActive: isWatch,
|
||||
activeActive: isActiveActive,
|
||||
maxWorkers: cli.Int("max-workers"),
|
||||
}
|
||||
|
||||
// If we are not using active/active and we are not removing
|
||||
@@ -1047,7 +1064,7 @@ func runMirror(ctx context.Context, srcURL, dstURL string, cli *cli.Context, enc
|
||||
|
||||
if d.Diff == differInSecond {
|
||||
diffBucket := strings.TrimPrefix(d.SecondURL, dstClt.GetURL().String())
|
||||
if !isFake && isRemove {
|
||||
if !isFake && isRemove && createDstBuckets {
|
||||
aliasedDstBucket := path.Join(dstURL, diffBucket)
|
||||
err := deleteBucket(ctx, aliasedDstBucket, false)
|
||||
mj.status.fatalIf(err, "Failed to start mirroring.")
|
||||
@@ -1064,6 +1081,15 @@ func runMirror(ctx context.Context, srcURL, dstURL string, cli *cli.Context, enc
|
||||
newDstClt, _ := newClient(newTgtURL)
|
||||
|
||||
if d.Diff == differInFirst {
|
||||
// This loop is responsible solely for bringing target on par with source at the bucket level.
|
||||
// createDstBuckets == false implies that the target itself represents a bucket.
|
||||
// So we don't want to perform MakeBucket (and in turn delete and recreate already existing buckets and objects) if it already exists.
|
||||
// Any differences at the object level between source and target's bucket will be synced as part of objectDifference() that gets
|
||||
// called later.
|
||||
if !createDstBuckets {
|
||||
continue
|
||||
}
|
||||
|
||||
var (
|
||||
withLock bool
|
||||
mode minio.RetentionMode
|
||||
@@ -1078,11 +1104,6 @@ func runMirror(ctx context.Context, srcURL, dstURL string, cli *cli.Context, enc
|
||||
}
|
||||
}
|
||||
|
||||
mj.status.PrintMsg(mirrorMessage{
|
||||
Source: newSrcURL,
|
||||
Target: newTgtURL,
|
||||
})
|
||||
|
||||
if mj.opts.isFake {
|
||||
continue
|
||||
}
|
||||
@@ -1092,6 +1113,11 @@ func runMirror(ctx context.Context, srcURL, dstURL string, cli *cli.Context, enc
|
||||
continue
|
||||
}
|
||||
|
||||
mj.status.PrintMsg(mirrorMessage{
|
||||
Source: newSrcURL,
|
||||
Target: newTgtURL,
|
||||
})
|
||||
|
||||
// Bucket only exists in the source, create the same bucket in the destination
|
||||
if err := newDstClt.MakeBucket(ctx, cli.String("region"), false, withLock); err != nil {
|
||||
errorIf(err, "Unable to create bucket at `%s`.", newTgtURL)
|
||||
@@ -1117,7 +1143,7 @@ func runMirror(ctx context.Context, srcURL, dstURL string, cli *cli.Context, enc
|
||||
}
|
||||
}
|
||||
|
||||
if mj.opts.isWatch {
|
||||
if mj.opts.isWatch || mj.opts.activeActive {
|
||||
// monitor mode will watch the source folders for changes,
|
||||
// and queue them for copying.
|
||||
if err := mj.watchURL(ctx, srcClt); err != nil {
|
||||
|
||||
+4
-5
@@ -22,6 +22,7 @@ import (
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"slices"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -198,11 +199,8 @@ func deltaSourceTarget(ctx context.Context, sourceURL, targetURL string, opts mi
|
||||
|
||||
if diffMsg.firstContent != nil {
|
||||
var found bool
|
||||
for _, esc := range opts.excludeStorageClasses {
|
||||
if esc == diffMsg.firstContent.StorageClass {
|
||||
found = true
|
||||
break
|
||||
}
|
||||
if slices.Contains(opts.excludeStorageClasses, diffMsg.firstContent.StorageClass) {
|
||||
found = true
|
||||
}
|
||||
if found {
|
||||
continue
|
||||
@@ -278,6 +276,7 @@ type mirrorOptions struct {
|
||||
userMetadata map[string]string
|
||||
checksum minio.ChecksumType
|
||||
sourceListingOnly bool
|
||||
maxWorkers int
|
||||
}
|
||||
|
||||
// Prepares urls that need to be copied or removed based on requested options.
|
||||
|
||||
+20
-8
@@ -59,6 +59,11 @@ var (
|
||||
Name: "disable-multipart",
|
||||
Usage: "disable multipart upload feature",
|
||||
},
|
||||
cli.StringFlag{
|
||||
Name: "tags",
|
||||
Usage: "apply one or more tags to the uploaded objects",
|
||||
},
|
||||
checksumFlag,
|
||||
}
|
||||
)
|
||||
|
||||
@@ -112,23 +117,29 @@ EXAMPLES:
|
||||
09. Move a list of objects from local file system to MinIO cloud storage with specified metadata, separated by ";"
|
||||
{{.Prompt}} {{.HelpName}} --attr "key1=value1;key2=value2" Music/*.mp4 play/mybucket/
|
||||
|
||||
10. Move a folder recursively from MinIO cloud storage to Amazon S3 cloud storage with Cache-Control and custom metadata, separated by ";".
|
||||
10. Move a list of objects from local file system to MinIO cloud storage and set tags to the uploaded objects
|
||||
{{.Prompt}} {{.HelpName}} --tag "key1=value1" Music/*.mp4 play/mybucket/
|
||||
|
||||
11. Move a folder recursively from MinIO cloud storage to Amazon S3 cloud storage with Cache-Control and custom metadata, separated by ";".
|
||||
{{.Prompt}} {{.HelpName}} --attr "Cache-Control=max-age=90000,min-fresh=9000;key1=value1;key2=value2" --recursive play/mybucket/myfolder/ s3/mybucket/
|
||||
|
||||
11. Move a text file to an object storage and assign REDUCED_REDUNDANCY storage-class to the uploaded object.
|
||||
12. Move a text file to an object storage and assign REDUCED_REDUNDANCY storage-class to the uploaded object.
|
||||
{{.Prompt}} {{.HelpName}} --storage-class REDUCED_REDUNDANCY myobject.txt play/mybucket
|
||||
|
||||
12. Move a text file to an object storage and preserve the file system attribute as metadata.
|
||||
13. Move a text file to an object storage and preserve the file system attribute as metadata.
|
||||
{{.Prompt}} {{.HelpName}} -a myobject.txt play/mybucket
|
||||
|
||||
13. Move a text file to an object storage and disable multipart upload feature.
|
||||
14. Move a text file to an object storage and disable multipart upload feature.
|
||||
{{.Prompt}} {{.HelpName}} --disable-multipart myobject.txt play/mybucket
|
||||
|
||||
14. Move a folder using client provided encryption keys from Amazon S3 to MinIO cloud storage.
|
||||
15. Move a folder using client provided encryption keys from Amazon S3 to MinIO cloud storage.
|
||||
{{.Prompt}} {{.HelpName}} --r --enc-c "s3/documents/=MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTIzNDU2Nzg5MBB" --enc-c "myminio/documents/=MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTIzNDU2Nzg5MDA" s3/documents/ myminio/documents/
|
||||
|
||||
15. Move a folder using specific server managed encryption keys from Amazon S3 to MinIO cloud storage.
|
||||
16. Move a folder using specific server managed encryption keys from Amazon S3 to MinIO cloud storage.
|
||||
{{.Prompt}} {{.HelpName}} --r --enc-s3 "s3/documents" --enc-s3 "myminio/documents" s3/documents/ myminio/documents/
|
||||
|
||||
17. Add SHA256 checksum to move a text file to MinIO cloud storage.
|
||||
{{.Prompt}} {{.HelpName}} --checksum SHA256 myobject.txt play/mybucket
|
||||
`,
|
||||
}
|
||||
|
||||
@@ -210,8 +221,9 @@ func mainMove(cliCtx *cli.Context) error {
|
||||
args := cliCtx.Args()
|
||||
srcURL := args.Get(0)
|
||||
dstURL := args.Get(1)
|
||||
if srcURL == dstURL {
|
||||
fatalIf(errDummy().Trace(), fmt.Sprintf("Source and destination urls cannot be the same: %v.", srcURL))
|
||||
if isURLPrefix(srcURL, dstURL) {
|
||||
fatalIf(errDummy().Trace(), fmt.Sprintf("The source %v and destination %v cannot be subdirectories of each other", srcURL, dstURL))
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+11
-3
@@ -76,11 +76,18 @@ type ParallelManager struct {
|
||||
|
||||
// The maximum memory to use
|
||||
maxMem uint64
|
||||
|
||||
// The maximum workers will be created
|
||||
maxWorkers int
|
||||
}
|
||||
|
||||
// addWorker creates a new worker to process tasks
|
||||
func (p *ParallelManager) addWorker() {
|
||||
if atomic.LoadUint32(&p.workersNum) >= maxParallelWorkers {
|
||||
maxWorkers := maxParallelWorkers
|
||||
if p.maxWorkers > 0 {
|
||||
maxWorkers = p.maxWorkers
|
||||
}
|
||||
if int(atomic.LoadUint32(&p.workersNum)) >= maxWorkers {
|
||||
// Number of maximum workers is reached, no need to
|
||||
// to create a new one.
|
||||
return
|
||||
@@ -154,7 +161,7 @@ func (p *ParallelManager) monitorProgress() {
|
||||
maxBandwidth = bandwidth
|
||||
}
|
||||
|
||||
for i := 0; i < defaultWorkerFactor; i++ {
|
||||
for range defaultWorkerFactor {
|
||||
p.addWorker()
|
||||
}
|
||||
}
|
||||
@@ -266,7 +273,7 @@ func availableMemory() (available uint64) {
|
||||
}
|
||||
|
||||
// newParallelManager starts new workers waiting for executing tasks
|
||||
func newParallelManager(resultCh chan URLs) *ParallelManager {
|
||||
func newParallelManager(resultCh chan URLs, maxWorkers int) *ParallelManager {
|
||||
p := &ParallelManager{
|
||||
wg: &sync.WaitGroup{},
|
||||
workersNum: 0,
|
||||
@@ -274,6 +281,7 @@ func newParallelManager(resultCh chan URLs) *ParallelManager {
|
||||
queueCh: make(chan task),
|
||||
resultCh: resultCh,
|
||||
maxMem: availableMemory(),
|
||||
maxWorkers: maxWorkers,
|
||||
}
|
||||
|
||||
// Start with runtime.NumCPU().
|
||||
|
||||
@@ -135,7 +135,6 @@ func TestParseDurationTime(t *testing.T) {
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
testCase := testCase
|
||||
t.Run("", func(t *testing.T) {
|
||||
myVal, err := ParseDuration(testCase.timeValue)
|
||||
if err != nil && err.Error() != testCase.err {
|
||||
|
||||
+174
-50
@@ -22,8 +22,11 @@ import (
|
||||
"fmt"
|
||||
"math"
|
||||
"net/url"
|
||||
"os"
|
||||
"os/signal"
|
||||
"strconv"
|
||||
"strings"
|
||||
"syscall"
|
||||
"text/tabwriter"
|
||||
"text/template"
|
||||
"time"
|
||||
@@ -58,6 +61,10 @@ var pingFlags = []cli.Flag{
|
||||
Name: "distributed, a",
|
||||
Usage: "ping all the servers in the cluster, use it when you have direct access to nodes/pods",
|
||||
},
|
||||
cli.StringFlag{
|
||||
Name: "node",
|
||||
Usage: "ping the specified node",
|
||||
},
|
||||
}
|
||||
|
||||
// return latency and liveness probe.
|
||||
@@ -113,14 +120,15 @@ func (pr PingResult) JSON() string {
|
||||
var colorMap = template.FuncMap{
|
||||
"colorWhite": color.New(color.FgWhite).SprintfFunc(),
|
||||
"colorRed": color.New(color.FgRed).SprintfFunc(),
|
||||
"colorGreen": color.New(color.FgGreen).SprintfFunc(),
|
||||
}
|
||||
|
||||
// PingDist is the template for ping result in distributed mode
|
||||
const PingDist = `{{$x := .Counter}}{{range .EndPointsStats}}{{if eq "0 " .CountErr}}{{colorWhite $x}}{{colorWhite ": "}}{{colorWhite .Endpoint.Scheme}}{{colorWhite "://"}}{{colorWhite .Endpoint.Host}}{{if ne "" .Endpoint.Port}}{{colorWhite ":"}}{{colorWhite .Endpoint.Port}}{{end}}{{"\t"}}{{ colorWhite "min="}}{{colorWhite .Min}}{{"\t"}}{{colorWhite "max="}}{{colorWhite .Max}}{{"\t"}}{{colorWhite "average="}}{{colorWhite .Average}}{{"\t"}}{{colorWhite "errors="}}{{colorWhite .CountErr}}{{" "}}{{colorWhite "roundtrip="}}{{colorWhite .Roundtrip}}{{else}}{{colorRed $x}}{{colorRed ": "}}{{colorRed .Endpoint.Scheme}}{{colorRed "://"}}{{colorRed .Endpoint.Host}}{{if ne "" .Endpoint.Port}}{{colorRed ":"}}{{colorRed .Endpoint.Port}}{{end}}{{"\t"}}{{ colorRed "min="}}{{colorRed .Min}}{{"\t"}}{{colorRed "max="}}{{colorRed .Max}}{{"\t"}}{{colorRed "average="}}{{colorRed .Average}}{{"\t"}}{{colorRed "errors="}}{{colorRed .CountErr}}{{" "}}{{colorRed "roundtrip="}}{{colorRed .Roundtrip}}{{end}}
|
||||
const PingDist = `{{$x := .Counter}}{{range .EndPointsStats}}{{if eq "ok " .Status}}{{colorWhite $x}}{{colorWhite ": "}}{{colorWhite .Endpoint.Scheme}}{{colorWhite "://"}}{{colorWhite .Endpoint.Host}}{{"\t"}}{{colorWhite "status="}}{{colorGreen .Status}}{{" "}}{{colorWhite "time="}}{{colorWhite .Time}}{{else}}{{colorRed $x}}{{colorRed ": "}}{{colorRed .Endpoint.Scheme}}{{colorRed "://"}}{{colorRed .Endpoint.Host}}{{"\t"}}{{colorRed "status="}}{{colorRed .Status}}{{" "}}{{colorRed "time="}}{{colorRed .Time}}{{end}}
|
||||
{{end}}`
|
||||
|
||||
// Ping is the template for ping result
|
||||
const Ping = `{{$x := .Counter}}{{range .EndPointsStats}}{{if eq "0 " .CountErr}}{{colorWhite $x}}{{colorWhite ": "}}{{colorWhite .Endpoint.Scheme}}{{colorWhite "://"}}{{colorWhite .Endpoint.Host}}{{if ne "" .Endpoint.Port}}{{colorWhite ":"}}{{colorWhite .Endpoint.Port}}{{end}}{{"\t"}}{{ colorWhite "min="}}{{colorWhite .Min}}{{"\t"}}{{colorWhite "max="}}{{colorWhite .Max}}{{"\t"}}{{colorWhite "average="}}{{colorWhite .Average}}{{"\t"}}{{colorWhite "errors="}}{{colorWhite .CountErr}}{{" "}}{{colorWhite "roundtrip="}}{{colorWhite .Roundtrip}}{{else}}{{colorRed $x}}{{colorRed ": "}}{{colorRed .Endpoint.Scheme}}{{colorRed "://"}}{{colorRed .Endpoint.Host}}{{if ne "" .Endpoint.Port}}{{colorRed ":"}}{{colorRed .Endpoint.Port}}{{end}}{{"\t"}}{{ colorRed "min="}}{{colorRed .Min}}{{"\t"}}{{colorRed "max="}}{{colorRed .Max}}{{"\t"}}{{colorRed "average="}}{{colorRed .Average}}{{"\t"}}{{colorRed "errors="}}{{colorRed .CountErr}}{{" "}}{{colorRed "roundtrip="}}{{colorRed .Roundtrip}}{{end}}{{end}}`
|
||||
const Ping = `{{$x := .Counter}}{{range .EndPointsStats}}{{if eq "ok " .Status}}{{colorWhite $x}}{{colorWhite ": "}}{{colorWhite .Endpoint.Scheme}}{{colorWhite "://"}}{{colorWhite .Endpoint.Host}}{{"\t"}}{{colorWhite "status="}}{{colorGreen .Status}}{{" "}}{{colorWhite "time="}}{{colorWhite .Time}}{{else}}{{colorRed $x}}{{colorRed ": "}}{{colorRed .Endpoint.Scheme}}{{colorRed "://"}}{{colorRed .Endpoint.Host}}{{"\t"}}{{colorRed "status="}}{{colorRed .Status}}{{" "}}{{colorRed "time="}}{{colorRed .Time}}{{end}}{{end}}`
|
||||
|
||||
// PingTemplateDist - captures ping template
|
||||
var PingTemplateDist = template.Must(template.New("ping-list").Funcs(colorMap).Parse(PingDist))
|
||||
@@ -145,14 +153,11 @@ func (pr PingResult) String() string {
|
||||
|
||||
// EndPointStats - container to hold server ping stats
|
||||
type EndPointStats struct {
|
||||
Endpoint *url.URL `json:"endpoint"`
|
||||
Min string `json:"min"`
|
||||
Max string `json:"max"`
|
||||
Average string `json:"average"`
|
||||
DNS string `json:"dns"`
|
||||
CountErr string `json:"error-count,omitempty"`
|
||||
Error string `json:"error,omitempty"`
|
||||
Roundtrip string `json:"roundtrip"`
|
||||
Endpoint *url.URL `json:"endpoint"`
|
||||
DNS string `json:"dns"`
|
||||
Status string `json:"status,omitempty"`
|
||||
Error string `json:"error,omitempty"`
|
||||
Time string `json:"time"`
|
||||
}
|
||||
|
||||
// PingResult contains ping output
|
||||
@@ -162,15 +167,71 @@ type PingResult struct {
|
||||
EndPointsStats []EndPointStats `json:"servers"`
|
||||
}
|
||||
|
||||
type serverStats struct {
|
||||
min uint64
|
||||
max uint64
|
||||
sum uint64
|
||||
avg uint64
|
||||
dns uint64 // last DNS resolving time
|
||||
errorCount int // used to keep a track of consecutive errors
|
||||
err string
|
||||
counter int // used to find the average, acts as denominator
|
||||
// PingSummary Summarizes the results of the ping execution.
|
||||
type PingSummary struct {
|
||||
Status string `json:"status"`
|
||||
// map to contain server stats for all the servers
|
||||
ServerMap map[string]ServerStats `json:"serverMap"`
|
||||
}
|
||||
|
||||
// JSON jsonified ping summary message.
|
||||
func (ps PingSummary) JSON() string {
|
||||
pingJSONBytes, e := json.MarshalIndent(ps, "", " ")
|
||||
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
|
||||
|
||||
return string(pingJSONBytes)
|
||||
}
|
||||
|
||||
// String colorized ping summary message.
|
||||
func (ps PingSummary) String() string {
|
||||
dspOrder := []col{colGreen} // Header
|
||||
for i := 0; i < len(ps.ServerMap); i++ {
|
||||
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, false, false}, 0)
|
||||
|
||||
var builder strings.Builder
|
||||
cellText := make([][]string, len(ps.ServerMap)+1)
|
||||
cellText[0] = []string{
|
||||
"Endpoint",
|
||||
"Min",
|
||||
"Avg",
|
||||
"Max",
|
||||
"Error",
|
||||
"Count",
|
||||
}
|
||||
index := 0
|
||||
for endpoint, ping := range ps.ServerMap {
|
||||
index++
|
||||
cellText[index] = []string{
|
||||
ping.Endpoint.Scheme + "://" + endpoint,
|
||||
trimToTwoDecimal(time.Duration(ping.Min)),
|
||||
trimToTwoDecimal(time.Duration(ping.Avg)),
|
||||
trimToTwoDecimal(time.Duration(ping.Max)),
|
||||
strconv.Itoa(ping.ErrorCount),
|
||||
strconv.Itoa(ping.Counter),
|
||||
}
|
||||
}
|
||||
e := tbl.PopulateTable(&builder, cellText)
|
||||
fatalIf(probe.NewError(e), "unable to populate the table")
|
||||
return builder.String()
|
||||
}
|
||||
|
||||
// ServerStats ping result of each endpoint
|
||||
type ServerStats struct {
|
||||
Endpoint *url.URL `json:"endpoint"`
|
||||
Min uint64 `json:"min"`
|
||||
Max uint64 `json:"max"`
|
||||
Sum uint64 `json:"sum"`
|
||||
Avg uint64 `json:"avg"`
|
||||
DNS uint64 `json:"dns"` // last DNS resolving time
|
||||
ErrorCount int `json:"errorCount"` // used to keep a track of consecutive errors
|
||||
Err string `json:"err"`
|
||||
Counter int `json:"counter"` // used to find the average, acts as denominator
|
||||
}
|
||||
|
||||
func fetchAdminInfo(admClnt *madmin.AdminClient) (madmin.InfoMessage, error) {
|
||||
@@ -201,30 +262,49 @@ func fetchAdminInfo(admClnt *madmin.AdminClient) (madmin.InfoMessage, error) {
|
||||
}
|
||||
}
|
||||
|
||||
func ping(ctx context.Context, cliCtx *cli.Context, anonClient *madmin.AnonymousClient, admInfo madmin.InfoMessage, endPointMap map[string]serverStats, index int) {
|
||||
func filterAdminInfo(admClnt *madmin.AdminClient, nodeName string) (madmin.InfoMessage, error) {
|
||||
admInfo, e := fetchAdminInfo(admClnt)
|
||||
if e != nil {
|
||||
return madmin.InfoMessage{}, e
|
||||
}
|
||||
if len(admInfo.Servers) <= 0 || nodeName == "" {
|
||||
return admInfo, nil
|
||||
}
|
||||
for _, server := range admInfo.Servers {
|
||||
if server.Endpoint == nodeName {
|
||||
admInfo.Servers = []madmin.ServerProperties{server}
|
||||
return admInfo, nil
|
||||
}
|
||||
}
|
||||
fatalIf(errInvalidArgument().Trace(), "Node "+nodeName+" not exist")
|
||||
return madmin.InfoMessage{}, e
|
||||
}
|
||||
|
||||
func ping(ctx context.Context, cliCtx *cli.Context, anonClient *madmin.AnonymousClient, admInfo madmin.InfoMessage, pingSummary PingSummary, index int) {
|
||||
var endPointStats []EndPointStats
|
||||
var servers []madmin.ServerProperties
|
||||
if cliCtx.Bool("distributed") {
|
||||
if cliCtx.Bool("distributed") || cliCtx.IsSet("node") {
|
||||
servers = admInfo.Servers
|
||||
}
|
||||
allOK := true
|
||||
|
||||
for result := range anonClient.Alive(ctx, madmin.AliveOpts{}, servers...) {
|
||||
stat := pingStats(cliCtx, result, endPointMap)
|
||||
stat := pingStats(cliCtx, result, pingSummary)
|
||||
status := "ok "
|
||||
if !result.Online {
|
||||
status = "failed "
|
||||
}
|
||||
|
||||
allOK = allOK && result.Online
|
||||
endPointStat := EndPointStats{
|
||||
Endpoint: result.Endpoint,
|
||||
Min: trimToTwoDecimal(time.Duration(stat.min)),
|
||||
Max: trimToTwoDecimal(time.Duration(stat.max)),
|
||||
Average: trimToTwoDecimal(time.Duration(stat.avg)),
|
||||
DNS: time.Duration(stat.dns).String(),
|
||||
CountErr: pad(strconv.Itoa(stat.errorCount), " ", 3-len(strconv.Itoa(stat.errorCount)), false),
|
||||
Error: stat.err,
|
||||
Roundtrip: trimToTwoDecimal(result.ResponseTime),
|
||||
Endpoint: result.Endpoint,
|
||||
DNS: time.Duration(stat.DNS).String(),
|
||||
Status: status,
|
||||
Error: stat.Err,
|
||||
Time: trimToTwoDecimal(result.ResponseTime),
|
||||
}
|
||||
endPointStats = append(endPointStats, endPointStat)
|
||||
endPointMap[result.Endpoint.Host] = stat
|
||||
pingSummary.ServerMap[result.Endpoint.Host] = stat
|
||||
|
||||
}
|
||||
stop = stop || cliCtx.Bool("exit") && allOK
|
||||
@@ -280,7 +360,7 @@ func pad(s, p string, count int, left bool) string {
|
||||
return string(ret)
|
||||
}
|
||||
|
||||
func pingStats(cliCtx *cli.Context, result madmin.AliveResult, serverMap map[string]serverStats) serverStats {
|
||||
func pingStats(cliCtx *cli.Context, result madmin.AliveResult, ps PingSummary) ServerStats {
|
||||
var errorString string
|
||||
var sum, avg, dns uint64
|
||||
minPing := uint64(math.MaxUint64)
|
||||
@@ -289,13 +369,13 @@ func pingStats(cliCtx *cli.Context, result madmin.AliveResult, serverMap map[str
|
||||
|
||||
if result.Error != nil {
|
||||
errorString = result.Error.Error()
|
||||
if stat, ok := serverMap[result.Endpoint.Host]; ok {
|
||||
minPing = stat.min
|
||||
maxPing = stat.max
|
||||
sum = stat.sum
|
||||
counter = stat.counter
|
||||
avg = stat.avg
|
||||
errorCount = stat.errorCount + 1
|
||||
if stat, ok := ps.ServerMap[result.Endpoint.Host]; ok {
|
||||
minPing = stat.Min
|
||||
maxPing = stat.Max
|
||||
sum = stat.Sum
|
||||
counter = stat.Counter
|
||||
avg = stat.Avg
|
||||
errorCount = stat.ErrorCount + 1
|
||||
|
||||
} else {
|
||||
minPing = 0
|
||||
@@ -308,17 +388,17 @@ func pingStats(cliCtx *cli.Context, result madmin.AliveResult, serverMap map[str
|
||||
} else {
|
||||
// reset consecutive error count
|
||||
errorCount = 0
|
||||
if stat, ok := serverMap[result.Endpoint.Host]; ok {
|
||||
if stat, ok := ps.ServerMap[result.Endpoint.Host]; ok {
|
||||
var minVal uint64
|
||||
if stat.min == 0 {
|
||||
if stat.Min == 0 {
|
||||
minVal = uint64(result.ResponseTime)
|
||||
} else {
|
||||
minVal = stat.min
|
||||
minVal = stat.Min
|
||||
}
|
||||
minPing = uint64(math.Min(float64(minVal), float64(uint64(result.ResponseTime))))
|
||||
maxPing = uint64(math.Max(float64(stat.max), float64(uint64(result.ResponseTime))))
|
||||
sum = stat.sum + uint64(result.ResponseTime.Nanoseconds())
|
||||
counter = stat.counter + 1
|
||||
maxPing = uint64(math.Max(float64(stat.Max), float64(uint64(result.ResponseTime))))
|
||||
sum = stat.Sum + uint64(result.ResponseTime.Nanoseconds())
|
||||
counter = stat.Counter + 1
|
||||
|
||||
} else {
|
||||
minPing = uint64(math.Min(float64(minPing), float64(uint64(result.ResponseTime))))
|
||||
@@ -329,7 +409,38 @@ func pingStats(cliCtx *cli.Context, result madmin.AliveResult, serverMap map[str
|
||||
avg = sum / uint64(counter)
|
||||
dns = uint64(result.DNSResolveTime.Nanoseconds())
|
||||
}
|
||||
return serverStats{minPing, maxPing, sum, avg, dns, errorCount, errorString, counter}
|
||||
return ServerStats{result.Endpoint, minPing, maxPing, sum, avg, dns, errorCount, errorString, counter}
|
||||
}
|
||||
|
||||
func watchSignals(ps PingSummary) {
|
||||
c := make(chan os.Signal, 1)
|
||||
signal.Notify(c, syscall.SIGTERM, syscall.SIGINT)
|
||||
go func() {
|
||||
s := <-c
|
||||
// Ensure that the table structure is not disrupted when manually canceling.
|
||||
fmt.Println("")
|
||||
printMsg(ps)
|
||||
|
||||
// Stop profiling if enabled, this needs to be before canceling the
|
||||
// global context to check for any unusual cpu/mem/goroutines usage
|
||||
stopProfiling()
|
||||
|
||||
// Cancel the global context
|
||||
globalCancel()
|
||||
|
||||
var exitCode int
|
||||
switch s.String() {
|
||||
case "interrupt":
|
||||
exitCode = globalCancelExitStatus
|
||||
case "killed":
|
||||
exitCode = globalKillExitStatus
|
||||
case "terminated":
|
||||
exitCode = globalTerminatExitStatus
|
||||
default:
|
||||
exitCode = globalErrorExitStatus
|
||||
}
|
||||
os.Exit(exitCode)
|
||||
}()
|
||||
}
|
||||
|
||||
// mainPing is entry point for ping command.
|
||||
@@ -356,9 +467,19 @@ func mainPing(cliCtx *cli.Context) error {
|
||||
admInfo, e = fetchAdminInfo(admClient)
|
||||
fatalIf(probe.NewError(e).Trace(aliasedURL), "Unable to get server info")
|
||||
}
|
||||
if cliCtx.IsSet("node") {
|
||||
var e error
|
||||
admInfo, e = filterAdminInfo(admClient, cliCtx.String("node"))
|
||||
fatalIf(probe.NewError(e).Trace(aliasedURL), "Unable to get server info")
|
||||
}
|
||||
pingSummary := PingSummary{
|
||||
ServerMap: make(map[string]ServerStats),
|
||||
Status: "success",
|
||||
}
|
||||
|
||||
// map to contain server stats for all the servers
|
||||
serverMap := make(map[string]serverStats)
|
||||
// stop global signals trap.
|
||||
GlobalTrapSignals = false
|
||||
watchSignals(pingSummary)
|
||||
|
||||
index := 1
|
||||
if cliCtx.IsSet("count") {
|
||||
@@ -369,9 +490,10 @@ func mainPing(cliCtx *cli.Context) error {
|
||||
for index <= count {
|
||||
// return if consecutive error count more then specified value
|
||||
if stop {
|
||||
printMsg(pingSummary)
|
||||
return nil
|
||||
}
|
||||
ping(ctx, cliCtx, anonClient, admInfo, serverMap, index)
|
||||
ping(ctx, cliCtx, anonClient, admInfo, pingSummary, index)
|
||||
index++
|
||||
}
|
||||
} else {
|
||||
@@ -382,12 +504,14 @@ func mainPing(cliCtx *cli.Context) error {
|
||||
default:
|
||||
// return if consecutive error count more then specified value
|
||||
if stop {
|
||||
printMsg(pingSummary)
|
||||
return nil
|
||||
}
|
||||
ping(ctx, cliCtx, anonClient, admInfo, serverMap, index)
|
||||
ping(ctx, cliCtx, anonClient, admInfo, pingSummary, index)
|
||||
index++
|
||||
}
|
||||
}
|
||||
}
|
||||
printMsg(pingSummary)
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -34,7 +34,7 @@ func testPipeChan(inputCh, outputCh chan notify.EventInfo, totalMsgs int) error
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
for i := 0; i < totalMsgs; i++ {
|
||||
for range totalMsgs {
|
||||
inputCh <- msgCtnt
|
||||
}
|
||||
close(inputCh)
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user