diff --git a/cmd/admin-top-scanner.go b/cmd/admin-top-scanner.go new file mode 100644 index 00000000..da256226 --- /dev/null +++ b/cmd/admin-top-scanner.go @@ -0,0 +1,382 @@ +// 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 . + +package cmd + +import ( + "bytes" + "context" + "errors" + "fmt" + "os" + "sort" + "strings" + "time" + + "github.com/charmbracelet/bubbles/spinner" + tea "github.com/charmbracelet/bubbletea" + "github.com/charmbracelet/lipgloss" + "github.com/fatih/color" + "github.com/minio/cli" + json "github.com/minio/colorjson" + "github.com/minio/madmin-go" + "github.com/minio/mc/pkg/probe" + "github.com/minio/pkg/console" + "github.com/olekukonko/tablewriter" +) + +var adminTopScannerFlags = []cli.Flag{ + cli.StringFlag{ + Name: "nodes", + Usage: "show only on matching servers, comma separate multiple", + }, + cli.IntFlag{ + Name: "n", + Usage: "number of requests to run before exiting. 0 for endless", + Value: 0, + }, + cli.IntFlag{ + Name: "interval", + Usage: "interval between requests in seconds", + Value: 3, + }, + cli.IntFlag{ + Name: "max-paths", + Usage: "maximum number of active paths to show. -1 for unlimited", + Value: -1, + }, +} + +var adminTopScannerCmd = cli.Command{ + Name: "scanner", + Usage: "summarize scanner events on MinIO server in real-time", + Action: mainAdminTopScanner, + OnUsageError: onUsageError, + Before: setGlobalsFromContext, + Flags: append(adminTopScannerFlags, globalFlags...), + HideHelpCommand: true, + CustomHelpTemplate: `NAME: + {{.HelpName}} - {{.Usage}} + +USAGE: + {{.HelpName}} [FLAGS] TARGET + +FLAGS: + {{range .VisibleFlags}}{{.}} + {{end}} +EXAMPLES: + 1. Display current in-progress all scanner operations. + {{.Prompt}} {{.HelpName}} myminio/ +`, +} + +// checkAdminTopAPISyntax - validate all the passed arguments +func checkAdminTopScannerSyntax(ctx *cli.Context) { + if len(ctx.Args()) == 0 || len(ctx.Args()) > 1 { + cli.ShowCommandHelpAndExit(ctx, "scanner", 1) // last argument is exit code + } +} + +func mainAdminTopScanner(ctx *cli.Context) error { + checkAdminTopScannerSyntax(ctx) + + aliasedURL := ctx.Args().Get(0) + + // Create a new MinIO Admin Client + client, err := newAdminClient(aliasedURL) + if err != nil { + fatalIf(err.Trace(aliasedURL), "Unable to initialize admin client.") + return nil + } + + ctxt, cancel := context.WithCancel(globalContext) + defer cancel() + + opts := madmin.MetricsOptions{ + Type: madmin.MetricsScanner, + N: ctx.Int("n"), + Interval: time.Duration(ctx.Int("interval")) * time.Second, + Hosts: strings.Split(ctx.String("nodes"), ","), + ByHost: false, + } + ui := tea.NewProgram(initScannerMetricsUI(ctx.Int("max-paths"))) + if !globalJSON { + go func() { + if e := ui.Start(); e != nil { + cancel() + os.Exit(1) + } + os.Exit(0) + }() + } + cerr := client.Metrics(ctxt, opts, func(metrics madmin.RealtimeMetrics) { + if globalJSON { + printMsg(metricsMessage{RealtimeMetrics: metrics}) + return + } + ui.Send(metrics) + }) + + if cerr != nil && !errors.Is(cerr, context.Canceled) { + fatalIf(probe.NewError(cerr).Trace(aliasedURL), "Error making request") + return nil + } + + return nil +} + +type metricsMessage struct { + madmin.RealtimeMetrics +} + +func (s metricsMessage) JSON() string { + buf := &bytes.Buffer{} + enc := json.NewEncoder(buf) + enc.SetIndent("", " ") + enc.SetEscapeHTML(false) + + fatalIf(probe.NewError(enc.Encode(s)), "Unable to marshal into JSON.") + return buf.String() +} + +func (s metricsMessage) String() string { + return s.JSON() +} + +func initScannerMetricsUI(maxPaths int) *scannerMetricsUI { + s := spinner.New() + s.Spinner = spinner.Points + s.Style = lipgloss.NewStyle().Foreground(lipgloss.Color("205")) + console.SetColor("metrics-duration", color.New(color.FgHiWhite)) + console.SetColor("metrics-path", color.New(color.FgGreen)) + console.SetColor("metrics-error", color.New(color.FgHiRed)) + console.SetColor("metrics-title", color.New(color.FgCyan)) + console.SetColor("metrics-top-title", color.New(color.FgHiCyan)) + console.SetColor("metrics-number", color.New(color.FgHiWhite)) + console.SetColor("metrics-zero", color.New(color.FgHiWhite)) + console.SetColor("metrics-date", color.New(color.FgHiWhite)) + return &scannerMetricsUI{ + spinner: s, + maxPaths: maxPaths, + } +} + +type scannerMetricsUI struct { + current madmin.RealtimeMetrics + spinner spinner.Model + quitting bool + maxPaths int +} + +func (m *scannerMetricsUI) Init() tea.Cmd { + return m.spinner.Tick +} + +func (m *scannerMetricsUI) Update(msg tea.Msg) (tea.Model, tea.Cmd) { + switch msg := msg.(type) { + case tea.KeyMsg: + switch msg.String() { + case "ctrl+c": + m.quitting = true + return m, tea.Quit + default: + return m, nil + } + case madmin.RealtimeMetrics: + m.current = msg + if msg.Final { + m.quitting = true + return m, tea.Quit + } + return m, nil + + case spinner.TickMsg: + var cmd tea.Cmd + m.spinner, cmd = m.spinner.Update(msg) + return m, cmd + default: + return m, nil + } +} + +func (m *scannerMetricsUI) View() string { + var s strings.Builder + + if !m.quitting { + s.WriteString(fmt.Sprintf("%s %s\n", console.Colorize("metrics-top-title", "Scanner Activity:"), m.spinner.View())) + } + + // Set table header + table := tablewriter.NewWriter(&s) + table.SetAutoWrapText(false) + table.SetHeaderAlignment(tablewriter.ALIGN_LEFT) + table.SetAlignment(tablewriter.ALIGN_LEFT) + table.SetBorder(true) + table.SetRowLine(false) + addRow := func(s string) { + table.Append([]string{s}) + } + _ = addRow + addRowF := func(format string, vals ...interface{}) { + s := fmt.Sprintf(format, vals...) + table.Append([]string{s}) + } + sc := m.current.Aggregated.Scanner + if sc == nil { + s.WriteString("(waiting for data)") + return s.String() + } + + title := metricsTitle + ui := metricsUint64 + const wantCycles = 16 + if len(sc.CyclesCompletedAt) < 2 { + addRow("Scan time: Unknown (not enough data)") + } else { + sort.Slice(sc.CyclesCompletedAt, func(i, j int) bool { + return sc.CyclesCompletedAt[i].After(sc.CyclesCompletedAt[j]) + }) + if len(sc.CyclesCompletedAt) >= wantCycles { + sinceLast := sc.CyclesCompletedAt[0].Sub(sc.CyclesCompletedAt[wantCycles-1]) + perMonth := float64(30*24*time.Hour) / float64(sinceLast) + cycleTime := console.Colorize("metrics-number", fmt.Sprintf("%dd%dh%dm", int(sinceLast.Hours()/24), int(sinceLast.Hours())%24, int(sinceLast.Minutes())%60)) + perms := console.Colorize("metrics-number", fmt.Sprintf("%.02f", perMonth)) + addRowF(title("Last full scan time:")+" %s; Estimated %s/month", cycleTime, perms) + } else { + sinceLast := sc.CyclesCompletedAt[0].Sub(sc.CyclesCompletedAt[1]) * time.Duration(wantCycles) + perMonth := float64(30*24*time.Hour) / float64(sinceLast) + cycleTime := console.Colorize("metrics-number", fmt.Sprintf("%dd%dh%dm", int(sinceLast.Hours()/24), int(sinceLast.Hours())%24, int(sinceLast.Minutes())%60)) + perms := console.Colorize("metrics-number", fmt.Sprintf("%.02f", perMonth)) + addRowF(title("Est. full scan time:")+" %s; Estimated %s/month", cycleTime, perms) + } + } + if sc.CurrentCycle > 0 { + addRowF(title("Current cycle:")+" %s; Started: %v", ui(sc.CurrentCycle), console.Colorize("metrics-date", sc.CurrentStarted)) + addRowF(title("Active disks:")+" %s", ui(uint64(len(sc.ActivePaths)))) + } else { + addRowF(title("Current cycle:") + " (between cycles)") + addRowF(title("Active disks:")+" %s", ui(uint64(len(sc.ActivePaths)))) + } + addRow("-------------------------------------- Last Minute Statistics ---------------------------------------") + objs := uint64(0) + x := sc.LastMinute.Actions["ScanObject"] + { + avg := x.Avg() + rate := "" + if x.AccTime > 0 { + rate = fmt.Sprintf("; Rate: %v/day", ui(uint64(float64(24*time.Hour)/(float64(time.Minute)/float64(x.Count))))) + } + addRowF(title("Objects Scanned:")+" %s objects; Avg: %v%s", ui(x.Count), metricsDuration(avg), rate) + objs = x.Count + } + x = sc.LastMinute.Actions["ApplyVersion"] + { + avg := x.Avg() + rate := "" + if x.AccTime > 0 { + rate = fmt.Sprintf("; Rate: %s/day", ui(uint64(float64(24*time.Hour)/(float64(time.Minute)/float64(x.Count))))) + } + addRowF(title("Versions Scanned:")+" %s versions; Avg: %v%s", ui(x.Count), metricsDuration(avg), rate) + } + x = sc.LastMinute.Actions["HealCheck"] + { + avg := x.Avg() + rate := "" + if x.AccTime > 0 { + rate = fmt.Sprintf("; Rate: %s/day", ui(uint64(float64(24*time.Hour)/(float64(time.Minute)/float64(x.Count))))) + } + addRowF(title("Versions Heal Checked:")+" %s versions; Avg: %v%s", ui(x.Count), metricsDuration(avg), rate) + } + x = sc.LastMinute.Actions["ReadMetadata"] + addRowF(title("Read Metadata:")+" %s objects; Avg: %v, Size: %v bytes/obj", ui(x.Count), metricsDuration(x.Avg()), ui(x.AvgBytes())) + x = sc.LastMinute.Actions["ILM"] + addRowF(title("ILM checks:")+" %s versions; Avg: %v", ui(x.Count), metricsDuration(x.Avg())) + x = sc.LastMinute.Actions["CheckReplication"] + addRowF(title("Check Replication:")+" %s versions; Avg: %v", ui(x.Count), metricsDuration(x.Avg())) + x = sc.LastMinute.Actions["TierObjSweep"] + if x.Count > 0 { + addRowF(title("Sweep Tiered:")+" %s versions; Avg: %v", ui(x.Count), metricsDuration(x.Avg())) + } + x = sc.LastMinute.Actions["CheckMissing"] + addRowF(title("Verify Deleted:")+" %s folders; Avg: %v", ui(x.Count), metricsDuration(x.Avg())) + for k, x := range sc.LastMinute.ILM { + const length = 17 + k += ":" + if len(k) < length { + k += strings.Repeat(" ", length-len(k)) + } + addRowF(title("ILM, %s")+" %s actions; Avg: %v.", k, ui(x.Count), metricsDuration(x.Avg())) + } + x = sc.LastMinute.Actions["Yield"] + { + avg := fmt.Sprintf("%v", metricsDuration(x.Avg())) + if objs > 0 { + avg = console.Colorize("metrics-duration", fmt.Sprintf("%v/obj", metricsDuration(time.Duration(x.AccTime/objs)))) + } + addRowF(title("Yield:")+" %v total; Avg: %s", metricsDuration(time.Duration(x.AccTime)), avg) + } + + if m.maxPaths != 0 && len(sc.ActivePaths) > 0 { + addRow("------------------------------------- Currently Scanning Paths --------------------------------------") + const length = 100 + for i, s := range sc.ActivePaths { + if i == m.maxPaths { + break + } + if len(s) > length { + s = s[:length-3] + "..." + } + s = strings.ReplaceAll(s, "\\", "/") + addRow(console.Colorize("metrics-path", s)) + } + } + if errs := m.current.Errors; len(errs) > 0 { + addRow("------------------------------------------- Errors --------------------------------------------------") + for _, s := range errs { + addRow(console.Colorize("metrics-error", s)) + } + } + table.Render() + return s.String() +} + +func metricsDuration(d time.Duration) string { + if d == 0 { + return console.Colorize("metrics-zero", "0ms") + } + if d > time.Millisecond { + d = d.Round(time.Microsecond) + } + if d > time.Second { + d = d.Round(time.Millisecond) + } + if d > time.Minute { + d = d.Round(time.Second / 10) + } + return console.Colorize("metrics-duration", d) +} + +func metricsUint64(v uint64) string { + if v == 0 { + return console.Colorize("metrics-zero", v) + } + return console.Colorize("metrics-number", v) +} + +func metricsTitle(s string) string { + return console.Colorize("metrics-title", s) +} diff --git a/cmd/admin-top.go b/cmd/admin-top.go index 8c036877..920b2413 100644 --- a/cmd/admin-top.go +++ b/cmd/admin-top.go @@ -22,6 +22,7 @@ import "github.com/minio/cli" var adminTopSubcommands = []cli.Command{ adminTopAPICmd, adminTopLocksCmd, + adminTopScannerCmd, } var adminTopCmd = cli.Command{ diff --git a/cmd/admin-trace.go b/cmd/admin-trace.go index 55d49d4b..44119482 100644 --- a/cmd/admin-trace.go +++ b/cmd/admin-trace.go @@ -47,7 +47,7 @@ var adminTraceFlags = []cli.Flag{ }, cli.StringSliceFlag{ Name: "call", - Usage: "trace only matching Call types (values: `s3`, `internal`, `storage`, `os`)", + Usage: "trace only matching Call types (values: `s3`, `internal`, `storage`, `os`, 'scanner')", }, cli.StringFlag{ Name: "response-threshold", @@ -145,7 +145,7 @@ func matchTrace(opts matchOpts, traceInfo madmin.ServiceTraceInfo) bool { if len(opts.apiPaths) > 0 { matched := false for _, apiPath := range opts.apiPaths { - if pathMatch(path.Join("/", apiPath), traceInfo.Trace.ReqInfo.Path) { + if pathMatch(path.Join("/", apiPath), traceInfo.Trace.Path) { matched = true break } @@ -159,7 +159,7 @@ func matchTrace(opts matchOpts, traceInfo madmin.ServiceTraceInfo) bool { if len(opts.statusCodes) > 0 { matched := false for _, code := range opts.statusCodes { - if traceInfo.Trace.RespInfo.StatusCode == code { + if traceInfo.Trace.HTTP.RespInfo.StatusCode == code { matched = true break } @@ -174,7 +174,7 @@ func matchTrace(opts matchOpts, traceInfo madmin.ServiceTraceInfo) bool { if len(opts.methods) > 0 { matched := false for _, method := range opts.methods { - if traceInfo.Trace.ReqInfo.Method == method { + if traceInfo.Trace.HTTP.ReqInfo.Method == method { matched = true break } @@ -229,12 +229,11 @@ func tracingOpts(ctx *cli.Context) (opts madmin.ServiceTraceOpts, e error) { opts.OnlyErrors = ctx.Bool("errors") if ctx.Bool("all") { - opts.All = true // Deprecated - opts.S3 = true opts.Internal = true opts.Storage = true opts.OS = true + opts.Scanner = true return } @@ -256,6 +255,8 @@ func tracingOpts(ctx *cli.Context) (opts madmin.ServiceTraceOpts, e error) { opts.S3 = true case "os": opts.OS = true + case "scanner": + opts.Scanner = true } } @@ -324,21 +325,20 @@ func mainAdminTrace(ctx *cli.Context) error { // Short trace record type shortTraceMsg struct { - Status string `json:"status"` - Host string `json:"host"` - Time time.Time `json:"time"` - Client string `json:"client"` - CallStats callStats `json:"callStats"` - FuncName string `json:"api"` - Path string `json:"path"` - Query string `json:"query"` - StatusCode int `json:"statusCode"` - StatusMsg string `json:"statusMsg"` + Status string `json:"status"` + Host string `json:"host"` + Time time.Time `json:"time"` + Client string `json:"client"` + CallStats *callStats `json:"callStats,omitempty"` + Duration time.Duration `json:"duration"` + FuncName string `json:"api"` + Path string `json:"path"` + Query string `json:"query"` + StatusCode int `json:"statusCode"` + StatusMsg string `json:"statusMsg"` + Type string `json:"type"` - StorageStats storageStats `json:"storageStats"` - OSStats osStats `json:"osStats"` - trcType madmin.TraceType `json:"-"` - Type string `json:"type"` + trcType madmin.TraceType } type traceMessage struct { @@ -370,41 +370,20 @@ type callStats struct { Ttfb time.Duration `json:"timeToFirstByte"` } -type osStats struct { - Duration time.Duration `json:"duration"` - Path string `json:"path"` -} - -type storageStats struct { - Duration time.Duration `json:"duration"` - Path string `json:"path"` -} - type verboseTrace struct { - trcType madmin.TraceType `json:"-"` - Type string `json:"type"` + Type string `json:"type"` - NodeName string `json:"host"` - FuncName string `json:"api"` - Time time.Time `json:"time"` + NodeName string `json:"host"` + FuncName string `json:"api"` + Time time.Time `json:"time"` + Duration time.Duration `json:"duration"` + Path string `json:"path"` - RequestInfo requestInfo `json:"request"` - ResponseInfo responseInfo `json:"response"` - CallStats callStats `json:"callStats"` + RequestInfo *requestInfo `json:"request,omitempty"` + ResponseInfo *responseInfo `json:"response,omitempty"` + CallStats *callStats `json:"callStats,omitempty"` - StorageStats storageStats `json:"storageStats"` - OSStats osStats `json:"osStats"` -} - -func toTypeStr(t madmin.TraceType) string { - switch t { - case madmin.TraceStorage: - return "STORAGE" - case madmin.TraceOS: - return "OS" - default: - return "S3" - } + trcType madmin.TraceType } // return a struct with minimal trace info. @@ -413,32 +392,23 @@ func shortTrace(ti madmin.ServiceTraceInfo) shortTraceMsg { t := ti.Trace s.trcType = t.TraceType - s.Type = toTypeStr(t.TraceType) + s.Type = t.TraceType.String() s.FuncName = t.FuncName s.Time = t.Time + s.Path = t.Path + s.Host = t.NodeName + s.Duration = t.Duration switch t.TraceType { - case madmin.TraceStorage: - s.Path = t.StorageStats.Path - s.Host = t.NodeName - s.StorageStats.Duration = t.StorageStats.Duration - case madmin.TraceOS: - s.Path = t.OSStats.Path - s.Host = t.NodeName - s.OSStats.Duration = t.OSStats.Duration - case madmin.TraceHTTP: - s.Host = t.NodeName - s.Path = t.ReqInfo.Path - s.Query = t.ReqInfo.RawQuery - s.StatusCode = t.RespInfo.StatusCode - s.StatusMsg = http.StatusText(t.RespInfo.StatusCode) - s.Client = t.ReqInfo.Client - s.CallStats.Duration = t.CallStats.Latency - s.CallStats.Rx = t.CallStats.InputBytes - s.CallStats.Tx = t.CallStats.OutputBytes - - // Support older versions of MinIO server - s.Time = t.ReqInfo.Time + case madmin.TraceS3, madmin.TraceInternal: + s.Query = t.HTTP.ReqInfo.RawQuery + s.StatusCode = t.HTTP.RespInfo.StatusCode + 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.Rx = t.HTTP.CallStats.InputBytes + s.CallStats.Tx = t.HTTP.CallStats.OutputBytes } return s } @@ -465,17 +435,12 @@ func (s shortTraceMsg) String() string { fmt.Fprintf(b, "%s ", s.Time.Local().Format(traceTimeFormat)) switch s.trcType { - case madmin.TraceStorage: - fmt.Fprintf(b, "[%s] %s %s %s %2s", console.Colorize("RespStatus", "STORAGE"), console.Colorize("FuncName", s.FuncName), + case madmin.TraceS3, madmin.TraceInternal: + default: + fmt.Fprintf(b, "[%s] %s %s %s %2s", console.Colorize("RespStatus", strings.ToUpper(s.trcType.String())), console.Colorize("FuncName", s.FuncName), hostStr, s.Path, - console.Colorize("HeaderValue", s.StorageStats.Duration)) - return b.String() - case madmin.TraceOS: - fmt.Fprintf(b, "[%s] %s %s %s %2s", console.Colorize("RespStatus", "OS"), console.Colorize("FuncName", s.FuncName), - hostStr, - s.Path, - console.Colorize("HeaderValue", s.OSStats.Duration)) + console.Colorize("HeaderValue", s.Duration)) return b.String() } @@ -518,23 +483,33 @@ func colorizedNodeName(nodeName string) string { func (t traceMessage) JSON() string { t.Status = "success" - rqHdrs := make(map[string]string) - rspHdrs := make(map[string]string) - rq := t.Trace.ReqInfo - rs := t.Trace.RespInfo - for k, v := range rq.Headers { - rqHdrs[k] = strings.Join(v, " ") - } - for k, v := range rs.Headers { - rspHdrs[k] = strings.Join(v, " ") - } + trc := verboseTrace{ trcType: t.Trace.TraceType, - Type: toTypeStr(t.Trace.TraceType), + Type: t.Trace.TraceType.String(), NodeName: t.Trace.NodeName, FuncName: t.Trace.FuncName, Time: t.Trace.Time, - RequestInfo: requestInfo{ + Duration: t.Trace.Duration, + Path: t.Trace.Path, + } + + if t.Trace.HTTP != nil { + rq := t.Trace.HTTP.ReqInfo + rs := t.Trace.HTTP.RespInfo + + var ( + rqHdrs = make(map[string]string) + rspHdrs = make(map[string]string) + ) + for k, v := range rq.Headers { + rqHdrs[k] = strings.Join(v, " ") + } + for k, v := range rs.Headers { + rspHdrs[k] = strings.Join(v, " ") + } + + trc.RequestInfo = &requestInfo{ Time: rq.Time, Proto: rq.Proto, Method: rq.Method, @@ -542,27 +517,19 @@ func (t traceMessage) JSON() string { RawQuery: rq.RawQuery, Body: string(rq.Body), Headers: rqHdrs, - }, - ResponseInfo: responseInfo{ + } + trc.ResponseInfo = &responseInfo{ Time: rs.Time, Body: string(rs.Body), Headers: rspHdrs, StatusCode: rs.StatusCode, - }, - CallStats: callStats{ - Duration: t.Trace.CallStats.Latency, - Rx: t.Trace.CallStats.InputBytes, - Tx: t.Trace.CallStats.OutputBytes, - Ttfb: t.Trace.CallStats.TimeToFirstByte, - }, - OSStats: osStats{ - Duration: t.Trace.OSStats.Duration, - Path: t.Trace.OSStats.Path, - }, - StorageStats: storageStats{ - Duration: t.Trace.StorageStats.Duration, - Path: t.Trace.StorageStats.Path, - }, + } + trc.CallStats = &callStats{ + Duration: t.Trace.Duration, + Rx: t.Trace.HTTP.CallStats.InputBytes, + Tx: t.Trace.HTTP.CallStats.OutputBytes, + Ttfb: t.Trace.HTTP.CallStats.TimeToFirstByte, + } } buf := &bytes.Buffer{} enc := json.NewEncoder(buf) @@ -585,16 +552,17 @@ func (t traceMessage) String() string { } switch trc.TraceType { - case madmin.TraceStorage: - fmt.Fprintf(b, "%s %s [%s] %s %s", nodeNameStr, console.Colorize("Request", fmt.Sprintf("[STORAGE %s]", trc.FuncName)), trc.Time.Local().Format(traceTimeFormat), trc.StorageStats.Path, trc.StorageStats.Duration) - return b.String() - case madmin.TraceOS: - fmt.Fprintf(b, "%s %s [%s] %s %s", nodeNameStr, console.Colorize("Request", fmt.Sprintf("[OS %s]", trc.FuncName)), trc.Time.Local().Format(traceTimeFormat), trc.OSStats.Path, trc.OSStats.Duration) + case madmin.TraceS3, madmin.TraceInternal: + if trc.HTTP == nil { + return "" + } + default: + fmt.Fprintf(b, "%s %s [%s] %s %s", nodeNameStr, console.Colorize("Request", fmt.Sprintf("[%s %s]", strings.ToUpper(trc.TraceType.String()), trc.FuncName)), trc.Time.Local().Format(traceTimeFormat), trc.Path, trc.Duration) return b.String() } - ri := trc.ReqInfo - rs := trc.RespInfo + ri := trc.HTTP.ReqInfo + rs := trc.HTTP.RespInfo fmt.Fprintf(b, "%s%s", nodeNameStr, console.Colorize("Request", fmt.Sprintf("[REQUEST %s] ", trc.FuncName))) fmt.Fprintf(b, "[%s] %s\n", ri.Time.Local().Format(traceTimeFormat), console.Colorize("Host", fmt.Sprintf("[Client IP: %s]", ri.Client))) fmt.Fprintf(b, "%s%s", nodeNameStr, console.Colorize("Method", fmt.Sprintf("%s %s", ri.Method, ri.Path))) @@ -617,7 +585,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.CallStats.Latency.Round(time.Microsecond), humanize.IBytes(uint64(trc.CallStats.InputBytes)), humanize.IBytes(uint64(trc.CallStats.OutputBytes))))) + 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))))) statusStr := console.Colorize("RespStatus", fmt.Sprintf("%d %s", rs.StatusCode, http.StatusText(rs.StatusCode))) if rs.StatusCode != http.StatusOK { diff --git a/cmd/auto-complete.go b/cmd/auto-complete.go index ab322dca..2b25728e 100644 --- a/cmd/auto-complete.go +++ b/cmd/auto-complete.go @@ -323,13 +323,14 @@ var completeCmds = map[string]complete.Predictor{ "/admin/decommission/status": aliasCompleter, "/admin/decommission/cancel": aliasCompleter, - "/admin/trace": aliasCompleter, - "/admin/speedtest": aliasCompleter, - "/admin/console": aliasCompleter, - "/admin/update": aliasCompleter, - "/admin/inspect": s3Completer, - "/admin/top/locks": aliasCompleter, - "/admin/top/api": aliasCompleter, + "/admin/trace": aliasCompleter, + "/admin/speedtest": aliasCompleter, + "/admin/console": aliasCompleter, + "/admin/update": aliasCompleter, + "/admin/inspect": s3Completer, + "/admin/top/locks": aliasCompleter, + "/admin/top/api": aliasCompleter, + "/admin/top/scanner": aliasCompleter, "/admin/service/stop": aliasCompleter, "/admin/service/restart": aliasCompleter, diff --git a/cmd/client-admin.go b/cmd/client-admin.go index 808090ba..925b2a79 100644 --- a/cmd/client-admin.go +++ b/cmd/client-admin.go @@ -24,9 +24,11 @@ import ( "net" "net/http" "net/url" + "os" "sync" "time" + "github.com/klauspost/compress/gzhttp" "github.com/mattn/go-ieproxy" "github.com/minio/madmin-go" "github.com/minio/mc/pkg/httptracer" @@ -102,14 +104,9 @@ func NewAdminFactory() func(config *Config) (*madmin.AdminClient, *probe.Error) TLSHandshakeTimeout: 10 * time.Second, ExpectContinueTimeout: 10 * time.Second, TLSClientConfig: tlsConfig, - // Set this value so that the underlying transport round-tripper - // doesn't try to auto decode the body of objects with - // content-encoding set to `gzip`. - // - // Refer: - // https://golang.org/src/net/http/transport.go?h=roundTrip#L1843 - DisableCompression: true, + DisableCompression: true, } + transport = gzhttp.Transport(transport) if config.Debug { transport = httptracer.GetNewTraceTransport(newTraceV4(), transport) @@ -152,6 +149,9 @@ func newAdminClient(aliasedURL string) (*madmin.AdminClient, *probe.Error) { if err != nil { return nil, err.Trace(alias, urlStrFull) } + if globalDebug { + s3Client.TraceOn(os.Stdout) + } return s3Client, nil } diff --git a/cmd/top-api-spinner.go b/cmd/top-api-spinner.go index e5d3598b..960f5924 100644 --- a/cmd/top-api-spinner.go +++ b/cmd/top-api-spinner.go @@ -27,7 +27,7 @@ import ( "github.com/charmbracelet/bubbles/spinner" tea "github.com/charmbracelet/bubbletea" "github.com/charmbracelet/lipgloss" - humanize "github.com/dustin/go-humanize" + "github.com/dustin/go-humanize" "github.com/minio/madmin-go" "github.com/olekukonko/tablewriter" ) @@ -149,8 +149,10 @@ func (m *traceUI) View() string { traceSt = &topAPIStats{} } traceSt.addAPICall(1) - traceSt.addAPIBytesRX(res.Trace.CallStats.InputBytes) - traceSt.addAPIBytesTX(res.Trace.CallStats.OutputBytes) + if res.Trace.HTTP != nil { + traceSt.addAPIBytesRX(res.Trace.HTTP.CallStats.InputBytes) + traceSt.addAPIBytesTX(res.Trace.HTTP.CallStats.OutputBytes) + } m.apiStatsMap[res.Trace.FuncName] = traceSt } diff --git a/go.mod b/go.mod index f49e7340..312c86c3 100644 --- a/go.mod +++ b/go.mod @@ -19,7 +19,7 @@ require ( github.com/minio/cli v1.22.0 github.com/minio/colorjson v1.0.2 github.com/minio/filepath v1.0.0 - github.com/minio/madmin-go v1.3.20 + github.com/minio/madmin-go v1.4.2 github.com/minio/md5-simd v1.1.2 // indirect github.com/minio/minio-go/v7 v7.0.30 github.com/minio/pkg v1.1.22 diff --git a/go.sum b/go.sum index 8883784c..b7165029 100644 --- a/go.sum +++ b/go.sum @@ -340,10 +340,8 @@ github.com/minio/colorjson v1.0.2/go.mod h1:JWxcL2n8T8JVf+NY6awl6kn5nK49aAzHOeQE github.com/minio/filepath v1.0.0 h1:fvkJu1+6X+ECRA6G3+JJETj4QeAYO9sV43I79H8ubDY= github.com/minio/filepath v1.0.0/go.mod h1:/nRZA2ldl5z6jT9/KQuvZcQlxZIMQoFFQPvEXx9T/Bw= github.com/minio/madmin-go v1.3.5/go.mod h1:vGKGboQgGIWx4DuDUaXixjlIEZOCIp6ivJkQoiVaACc= -github.com/minio/madmin-go v1.3.19 h1:X/L4MTnDoR1VG1wwkeaQOBIQQohMTp5k8mjKNBbxGkE= -github.com/minio/madmin-go v1.3.19/go.mod h1:ez87VmMtsxP7DRxjKJKD4RDNW+nhO2QF9KSzwxBDQ98= -github.com/minio/madmin-go v1.3.20 h1:XHlIdewxAEEd/poI43CPiSmHGgJplkbFKFXZ1vZ6zMY= -github.com/minio/madmin-go v1.3.20/go.mod h1:ez87VmMtsxP7DRxjKJKD4RDNW+nhO2QF9KSzwxBDQ98= +github.com/minio/madmin-go v1.4.2 h1:RiGSOjn4bUmtZBB1dmCDKgwBcLmygIDqjudpCTvbP70= +github.com/minio/madmin-go v1.4.2/go.mod h1:ez87VmMtsxP7DRxjKJKD4RDNW+nhO2QF9KSzwxBDQ98= github.com/minio/md5-simd v1.1.0/go.mod h1:XpBqgZULrMYD3R+M28PcmP0CkI7PEMzB3U77ZrKZ0Gw= github.com/minio/md5-simd v1.1.2 h1:Gdi1DZK69+ZVMoNHRXJyNcxrMA4dSxoYHZSQbirFg34= github.com/minio/md5-simd v1.1.2/go.mod h1:MzdKDxYpY2BT9XQFocsiZf/NKVtR7nkE4RoEpN+20RM=