github.com/zhuohuang-hust/src-cbuild@v0.0.0-20230105071821-c7aab3e7c840/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/service" 13 "github.com/docker/docker/opts" 14 "github.com/spf13/cobra" 15 ) 16 17 type servicesOptions struct { 18 quiet bool 19 filter opts.FilterOpt 20 namespace string 21 } 22 23 func newServicesCommand(dockerCli *command.DockerCli) *cobra.Command { 24 opts := servicesOptions{filter: opts.NewFilterOpt()} 25 26 cmd := &cobra.Command{ 27 Use: "services [OPTIONS] STACK", 28 Short: "List the services in the stack", 29 Args: cli.ExactArgs(1), 30 RunE: func(cmd *cobra.Command, args []string) error { 31 opts.namespace = args[0] 32 return runServices(dockerCli, opts) 33 }, 34 } 35 flags := cmd.Flags() 36 flags.BoolVarP(&opts.quiet, "quiet", "q", false, "Only display IDs") 37 flags.VarP(&opts.filter, "filter", "f", "Filter output based on conditions provided") 38 39 return cmd 40 } 41 42 func runServices(dockerCli *command.DockerCli, opts servicesOptions) error { 43 ctx := context.Background() 44 client := dockerCli.Client() 45 46 filter := opts.filter.Value() 47 filter.Add("label", labelNamespace+"="+opts.namespace) 48 49 services, err := client.ServiceList(ctx, types.ServiceListOptions{Filters: filter}) 50 if err != nil { 51 return err 52 } 53 54 out := dockerCli.Out() 55 56 // if no services in this stack, print message and exit 0 57 if len(services) == 0 { 58 fmt.Fprintf(out, "Nothing found in stack: %s\n", opts.namespace) 59 return nil 60 } 61 62 if opts.quiet { 63 service.PrintQuiet(out, services) 64 } else { 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 nodes, err := client.NodeList(ctx, types.NodeListOptions{}) 75 if err != nil { 76 return err 77 } 78 service.PrintNotQuiet(out, services, nodes, tasks) 79 } 80 return nil 81 }