services.go 2.0 KB

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