ps.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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/swarm"
  7. "github.com/docker/docker/cli"
  8. "github.com/docker/docker/cli/command"
  9. "github.com/docker/docker/cli/command/idresolver"
  10. "github.com/docker/docker/cli/command/task"
  11. "github.com/docker/docker/opts"
  12. "github.com/spf13/cobra"
  13. )
  14. type psOptions struct {
  15. all bool
  16. filter opts.FilterOpt
  17. noTrunc bool
  18. namespace string
  19. noResolve bool
  20. }
  21. func newPsCommand(dockerCli *command.DockerCli) *cobra.Command {
  22. opts := psOptions{filter: opts.NewFilterOpt()}
  23. cmd := &cobra.Command{
  24. Use: "ps [OPTIONS] STACK",
  25. Short: "List the tasks in the stack",
  26. Args: cli.ExactArgs(1),
  27. RunE: func(cmd *cobra.Command, args []string) error {
  28. opts.namespace = args[0]
  29. return runPS(dockerCli, opts)
  30. },
  31. }
  32. flags := cmd.Flags()
  33. flags.BoolVarP(&opts.all, "all", "a", false, "Display all tasks")
  34. flags.BoolVar(&opts.noTrunc, "no-trunc", false, "Do not truncate output")
  35. flags.BoolVar(&opts.noResolve, "no-resolve", false, "Do not map IDs to Names")
  36. flags.VarP(&opts.filter, "filter", "f", "Filter output based on conditions provided")
  37. return cmd
  38. }
  39. func runPS(dockerCli *command.DockerCli, opts psOptions) error {
  40. namespace := opts.namespace
  41. client := dockerCli.Client()
  42. ctx := context.Background()
  43. filter := getStackFilterFromOpt(opts.namespace, opts.filter)
  44. if !opts.all && !filter.Include("desired-state") {
  45. filter.Add("desired-state", string(swarm.TaskStateRunning))
  46. filter.Add("desired-state", string(swarm.TaskStateAccepted))
  47. }
  48. tasks, err := client.TaskList(ctx, types.TaskListOptions{Filters: filter})
  49. if err != nil {
  50. return err
  51. }
  52. if len(tasks) == 0 {
  53. fmt.Fprintf(dockerCli.Out(), "Nothing found in stack: %s\n", namespace)
  54. return nil
  55. }
  56. return task.Print(dockerCli, ctx, tasks, idresolver.New(client, opts.noResolve), opts.noTrunc)
  57. }