services.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. package stack
  2. import (
  3. "fmt"
  4. "golang.org/x/net/context"
  5. "github.com/docker/docker/api/types"
  6. "github.com/docker/docker/api/types/filters"
  7. "github.com/docker/docker/cli"
  8. "github.com/docker/docker/cli/command"
  9. "github.com/docker/docker/cli/command/service"
  10. "github.com/docker/docker/opts"
  11. "github.com/spf13/cobra"
  12. )
  13. type servicesOptions struct {
  14. quiet bool
  15. filter opts.FilterOpt
  16. namespace string
  17. }
  18. func newServicesCommand(dockerCli *command.DockerCli) *cobra.Command {
  19. opts := servicesOptions{filter: opts.NewFilterOpt()}
  20. cmd := &cobra.Command{
  21. Use: "services [OPTIONS] STACK",
  22. Short: "List the services in the stack",
  23. Args: cli.ExactArgs(1),
  24. RunE: func(cmd *cobra.Command, args []string) error {
  25. opts.namespace = args[0]
  26. return runServices(dockerCli, opts)
  27. },
  28. }
  29. flags := cmd.Flags()
  30. flags.BoolVarP(&opts.quiet, "quiet", "q", false, "Only display IDs")
  31. flags.VarP(&opts.filter, "filter", "f", "Filter output based on conditions provided")
  32. return cmd
  33. }
  34. func runServices(dockerCli *command.DockerCli, opts servicesOptions) error {
  35. ctx := context.Background()
  36. client := dockerCli.Client()
  37. filter := opts.filter.Value()
  38. filter.Add("label", labelNamespace+"="+opts.namespace)
  39. services, err := client.ServiceList(ctx, types.ServiceListOptions{Filters: filter})
  40. if err != nil {
  41. return err
  42. }
  43. out := dockerCli.Out()
  44. // if no services in this stack, print message and exit 0
  45. if len(services) == 0 {
  46. fmt.Fprintf(out, "Nothing found in stack: %s\n", opts.namespace)
  47. return nil
  48. }
  49. if opts.quiet {
  50. service.PrintQuiet(out, services)
  51. } else {
  52. taskFilter := filters.NewArgs()
  53. for _, service := range services {
  54. taskFilter.Add("service", service.ID)
  55. }
  56. tasks, err := client.TaskList(ctx, types.TaskListOptions{Filters: taskFilter})
  57. if err != nil {
  58. return err
  59. }
  60. nodes, err := client.NodeList(ctx, types.NodeListOptions{})
  61. if err != nil {
  62. return err
  63. }
  64. service.PrintNotQuiet(out, services, nodes, tasks)
  65. }
  66. return nil
  67. }