diff --git a/cmd/auto-complete.go b/cmd/auto-complete.go index 996c7da7..e122e34e 100644 --- a/cmd/auto-complete.go +++ b/cmd/auto-complete.go @@ -266,12 +266,12 @@ var completeCmds = map[string]complete.Predictor{ "/encrypt/info": s3Complete{deepLevel: 2}, "/encrypt/clear": s3Complete{deepLevel: 2}, - "/replicate/add": s3Complete{deepLevel: 2}, - "/replicate/edit": s3Complete{deepLevel: 2}, - "/replicate/update": s3Complete{deepLevel: 2}, - "/replicate/list": s3Complete{deepLevel: 2}, - "/replicate/remove": s3Complete{deepLevel: 2}, - "/replicate/diff": s3Complete{deepLevel: 2}, + "/replicate/add": s3Complete{deepLevel: 2}, + "/replicate/edit": s3Complete{deepLevel: 2}, + "/replicate/update": s3Complete{deepLevel: 2}, + "/replicate/list": s3Complete{deepLevel: 2}, + "/replicate/remove": s3Complete{deepLevel: 2}, + "/replicate/backlog": s3Complete{deepLevel: 2}, "/replicate/export": s3Complete{deepLevel: 2}, "/replicate/import": s3Complete{deepLevel: 2}, diff --git a/cmd/replicate-diff.go b/cmd/replicate-backlog.go similarity index 56% rename from cmd/replicate-diff.go rename to cmd/replicate-backlog.go index c8c5367c..f148bbe1 100644 --- a/cmd/replicate-diff.go +++ b/cmd/replicate-backlog.go @@ -20,7 +20,9 @@ package cmd import ( "context" "fmt" + "path" "path/filepath" + "strconv" "strings" "github.com/charmbracelet/bubbles/help" @@ -38,7 +40,7 @@ import ( "github.com/minio/pkg/console" ) -var replicateDiffFlags = []cli.Flag{ +var replicateBacklogFlags = []cli.Flag{ cli.StringFlag{ Name: "arn", Usage: "unique role ARN", @@ -47,15 +49,26 @@ var replicateDiffFlags = []cli.Flag{ Name: "verbose,v", Usage: "include replicated versions", }, + cli.StringFlag{ + Name: "nodes,n", + Usage: "show most recent failures for one or more nodes. Valid values are 'all', or node name", + Value: "all", + }, + cli.BoolFlag{ + Name: "full,a", + Usage: "list and show all replication failures for bucket", + }, } -var replicateDiffCmd = cli.Command{ - Name: "diff", - Usage: "show unreplicated object versions", - Action: mainReplicateDiff, - OnUsageError: onUsageError, - Before: setGlobalsFromContext, - Flags: append(globalFlags, replicateDiffFlags...), +var replicateBacklogCmd = cli.Command{ + Name: "backlog", + Aliases: []string{"diff"}, + HiddenAliases: true, + Usage: "show unreplicated object versions", + Action: mainReplicateBacklog, + OnUsageError: onUsageError, + Before: setGlobalsFromContext, + Flags: append(globalFlags, replicateBacklogFlags...), CustomHelpTemplate: `NAME: {{.HelpName}} - {{.Usage}} @@ -66,43 +79,63 @@ FLAGS: {{range .VisibleFlags}}{{.}} {{end}} EXAMPLES: - 1. Show unreplicated objects on "myminio" alias for objects in prefix "path/to/prefix" of "mybucket" for a specific remote target - {{.Prompt}} {{.HelpName}} myminio/mybucket/path/to/prefix --arn + 1. Show most recent replication failures on "myminio" alias for objects in bucket "mybucket" + {{.Prompt}} {{.HelpName}} myminio/mybucket - 2. Show unreplicated objects on "myminio" alias for objects in prefix "path/to/prefix" of "mybucket" for all targets. - {{.Prompt}} {{.HelpName}} myminio/mybucket/path/to/prefix + 2. Show all unreplicated objects on "myminio" alias for objects in prefix "path/to/prefix" of "mybucket" for all targets. + This will perform full listing of all objects in the prefix to find unreplicated objects. + {{.Prompt}} {{.HelpName}} myminio/mybucket/path/to/prefix --full `, } -// checkReplicateDiffSyntax - validate all the passed arguments -func checkReplicateDiffSyntax(ctx *cli.Context) { +// checkReplicateBacklogSyntax - validate all the passed arguments +func checkReplicateBacklogSyntax(ctx *cli.Context) { if len(ctx.Args()) != 1 { showCommandHelpAndExit(ctx, 1) // last argument is exit code } } -type replicateDiffMessage struct { - Op string `json:"op"` - madmin.DiffInfo - OpStatus string `json:"opStatus"` - arn string `json:"-"` - verbose bool `json:"-"` +type replicateBacklogMessage struct { + Op string `json:"op"` + Diff madmin.DiffInfo `json:"diff,omitempty"` + MRF madmin.ReplicationMRF `json:"mrf,omitempty"` + OpStatus string `json:"opStatus"` + arn string `json:"-"` + verbose bool `json:"-"` } -func (r replicateDiffMessage) JSON() string { - r.OpStatus = "success" - jsonMessageBytes, e := json.MarshalIndent(r, "", " ") +func (r replicateBacklogMessage) JSON() string { + var e error + var jsonMessageBytes []byte + switch r.Op { + case "diff": + jsonMessageBytes, e = json.MarshalIndent(r.Diff, "", " ") + + case "mrf": + jsonMessageBytes, e = json.MarshalIndent(r.MRF, "", " ") + } fatalIf(probe.NewError(e), "Unable to marshal into JSON.") return string(jsonMessageBytes) } -func (r replicateDiffMessage) toRow() (row table.Row) { - if r.Object == "" { +func (r replicateBacklogMessage) toRow() (row table.Row) { + switch r.Op { + case "diff": + return r.toDiffRow() + case "mrf": + return r.toMRFRow() + } + return +} + +func (r replicateBacklogMessage) toDiffRow() (row table.Row) { + d := r.Diff + if d.Object == "" { return } op := "" - if r.VersionID != "" { - switch r.IsDeleteMarker { + if d.VersionID != "" { + switch d.IsDeleteMarker { case true: op = "DEL" default: @@ -110,7 +143,7 @@ func (r replicateDiffMessage) toRow() (row table.Row) { } } st := r.replStatus() - replTimeStamp := r.ReplicationTimestamp.Format(printDate) + replTimeStamp := d.ReplicationTimestamp.Format(printDate) switch { case st == "PENDING": replTimeStamp = "" @@ -118,20 +151,31 @@ func (r replicateDiffMessage) toRow() (row table.Row) { replTimeStamp = "" } return table.Row{ - replTimeStamp, r.LastModified.Format(printDate), st, r.VersionID, op, r.Object, + replTimeStamp, d.LastModified.Format(printDate), st, d.VersionID, op, d.Object, } } -func (r *replicateDiffMessage) replStatus() string { +func (r replicateBacklogMessage) toMRFRow() (row table.Row) { + d := r.MRF + if d.Object == "" { + return + } + return table.Row{ + d.NodeName, d.VersionID, strconv.Itoa(d.RetryCount), path.Join(d.Bucket, d.Object), + } +} + +func (r *replicateBacklogMessage) replStatus() string { var st string + d := r.Diff if r.arn == "" { // report overall replication status - if r.DeleteReplicationStatus != "" { - st = r.DeleteReplicationStatus + if d.DeleteReplicationStatus != "" { + st = d.DeleteReplicationStatus } else { - st = r.ReplicationStatus + st = d.ReplicationStatus } } else { // report target replication diff - for arn, t := range r.Targets { + for arn, t := range d.Targets { if arn != r.arn { continue } @@ -141,19 +185,20 @@ func (r *replicateDiffMessage) replStatus() string { st = t.ReplicationStatus } } - if len(r.Targets) == 0 { + if len(d.Targets) == 0 { st = "" } } return st } -const rowLimit = 10000 - -type replicateDiffUI struct { +type replicateBacklogUI struct { spinner spinner.Model - sub <-chan madmin.DiffInfo + sub interface{} + diffCh chan madmin.DiffInfo + mrfCh chan madmin.ReplicationMRF arn string + op string quitting bool table table.Model rows []table.Row @@ -189,11 +234,11 @@ func newKeyMap() keyMap { } } -func initReplicateDiffUI(arn string, diffCh <-chan madmin.DiffInfo) *replicateDiffUI { +func initReplicateBacklogUI(arn string, op string, diffCh interface{}) *replicateBacklogUI { s := spinner.New() s.Spinner = spinner.Points s.Style = lipgloss.NewStyle().Foreground(lipgloss.Color("205")) - columns := getDiffHeader() + columns := getBacklogHeader(op) t := table.New( table.WithColumns(columns), @@ -201,35 +246,62 @@ func initReplicateDiffUI(arn string, diffCh <-chan madmin.DiffInfo) *replicateDi table.WithHeight(7), ) - ts := getDiffStyles() + ts := getBacklogStyles() t.SetStyles(ts) - return &replicateDiffUI{ + ui := &replicateBacklogUI{ spinner: s, sub: diffCh, + op: op, arn: arn, table: t, help: help.New(), keymap: newKeyMap(), } + if ch, ok := diffCh.(chan madmin.DiffInfo); ok { + ui.diffCh = ch + } + if ch, ok := diffCh.(chan madmin.ReplicationMRF); ok { + ui.mrfCh = ch + } + return ui } -func (m *replicateDiffUI) Init() tea.Cmd { +func (m *replicateBacklogUI) Init() tea.Cmd { return tea.Batch( m.spinner.Tick, - waitForActivity(m.sub), // wait for activity + waitForActivity(m.sub, m.op), // wait for activity ) } +const rowLimit = 10000 + // A command that waits for the activity on a channel. -func waitForActivity(sub <-chan madmin.DiffInfo) tea.Cmd { +func waitForActivity(sub interface{}, op string) tea.Cmd { return func() tea.Msg { - msg := <-sub - return msg + switch op { + case "diff": + msg := <-sub.(<-chan madmin.DiffInfo) + return msg + case "mrf": + msg := <-sub.(<-chan madmin.ReplicationMRF) + return msg + } + return "unexpected message" } } -func getDiffHeader() []table.Column { +func getBacklogHeader(op string) []table.Column { + switch op { + case "diff": + return getBacklogDiffHeader() + case "mrf": + return getBacklogMRFHeader() + } + return nil +} + +func getBacklogDiffHeader() []table.Column { return []table.Column{ {Title: "Attempted At", Width: 23}, {Title: "Created", Width: 23}, @@ -240,7 +312,16 @@ func getDiffHeader() []table.Column { } } -func getDiffStyles() table.Styles { +func getBacklogMRFHeader() []table.Column { + return []table.Column{ + {Title: "Node", Width: 40}, + {Title: "VersionID", Width: 36}, + {Title: "Retry", Width: 5}, + {Title: "Object", Width: 60}, + } +} + +func getBacklogStyles() table.Styles { ts := table.DefaultStyles() ts.Header = ts.Header. BorderStyle(lipgloss.NormalBorder()). @@ -254,9 +335,8 @@ func getDiffStyles() table.Styles { return ts } -func (m *replicateDiffUI) Update(msg tea.Msg) (tea.Model, tea.Cmd) { +func (m *replicateBacklogUI) Update(msg tea.Msg) (tea.Model, tea.Cmd) { var cmd tea.Cmd - switch msg := msg.(type) { case tea.KeyMsg: switch msg.String() { @@ -270,8 +350,8 @@ func (m *replicateDiffUI) Update(msg tea.Msg) (tea.Model, tea.Cmd) { m.quitting = true return m, tea.Quit case "enter": - columns := getDiffHeader() - ts := getDiffStyles() + columns := getBacklogHeader(m.op) + ts := getBacklogStyles() m.table = table.New( table.WithColumns(columns), table.WithRows(m.rows), @@ -285,17 +365,42 @@ func (m *replicateDiffUI) Update(msg tea.Msg) (tea.Model, tea.Cmd) { if msg.Object != "" { m.count++ if m.count <= rowLimit { // don't buffer more than 10k entries - rdif := replicateDiffMessage{ - DiffInfo: msg, - arn: m.arn, + rdif := replicateBacklogMessage{ + Op: "diff", + Diff: msg, + arn: m.arn, } m.rows = append(m.rows, rdif.toRow()) } - return m, waitForActivity(m.sub) + return m, waitForActivity(m.sub, m.op) } m.quitting = true - columns := getDiffHeader() - ts := getDiffStyles() + columns := getBacklogDiffHeader() + ts := getBacklogStyles() + m.table = table.New( + table.WithColumns(columns), + table.WithRows(m.rows), + table.WithFocused(true), + table.WithHeight(10), + ) + m.table.SetStyles(ts) + return m, nil + case madmin.ReplicationMRF: + if msg.Object != "" { + m.count++ + if m.count <= rowLimit { // don't buffer more than 10k entries + rdif := replicateBacklogMessage{ + Op: "mrf", + MRF: msg, + arn: m.arn, + } + m.rows = append(m.rows, rdif.toRow()) + } + return m, waitForActivity(m.sub, m.op) + } + m.quitting = true + columns := getBacklogMRFHeader() + ts := getBacklogStyles() m.table = table.New( table.WithColumns(columns), table.WithRows(m.rows), @@ -343,7 +448,7 @@ var ( BorderForeground(subtle) ) -func (m *replicateDiffUI) helpView() string { +func (m *replicateBacklogUI) helpView() string { return "\n" + m.help.ShortHelpView([]key.Binding{ m.keymap.enter, m.keymap.down, @@ -352,7 +457,7 @@ func (m *replicateDiffUI) helpView() string { }) } -func (m *replicateDiffUI) View() string { +func (m *replicateBacklogUI) View() string { var sb strings.Builder if !m.quitting { sb.WriteString(fmt.Sprintf("%s\n", m.spinner.View())) @@ -375,8 +480,8 @@ func (m *replicateDiffUI) View() string { return sb.String() } -func mainReplicateDiff(cliCtx *cli.Context) error { - checkReplicateDiffSyntax(cliCtx) +func mainReplicateBacklog(cliCtx *cli.Context) error { + checkReplicateBacklogSyntax(cliCtx) console.SetColor("diff-msg", color.New(color.FgHiCyan, color.Bold)) // Get the alias parameter from cli args := cliCtx.Args() @@ -393,6 +498,29 @@ func mainReplicateDiff(cliCtx *cli.Context) error { // Create a new MinIO Admin Client client, cerr := newAdminClient(aliasedURL) fatalIf(cerr, "Unable to initialize admin connection.") + if !cliCtx.IsSet("full") { + mrfCh := client.BucketReplicationMRF(ctx, bucket, cliCtx.String("nodes")) + if globalJSON { + for mrf := range mrfCh { + if mrf.Err != "" { + fatalIf(probe.NewError(fmt.Errorf("%s", mrf.Err)), "Unable to fetch replication backlog.") + } + printMsg(replicateMRFMessage{ + Op: "mrf", + Status: "success", + ReplicationMRF: mrf, + }) + } + return nil + } + ui := tea.NewProgram(initReplicateBacklogUI("", "mrf", mrfCh)) + if _, e := ui.Run(); e != nil { + cancel() + fatalIf(probe.NewError(e).Trace(aliasedURL), "Unable to fetch replication backlog") + } + return nil + } + verbose := cliCtx.Bool("verbose") arn := cliCtx.String("arn") diffCh := client.BucketReplicationDiff(ctx, bucket, madmin.ReplDiffOpts{ @@ -402,20 +530,21 @@ func mainReplicateDiff(cliCtx *cli.Context) error { }) if globalJSON { for di := range diffCh { - console.Println(replicateDiffMessage{ - Op: "diff", - DiffInfo: di, - arn: arn, - verbose: verbose, + console.Println(replicateBacklogMessage{ + Op: "diff", + Diff: di, + arn: arn, + verbose: verbose, }.JSON()) } return nil } - ui := tea.NewProgram(initReplicateDiffUI(arn, diffCh)) + ui := tea.NewProgram(initReplicateBacklogUI(arn, "diff", diffCh)) if _, e := ui.Run(); e != nil { cancel() - fatalIf(probe.NewError(e).Trace(aliasedURL), "Unable to fetch replication diff") + fatalIf(probe.NewError(e).Trace(aliasedURL), "Unable to fetch replication backlog") } + return nil } diff --git a/cmd/replicate-main.go b/cmd/replicate-main.go index 391e0f33..890caba9 100644 --- a/cmd/replicate-main.go +++ b/cmd/replicate-main.go @@ -28,7 +28,7 @@ var replicateSubcommands = []cli.Command{ replicateExportCmd, replicateImportCmd, replicateRemoveCmd, - replicateDiffCmd, + replicateBacklogCmd, } var replicateCmd = cli.Command{ diff --git a/cmd/replicate-status.go b/cmd/replicate-status.go index 1515926e..39afb800 100644 --- a/cmd/replicate-status.go +++ b/cmd/replicate-status.go @@ -20,6 +20,7 @@ package cmd import ( "context" "fmt" + "hash/fnv" "math" "sort" @@ -33,13 +34,21 @@ import ( "github.com/minio/pkg/console" ) +var replicateStatusFlags = []cli.Flag{ + cli.StringFlag{ + Name: "backlog,b", + Usage: "show most recent failures for one or more nodes. Valid values are 'all', or node name", + Value: "all", + }, +} + var replicateStatusCmd = cli.Command{ Name: "status", Usage: "show server side replication status", Action: mainReplicateStatus, OnUsageError: onUsageError, Before: setGlobalsFromContext, - Flags: globalFlags, + Flags: append(globalFlags, replicateStatusFlags...), CustomHelpTemplate: `NAME: {{.HelpName}} - {{.Usage}} @@ -52,6 +61,9 @@ FLAGS: EXAMPLES: 1. Get server side replication metrics for bucket "mybucket" for alias "myminio". {{.Prompt}} {{.HelpName}} myminio/mybucket + + 2. Get most recent replication failures for bucket "mybucket" for alias "myminio". + {{.Prompt}} {{.HelpName}} --backlog "all" myminio/mybucket `, } @@ -270,7 +282,11 @@ func mainReplicateStatus(cliCtx *cli.Context) error { console.SetColor("Replica", color.New(color.FgCyan)) console.SetColor("Failed", color.New(color.Bold, color.FgRed)) - + console.SetColor("Object", color.New(color.FgWhite)) + console.SetColor("Count", color.New(color.FgWhite)) + for _, c := range colors { + console.SetColor(fmt.Sprintf("Node%d", c), color.New(c)) + } checkReplicateStatusSyntax(cliCtx) // Get the alias parameter from cli @@ -279,12 +295,27 @@ func mainReplicateStatus(cliCtx *cli.Context) error { // Create a new Client client, err := newClient(aliasedURL) fatalIf(err, "Unable to initialize connection.") - replicateStatus, err := client.GetReplicationMetrics(ctx) - fatalIf(err.Trace(args...), "Unable to get replication status") // Create a new MinIO Admin Client admClient, cerr := newAdminClient(aliasedURL) fatalIf(cerr, "Unable to initialize admin connection.") _, sourceBucket := url2Alias(args[0]) + + if cliCtx.IsSet("backlog") { + mrfCh := admClient.BucketReplicationMRF(ctx, sourceBucket, cliCtx.String("backlog")) + for mrf := range mrfCh { + if mrf.Err != "" { + fatalIf(probe.NewError(fmt.Errorf("%s", mrf.Err)), "Unable to fetch replication backlog.") + } + printMsg(replicateMRFMessage{ + Op: cliCtx.Command.Name, + Status: "success", + ReplicationMRF: mrf, + }) + } + return nil + } + replicateStatus, err := client.GetReplicationMetrics(ctx) + fatalIf(err.Trace(args...), "Unable to get replication status") targets, e := admClient.ListRemoteTargets(globalContext, sourceBucket, "") fatalIf(probe.NewError(e).Trace(args...), "Unable to fetch remote target.") cfg, err := client.GetReplication(ctx) @@ -300,3 +331,33 @@ func mainReplicateStatus(cliCtx *cli.Context) error { return nil } + +type replicateMRFMessage struct { + Op string `json:"op"` + Status string `json:"status"` + madmin.ReplicationMRF +} + +func (m replicateMRFMessage) JSON() string { + m.Status = "success" + jsonMessageBytes, e := json.MarshalIndent(m, "", " ") + fatalIf(probe.NewError(e), "Unable to marshal into JSON.") + return string(jsonMessageBytes) +} + +func (m replicateMRFMessage) String() string { + return console.Colorize("", newPrettyTable(" | ", + Field{getNodeTheme(m.ReplicationMRF.NodeName), len(m.ReplicationMRF.NodeName) + 3}, + Field{"Count", 7}, + Field{"Object", -1}, + ).buildRow(m.ReplicationMRF.NodeName, fmt.Sprintf("Retry=%d", m.ReplicationMRF.RetryCount), fmt.Sprintf("%s (%s)", m.ReplicationMRF.Object, m.ReplicationMRF.VersionID))) +} + +// colorize node name +func getNodeTheme(nodeName string) string { + nodeHash := fnv.New32a() + nodeHash.Write([]byte(nodeName)) + nHashSum := nodeHash.Sum32() + idx := nHashSum % uint32(len(colors)) + return fmt.Sprintf("Node%d", colors[idx]) +}