diff --git a/cmd/admin-top-api.go b/cmd/admin-top-api.go
new file mode 100644
index 00000000..480f0897
--- /dev/null
+++ b/cmd/admin-top-api.go
@@ -0,0 +1,122 @@
+// 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 (
+ "context"
+ "os"
+
+ tea "github.com/charmbracelet/bubbletea"
+ "github.com/minio/cli"
+ "github.com/minio/madmin-go"
+ "github.com/minio/mc/pkg/probe"
+)
+
+var adminTopAPIFlags = []cli.Flag{
+ cli.StringSliceFlag{
+ Name: "name",
+ Usage: "summarize current calls for matching API name",
+ },
+ cli.StringSliceFlag{
+ Name: "path",
+ Usage: "summarize current API calls only on matching path",
+ },
+ cli.StringSliceFlag{
+ Name: "node",
+ Usage: "summarize current API calls only on matching servers",
+ },
+ cli.BoolFlag{
+ Name: "errors, e",
+ Usage: "summarize current API calls throwing only errors",
+ },
+}
+
+var adminTopAPICmd = cli.Command{
+ Name: "api",
+ Usage: "summarize API events on MinIO server in real-time",
+ Action: mainAdminTopAPI,
+ OnUsageError: onUsageError,
+ Before: setGlobalsFromContext,
+ Flags: append(adminTopAPIFlags, globalFlags...),
+ HideHelpCommand: true,
+ CustomHelpTemplate: `NAME:
+ {{.HelpName}} - {{.Usage}}
+
+USAGE:
+ {{.HelpName}} [FLAGS] TARGET
+
+FLAGS:
+ {{range .VisibleFlags}}{{.}}
+ {{end}}
+EXAMPLES:
+`,
+}
+
+func mainAdminTopAPI(ctx *cli.Context) error {
+ 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, e := tracingOpts(ctx)
+ fatalIf(probe.NewError(e), "Unable to start tracing")
+
+ mopts := matchOpts{
+ funcNames: ctx.StringSlice("name"),
+ apiPaths: ctx.StringSlice("path"),
+ nodes: ctx.StringSlice("node"),
+ }
+
+ // Start listening on all trace activity.
+ traceCh := client.ServiceTrace(ctxt, opts)
+ done := make(chan struct{})
+
+ p := tea.NewProgram(initTraceUI())
+ go func() {
+ if e := p.Start(); e != nil {
+ os.Exit(1)
+ }
+ close(done)
+ }()
+
+ go func() {
+ for apiCallInfo := range traceCh {
+ if apiCallInfo.Err != nil {
+ fatalIf(probe.NewError(apiCallInfo.Err), "Unable to fetch top API events")
+ }
+ if matchTrace(mopts, apiCallInfo) {
+ p.Send(topAPIResult{
+ apiCallInfo: apiCallInfo,
+ })
+ }
+ p.Send(topAPIResult{
+ apiCallInfo: madmin.ServiceTraceInfo{},
+ })
+ }
+ }()
+
+ <-done
+ return nil
+}
diff --git a/cmd/admin-top.go b/cmd/admin-top.go
index 8e103e63..8c036877 100644
--- a/cmd/admin-top.go
+++ b/cmd/admin-top.go
@@ -20,6 +20,7 @@ package cmd
import "github.com/minio/cli"
var adminTopSubcommands = []cli.Command{
+ adminTopAPICmd,
adminTopLocksCmd,
}
diff --git a/cmd/admin-trace.go b/cmd/admin-trace.go
index dbc06dae..55d49d4b 100644
--- a/cmd/admin-trace.go
+++ b/cmd/admin-trace.go
@@ -53,7 +53,6 @@ var adminTraceFlags = []cli.Flag{
Name: "response-threshold",
Usage: "trace calls only with response duration greater than this threshold (e.g. `5ms`)",
},
-
cli.IntSliceFlag{
Name: "status-code",
Usage: "trace only matching status code",
@@ -70,6 +69,10 @@ var adminTraceFlags = []cli.Flag{
Name: "path",
Usage: "trace only matching path",
},
+ cli.StringSliceFlag{
+ Name: "node",
+ Usage: "trace only matching servers",
+ },
cli.BoolFlag{
Name: "errors, e",
Usage: "trace only failed requests",
@@ -129,21 +132,19 @@ func printTrace(verbose bool, traceInfo madmin.ServiceTraceInfo) {
}
}
-func matchTrace(ctx *cli.Context, traceInfo madmin.ServiceTraceInfo) bool {
- statusCodes := ctx.IntSlice("status-code")
- methods := ctx.StringSlice("method")
- funcNames := ctx.StringSlice("funcname")
- apiPaths := ctx.StringSlice("path")
-
- if len(statusCodes) == 0 && len(methods) == 0 && len(funcNames) == 0 && len(apiPaths) == 0 {
- // no specific filtering found trace all the requests
- return true
- }
+type matchOpts struct {
+ statusCodes []int
+ methods []string
+ funcNames []string
+ apiPaths []string
+ nodes []string
+}
+func matchTrace(opts matchOpts, traceInfo madmin.ServiceTraceInfo) bool {
// Filter request path if passed by the user
- if len(apiPaths) > 0 {
+ if len(opts.apiPaths) > 0 {
matched := false
- for _, apiPath := range apiPaths {
+ for _, apiPath := range opts.apiPaths {
if pathMatch(path.Join("/", apiPath), traceInfo.Trace.ReqInfo.Path) {
matched = true
break
@@ -155,9 +156,9 @@ func matchTrace(ctx *cli.Context, traceInfo madmin.ServiceTraceInfo) bool {
}
// Filter response status codes if passed by the user
- if len(statusCodes) > 0 {
+ if len(opts.statusCodes) > 0 {
matched := false
- for _, code := range statusCodes {
+ for _, code := range opts.statusCodes {
if traceInfo.Trace.RespInfo.StatusCode == code {
matched = true
break
@@ -170,9 +171,9 @@ func matchTrace(ctx *cli.Context, traceInfo madmin.ServiceTraceInfo) bool {
}
// Filter request method if passed by the user
- if len(methods) > 0 {
+ if len(opts.methods) > 0 {
matched := false
- for _, method := range methods {
+ for _, method := range opts.methods {
if traceInfo.Trace.ReqInfo.Method == method {
matched = true
break
@@ -184,10 +185,10 @@ func matchTrace(ctx *cli.Context, traceInfo madmin.ServiceTraceInfo) bool {
}
- if len(funcNames) > 0 {
+ if len(opts.funcNames) > 0 {
matched := false
// Filter request function handler names if passed by the user.
- for _, funcName := range funcNames {
+ for _, funcName := range opts.funcNames {
if nameMatch(funcName, traceInfo.Trace.FuncName) {
matched = true
break
@@ -198,6 +199,20 @@ func matchTrace(ctx *cli.Context, traceInfo madmin.ServiceTraceInfo) bool {
}
}
+ if len(opts.nodes) > 0 {
+ matched := false
+ // Filter request by node if passed by the user.
+ for _, node := range opts.nodes {
+ if nameMatch(node, traceInfo.Trace.NodeName) {
+ matched = true
+ break
+ }
+ }
+ if !matched {
+ return false
+ }
+ }
+
return true
}
@@ -286,13 +301,21 @@ func mainAdminTrace(ctx *cli.Context) error {
opts, e := tracingOpts(ctx)
fatalIf(probe.NewError(e), "Unable to start tracing")
+ mopts := matchOpts{
+ statusCodes: ctx.IntSlice("status-code"),
+ methods: ctx.StringSlice("method"),
+ funcNames: ctx.StringSlice("funcname"),
+ apiPaths: ctx.StringSlice("path"),
+ nodes: ctx.StringSlice("node"),
+ }
+
// Start listening on all trace activity.
traceCh := client.ServiceTrace(ctxt, opts)
for traceInfo := range traceCh {
if traceInfo.Err != nil {
fatalIf(probe.NewError(traceInfo.Err), "Unable to listen to http trace")
}
- if matchTrace(ctx, traceInfo) {
+ if matchTrace(mopts, traceInfo) {
printTrace(verbose, traceInfo)
}
}
diff --git a/cmd/auto-complete.go b/cmd/auto-complete.go
index edb26ea8..b23476d9 100644
--- a/cmd/auto-complete.go
+++ b/cmd/auto-complete.go
@@ -329,6 +329,7 @@ var completeCmds = map[string]complete.Predictor{
"/admin/update": aliasCompleter,
"/admin/inspect": s3Completer,
"/admin/top/locks": aliasCompleter,
+ "/admin/top/api": aliasCompleter,
"/admin/service/stop": aliasCompleter,
"/admin/service/restart": aliasCompleter,
diff --git a/cmd/top-api-spinner.go b/cmd/top-api-spinner.go
new file mode 100644
index 00000000..debbf851
--- /dev/null
+++ b/cmd/top-api-spinner.go
@@ -0,0 +1,193 @@
+// 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 (
+ "fmt"
+ "sort"
+ "strings"
+ "sync/atomic"
+ "time"
+
+ "github.com/charmbracelet/bubbles/spinner"
+ tea "github.com/charmbracelet/bubbletea"
+ "github.com/charmbracelet/lipgloss"
+ humanize "github.com/dustin/go-humanize"
+ "github.com/minio/madmin-go"
+ "github.com/olekukonko/tablewriter"
+)
+
+// TODO: Add ART (Average Response Time) latency
+type topAPIStats struct {
+ TotalCalls uint64
+ TotalBytesRX uint64
+ TotalBytesTX uint64
+}
+
+func (s *topAPIStats) addAPICall(n int) {
+ atomic.AddUint64(&s.TotalCalls, uint64(n))
+}
+
+func (s *topAPIStats) addAPIBytesRX(n int) {
+ atomic.AddUint64(&s.TotalBytesRX, uint64(n))
+}
+
+func (s *topAPIStats) addAPIBytesTX(n int) {
+ atomic.AddUint64(&s.TotalBytesTX, uint64(n))
+}
+
+func (s *topAPIStats) loadAPICall() uint64 {
+ return atomic.LoadUint64(&s.TotalCalls)
+}
+
+func (s *topAPIStats) loadAPIBytesRX() uint64 {
+ return atomic.LoadUint64(&s.TotalBytesRX)
+}
+
+func (s *topAPIStats) loadAPIBytesTX() uint64 {
+ return atomic.LoadUint64(&s.TotalBytesTX)
+}
+
+type traceUI struct {
+ spinner spinner.Model
+ quitting bool
+ startTime time.Time
+ result topAPIResult
+ apiStatsMap map[string]*topAPIStats
+}
+
+type topAPIResult struct {
+ final bool
+ apiCallInfo madmin.ServiceTraceInfo
+}
+
+func initTraceUI() *traceUI {
+ s := spinner.New()
+ s.Spinner = spinner.Points
+ s.Style = lipgloss.NewStyle().Foreground(lipgloss.Color("205"))
+ return &traceUI{
+ spinner: s,
+ startTime: time.Now(),
+ apiStatsMap: make(map[string]*topAPIStats),
+ }
+}
+
+func (m *traceUI) Init() tea.Cmd {
+ return m.spinner.Tick
+}
+
+func (m *traceUI) 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 topAPIResult:
+ m.result = 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 *traceUI) View() string {
+ var s strings.Builder
+ s.WriteString("\n")
+
+ // Set table header
+ table := tablewriter.NewWriter(&s)
+ table.SetAutoWrapText(false)
+ table.SetAutoFormatHeaders(true)
+ table.SetHeaderAlignment(tablewriter.ALIGN_LEFT)
+ table.SetAlignment(tablewriter.ALIGN_LEFT)
+ table.SetCenterSeparator("")
+ table.SetColumnSeparator("")
+ table.SetRowSeparator("")
+ table.SetHeaderLine(false)
+ table.SetBorder(false)
+ table.SetTablePadding("\t") // pad with tabs
+ table.SetNoWhiteSpace(true)
+
+ res := m.result.apiCallInfo
+ if res.Trace.FuncName != "" && res.Trace.FuncName != "errorResponseHandler" {
+ traceSt, ok := m.apiStatsMap[res.Trace.FuncName]
+ if !ok {
+ traceSt = &topAPIStats{}
+ }
+ traceSt.addAPICall(1)
+ traceSt.addAPIBytesRX(res.Trace.CallStats.InputBytes)
+ traceSt.addAPIBytesTX(res.Trace.CallStats.OutputBytes)
+ m.apiStatsMap[res.Trace.FuncName] = traceSt
+ }
+
+ table.SetHeader([]string{"API", "RX", "TX", "N"})
+ data := make([][]string, 0, len(m.apiStatsMap))
+
+ for k, stats := range m.apiStatsMap {
+ data = append(data, []string{
+ k,
+ whiteStyle.Render(humanize.IBytes(stats.loadAPIBytesRX())),
+ whiteStyle.Render(humanize.IBytes(stats.loadAPIBytesTX())),
+ whiteStyle.Render(fmt.Sprintf("%d", stats.loadAPICall())),
+ })
+ }
+ sort.Slice(data, func(i, j int) bool {
+ return data[i][0] < data[j][0]
+ })
+
+ table.AppendBulk(data)
+ table.Render()
+
+ if !m.quitting {
+ s.WriteString(fmt.Sprintf("\nTopAPI: %s", m.spinner.View()))
+ } else {
+ var totalTX, totalRX, totalCalls uint64
+ currentTime := time.Now()
+ duration := currentTime.Sub(m.startTime).Seconds()
+ if duration == 0 {
+ duration = 1 // duration is always 1-sec atleast
+ }
+ for _, stats := range m.apiStatsMap {
+ totalRX += stats.loadAPIBytesRX()
+ totalTX += stats.loadAPIBytesTX()
+ totalCalls += stats.loadAPICall()
+ }
+ msg := fmt.Sprintf("\n========\n%d IOP/s, RX %s/s, TX %s/s - in the last %s",
+ totalCalls/uint64(duration),
+ humanize.IBytes(totalRX/uint64(duration)),
+ humanize.IBytes(totalTX/uint64(duration)),
+ humanize.RelTime(m.startTime, currentTime, "", ""),
+ )
+ s.WriteString(msg)
+ s.WriteString("\n")
+ }
+ return s.String()
+}