forked from hashicorp/consul
-
Notifications
You must be signed in to change notification settings - Fork 0
/
operator_raft_list.go
104 lines (84 loc) · 2.23 KB
/
operator_raft_list.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
package command
import (
"flag"
"fmt"
"strings"
"github.com/hashicorp/consul/api"
"github.com/hashicorp/consul/command/base"
"github.com/hashicorp/serf/serf"
"github.com/ryanuber/columnize"
)
type OperatorRaftListCommand struct {
base.Command
}
func (c *OperatorRaftListCommand) Help() string {
helpText := `
Usage: consul operator raft list-peers [options]
Displays the current Raft peer configuration.
` + c.Command.Help()
return strings.TrimSpace(helpText)
}
func (c *OperatorRaftListCommand) Synopsis() string {
return "Display the current Raft peer configuration"
}
func (c *OperatorRaftListCommand) Run(args []string) int {
c.Command.NewFlagSet(c)
if err := c.Command.Parse(args); err != nil {
if err == flag.ErrHelp {
return 0
}
c.UI.Error(fmt.Sprintf("Failed to parse args: %v", err))
return 1
}
// Set up a client.
client, err := c.Command.HTTPClient()
if err != nil {
c.UI.Error(fmt.Sprintf("Error initializing client: %s", err))
return 1
}
// Fetch the current configuration.
result, err := raftListPeers(client, c.Command.HTTPStale())
if err != nil {
c.UI.Error(fmt.Sprintf("Error getting peers: %v", err))
}
c.UI.Output(result)
return 0
}
func raftListPeers(client *api.Client, stale bool) (string, error) {
raftProtocols := make(map[string]string)
members, err := client.Agent().Members(false)
if err != nil {
return "", err
}
for _, member := range members {
if serf.MemberStatus(member.Status) == serf.StatusLeft {
continue
}
if member.Tags["role"] != "consul" {
continue
}
raftProtocols[member.Name] = member.Tags["raft_vsn"]
}
q := &api.QueryOptions{
AllowStale: stale,
}
reply, err := client.Operator().RaftGetConfiguration(q)
if err != nil {
return "", fmt.Errorf("Failed to retrieve raft configuration: %v", err)
}
// Format it as a nice table.
result := []string{"Node|ID|Address|State|Voter|RaftProtocol"}
for _, s := range reply.Servers {
raftProtocol := raftProtocols[s.Node]
if raftProtocol == "" {
raftProtocol = "<=1"
}
state := "follower"
if s.Leader {
state = "leader"
}
result = append(result, fmt.Sprintf("%s|%s|%s|%s|%v|%s",
s.Node, s.ID, s.Address, state, s.Voter, raftProtocol))
}
return columnize.SimpleFormat(result), nil
}