github.com/kobeld/docker@v1.12.0-rc1/api/client/node/list.go (about) 1 package node 2 3 import ( 4 "fmt" 5 "io" 6 "text/tabwriter" 7 8 "golang.org/x/net/context" 9 10 "github.com/docker/docker/api/client" 11 "github.com/docker/docker/cli" 12 "github.com/docker/docker/opts" 13 "github.com/docker/engine-api/types" 14 "github.com/docker/engine-api/types/swarm" 15 "github.com/spf13/cobra" 16 ) 17 18 const ( 19 listItemFmt = "%s\t%s\t%s\t%s\t%s\t%s\t%s\n" 20 ) 21 22 type listOptions struct { 23 quiet bool 24 filter opts.FilterOpt 25 } 26 27 func newListCommand(dockerCli *client.DockerCli) *cobra.Command { 28 opts := listOptions{filter: opts.NewFilterOpt()} 29 30 cmd := &cobra.Command{ 31 Use: "ls", 32 Aliases: []string{"list"}, 33 Short: "List nodes in the swarm", 34 Args: cli.NoArgs, 35 RunE: func(cmd *cobra.Command, args []string) error { 36 return runList(dockerCli, opts) 37 }, 38 } 39 flags := cmd.Flags() 40 flags.BoolVarP(&opts.quiet, "quiet", "q", false, "Only display IDs") 41 flags.VarP(&opts.filter, "filter", "f", "Filter output based on conditions provided") 42 43 return cmd 44 } 45 46 func runList(dockerCli *client.DockerCli, opts listOptions) error { 47 client := dockerCli.Client() 48 ctx := context.Background() 49 50 nodes, err := client.NodeList( 51 ctx, 52 types.NodeListOptions{Filter: opts.filter.Value()}) 53 if err != nil { 54 return err 55 } 56 57 info, err := client.Info(ctx) 58 if err != nil { 59 return err 60 } 61 62 out := dockerCli.Out() 63 if opts.quiet { 64 printQuiet(out, nodes) 65 } else { 66 printTable(out, nodes, info) 67 } 68 return nil 69 } 70 71 func printTable(out io.Writer, nodes []swarm.Node, info types.Info) { 72 writer := tabwriter.NewWriter(out, 0, 4, 2, ' ', 0) 73 74 // Ignore flushing errors 75 defer writer.Flush() 76 77 fmt.Fprintf(writer, listItemFmt, "ID", "NAME", "MEMBERSHIP", "STATUS", "AVAILABILITY", "MANAGER STATUS", "LEADER") 78 for _, node := range nodes { 79 name := node.Spec.Name 80 availability := string(node.Spec.Availability) 81 membership := string(node.Spec.Membership) 82 83 if name == "" { 84 name = node.Description.Hostname 85 } 86 87 leader := "" 88 if node.ManagerStatus != nil && node.ManagerStatus.Leader { 89 leader = "Yes" 90 } 91 92 reachability := "" 93 if node.ManagerStatus != nil { 94 reachability = string(node.ManagerStatus.Reachability) 95 } 96 97 ID := node.ID 98 if node.ID == info.Swarm.NodeID { 99 ID = ID + " *" 100 } 101 102 fmt.Fprintf( 103 writer, 104 listItemFmt, 105 ID, 106 name, 107 client.PrettyPrint(membership), 108 client.PrettyPrint(string(node.Status.State)), 109 client.PrettyPrint(availability), 110 client.PrettyPrint(reachability), 111 leader) 112 } 113 } 114 115 func printQuiet(out io.Writer, nodes []swarm.Node) { 116 for _, node := range nodes { 117 fmt.Fprintln(out, node.ID) 118 } 119 }