github.com/kobeld/docker@v1.12.0-rc1/api/client/service/list.go (about) 1 package service 2 3 import ( 4 "fmt" 5 "io" 6 "strings" 7 "text/tabwriter" 8 9 "golang.org/x/net/context" 10 11 "github.com/docker/docker/api/client" 12 "github.com/docker/docker/cli" 13 "github.com/docker/docker/opts" 14 "github.com/docker/docker/pkg/stringid" 15 "github.com/docker/engine-api/types" 16 "github.com/docker/engine-api/types/swarm" 17 "github.com/spf13/cobra" 18 ) 19 20 const ( 21 listItemFmt = "%s\t%s\t%s\t%s\t%s\n" 22 ) 23 24 type listOptions struct { 25 quiet bool 26 filter opts.FilterOpt 27 } 28 29 func newListCommand(dockerCli *client.DockerCli) *cobra.Command { 30 opts := listOptions{filter: opts.NewFilterOpt()} 31 32 cmd := &cobra.Command{ 33 Use: "ls", 34 Aliases: []string{"list"}, 35 Short: "List services", 36 Args: cli.NoArgs, 37 RunE: func(cmd *cobra.Command, args []string) error { 38 return runList(dockerCli, opts) 39 }, 40 } 41 42 flags := cmd.Flags() 43 flags.BoolVarP(&opts.quiet, "quiet", "q", false, "Only display IDs") 44 flags.VarP(&opts.filter, "filter", "f", "Filter output based on conditions provided") 45 46 return cmd 47 } 48 49 func runList(dockerCli *client.DockerCli, opts listOptions) error { 50 client := dockerCli.Client() 51 52 services, err := client.ServiceList( 53 context.Background(), 54 types.ServiceListOptions{Filter: opts.filter.Value()}) 55 if err != nil { 56 return err 57 } 58 59 out := dockerCli.Out() 60 if opts.quiet { 61 printQuiet(out, services) 62 } else { 63 printTable(out, services) 64 } 65 return nil 66 } 67 68 func printTable(out io.Writer, services []swarm.Service) { 69 writer := tabwriter.NewWriter(out, 0, 4, 2, ' ', 0) 70 71 // Ignore flushing errors 72 defer writer.Flush() 73 74 fmt.Fprintf(writer, listItemFmt, "ID", "NAME", "SCALE", "IMAGE", "COMMAND") 75 for _, service := range services { 76 scale := "" 77 if service.Spec.Mode.Replicated != nil && service.Spec.Mode.Replicated.Replicas != nil { 78 scale = fmt.Sprintf("%d", *service.Spec.Mode.Replicated.Replicas) 79 } else if service.Spec.Mode.Global != nil { 80 scale = "global" 81 } 82 fmt.Fprintf( 83 writer, 84 listItemFmt, 85 stringid.TruncateID(service.ID), 86 service.Spec.Name, 87 scale, 88 service.Spec.TaskTemplate.ContainerSpec.Image, 89 strings.Join(service.Spec.TaskTemplate.ContainerSpec.Args, " ")) 90 } 91 } 92 93 func printQuiet(out io.Writer, services []swarm.Service) { 94 for _, service := range services { 95 fmt.Fprintln(out, service.ID) 96 } 97 }