services.go 2.0 KB

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