github.com/fabiokung/docker@v0.11.2-0.20170222101415-4534dcd49497/cli/command/stack/services.go (about) 1 package stack 2 3 import ( 4 "fmt" 5 6 "golang.org/x/net/context" 7 8 "github.com/docker/docker/api/types" 9 "github.com/docker/docker/api/types/filters" 10 "github.com/docker/docker/cli" 11 "github.com/docker/docker/cli/command" 12 "github.com/docker/docker/cli/command/formatter" 13 "github.com/docker/docker/cli/command/service" 14 "github.com/docker/docker/opts" 15 "github.com/spf13/cobra" 16 ) 17 18 type servicesOptions struct { 19 quiet bool 20 format string 21 filter opts.FilterOpt 22 namespace string 23 } 24 25 func newServicesCommand(dockerCli *command.DockerCli) *cobra.Command { 26 opts := servicesOptions{filter: opts.NewFilterOpt()} 27 28 cmd := &cobra.Command{ 29 Use: "services [OPTIONS] STACK", 30 Short: "List the services in the stack", 31 Args: cli.ExactArgs(1), 32 RunE: func(cmd *cobra.Command, args []string) error { 33 opts.namespace = args[0] 34 return runServices(dockerCli, opts) 35 }, 36 } 37 flags := cmd.Flags() 38 flags.BoolVarP(&opts.quiet, "quiet", "q", false, "Only display IDs") 39 flags.StringVar(&opts.format, "format", "", "Pretty-print services using a Go template") 40 flags.VarP(&opts.filter, "filter", "f", "Filter output based on conditions provided") 41 42 return cmd 43 } 44 45 func runServices(dockerCli *command.DockerCli, opts servicesOptions) error { 46 ctx := context.Background() 47 client := dockerCli.Client() 48 49 filter := getStackFilterFromOpt(opts.namespace, opts.filter) 50 services, err := client.ServiceList(ctx, types.ServiceListOptions{Filters: filter}) 51 if err != nil { 52 return err 53 } 54 55 out := dockerCli.Out() 56 57 // if no services in this stack, print message and exit 0 58 if len(services) == 0 { 59 fmt.Fprintf(out, "Nothing found in stack: %s\n", opts.namespace) 60 return nil 61 } 62 63 info := map[string]formatter.ServiceListInfo{} 64 if !opts.quiet { 65 taskFilter := filters.NewArgs() 66 for _, service := range services { 67 taskFilter.Add("service", service.ID) 68 } 69 70 tasks, err := client.TaskList(ctx, types.TaskListOptions{Filters: taskFilter}) 71 if err != nil { 72 return err 73 } 74 75 nodes, err := client.NodeList(ctx, types.NodeListOptions{}) 76 if err != nil { 77 return err 78 } 79 80 info = service.GetServicesStatus(services, nodes, tasks) 81 } 82 83 format := opts.format 84 if len(format) == 0 { 85 if len(dockerCli.ConfigFile().ServicesFormat) > 0 && !opts.quiet { 86 format = dockerCli.ConfigFile().ServicesFormat 87 } else { 88 format = formatter.TableFormatKey 89 } 90 } 91 92 servicesCtx := formatter.Context{ 93 Output: dockerCli.Out(), 94 Format: formatter.NewServiceListFormat(format, opts.quiet), 95 } 96 return formatter.ServiceListWrite(servicesCtx, services, info) 97 }