services.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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 := getStackFilterFromOpt(opts.namespace, opts.filter)
  38. services, err := client.ServiceList(ctx, types.ServiceListOptions{Filters: filter})
  39. if err != nil {
  40. return err
  41. }
  42. out := dockerCli.Out()
  43. // if no services in this stack, print message and exit 0
  44. if len(services) == 0 {
  45. fmt.Fprintf(out, "Nothing found in stack: %s\n", opts.namespace)
  46. return nil
  47. }
  48. if opts.quiet {
  49. service.PrintQuiet(out, services)
  50. } else {
  51. taskFilter := filters.NewArgs()
  52. for _, service := range services {
  53. taskFilter.Add("service", service.ID)
  54. }
  55. tasks, err := client.TaskList(ctx, types.TaskListOptions{Filters: taskFilter})
  56. if err != nil {
  57. return err
  58. }
  59. nodes, err := client.NodeList(ctx, types.NodeListOptions{})
  60. if err != nil {
  61. return err
  62. }
  63. service.PrintNotQuiet(out, services, nodes, tasks)
  64. }
  65. return nil
  66. }