add mc ping command (#4074)

This commit is contained in:
Ashish Kumar Sinha
2022-07-11 09:16:12 -07:00
committed by GitHub
parent afa79f2bd7
commit 1f22780d12
5 changed files with 351 additions and 3 deletions
+1
View File
@@ -432,6 +432,7 @@ var completeCmds = map[string]complete.Predictor{
"/update": nil,
"/ready": nil,
"/ping": nil,
}
// flagsToCompleteFlags transforms a cli.Flag to complete.Flags
+1
View File
@@ -451,6 +451,7 @@ var appCmds = []cli.Command{
configCmd,
updateCmd,
readyCmd,
pingCmd,
}
func printMCVersion(c *cli.Context) {
+342
View File
@@ -0,0 +1,342 @@
// Copyright (c) 2015-2022 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
import (
"context"
"fmt"
"os"
"sort"
"strconv"
"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"
)
const (
pingInterval = time.Second // keep it similar to unix ping interval
)
var pingFlags = []cli.Flag{
cli.IntFlag{
Name: "count, c",
Usage: "perform liveliness check for count number of times",
Value: 4,
},
cli.DurationFlag{
Name: "interval, i",
Usage: "Wait interval between each request",
Value: pingInterval,
},
}
// return latency and liveness probe.
var pingCmd = cli.Command{
Name: "ping",
Usage: "perform liveness check",
Action: mainPing,
Before: setGlobalsFromContext,
OnUsageError: onUsageError,
Flags: append(pingFlags, globalFlags...),
HideHelpCommand: true,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} [FLAGS] TARGET [TARGET...]
{{if .VisibleFlags}}
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}{{end}}
EXAMPLES:
1. Return Latency and liveness probe.
{{.Prompt}} {{.HelpName}} myminio
2. Return Latency and liveness probe 5 number of times.
{{.Prompt}} {{.HelpName}} --count 5 myminio
3. Return Latency and liveness with wait interval set to 30 seconds.
{{.Prompt}} {{.HelpName}} --interval 30s myminio
`,
}
// Validate command line arguments.
func checkPingSyntax(cliCtx *cli.Context) {
if !cliCtx.Args().Present() {
cli.ShowCommandHelpAndExit(cliCtx, "ping", 1) // last argument is exit code
}
}
// PingResult is result for each ping
type PingResult struct {
madmin.AliveResult
}
// PingResults is result for each ping for all hosts
type PingResults struct {
Results map[string][]PingResult
Final bool
}
// JSON jsonified ping result message.
func (pr PingResult) JSON() string {
statusJSONBytes, e := json.MarshalIndent(pr, "", " ")
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
return string(statusJSONBytes)
}
// String colorized ping result message.
func (pr PingResult) String() (msg string) {
if pr.Error == nil {
coloredDot := console.Colorize("Info", dot)
// Print server title
msg += fmt.Sprintf("%s %s:", coloredDot, console.Colorize("PrintB", pr.Endpoint.String()))
msg += fmt.Sprintf(" time=%s\n", pr.ResponseTime)
return
}
coloredDot := console.Colorize("InfoFail", dot)
msg += fmt.Sprintf("%s %s:", coloredDot, console.Colorize("PrintB", pr.Endpoint.String()))
msg += fmt.Sprintf(" time=%s, error=%s\n", pr.ResponseTime, console.Colorize("InfoFail", pr.Error.Error()))
return msg
}
type pingUI struct {
spinner spinner.Model
quitting bool
results PingResults
}
func initPingUI() *pingUI {
s := spinner.New()
s.Spinner = spinner.Points
s.Style = lipgloss.NewStyle().Foreground(lipgloss.Color("205"))
return &pingUI{
spinner: s,
}
}
func (m *pingUI) Init() tea.Cmd {
return m.spinner.Tick
}
func (m *pingUI) 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 PingResults:
m.results = 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 *pingUI) View() string {
var s strings.Builder
// 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.results
if len(res.Results) > 0 {
s.WriteString("\n")
}
trailerIfGreaterThan := func(in string, max int) string {
if len(in) < max {
return in
}
return in[:max] + "..."
}
table.SetHeader([]string{"Node", "Avg-Latency", "Count", ""})
data := make([][]string, 0, len(res.Results))
if len(res.Results) == 0 {
data = append(data, []string{
"...",
whiteStyle.Render("-- ms"),
whiteStyle.Render("--"),
"",
})
} else {
for k, results := range res.Results {
data = append(data, []string{
trailerIfGreaterThan(k, 64),
getAvgLatency(results...).String(),
strconv.Itoa(len(results)),
"",
})
}
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("\nPinging: %s", m.spinner.View()))
} else {
s.WriteString("\n")
}
return s.String()
}
func getAvgLatency(results ...PingResult) (avg time.Duration) {
if len(results) == 0 {
return avg
}
var totalDurationNS uint64
for _, result := range results {
totalDurationNS += uint64(result.ResponseTime.Nanoseconds())
}
return time.Duration(totalDurationNS / uint64(len(results)))
}
func fetchAdminInfo(admClnt *madmin.AdminClient) (madmin.InfoMessage, error) {
timer := time.NewTimer(time.Second)
defer timer.Stop()
for {
select {
case <-globalContext.Done():
return madmin.InfoMessage{}, globalContext.Err()
case <-timer.C:
ctx, cancel := context.WithTimeout(globalContext, 3*time.Second)
// Fetch the service status of the specified MinIO server
info, e := admClnt.ServerInfo(ctx)
cancel()
if e == nil {
return info, nil
}
timer.Reset(time.Second)
}
}
}
// mainPing is entry point for ping command.
func mainPing(cliCtx *cli.Context) error {
// check 'ping' cli arguments.
checkPingSyntax(cliCtx)
console.SetColor("Info", color.New(color.FgGreen, color.Bold))
console.SetColor("InfoFail", color.New(color.FgRed, color.Bold))
ctx, cancel := context.WithCancel(globalContext)
defer cancel()
aliasedURL := cliCtx.Args().Get(0)
count := cliCtx.Int("count")
if count < 1 {
fatalIf(errInvalidArgument().Trace(cliCtx.Args()...), "ping count cannot be less than 1")
}
interval := cliCtx.Duration("interval")
admClient, err := newAdminClient(aliasedURL)
fatalIf(err.Trace(aliasedURL), "Unable to initialize admin client for `"+aliasedURL+"`.")
anonClient, err := newAnonymousClient(aliasedURL)
fatalIf(err.Trace(aliasedURL), "Unable to initialize anonymous client for `"+aliasedURL+"`.")
done := make(chan struct{})
ui := tea.NewProgram(initPingUI())
if !globalJSON {
go func() {
if e := ui.Start(); e != nil {
cancel()
os.Exit(1)
}
close(done)
}()
}
admInfo, e := fetchAdminInfo(admClient)
fatalIf(probe.NewError(e).Trace(aliasedURL), "Unable to get server info")
pingResults := PingResults{
Results: make(map[string][]PingResult),
}
for i := 0; i < count; i++ {
for result := range anonClient.Alive(ctx, madmin.AliveOpts{}, admInfo.Servers...) {
if globalJSON {
printMsg(PingResult{result})
} else {
hostResults, ok := pingResults.Results[result.Endpoint.Host]
if !ok {
pingResults.Results[result.Endpoint.Host] = []PingResult{{result}}
} else {
hostResults = append(hostResults, PingResult{result})
pingResults.Results[result.Endpoint.Host] = hostResults
}
ui.Send(pingResults)
}
}
time.Sleep(interval)
}
if !globalJSON {
pingResults.Final = true
ui.Send(pingResults)
<-done
}
return nil
}
+1 -1
View File
@@ -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.4.3
github.com/minio/madmin-go v1.4.4
github.com/minio/md5-simd v1.1.2 // indirect
github.com/minio/minio-go/v7 v7.0.31
github.com/minio/pkg v1.1.22
+6 -2
View File
@@ -60,6 +60,7 @@ github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6r
github.com/bgentry/speakeasy v0.1.0/go.mod h1:+zsyZBPWlz7T6j88CTgSN5bM796AkVf0kBD4zp0CCIs=
github.com/bketelsen/crypt v0.0.4/go.mod h1:aI6NrJ0pMGgvZKL1iVgXLnfIFJtfV+bKCoqOes/6LfM=
github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU=
github.com/cespare/xxhash v1.1.0 h1:a6HrQnmkObjyL+Gs60czilIUGqrzKutQD6XZog3p+ko=
github.com/cespare/xxhash v1.1.0/go.mod h1:XrSqR1VqqWfGrhpAt58auRo0WTKS1nRRg3ghfAqPWnc=
github.com/cespare/xxhash/v2 v2.1.1/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
github.com/cespare/xxhash/v2 v2.1.2 h1:YRXhKfTDauu4ajMg1TPgFO5jnlC2HCbmLXMcTG5cbYE=
@@ -271,6 +272,7 @@ github.com/klauspost/compress v1.13.5/go.mod h1:/3/Vjq9QcHkK5uEr5lBEmyoZ1iFhe47e
github.com/klauspost/compress v1.13.6 h1:P76CopJELS0TiO2mebmnzgWaajssP/EszplttgQxcgc=
github.com/klauspost/compress v1.13.6/go.mod h1:/3/Vjq9QcHkK5uEr5lBEmyoZ1iFhe47etQ6QUkpK6sk=
github.com/klauspost/cpuid v1.2.3/go.mod h1:Pj4uuM528wm8OyEC2QMXAi2YiTZ96dNQPGgoMS4s3ek=
github.com/klauspost/cpuid v1.3.1 h1:5JNjFYYQrZeKRJ0734q51WCEEn2huer72Dc7K+R/b6s=
github.com/klauspost/cpuid v1.3.1/go.mod h1:bYW4mA6ZgKPob1/Dlai2LviZJO7KGI3uoWLd42rAQw4=
github.com/klauspost/cpuid/v2 v2.0.1/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
github.com/klauspost/cpuid/v2 v2.0.4/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
@@ -340,8 +342,10 @@ 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.4.3 h1:5/kBHjKTjYOQQHvyznu51weN5hJtFW67LB2VLz+hmzU=
github.com/minio/madmin-go v1.4.3/go.mod h1:ez87VmMtsxP7DRxjKJKD4RDNW+nhO2QF9KSzwxBDQ98=
github.com/minio/madmin-go v1.3.11/go.mod h1:ez87VmMtsxP7DRxjKJKD4RDNW+nhO2QF9KSzwxBDQ98=
github.com/minio/madmin-go v1.3.11/go.mod h1:ez87VmMtsxP7DRxjKJKD4RDNW+nhO2QF9KSzwxBDQ98=
github.com/minio/madmin-go v1.4.4 h1:6nf5Ut4szFvG1yeoOD5Tuvl7uRHF/XXh7LSuBTlKzL0=
github.com/minio/madmin-go v1.4.4/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=