github.com/sl1pm4t/consul@v1.4.5-0.20190325224627-74c31c540f9c/command/operator/raft/listpeers/operator_raft_list.go (about) 1 package listpeers 2 3 import ( 4 "flag" 5 "fmt" 6 7 "github.com/hashicorp/consul/api" 8 "github.com/hashicorp/consul/command/flags" 9 "github.com/mitchellh/cli" 10 "github.com/ryanuber/columnize" 11 ) 12 13 func New(ui cli.Ui) *cmd { 14 c := &cmd{UI: ui} 15 c.init() 16 return c 17 } 18 19 type cmd struct { 20 UI cli.Ui 21 flags *flag.FlagSet 22 http *flags.HTTPFlags 23 help string 24 } 25 26 func (c *cmd) init() { 27 c.flags = flag.NewFlagSet("", flag.ContinueOnError) 28 c.http = &flags.HTTPFlags{} 29 flags.Merge(c.flags, c.http.ClientFlags()) 30 flags.Merge(c.flags, c.http.ServerFlags()) 31 c.help = flags.Usage(help, c.flags) 32 } 33 34 func (c *cmd) Run(args []string) int { 35 if err := c.flags.Parse(args); err != nil { 36 if err == flag.ErrHelp { 37 return 0 38 } 39 c.UI.Error(fmt.Sprintf("Failed to parse args: %v", err)) 40 return 1 41 } 42 43 // Set up a client. 44 client, err := c.http.APIClient() 45 if err != nil { 46 c.UI.Error(fmt.Sprintf("Error initializing client: %s", err)) 47 return 1 48 } 49 50 // Fetch the current configuration. 51 result, err := raftListPeers(client, c.http.Stale()) 52 if err != nil { 53 c.UI.Error(fmt.Sprintf("Error getting peers: %v", err)) 54 return 1 55 } 56 57 c.UI.Output(result) 58 return 0 59 } 60 61 func raftListPeers(client *api.Client, stale bool) (string, error) { 62 q := &api.QueryOptions{ 63 AllowStale: stale, 64 } 65 reply, err := client.Operator().RaftGetConfiguration(q) 66 if err != nil { 67 return "", fmt.Errorf("Failed to retrieve raft configuration: %v", err) 68 } 69 70 // Format it as a nice table. 71 result := []string{"Node|ID|Address|State|Voter|RaftProtocol"} 72 for _, s := range reply.Servers { 73 raftProtocol := s.ProtocolVersion 74 75 if raftProtocol == "" { 76 raftProtocol = "<=1" 77 } 78 state := "follower" 79 if s.Leader { 80 state = "leader" 81 } 82 result = append(result, fmt.Sprintf("%s|%s|%s|%s|%v|%s", 83 s.Node, s.ID, s.Address, state, s.Voter, raftProtocol)) 84 } 85 86 return columnize.SimpleFormat(result), nil 87 } 88 89 func (c *cmd) Synopsis() string { 90 return synopsis 91 } 92 93 func (c *cmd) Help() string { 94 return c.help 95 } 96 97 const synopsis = "Display the current Raft peer configuration" 98 const help = ` 99 Usage: consul operator raft list-peers [options] 100 101 Displays the current Raft peer configuration. 102 `