diff --git a/.github/workflows/go.yml b/.github/workflows/go.yml index edc135b4..81e4d319 100644 --- a/.github/workflows/go.yml +++ b/.github/workflows/go.yml @@ -73,3 +73,7 @@ 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 && staticcheck -tests=false -checks="all,-ST1000,-ST1003,-ST1016,-ST1020,-ST1021,-ST1022,-ST1023,-ST1005" ./... diff --git a/cmd/admin-bucket-info.go b/cmd/admin-bucket-info.go index 21fe8e5d..7317fd4a 100644 --- a/cmd/admin-bucket-info.go +++ b/cmd/admin-bucket-info.go @@ -23,7 +23,7 @@ import ( "sort" "strings" - humanize "github.com/dustin/go-humanize" + "github.com/dustin/go-humanize" "github.com/fatih/color" "github.com/minio/cli" json "github.com/minio/colorjson" @@ -79,18 +79,18 @@ func countDigits(num uint64) (count uint) { func (bi adminBucketInfoMessage) String() string { var b strings.Builder - fmt.Fprintf(&b, console.Colorize("Title", "Usage:\n")) + fmt.Fprint(&b, console.Colorize("Title", "Usage:\n")) fmt.Fprintf(&b, "%16s: %s\n", "Total size", console.Colorize("Count", humanize.IBytes(bi.UsageInfo.Size))) fmt.Fprintf(&b, "%16s: %s\n", "Objects count", console.Colorize("Count", humanize.Comma(int64(bi.UsageInfo.ObjectsCount)))) fmt.Fprintf(&b, "%16s: %s\n", "Versions count", console.Colorize("Count", humanize.Comma(int64(bi.UsageInfo.VersionsCount)))) fmt.Fprintf(&b, "\n") - fmt.Fprintf(&b, console.Colorize("Title", "Properties:\n")) - fmt.Fprintf(&b, prettyPrintBucketMetadata(bi.Props)) + fmt.Fprint(&b, console.Colorize("Title", "Properties:\n")) + fmt.Fprint(&b, prettyPrintBucketMetadata(bi.Props)) fmt.Fprintf(&b, "\n") - fmt.Fprintf(&b, console.Colorize("Title", "Object sizes histogram:\n")) + fmt.Fprint(&b, console.Colorize("Title", "Object sizes histogram:\n")) var maxDigits uint for _, val := range bi.UsageInfo.ObjectSizesHistogram { diff --git a/cmd/admin-cluster-bucket-export.go b/cmd/admin-cluster-bucket-export.go index 7b2cf508..5b7bb8df 100644 --- a/cmd/admin-cluster-bucket-export.go +++ b/cmd/admin-cluster-bucket-export.go @@ -21,7 +21,6 @@ import ( "context" "fmt" "io" - "io/ioutil" "os" "path/filepath" "time" @@ -92,7 +91,7 @@ func mainClusterBucketExport(ctx *cli.Context) error { } // Create bucket metadata zip file - tmpFile, e := ioutil.TempFile("", fmt.Sprintf("%s-metadata-", bucket)) + tmpFile, e := os.CreateTemp("", fmt.Sprintf("%s-metadata-", bucket)) fatalIf(probe.NewError(e), "Unable to download file data.") ext := "zip" diff --git a/cmd/admin-cluster-bucket-import.go b/cmd/admin-cluster-bucket-import.go index ece4febf..e2c05c90 100644 --- a/cmd/admin-cluster-bucket-import.go +++ b/cmd/admin-cluster-bucket-import.go @@ -177,7 +177,6 @@ func (i importMetaMsg) String() string { } func (i importMetaMsg) JSON() string { - i.Status = "success" buf := &bytes.Buffer{} enc := json.NewEncoder(buf) enc.SetIndent("", " ") diff --git a/cmd/admin-cluster-iam-export.go b/cmd/admin-cluster-iam-export.go index 172f74d1..71ad0d50 100644 --- a/cmd/admin-cluster-iam-export.go +++ b/cmd/admin-cluster-iam-export.go @@ -21,7 +21,6 @@ import ( "context" "fmt" "io" - "io/ioutil" "os" "time" @@ -82,7 +81,7 @@ func mainClusterIAMExport(ctx *cli.Context) error { fatalIf(probe.NewError(e).Trace(aliasedURL), "Unable to export IAM info.") // Create iam info zip file - tmpFile, e := ioutil.TempFile("", fmt.Sprintf("%s-iam-info", aliasedURL)) + tmpFile, e := os.CreateTemp("", fmt.Sprintf("%s-iam-info", aliasedURL)) fatalIf(probe.NewError(e), "Unable to download file data.") ext := "zip" diff --git a/cmd/admin-heal.go b/cmd/admin-heal.go index b3f5959d..5e989142 100644 --- a/cmd/admin-heal.go +++ b/cmd/admin-heal.go @@ -378,17 +378,17 @@ func (s verboseBackgroundHealStatusMessage) String() string { _, ok := offlineEndpoints[endpoint] if ok { stateText := console.Colorize("NodeFailed", "OFFLINE") - fmt.Fprintf(&msg, fmt.Sprintf(" %s: %s\n", endpoint, stateText)) + fmt.Fprintf(&msg, " %s: %s\n", endpoint, stateText) continue } serverStatus := serversStatus[endpoint] switch { case showTolerance: serverHeader := " %s: (Tolerance: %d server(s))\n" - fmt.Fprintf(&msg, fmt.Sprintf(serverHeader, endpoint, poolsInfo[serverStatus.pool].tolerance)) + fmt.Fprintf(&msg, serverHeader, endpoint, poolsInfo[serverStatus.pool].tolerance) default: serverHeader := " %s:\n" - fmt.Fprintf(&msg, fmt.Sprintf(serverHeader, endpoint)) + fmt.Fprintf(&msg, serverHeader, endpoint) } for _, d := range serverStatus.disks { @@ -439,11 +439,11 @@ func (s verboseBackgroundHealStatusMessage) String() string { summary := shortBackgroundHealStatusMessage{HealInfo: s.HealInfo} - fmt.Fprintf(&msg, "\n") - fmt.Fprintf(&msg, "Summary:\n") - fmt.Fprintf(&msg, "=======\n") - fmt.Fprintf(&msg, summary.String()) - fmt.Fprintf(&msg, "\n") + fmt.Fprint(&msg, "\n") + fmt.Fprint(&msg, "Summary:\n") + fmt.Fprint(&msg, "=======\n") + fmt.Fprint(&msg, summary.String()) + fmt.Fprint(&msg, "\n") return msg.String() } @@ -540,7 +540,7 @@ func (s shortBackgroundHealStatusMessage) String() string { bytesHealedPerSec += float64(time.Second) * float64(disk.HealInfo.BytesDone) / float64(disk.HealInfo.LastUpdate.Sub(disk.HealInfo.Started)) itemsHealedPerSec += float64(time.Second) * float64(disk.HealInfo.ItemsHealed+disk.HealInfo.ItemsFailed) / float64(disk.HealInfo.LastUpdate.Sub(disk.HealInfo.Started)) - scanSpeed := float64(disk.UsedSpace) / float64(time.Now().Sub(disk.HealInfo.Started)) + scanSpeed := float64(disk.UsedSpace) / float64(time.Since(disk.HealInfo.Started)) remainingTime := time.Duration(float64(setsStatus[diskSet].maxUsedSpace-disk.UsedSpace) / scanSpeed) if remainingTime > healingRemaining { healingRemaining = remainingTime diff --git a/cmd/admin-info.go b/cmd/admin-info.go index e0dc964d..4d848ee4 100644 --- a/cmd/admin-info.go +++ b/cmd/admin-info.go @@ -25,7 +25,7 @@ import ( "strings" "time" - humanize "github.com/dustin/go-humanize" + "github.com/dustin/go-humanize" "github.com/dustin/go-humanize/english" "github.com/fatih/color" "github.com/minio/cli" @@ -269,7 +269,7 @@ func (u clusterStruct) String() (msg string) { } if backendType == madmin.Erasure { - msg += fmt.Sprintf("Pools:\n") + msg += "Pools:\n" for pool, summary := range clusterSummary { msg += fmt.Sprintf(" %s, Erasure sets: %d, Drives per erasure set: %d\n", console.Colorize("Info", humanize.Ordinal(pool+1)), summary.setsCount, summary.drivesPerSet) diff --git a/cmd/admin-kms-key-create.go b/cmd/admin-kms-key-create.go index 79185cab..9b8a12e1 100644 --- a/cmd/admin-kms-key-create.go +++ b/cmd/admin-kms-key-create.go @@ -25,7 +25,7 @@ import ( "github.com/minio/cli" "github.com/minio/mc/pkg/probe" "github.com/minio/pkg/console" - "golang.org/x/crypto/ssh/terminal" + "golang.org/x/term" ) var adminKMSCreateKeyCmd = cli.Command{ @@ -63,7 +63,7 @@ func mainAdminKMSCreateKey(ctx *cli.Context) error { e := client.CreateKey(globalContext, keyID) fatalIf(probe.NewError(e), "Failed to create master key") - if terminal.IsTerminal(int(os.Stdout.Fd())) { + if term.IsTerminal(int(os.Stdout.Fd())) { console.Println(color.GreenString(fmt.Sprintf("Created master key `%s` successfully", keyID))) } return nil diff --git a/cmd/admin-policy-add.go b/cmd/admin-policy-add.go index 3172bcbb..7183d1ea 100644 --- a/cmd/admin-policy-add.go +++ b/cmd/admin-policy-add.go @@ -19,7 +19,7 @@ package cmd import ( "fmt" - "io/ioutil" + "os" "github.com/fatih/color" "github.com/minio/cli" @@ -126,7 +126,7 @@ func mainAdminPolicyAdd(ctx *cli.Context) error { args := ctx.Args() aliasedURL := args.Get(0) - policy, e := ioutil.ReadFile(args.Get(2)) + policy, e := os.ReadFile(args.Get(2)) fatalIf(probe.NewError(e).Trace(args...), "Unable to get policy") // Create a new MinIO Admin Client diff --git a/cmd/admin-prometheus-metrics.go b/cmd/admin-prometheus-metrics.go index 961ecbf9..16f8e6b8 100644 --- a/cmd/admin-prometheus-metrics.go +++ b/cmd/admin-prometheus-metrics.go @@ -19,7 +19,6 @@ package cmd import ( "io" - "io/ioutil" "net/http" "time" @@ -27,7 +26,7 @@ import ( json "github.com/minio/colorjson" "github.com/minio/mc/pkg/probe" dto "github.com/prometheus/client_model/go" - prom2json "github.com/prometheus/prom2json" + "github.com/prometheus/prom2json" ) var adminPrometheusMetricsCmd = cli.Command{ @@ -119,7 +118,7 @@ func (pm prometheusMetricsReader) JSON() string { // String - returns the string representation of the prometheus metrics func (pm prometheusMetricsReader) String() string { - respBytes, e := ioutil.ReadAll(pm.Reader) + respBytes, e := io.ReadAll(pm.Reader) if e != nil { fatalIf(probe.NewError(e), "error reading metrics:") } diff --git a/cmd/admin-replicate-remove.go b/cmd/admin-replicate-remove.go index a4cf3d0a..a4423faf 100644 --- a/cmd/admin-replicate-remove.go +++ b/cmd/admin-replicate-remove.go @@ -80,7 +80,7 @@ func (i srRemoveStatus) JSON() string { func (i srRemoveStatus) String() string { if i.RemoveAll { - return console.Colorize("UserMessage", fmt.Sprintf("All site(s) were removed successfully")) + return console.Colorize("UserMessage", "All site(s) were removed successfully") } return console.Colorize("UserMessage", fmt.Sprintf("Following site(s) %s were removed successfully", strings.Join(i.sites, ", "))) } diff --git a/cmd/admin-replicate-status.go b/cmd/admin-replicate-status.go index 721381d2..b97c834e 100644 --- a/cmd/admin-replicate-status.go +++ b/cmd/admin-replicate-status.go @@ -252,7 +252,7 @@ func (i srStatus) String() string { switch { case !ss.HasUser: - details = append(details, fmt.Sprintf("%s", blankCell)) + details = append(details, blankCell) case !ok, ss.UserInfoMismatch: details = append(details, fmt.Sprintf("%s in-sync", crossTickCell)) default: @@ -292,7 +292,7 @@ func (i srStatus) String() string { ss := ssMap[dID] switch { case !ss.HasGroup: - details = append(details, fmt.Sprintf("%s", blankCell)) + details = append(details, blankCell) case ss.GroupDescMismatch: details = append(details, fmt.Sprintf("%s in-sync", crossTickCell)) default: @@ -713,11 +713,11 @@ func mainAdminReplicationStatus(ctx *cli.Context) error { func syncStatus(mismatch, set bool) (string, string) { if !set { - return "Entity", fmt.Sprintf("%s", blankCell) + return "Entity", blankCell } if mismatch { - return "Entity", fmt.Sprintf("%s", crossTickCell) + return "Entity", crossTickCell } - return "Entity", fmt.Sprintf("%s", tickCell) + return "Entity", tickCell } diff --git a/cmd/admin-tier-add.go b/cmd/admin-tier-add.go index 7235faec..64910368 100644 --- a/cmd/admin-tier-add.go +++ b/cmd/admin-tier-add.go @@ -19,13 +19,13 @@ package cmd import ( "fmt" - "io/ioutil" + "os" "strings" "github.com/fatih/color" "github.com/minio/cli" json "github.com/minio/colorjson" - madmin "github.com/minio/madmin-go/v2" + "github.com/minio/madmin-go/v2" "github.com/minio/mc/pkg/probe" "github.com/minio/pkg/console" ) @@ -285,7 +285,7 @@ func fetchTierConfig(ctx *cli.Context, tierName string, tierType madmin.TierType } credsPath := ctx.String("credentials-file") - credsBytes, err := ioutil.ReadFile(credsPath) + credsBytes, err := os.ReadFile(credsPath) if err != nil { fatalIf(probe.NewError(err), "Failed to read credentials file") } diff --git a/cmd/admin-tier-edit.go b/cmd/admin-tier-edit.go index 35d11f15..01f9481d 100644 --- a/cmd/admin-tier-edit.go +++ b/cmd/admin-tier-edit.go @@ -18,11 +18,11 @@ package cmd import ( - "io/ioutil" + "os" "github.com/fatih/color" "github.com/minio/cli" - madmin "github.com/minio/madmin-go/v2" + "github.com/minio/madmin-go/v2" "github.com/minio/mc/pkg/probe" "github.com/minio/pkg/console" ) @@ -126,7 +126,7 @@ func mainAdminTierEdit(ctx *cli.Context) error { case accountKey != "": // Azure tier creds.SecretKey = accountKey case credsPath != "": // GCS tier - credsBytes, err := ioutil.ReadFile(credsPath) + credsBytes, err := os.ReadFile(credsPath) if err != nil { fatalIf(probe.NewError(err), "Failed to read credentials file") } diff --git a/cmd/admin-tier-info-ui.go b/cmd/admin-tier-info-ui.go index f4860663..7dd8b7b9 100644 --- a/cmd/admin-tier-info-ui.go +++ b/cmd/admin-tier-info-ui.go @@ -21,7 +21,7 @@ import ( "fmt" "strconv" - humanize "github.com/dustin/go-humanize" + "github.com/dustin/go-humanize" "github.com/gdamore/tcell/v2" "github.com/minio/madmin-go/v2" "github.com/navidys/tvxwidgets" @@ -46,7 +46,7 @@ func quitOnKeys(app *tview.Application) func(event *tcell.EventKey) *tcell.Event } } -func (ts tierInfos) TableUI() *tview.Table { +func (t tierInfos) TableUI() *tview.Table { table := tview.NewTable(). SetBorders(true) columnHdrs := []string{"Name", "API", "Type", "Usage", "Objects", "Versions"} @@ -63,7 +63,7 @@ func (ts tierInfos) TableUI() *tview.Table { } return "warm" } - for i, tInfo := range ts { + for i, tInfo := range t { table.SetCell(i+1, 0, tview.NewTableCell(tInfo.Name). SetTextColor(tcell.ColorWhite). @@ -93,10 +93,10 @@ func (ts tierInfos) TableUI() *tview.Table { return table } -func (ts tierInfos) Barcharts(tier string) (objects *tvxwidgets.BarChart, versions *tvxwidgets.BarChart) { +func (t tierInfos) Barcharts(tier string) (objects *tvxwidgets.BarChart, versions *tvxwidgets.BarChart) { var maxObj int var maxVer int - for _, t := range ts { + for _, t := range t { if maxObj < t.Stats.NumObjects { maxObj = t.Stats.NumObjects } @@ -116,7 +116,7 @@ func (ts tierInfos) Barcharts(tier string) (objects *tvxwidgets.BarChart, versio versions.SetMaxValue(maxVer) var tInfo madmin.TierInfo - for _, t := range ts { + for _, t := range t { if t.Name == tier { tInfo = t break @@ -131,9 +131,8 @@ func (ts tierInfos) Barcharts(tier string) (objects *tvxwidgets.BarChart, versio hrs := 23 for i := 1; i <= 24; i++ { if hrs == 0 { - objects.AddBar(fmt.Sprintf("now"), dailyStats.Bins[(lastIdx+i)%24].NumObjects, tcell.ColorRed) - versions.AddBar(fmt.Sprintf("now"), dailyStats.Bins[(lastIdx+i)%24].NumVersions, tcell.ColorBlue) - + objects.AddBar("now", dailyStats.Bins[(lastIdx+i)%24].NumObjects, tcell.ColorRed) + versions.AddBar("now", dailyStats.Bins[(lastIdx+i)%24].NumVersions, tcell.ColorBlue) } else { objects.AddBar(fmt.Sprintf("-%d", hrs), dailyStats.Bins[(lastIdx+i)%24].NumObjects, tcell.ColorRed) versions.AddBar(fmt.Sprintf("-%d", hrs), dailyStats.Bins[(lastIdx+i)%24].NumVersions, tcell.ColorBlue) diff --git a/cmd/admin-trace.go b/cmd/admin-trace.go index 0d82e5a4..0ff1c44b 100644 --- a/cmd/admin-trace.go +++ b/cmd/admin-trace.go @@ -459,7 +459,7 @@ func shortTrace(ti madmin.ServiceTraceInfo) shortTraceMsg { s.StatusMsg = http.StatusText(t.HTTP.RespInfo.StatusCode) s.Client = t.HTTP.ReqInfo.Client s.CallStats = &callStats{} - s.CallStats.Duration = t.HTTP.CallStats.Latency + s.CallStats.Duration = t.Duration s.CallStats.Rx = t.HTTP.CallStats.InputBytes s.CallStats.Tx = t.HTTP.CallStats.OutputBytes } @@ -543,8 +543,6 @@ func colorizedNodeName(nodeName string) string { } func (t traceMessage) JSON() string { - t.Status = "success" - trc := verboseTrace{ trcType: t.Trace.TraceType, Type: t.Trace.TraceType.String(), @@ -653,7 +651,7 @@ func (t traceMessage) String() string { fmt.Fprintf(b, "%s%s", nodeNameStr, console.Colorize("Body", fmt.Sprintf("%s\n", string(ri.Body)))) fmt.Fprintf(b, "%s%s", nodeNameStr, console.Colorize("Response", "[RESPONSE] ")) fmt.Fprintf(b, "[%s] ", rs.Time.Local().Format(traceTimeFormat)) - fmt.Fprint(b, console.Colorize("Stat", fmt.Sprintf("[ Duration %2s ↑ %s ↓ %s ]\n", trc.HTTP.CallStats.Latency.Round(time.Microsecond), humanize.IBytes(uint64(trc.HTTP.CallStats.InputBytes)), humanize.IBytes(uint64(trc.HTTP.CallStats.OutputBytes))))) + fmt.Fprint(b, console.Colorize("Stat", fmt.Sprintf("[ Duration %2s ↑ %s ↓ %s ]\n", trc.Duration.Round(time.Microsecond), humanize.IBytes(uint64(trc.HTTP.CallStats.InputBytes)), humanize.IBytes(uint64(trc.HTTP.CallStats.OutputBytes))))) statusStr := console.Colorize("RespStatus", fmt.Sprintf("%d %s", rs.StatusCode, http.StatusText(rs.StatusCode))) if rs.StatusCode != http.StatusOK { diff --git a/cmd/admin-user-add.go b/cmd/admin-user-add.go index 7ede9168..a0ff1eb2 100644 --- a/cmd/admin-user-add.go +++ b/cmd/admin-user-add.go @@ -28,7 +28,7 @@ import ( json "github.com/minio/colorjson" "github.com/minio/mc/pkg/probe" "github.com/minio/pkg/console" - "golang.org/x/crypto/ssh/terminal" + "golang.org/x/term" ) var adminUserAddCmd = cli.Command{ @@ -136,7 +136,7 @@ func fetchUserKeys(args cli.Args) (string, string) { accessKey := "" secretKey := "" console.SetColor(cred, color.New(color.FgYellow, color.Italic)) - isTerminal := terminal.IsTerminal(int(os.Stdin.Fd())) + isTerminal := term.IsTerminal(int(os.Stdin.Fd())) reader := bufio.NewReader(os.Stdin) argCount := len(args) @@ -154,7 +154,7 @@ func fetchUserKeys(args cli.Args) (string, string) { if argCount == 1 || argCount == 2 { if isTerminal { fmt.Printf("%s", console.Colorize(cred, "Enter Secret Key: ")) - bytePassword, _ := terminal.ReadPassword(int(os.Stdin.Fd())) + bytePassword, _ := term.ReadPassword(int(os.Stdin.Fd())) fmt.Printf("\n") secretKey = string(bytePassword) } else { diff --git a/cmd/admin-user-svcacct-add.go b/cmd/admin-user-svcacct-add.go index a538c4cf..62756b29 100644 --- a/cmd/admin-user-svcacct-add.go +++ b/cmd/admin-user-svcacct-add.go @@ -20,7 +20,7 @@ package cmd import ( "bytes" "fmt" - "io/ioutil" + "os" "strings" "github.com/fatih/color" @@ -163,7 +163,7 @@ func mainAdminUserSvcAcctAdd(ctx *cli.Context) error { if policyPath != "" { // Validate the policy document and ensure it has at least when statement var e error - policyBytes, e = ioutil.ReadFile(policyPath) + policyBytes, e = os.ReadFile(policyPath) fatalIf(probe.NewError(e), "Unable to open the policy document.") p, e := iampolicy.ParseConfig(bytes.NewReader(policyBytes)) fatalIf(probe.NewError(e), "Unable to parse the policy document.") diff --git a/cmd/admin-user-svcacct-set.go b/cmd/admin-user-svcacct-set.go index 9fd4decf..2620881e 100644 --- a/cmd/admin-user-svcacct-set.go +++ b/cmd/admin-user-svcacct-set.go @@ -18,7 +18,7 @@ package cmd import ( - "io/ioutil" + "os" "github.com/minio/cli" "github.com/minio/madmin-go/v2" @@ -85,7 +85,7 @@ func mainAdminUserSvcAcctSet(ctx *cli.Context) error { var buf []byte if policyPath != "" { var e error - buf, e = ioutil.ReadFile(policyPath) + buf, e = os.ReadFile(policyPath) fatalIf(probe.NewError(e), "Unable to open the policy document.") } diff --git a/cmd/alias-set.go b/cmd/alias-set.go index f141ca62..6904b0ca 100644 --- a/cmd/alias-set.go +++ b/cmd/alias-set.go @@ -35,7 +35,6 @@ import ( "github.com/minio/mc/pkg/probe" "github.com/minio/minio-go/v7" "github.com/minio/pkg/console" - "golang.org/x/crypto/ssh/terminal" "golang.org/x/term" ) @@ -268,7 +267,7 @@ func fetchAliasKeys(args cli.Args) (string, string) { accessKey := "" secretKey := "" console.SetColor(cred, color.New(color.FgYellow, color.Italic)) - isTerminal := terminal.IsTerminal(int(os.Stdin.Fd())) + isTerminal := term.IsTerminal(int(os.Stdin.Fd())) reader := bufio.NewReader(os.Stdin) argsNr := len(args) @@ -286,7 +285,7 @@ func fetchAliasKeys(args cli.Args) (string, string) { if argsNr == 2 || argsNr == 3 { if isTerminal { fmt.Printf("%s", console.Colorize(cred, "Enter Secret Key: ")) - bytePassword, _ := terminal.ReadPassword(int(os.Stdin.Fd())) + bytePassword, _ := term.ReadPassword(int(os.Stdin.Fd())) fmt.Printf("\n") secretKey = string(bytePassword) } else { diff --git a/cmd/batch-start.go b/cmd/batch-start.go index b36f9327..a3eab24d 100644 --- a/cmd/batch-start.go +++ b/cmd/batch-start.go @@ -20,7 +20,7 @@ package cmd import ( "context" "fmt" - "io/ioutil" + "os" "github.com/fatih/color" "github.com/minio/cli" @@ -93,7 +93,7 @@ func mainBatchStart(ctx *cli.Context) error { adminClient, err := newAdminClient(aliasedURL) fatalIf(err, "Unable to initialize admin connection.") - buf, e := ioutil.ReadFile(args.Get(1)) + buf, e := os.ReadFile(args.Get(1)) fatalIf(probe.NewError(e), "Unable to read %s", args.Get(1)) ctxt, cancel := context.WithCancel(globalContext) diff --git a/cmd/batch-status.go b/cmd/batch-status.go index b06d5d61..dfd11c2b 100644 --- a/cmd/batch-status.go +++ b/cmd/batch-status.go @@ -203,8 +203,8 @@ func (m *batchJobMetricsUI) View() string { addLine("Throughput: ", fmt.Sprintf("%s/s", humanize.IBytes(uint64(bytesTransferredPerSec)))) addLine("IOPs: ", fmt.Sprintf("%.2f objs/s", objectsPerSec)) } - addLine("Transferred: ", fmt.Sprintf("%s", humanize.IBytes(uint64(m.current.Replicate.BytesTransferred)))) - addLine("Elapsed: ", fmt.Sprintf("%s", accElapsedTime)) + addLine("Transferred: ", humanize.IBytes(uint64(m.current.Replicate.BytesTransferred))) + addLine("Elapsed: ", accElapsedTime.String()) addLine("CurrObjName: ", m.current.Replicate.Object) } diff --git a/cmd/cat_test.go b/cmd/cat_test.go index d0a0cb19..7943602c 100644 --- a/cmd/cat_test.go +++ b/cmd/cat_test.go @@ -20,7 +20,6 @@ package cmd import ( "bytes" "io" - "io/ioutil" "testing" ) @@ -54,7 +53,7 @@ func TestPrettyStdout(t *testing.T) { if int(n) != len(testCase.originText) { t.Fatalf("Test %d: copy error\n", i+1) } - prettyText, err := ioutil.ReadAll(fakeStdout) + prettyText, err := io.ReadAll(fakeStdout) if err != nil { t.Fatalf("Test %d: %v", i+1, err) } diff --git a/cmd/client-fs.go b/cmd/client-fs.go index 850760a7..c176f0f8 100644 --- a/cmd/client-fs.go +++ b/cmd/client-fs.go @@ -85,6 +85,7 @@ func fsNew(path string) (Client, *probe.Error) { }, nil } +//lint:ignore U1000 Used on some platforms. func isNotSupported(e error) bool { if e == nil { return false @@ -546,7 +547,7 @@ func (f *fsClient) Get(ctx context.Context, opts GetOptions) (io.ReadCloser, *pr return nil, err.Trace(f.PathURL.Path) } if opts.RangeStart != 0 { - _, e := fileData.Seek(opts.RangeStart, os.SEEK_SET) + _, e := fileData.Seek(opts.RangeStart, io.SeekStart) if e != nil { err := f.toClientError(e, f.PathURL.Path) return nil, err.Trace(f.PathURL.Path) diff --git a/cmd/client-fs_test.go b/cmd/client-fs_test.go index 00c48aef..e5aa042a 100644 --- a/cmd/client-fs_test.go +++ b/cmd/client-fs_test.go @@ -21,7 +21,6 @@ import ( "bytes" "context" "io" - "io/ioutil" "os" "path/filepath" "runtime" @@ -31,7 +30,7 @@ import ( // Test list files in a folder. func (s *TestSuite) TestList(c *C) { - root, e := ioutil.TempDir(os.TempDir(), "fs-") + root, e := os.MkdirTemp(os.TempDir(), "fs-") c.Assert(e, IsNil) defer os.RemoveAll(root) @@ -197,7 +196,7 @@ func (s *TestSuite) TestList(c *C) { // Test put bucket aka 'mkdir()' operation. func (s *TestSuite) TestPutBucket(c *C) { - root, e := ioutil.TempDir(os.TempDir(), "fs-") + root, e := os.MkdirTemp(os.TempDir(), "fs-") c.Assert(e, IsNil) defer os.RemoveAll(root) @@ -210,7 +209,7 @@ func (s *TestSuite) TestPutBucket(c *C) { // Test stat bucket aka 'stat()' operation. func (s *TestSuite) TestStatBucket(c *C) { - root, e := ioutil.TempDir(os.TempDir(), "fs-") + root, e := os.MkdirTemp(os.TempDir(), "fs-") c.Assert(e, IsNil) defer os.RemoveAll(root) @@ -226,7 +225,7 @@ func (s *TestSuite) TestStatBucket(c *C) { // Test bucket acl fails for directories. func (s *TestSuite) TestBucketACLFails(c *C) { - root, e := ioutil.TempDir(os.TempDir(), "fs-") + root, e := os.MkdirTemp(os.TempDir(), "fs-") c.Assert(e, IsNil) defer os.RemoveAll(root) @@ -248,7 +247,7 @@ func (s *TestSuite) TestBucketACLFails(c *C) { // Test creating a file. func (s *TestSuite) TestPut(c *C) { - root, e := ioutil.TempDir(os.TempDir(), "fs-") + root, e := os.MkdirTemp(os.TempDir(), "fs-") c.Assert(e, IsNil) defer os.RemoveAll(root) @@ -272,7 +271,7 @@ func (s *TestSuite) TestPut(c *C) { // Test read a file. func (s *TestSuite) TestGet(c *C) { - root, e := ioutil.TempDir(os.TempDir(), "fs-") + root, e := os.MkdirTemp(os.TempDir(), "fs-") c.Assert(e, IsNil) defer os.RemoveAll(root) @@ -301,7 +300,7 @@ func (s *TestSuite) TestGet(c *C) { // Test get range in a file. func (s *TestSuite) TestGetRange(c *C) { - root, e := ioutil.TempDir(os.TempDir(), "fs-") + root, e := os.MkdirTemp(os.TempDir(), "fs-") c.Assert(e, IsNil) defer os.RemoveAll(root) @@ -334,7 +333,7 @@ func (s *TestSuite) TestGetRange(c *C) { // Test stat file. func (s *TestSuite) TestStatObject(c *C) { - root, e := ioutil.TempDir(os.TempDir(), "fs-") + root, e := os.MkdirTemp(os.TempDir(), "fs-") c.Assert(e, IsNil) defer os.RemoveAll(root) @@ -361,7 +360,7 @@ func (s *TestSuite) TestStatObject(c *C) { // Test copy. func (s *TestSuite) TestCopy(c *C) { - root, e := ioutil.TempDir(os.TempDir(), "fs-") + root, e := os.MkdirTemp(os.TempDir(), "fs-") c.Assert(e, IsNil) defer os.RemoveAll(root) sourcePath := filepath.Join(root, "source") diff --git a/cmd/client-s3.go b/cmd/client-s3.go index 3b495538..c5cf62ff 100644 --- a/cmd/client-s3.go +++ b/cmd/client-s3.go @@ -1406,7 +1406,7 @@ func (c *S3Client) RemoveBucket(ctx context.Context, forceRemove bool) *probe.Er return probe.NewError(BucketInvalid{c.joinPath(bucket, object)}) } - opts := minio.BucketOptions{ForceDelete: forceRemove} + opts := minio.RemoveBucketOptions{ForceDelete: forceRemove} if e := c.api.RemoveBucketWithOptions(ctx, bucket, opts); e != nil { return probe.NewError(e) } diff --git a/cmd/config-fix.go b/cmd/config-fix.go index 58b8403a..ae43faa0 100644 --- a/cmd/config-fix.go +++ b/cmd/config-fix.go @@ -108,10 +108,7 @@ func fixConfigV3() { } // Use the correct hostConfig with JSON tags in it. - cfgV3.Hosts[host] = hostConfigV3{ - AccessKeyID: brokenHostCfgV3.AccessKeyID, - SecretAccessKey: brokenHostCfgV3.SecretAccessKey, - } + cfgV3.Hosts[host] = hostConfigV3(brokenHostCfgV3) } // We blindly drop ACL and Access fields from the broken config v3. diff --git a/cmd/config-migrate.go b/cmd/config-migrate.go index 20ca8fa2..a2bb3ecb 100644 --- a/cmd/config-migrate.go +++ b/cmd/config-migrate.go @@ -76,10 +76,7 @@ func migrateConfigV1ToV101() { // Copy hosts. for k, hostCfgV1 := range mcCfgV1.Data().(*configV1).Hosts { - cfgV101.Hosts[k] = hostConfigV101{ - AccessKeyID: hostCfgV1.AccessKeyID, - SecretAccessKey: hostCfgV1.SecretAccessKey, - } + cfgV101.Hosts[k] = hostConfigV101(hostCfgV1) } // Example localhost entry. @@ -137,10 +134,7 @@ func migrateConfigV101ToV2() { // Copy hosts. for k, hostCfgV101 := range mcCfgV101.Data().(*configV101).Hosts { - cfgV2.Hosts[k] = hostConfigV2{ - AccessKeyID: hostCfgV101.AccessKeyID, - SecretAccessKey: hostCfgV101.SecretAccessKey, - } + cfgV2.Hosts[k] = hostConfigV2(hostCfgV101) } mcCfgV2, e := quick.NewConfig(cfgV2, nil) @@ -179,10 +173,7 @@ func migrateConfigV2ToV3() { // Copy hosts. for k, hostCfgV2 := range mcCfgV2.Data().(*configV2).Hosts { // New hostConfV3 uses struct json tags. - cfgV3.Hosts[k] = hostConfigV3{ - AccessKeyID: hostCfgV2.AccessKeyID, - SecretAccessKey: hostCfgV2.SecretAccessKey, - } + cfgV3.Hosts[k] = hostConfigV3(hostCfgV2) } mcNewCfgV3, e := quick.NewConfig(cfgV3, nil) @@ -326,11 +317,7 @@ func migrateConfigV5ToV6() { host = "*s3*amazonaws.com" // Use this glob entry. } - cfgV6.Hosts[host] = hostConfigV6{ - AccessKeyID: hostCfgV5.AccessKeyID, - SecretAccessKey: hostCfgV5.SecretAccessKey, - API: hostCfgV5.API, - } + cfgV6.Hosts[host] = hostConfigV6(hostCfgV5) } mcNewCfgV6, e := quick.NewConfig(cfgV6, nil) diff --git a/cmd/fs-pathutils_windows.go b/cmd/fs-pathutils_windows.go index 1be67a1b..81a258b1 100644 --- a/cmd/fs-pathutils_windows.go +++ b/cmd/fs-pathutils_windows.go @@ -22,11 +22,12 @@ package cmd import ( "path/filepath" + "strings" "syscall" ) func normalizePath(path string) string { - if filepath.VolumeName(path) == "" && filepath.HasPrefix(path, "\\") { + if filepath.VolumeName(path) == "" && strings.HasPrefix(path, "\\") { var err error path, err = syscall.FullPath(path) if err != nil { diff --git a/cmd/head-main.go b/cmd/head-main.go index 9613f636..eefe1c64 100644 --- a/cmd/head-main.go +++ b/cmd/head-main.go @@ -23,7 +23,6 @@ import ( "compress/gzip" "context" "io" - "io/ioutil" "os" "strings" "syscall" @@ -114,7 +113,7 @@ func headURL(sourceURL, sourceVersion string, timeRef time.Time, encKeyDB map[st defer reader.Close() } else if strings.Contains(ctype, "bzip") { defer reader.Close() - reader = ioutil.NopCloser(bzip2.NewReader(reader)) + reader = io.NopCloser(bzip2.NewReader(reader)) } else { defer reader.Close() } diff --git a/cmd/ilm/options.go b/cmd/ilm/options.go index 7edb38f1..17d1d72c 100644 --- a/cmd/ilm/options.go +++ b/cmd/ilm/options.go @@ -93,7 +93,7 @@ func (opts LifecycleOptions) ToILMRule(config *lifecycle.Configuration) (lifecyc id = opts.ID status = func() string { - if opts.Status != nil && *opts.Status == false { + if opts.Status != nil && !*opts.Status { return "Disabled" } // Generating a new ILM rule without explicit status is enabled diff --git a/cmd/mirror-main.go b/cmd/mirror-main.go index 837a0771..6e197bd5 100644 --- a/cmd/mirror-main.go +++ b/cmd/mirror-main.go @@ -470,7 +470,7 @@ func (mj *mirrorJob) doMirror(ctx context.Context, sURLs URLs) URLs { now := time.Now() ret := uploadSourceToTargetURL(ctx, sURLs, mj.status, mj.opts.encKeyDB, mj.opts.isMetadata, false) if ret.Error == nil { - durationMs := time.Since(now) / time.Millisecond + durationMs := time.Since(now).Milliseconds() mirrorReplicationDurations.With(prometheus.Labels{"object_size": convertSizeToTag(sURLs.SourceContent.Size)}).Observe(float64(durationMs)) } return ret diff --git a/cmd/parallel-manager.go b/cmd/parallel-manager.go index 60348ff0..b3ddf0dd 100644 --- a/cmd/parallel-manager.go +++ b/cmd/parallel-manager.go @@ -18,7 +18,7 @@ package cmd import ( - "io/ioutil" + "os" "runtime" "strconv" "sync" @@ -26,7 +26,7 @@ import ( "time" "github.com/minio/minio-go/v7" - mem "github.com/shirou/gopsutil/v3/mem" + "github.com/shirou/gopsutil/v3/mem" ) const ( @@ -225,7 +225,7 @@ func (p *ParallelManager) stopAndWait() { const cgroupLimitFile = "/sys/fs/cgroup/memory/memory.limit_in_bytes" func cgroupLimit(limitFile string) (limit uint64) { - buf, err := ioutil.ReadFile(limitFile) + buf, err := os.ReadFile(limitFile) if err != nil { return 9223372036854771712 } diff --git a/cmd/retention-info.go b/cmd/retention-info.go index ff9f665f..f6c999d4 100644 --- a/cmd/retention-info.go +++ b/cmd/retention-info.go @@ -217,9 +217,9 @@ func (m retentionInfoMessageRecord) String() string { fmt.Fprintf(&msg, "Mode : ") if m.Mode == "" { - fmt.Fprintf(&msg, console.Colorize("RetentionNotFound", "NO RETENTION")) + fmt.Fprint(&msg, console.Colorize("RetentionNotFound", "NO RETENTION")) } else { - fmt.Fprintf(&msg, console.Colorize("RetentionSuccess", m.Mode)) + fmt.Fprint(&msg, console.Colorize("RetentionSuccess", m.Mode)) if !m.Until.IsZero() { msg.WriteString(", ") exp := "" @@ -231,10 +231,10 @@ func (m retentionInfoMessageRecord) String() string { prettyDuration := timeDurationToHumanizedDuration(m.Until.Sub(now)).StringShort() exp = console.Colorize("RetentionSuccess", "expiring in "+prettyDuration) } - fmt.Fprintf(&msg, exp) + fmt.Fprint(&msg, exp) } } - fmt.Fprintf(&msg, "\n") + fmt.Fprint(&msg, "\n") return msg.String() } diff --git a/cmd/session_test.go b/cmd/session_test.go index 3664e10c..17d4054c 100644 --- a/cmd/session_test.go +++ b/cmd/session_test.go @@ -18,12 +18,25 @@ package cmd import ( + "math/rand" "os" "regexp" . "gopkg.in/check.v1" ) +var letters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ") + +// newRandomID generates a random id of regular lower case and uppercase english characters. +func newRandomID(n int) string { + rand.Seed(UTCNow().UnixNano()) + sid := make([]rune, n) + for i := range sid { + sid[i] = letters[rand.Intn(len(letters))] + } + return string(sid) +} + func (s *TestSuite) TestValidSessionID(c *C) { validSid := regexp.MustCompile("^[a-zA-Z]+$") sid := newRandomID(8) diff --git a/cmd/sql-main.go b/cmd/sql-main.go index 109672ad..163d6cea 100644 --- a/cmd/sql-main.go +++ b/cmd/sql-main.go @@ -25,7 +25,6 @@ import ( "errors" "fmt" "io" - "io/ioutil" "os" "path/filepath" "regexp" @@ -323,7 +322,7 @@ func getCSVHeader(sourceURL string, encKeyDB map[string][]prefixSSEPair) ([]stri defer r.Close() } else if strings.Contains(ctype, "bzip") { defer r.Close() - r = ioutil.NopCloser(bzip2.NewReader(r)) + r = io.NopCloser(bzip2.NewReader(r)) } else { defer r.Close() } diff --git a/cmd/stat.go b/cmd/stat.go index 12c9478a..43cdbb18 100644 --- a/cmd/stat.go +++ b/cmd/stat.go @@ -369,57 +369,57 @@ func prettyPrintBucketMetadata(info BucketInfo) string { placeHolder := "" if info.Encryption.Algorithm != "" { fmt.Fprintf(&b, "%2s%s", placeHolder, "Encryption: ") - fmt.Fprintf(&b, console.Colorize("Key", "\n\tAlgorithm: ")) - fmt.Fprintf(&b, console.Colorize("Value", info.Encryption.Algorithm)) - fmt.Fprintf(&b, console.Colorize("Key", "\n\tKey ID: ")) - fmt.Fprintf(&b, console.Colorize("Value", info.Encryption.KeyID)) + fmt.Fprint(&b, console.Colorize("Key", "\n\tAlgorithm: ")) + fmt.Fprint(&b, console.Colorize("Value", info.Encryption.Algorithm)) + fmt.Fprint(&b, console.Colorize("Key", "\n\tKey ID: ")) + fmt.Fprint(&b, console.Colorize("Value", info.Encryption.KeyID)) fmt.Fprintln(&b) } fmt.Fprintf(&b, "%2s%s", placeHolder, "Versioning: ") if info.Versioning.Status == "" { - fmt.Fprintf(&b, console.Colorize("Unset", "Un-versioned")) + fmt.Fprint(&b, console.Colorize("Unset", "Un-versioned")) } else { - fmt.Fprintf(&b, console.Colorize("Set", info.Versioning.Status)) + fmt.Fprint(&b, console.Colorize("Set", info.Versioning.Status)) } fmt.Fprintln(&b) if info.Locking.Mode != "" { fmt.Fprintf(&b, "%2s%s\n", placeHolder, "LockConfiguration: ") fmt.Fprintf(&b, "%4s%s", placeHolder, "RetentionMode: ") - fmt.Fprintf(&b, console.Colorize("Value", info.Locking.Mode)) + fmt.Fprint(&b, console.Colorize("Value", info.Locking.Mode)) fmt.Fprintln(&b) fmt.Fprintf(&b, "%4s%s", placeHolder, "Retention Until Date: ") - fmt.Fprintf(&b, console.Colorize("Value", info.Locking.Validity)) + fmt.Fprint(&b, console.Colorize("Value", info.Locking.Validity)) fmt.Fprintln(&b) } if len(info.Notification.Config.TopicConfigs) > 0 { fmt.Fprintf(&b, "%2s%s", placeHolder, "Notification: ") - fmt.Fprintf(&b, console.Colorize("Set", "Set")) + fmt.Fprint(&b, console.Colorize("Set", "Set")) fmt.Fprintln(&b) } if info.Replication.Enabled { fmt.Fprintf(&b, "%2s%s", placeHolder, "Replication: ") - fmt.Fprintf(&b, console.Colorize("Set", "Enabled")) + fmt.Fprint(&b, console.Colorize("Set", "Enabled")) fmt.Fprintln(&b) } fmt.Fprintf(&b, "%2s%s", placeHolder, "Location: ") - fmt.Fprintf(&b, console.Colorize("Generic", info.Location)) + fmt.Fprint(&b, console.Colorize("Generic", info.Location)) fmt.Fprintln(&b) fmt.Fprintf(&b, "%2s%s", placeHolder, "Policy: ") if info.Policy.Type == "none" { - fmt.Fprintf(&b, console.Colorize("UnSet", info.Policy.Type)) + fmt.Fprint(&b, console.Colorize("UnSet", info.Policy.Type)) } else { - fmt.Fprintf(&b, console.Colorize("Set", info.Policy.Type)) + fmt.Fprint(&b, console.Colorize("Set", info.Policy.Type)) } fmt.Fprintln(&b) if info.Tags() != "" { fmt.Fprintf(&b, "%2s%s", placeHolder, "Tagging: ") - fmt.Fprintf(&b, console.Colorize("Generic", info.Tags())) + fmt.Fprint(&b, console.Colorize("Generic", info.Tags())) fmt.Fprintln(&b) } if info.ILM.Config != nil { fmt.Fprintf(&b, "%2s%s", placeHolder, "ILM: ") - fmt.Fprintf(&b, console.Colorize("Set", "Set")) + fmt.Fprint(&b, console.Colorize("Set", "Set")) fmt.Fprintln(&b) } diff --git a/cmd/subnet-utils.go b/cmd/subnet-utils.go index 9614ced5..9a34cad7 100644 --- a/cmd/subnet-utils.go +++ b/cmd/subnet-utils.go @@ -25,7 +25,6 @@ import ( "errors" "fmt" "io" - "io/ioutil" "mime/multipart" "net/http" "net/url" @@ -40,7 +39,7 @@ import ( "github.com/minio/mc/pkg/probe" "github.com/minio/pkg/licverifier" "github.com/tidwall/gjson" - "golang.org/x/crypto/ssh/terminal" + "golang.org/x/term" ) const ( @@ -192,7 +191,7 @@ func subnetReqDo(r *http.Request, headers map[string]string) (string, error) { } defer resp.Body.Close() - respBytes, e := ioutil.ReadAll(io.LimitReader(resp.Body, subnetRespBodyLimit)) + respBytes, e := io.ReadAll(io.LimitReader(resp.Body, subnetRespBodyLimit)) if e != nil { return "", e } @@ -435,7 +434,7 @@ func subnetLogin() (string, error) { } fmt.Print("Password: ") - bytepw, _ := terminal.ReadPassword(int(os.Stdin.Fd())) + bytepw, _ := term.ReadPassword(int(os.Stdin.Fd())) fmt.Println() loginReq := map[string]string{ @@ -451,7 +450,7 @@ func subnetLogin() (string, error) { if mfaRequired { mfaToken := gjson.Get(respStr, "mfa_token").String() fmt.Print("OTP received in email: ") - byteotp, _ := terminal.ReadPassword(int(os.Stdin.Fd())) + byteotp, _ := term.ReadPassword(int(os.Stdin.Fd())) fmt.Println() mfaLoginReq := SubnetMFAReq{Username: username, OTP: string(byteotp), Token: mfaToken} diff --git a/cmd/support-inspect.go b/cmd/support-inspect.go index 845df3d6..469c8ec9 100644 --- a/cmd/support-inspect.go +++ b/cmd/support-inspect.go @@ -88,9 +88,9 @@ func (t inspectMessage) String() string { msg += fmt.Sprintf("Encrypted file data successfully downloaded as %s\n", console.Colorize("File", t.File)) msg += fmt.Sprintf("Decryption key: %s\n\n", console.Colorize("Key", t.Key)) - msg += fmt.Sprintf("The decryption key will ONLY be shown here. It cannot be recovered.\n") - msg += fmt.Sprintf("The encrypted file can safely be shared without the decryption key.\n") - msg += fmt.Sprintf("Even with the decryption key, data stored with encryption cannot be accessed.\n") + msg += "The decryption key will ONLY be shown here. It cannot be recovered.\n" + msg += "The encrypted file can safely be shared without the decryption key.\n" + msg += "Even with the decryption key, data stored with encryption cannot be accessed.\n" } return msg } @@ -176,7 +176,7 @@ func mainSupportInspect(ctx *cli.Context) error { var keyHex string // Choose a name and move the inspect data to its final destination - downloadPath := fmt.Sprintf("inspect-data.enc") + downloadPath := "inspect-data.enc" if key != nil { // Create an id that is also crc. var id [4]byte diff --git a/cmd/support-perf-drive.go b/cmd/support-perf-drive.go index d9b88580..57251a98 100644 --- a/cmd/support-perf-drive.go +++ b/cmd/support-perf-drive.go @@ -22,7 +22,7 @@ import ( "os" tea "github.com/charmbracelet/bubbletea" - humanize "github.com/dustin/go-humanize" + "github.com/dustin/go-humanize" "github.com/minio/cli" "github.com/minio/madmin-go/v2" "github.com/minio/mc/pkg/probe" @@ -43,7 +43,7 @@ func mainAdminSpeedTestDrive(ctx *cli.Context, aliasedURL string, outCh chan<- P fatalIf(probe.NewError(e), "Unable to parse blocksize") return nil } - if blocksize < 0 { + if blocksize <= 0 { fatalIf(errInvalidArgument(), "blocksize cannot be <= 0") return nil } @@ -53,7 +53,7 @@ func mainAdminSpeedTestDrive(ctx *cli.Context, aliasedURL string, outCh chan<- P fatalIf(probe.NewError(e), "Unable to parse filesize") return nil } - if filesize < 0 { + if filesize <= 0 { fatalIf(errInvalidArgument(), "filesize cannot be <= 0") return nil } @@ -62,8 +62,8 @@ func mainAdminSpeedTestDrive(ctx *cli.Context, aliasedURL string, outCh chan<- P resultCh, e := client.DriveSpeedtest(ctxt, madmin.DriveSpeedTestOpts{ Serial: serial, - BlockSize: uint64(blocksize), - FileSize: uint64(filesize), + BlockSize: blocksize, + FileSize: filesize, }) if globalJSON { diff --git a/cmd/support-perf-object.go b/cmd/support-perf-object.go index 1819217f..5b3a069a 100644 --- a/cmd/support-perf-object.go +++ b/cmd/support-perf-object.go @@ -23,7 +23,7 @@ import ( "time" tea "github.com/charmbracelet/bubbletea" - humanize "github.com/dustin/go-humanize" + "github.com/dustin/go-humanize" "github.com/minio/cli" "github.com/minio/madmin-go/v2" "github.com/minio/mc/pkg/probe" @@ -70,8 +70,8 @@ func mainAdminSpeedTestObject(ctx *cli.Context, aliasedURL string, outCh chan<- fatalIf(probe.NewError(e), "Unable to parse object size") return nil } - if size < 0 { - fatalIf(errInvalidArgument(), "size is expected to be atleast 0 bytes") + if size <= 0 { + fatalIf(errInvalidArgument(), "size is expected to be more than 0 bytes") return nil } concurrent := ctx.Int("concurrent") diff --git a/cmd/support-profile.go b/cmd/support-profile.go index ded4e644..4798d37b 100644 --- a/cmd/support-profile.go +++ b/cmd/support-profile.go @@ -19,7 +19,6 @@ package cmd import ( "io" - "io/ioutil" "os" "strings" "time" @@ -139,7 +138,7 @@ func moveFile(sourcePath, destPath string) error { func saveProfileFile(data io.ReadCloser) { // Create profile zip file - tmpFile, e := ioutil.TempFile("", "mc-profile-") + tmpFile, e := os.CreateTemp("", "mc-profile-") fatalIf(probe.NewError(e), "Unable to download profile data.") // Copy zip content to target download file diff --git a/cmd/support-top-locks.go b/cmd/support-top-locks.go index f42f01d4..68ee8bf0 100644 --- a/cmd/support-top-locks.go +++ b/cmd/support-top-locks.go @@ -101,7 +101,6 @@ func (u lockMessage) String() string { // JSON jsonified top oldest locks message. func (u lockMessage) JSON() string { - u.Status = "success" type lockEntry struct { Timestamp time.Time `json:"time"` // When the lock was first granted Elapsed string `json:"elapsed"` // Humanized duration for which lock has been held diff --git a/cmd/undo-main.go b/cmd/undo-main.go index 8251728f..52936baf 100644 --- a/cmd/undo-main.go +++ b/cmd/undo-main.go @@ -228,7 +228,9 @@ func undoURL(ctx context.Context, aliasedURL string, last int, recursive, dryRun } // Undo the remaining versions found if any - exitErr = undoLastNOperations(ctx, clnt, perObjectVersions, last, dryRun) + if len(perObjectVersions) > 0 { + exitErr = undoLastNOperations(ctx, clnt, perObjectVersions, last, dryRun) + } if !atLeastOneUndoApplied { errorIf(errDummy().Trace(clnt.GetURL().String()), "Unable to find any object version to undo.") diff --git a/cmd/update-main.go b/cmd/update-main.go index 83fec033..ee4ee443 100644 --- a/cmd/update-main.go +++ b/cmd/update-main.go @@ -24,7 +24,6 @@ import ( "errors" "fmt" "io" - "io/ioutil" "net" "net/http" "net/url" @@ -36,7 +35,7 @@ import ( "time" "github.com/fatih/color" - isatty "github.com/mattn/go-isatty" + "github.com/mattn/go-isatty" "github.com/minio/cli" json "github.com/minio/colorjson" "github.com/minio/mc/pkg/probe" @@ -244,7 +243,7 @@ func downloadReleaseURL(releaseChecksumURL string, timeout time.Duration) (conte if resp.StatusCode != http.StatusOK { return content, probe.NewError(fmt.Errorf("Error downloading URL %s. Response: %v", releaseChecksumURL, resp.Status)) } - contentBytes, e := ioutil.ReadAll(resp.Body) + contentBytes, e := io.ReadAll(resp.Body) if e != nil { return content, probe.NewError(fmt.Errorf("Error reading response. %s", err)) } diff --git a/cmd/utils.go b/cmd/utils.go index 8740ec23..1c0c79c6 100644 --- a/cmd/utils.go +++ b/cmd/utils.go @@ -75,18 +75,6 @@ func UTCNow() time.Time { return time.Now().UTC() } -var letters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ") - -// newRandomID generates a random id of regular lower case and uppercase english characters. -func newRandomID(n int) string { - rand.Seed(UTCNow().UnixNano()) - sid := make([]rune, n) - for i := range sid { - sid[i] = letters[rand.Intn(len(letters))] - } - return string(sid) -} - func max(a, b int) int { if a > b { return a @@ -460,8 +448,8 @@ func httpClient(timeout time.Duration) *http.Client { } func getPrometheusToken(hostConfig *aliasConfigV10) (string, error) { - jwt := jwtgo.NewWithClaims(jwtgo.SigningMethodHS512, jwtgo.StandardClaims{ - ExpiresAt: UTCNow().Add(defaultPrometheusJWTExpiry).Unix(), + jwt := jwtgo.NewWithClaims(jwtgo.SigningMethodHS512, jwtgo.RegisteredClaims{ + ExpiresAt: jwtgo.NewNumericDate(UTCNow().Add(defaultPrometheusJWTExpiry)), Subject: hostConfig.AccessKey, Issuer: "prometheus", })