ps.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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 := opts.filter.Value()
  44. filter.Add("label", labelNamespace+"="+opts.namespace)
  45. if !opts.all && !filter.Include("desired-state") {
  46. filter.Add("desired-state", string(swarm.TaskStateRunning))
  47. filter.Add("desired-state", string(swarm.TaskStateAccepted))
  48. }
  49. tasks, err := client.TaskList(ctx, types.TaskListOptions{Filters: filter})
  50. if err != nil {
  51. return err
  52. }
  53. if len(tasks) == 0 {
  54. fmt.Fprintf(dockerCli.Out(), "Nothing found in stack: %s\n", namespace)
  55. return nil
  56. }
  57. return task.Print(dockerCli, ctx, tasks, idresolver.New(client, opts.noResolve), opts.noTrunc)
  58. }