diff --git a/Makefile b/Makefile index dd2a1651..bc5dcafe 100644 --- a/Makefile +++ b/Makefile @@ -8,6 +8,9 @@ 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 + all: build checks: @@ -16,7 +19,7 @@ checks: getdeps: @mkdir -p ${GOPATH}/bin - @echo "Installing golangci-lint" && curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(GOPATH)/bin + @echo "Installing 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 crosscompile: @@ -31,9 +34,13 @@ vet: @echo "Running $@" @GO111MODULE=on go vet github.com/minio/mc/... +lint-fix: getdeps ## runs golangci-lint suite of linters with automatic fixes + @echo "Running $@ check" + @$(GOLANGCI) run --build-tags kqueue --timeout=10m --config ./.golangci.yml --fix + lint: getdeps @echo "Running $@ check" - @GO111MODULE=on ${GOPATH}/bin/golangci-lint run --timeout=5m --config ./.golangci.yml + @$(GOLANGCI) run --build-tags kqueue --timeout=10m --config ./.golangci.yml # Builds mc, runs the verifiers then runs the tests. check: test diff --git a/cmd/admin-service-restart.go b/cmd/admin-service-restart.go index d398009b..bf0f0223 100644 --- a/cmd/admin-service-restart.go +++ b/cmd/admin-service-restart.go @@ -1,4 +1,4 @@ -// Copyright (c) 2015-2022 MinIO, Inc. +// Copyright (c) 2015-2024 MinIO, Inc. // // This file is part of MinIO Object Storage stack // @@ -21,11 +21,13 @@ import ( "context" "fmt" "strings" + "sync/atomic" "time" + "github.com/charmbracelet/bubbles/spinner" + tea "github.com/charmbracelet/bubbletea" + "github.com/charmbracelet/lipgloss" "github.com/fatih/color" - "github.com/jedib0t/go-pretty/v6/table" - "github.com/jedib0t/go-pretty/v6/text" "github.com/minio/cli" json "github.com/minio/colorjson" "github.com/minio/madmin-go/v3" @@ -38,6 +40,10 @@ var serviceRestartFlag = []cli.Flag{ Name: "dry-run", Usage: "do not attempt a restart, however verify the peer status", }, + cli.BoolFlag{ + Name: "wait, w", + Usage: "wait for background initializations to complete", + }, } var adminServiceRestartCmd = cli.Command{ @@ -62,70 +68,154 @@ EXAMPLES: `, } -// serviceRestartCommand is container for service restart command success and failure messages. -type serviceRestartCommand struct { - Status string `json:"status"` - ServerURL string `json:"serverURL"` - Result madmin.ServiceActionResult `json:"result"` - TimeTaken time.Duration `json:"timeTaken"` +type serviceRestartUI struct { + current atomic.Value + tbl *console.Table + meter spinner.Model + quitting bool } -// String colorized service restart command message. -func (s serviceRestartCommand) String() string { - var s1 strings.Builder - s1.WriteString("Restart command successfully acknowledged by `" + s.ServerURL + "` in " + timeDurationToHumanizedDuration(s.TimeTaken).StringShort() + ". Type Ctrl-C to quit or wait to follow the status of the restart process.") +func (m *serviceRestartUI) add(msg serviceRestartMessage) { + m.current.Store(msg) +} - if len(s.Result.Results) > 0 { - s1.WriteString("\n") - var rows []table.Row - for _, peerRes := range s.Result.Results { - errStr := tickCell - if peerRes.Err != "" { - errStr = peerRes.Err - } else if len(peerRes.WaitingDrives) > 0 { - errStr = fmt.Sprintf("%d drives are waiting for I/O and are offline, manual restart of OS is recommended", len(peerRes.WaitingDrives)) - } - rows = append(rows, table.Row{peerRes.Host, errStr}) +func (m *serviceRestartUI) Init() tea.Cmd { + return m.meter.Tick +} + +func (m *serviceRestartUI) Update(msg tea.Msg) (tea.Model, tea.Cmd) { + if m.quitting { + return m, tea.Quit + } + switch msg := msg.(type) { + case tea.KeyMsg: + switch msg.String() { + case "q", "esc", "ctrl+c": + m.quitting = true + return m, tea.Quit + default: + return m, nil } + case spinner.TickMsg: + var cmd tea.Cmd + m.meter, cmd = m.meter.Update(msg) + return m, cmd + } + return m, nil +} - t := table.NewWriter() - t.SetOutputMirror(&s1) - t.SetColumnConfigs([]table.ColumnConfig{{Align: text.AlignCenter}}) +func (m *serviceRestartUI) View() string { + var s strings.Builder - t.AppendHeader(table.Row{"Host", "Status"}) - t.AppendRows(rows) - t.SetStyle(table.StyleLight) - t.Render() + msgI := m.current.Load() + if msgI == nil { + s.WriteString("(waiting for data)") + return s.String() } - return console.Colorize("ServiceRestart", s1.String()) + s.WriteString(fmt.Sprintf("Service status: %s ", m.meter.View())) + + msg := msgI.(serviceRestartMessage) + state := msg.State + switch state { + case restarting: + // Actually still restarting, no response yet from the server. + s.WriteString("[RESTARTING]\n") + case waiting: + // Waiting on background initializations such as IAM and bucket metadata + s.WriteString(console.Colorize("ServiceInitializing", "[WAITING]")) + s.WriteString("\n") + case done: + m.quitting = true + + // Finished restarting and optionally waiting for the background initializations to complete. + s.WriteString(console.Colorize("ServiceRestarted", "[DONE]")) + s.WriteString("\n") + var ( + totalNodes = len(msg.Result.Results) + totalOfflineNodes int + totalHungNodes int + ) + + for _, peerRes := range msg.Result.Results { + if peerRes.Err != "" { + totalOfflineNodes++ + } else if len(peerRes.WaitingDrives) > 0 { + totalHungNodes++ + } + } + + s.WriteString("Summary:\n") + + var cellText [][]string + cellText = append(cellText, []string{ + "Servers:", + fmt.Sprintf("%d online, %d offline, %d hung", totalNodes-(totalOfflineNodes+totalHungNodes), totalOfflineNodes, totalHungNodes), + }) + + cellText = append(cellText, []string{ + "Restart Time:", + msg.RestartDuration.String(), + }) + + if msg.WaitingDuration > 0 { + cellText = append(cellText, []string{ + "Background Init Time:", + msg.WaitingDuration.String(), + }) + } + + fatalIf(probe.NewError(m.tbl.PopulateTable(&s, cellText)), "unable to populate the table") + } + + return s.String() +} + +func initServiceRestartUI(rowCount int, currentCh chan serviceRestartMessage) *serviceRestartUI { + var printColors []*color.Color + for i := 0; i < rowCount; i++ { + printColors = append(printColors, getPrintCol(colGreen)) + } + + tbl := console.NewTable(printColors, []bool{false, false}, 4) + + meter := spinner.New() + meter.Spinner = spinner.Meter + meter.Style = lipgloss.NewStyle().Foreground(lipgloss.Color("205")) + + svcUI := &serviceRestartUI{tbl: tbl, meter: meter} + go func() { + for msg := range currentCh { + if msg.Status != "" { + svcUI.add(msg) + } + } + }() + return svcUI +} + +const ( + restarting = iota + waiting + done +) + +// serviceRestartMessage is container for service restart command success and failure messages. +type serviceRestartMessage struct { + Status string `json:"status"` + ServerURL string `json:"serverURL"` + Result madmin.ServiceActionResult `json:"result"` + RestartDuration time.Duration `json:"restartDuration"` + WaitingDuration time.Duration `json:"waitingDuration"` + TimeTaken time.Duration `json:"timeTaken"` // deprecated use "restartDuration" instead. + State int `json:"state"` +} + +func (s serviceRestartMessage) String() string { + return s.JSON() } // JSON jsonified service restart command message. -func (s serviceRestartCommand) JSON() string { - serviceRestartJSONBytes, e := json.MarshalIndent(s, "", " ") - fatalIf(probe.NewError(e), "Unable to marshal into JSON.") - - return string(serviceRestartJSONBytes) -} - -// serviceRestartMessage is container for service restart success and failure messages. -type serviceRestartMessage struct { - Status string `json:"status"` - ServerURL string `json:"serverURL"` - TimeTaken time.Duration `json:"timeTaken"` - Err error `json:"error,omitempty"` -} - -// String colorized service restart message. -func (s serviceRestartMessage) String() string { - if s.Err == nil { - return console.Colorize("ServiceRestart", fmt.Sprintf("\nEstablished quorum on `%s` successfully in %s", s.ServerURL, timeDurationToHumanizedDuration(s.TimeTaken).StringShort())) - } - return console.Colorize("FailedServiceRestart", "Failed to restart `"+s.ServerURL+"`. error: "+s.Err.Error()) -} - -// JSON jsonified service restart message. func (s serviceRestartMessage) JSON() string { serviceRestartJSONBytes, e := json.MarshalIndent(s, "", " ") fatalIf(probe.NewError(e), "Unable to marshal into JSON.") @@ -150,7 +240,7 @@ func mainAdminServiceRestart(ctx *cli.Context) error { // Set color. console.SetColor("ServiceOffline", color.New(color.FgRed, color.Bold)) console.SetColor("ServiceInitializing", color.New(color.FgYellow, color.Bold)) - console.SetColor("ServiceRestart", color.New(color.FgGreen, color.Bold)) + console.SetColor("ServiceRestarted", color.New(color.FgGreen, color.Bold)) console.SetColor("FailedServiceRestart", color.New(color.FgRed, color.Bold)) // Get the alias parameter from cli @@ -160,68 +250,108 @@ func mainAdminServiceRestart(ctx *cli.Context) error { client, err := newAdminClient(aliasedURL) fatalIf(err, "Unable to initialize admin connection.") - t := time.Now() - // Restart the specified MinIO server - result, e := client.ServiceAction(ctxt, madmin.ServiceActionOpts{ - Action: madmin.ServiceActionRestart, - DryRun: ctx.Bool("dry-run"), - }) - if e != nil { - // Attempt an older API server might be old - e = client.ServiceRestart(ctxt) + rowCount := 2 + toWait := ctx.IsSet("wait") + if toWait { + rowCount = 3 } - fatalIf(probe.NewError(e), "Unable to restart the server.") - // Success.. - printMsg(serviceRestartCommand{Status: "success", ServerURL: aliasedURL, Result: result, TimeTaken: time.Since(t)}) + ch := make(chan serviceRestartMessage, 1) - // Start pinging the service until it is ready + svcUI := initServiceRestartUI(rowCount, ch) + go func() { + t := time.Now() - anonClient, err := newAnonymousClient(aliasedURL) - fatalIf(err.Trace(aliasedURL), "Could not ping `"+aliasedURL+"`.") + // Restart the specified MinIO server + result, e := client.ServiceAction(ctxt, madmin.ServiceActionOpts{ + Action: madmin.ServiceActionRestart, + DryRun: ctx.Bool("dry-run"), + }) + if e != nil { + // Attempt an older API server might be old + e = client.ServiceRestart(ctxt) + } + fatalIf(probe.NewError(e), "Unable to restart the server.") - coloring := color.New(color.FgRed) - mark := "..." + timeTaken := time.Since(t) + restart := restarting + if !toWait { + restart = done + } - // Print restart progress - printProgress := func() { - if !globalQuiet && !globalJSON { - coloring.Printf(mark) + ch <- serviceRestartMessage{ + Status: "success", + ServerURL: aliasedURL, + Result: result, + RestartDuration: timeTaken, + TimeTaken: timeTaken, + State: restart, + } + + if toWait { + sleepInterval := 500 * time.Millisecond + go func() { + defer close(ch) + + wt := time.Now() + + // Start pinging the service until it is ready + anonClient, err := newAnonymousClient(aliasedURL) + fatalIf(err.Trace(aliasedURL), "unable to initialize anonymous client for`"+aliasedURL+"`.") + + for { + healthCtx, healthCancel := context.WithTimeout(ctxt, 2*time.Second) + + // Fetch the health status of the specified MinIO server + healthResult, healthErr := anonClient.Healthy(healthCtx, madmin.HealthOpts{}) + healthCancel() + + switch { + case healthErr == nil && healthResult.Healthy: + ch <- serviceRestartMessage{ + Status: "success", + ServerURL: aliasedURL, + Result: result, + RestartDuration: timeTaken, + TimeTaken: timeTaken, + WaitingDuration: time.Since(wt), + State: done, + } + return + } + + ch <- serviceRestartMessage{ + Status: "success", + ServerURL: aliasedURL, + Result: result, + WaitingDuration: time.Since(wt), + RestartDuration: timeTaken, + TimeTaken: timeTaken, + State: waiting, + } + + time.Sleep(sleepInterval) + } + }() + } else { + close(ch) + } + }() + + if !globalJSON { + ui := tea.NewProgram(svcUI) + if _, e := ui.Run(); e != nil { + cancel() + fatalIf(probe.NewError(e).Trace(aliasedURL), "Unable to initialize service restart UI") + } + } else { + for msg := range ch { + printMsg(msg) + if msg.State == done { + break + } } } - printProgress() - mark = "." - - t = time.Now() - for { - healthCtx, healthCancel := context.WithTimeout(ctxt, 2*time.Second) - - // Fetch the health status of the specified MinIO server - healthResult, healthErr := anonClient.Healthy(healthCtx, madmin.HealthOpts{}) - healthCancel() - - switch { - case healthErr == nil && healthResult.Healthy: - printMsg(serviceRestartMessage{ - Status: "success", - ServerURL: aliasedURL, - TimeTaken: time.Since(t), - }) - return nil - case healthErr == nil && !healthResult.Healthy: - coloring = color.New(color.FgYellow) - mark = "!" - fallthrough - default: - printProgress() - } - - select { - case <-ctxt.Done(): - return ctxt.Err() - default: - time.Sleep(500 * time.Millisecond) - } - } + return nil } diff --git a/cmd/trace-stats-ui.go b/cmd/trace-stats-ui.go index 7bc5c240..45826b52 100644 --- a/cmd/trace-stats-ui.go +++ b/cmd/trace-stats-ui.go @@ -1,3 +1,20 @@ +// 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 . + package cmd import (