ps.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. package node
  2. import (
  3. "fmt"
  4. "strings"
  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. "golang.org/x/net/context"
  14. )
  15. type psOptions struct {
  16. nodeIDs []string
  17. noResolve bool
  18. noTrunc bool
  19. filter opts.FilterOpt
  20. }
  21. func newPsCommand(dockerCli *command.DockerCli) *cobra.Command {
  22. opts := psOptions{filter: opts.NewFilterOpt()}
  23. cmd := &cobra.Command{
  24. Use: "ps [OPTIONS] [NODE...]",
  25. Short: "List tasks running on one or more nodes, defaults to current node",
  26. Args: cli.RequiresMinArgs(0),
  27. RunE: func(cmd *cobra.Command, args []string) error {
  28. opts.nodeIDs = []string{"self"}
  29. if len(args) != 0 {
  30. opts.nodeIDs = args
  31. }
  32. return runPs(dockerCli, opts)
  33. },
  34. }
  35. flags := cmd.Flags()
  36. flags.BoolVar(&opts.noTrunc, "no-trunc", false, "Do not truncate output")
  37. flags.BoolVar(&opts.noResolve, "no-resolve", false, "Do not map IDs to Names")
  38. flags.VarP(&opts.filter, "filter", "f", "Filter output based on conditions provided")
  39. return cmd
  40. }
  41. func runPs(dockerCli *command.DockerCli, opts psOptions) error {
  42. client := dockerCli.Client()
  43. ctx := context.Background()
  44. var (
  45. errs []string
  46. tasks []swarm.Task
  47. )
  48. for _, nodeID := range opts.nodeIDs {
  49. nodeRef, err := Reference(ctx, client, nodeID)
  50. if err != nil {
  51. errs = append(errs, err.Error())
  52. continue
  53. }
  54. node, _, err := client.NodeInspectWithRaw(ctx, nodeRef)
  55. if err != nil {
  56. errs = append(errs, err.Error())
  57. continue
  58. }
  59. filter := opts.filter.Value()
  60. filter.Add("node", node.ID)
  61. nodeTasks, err := client.TaskList(ctx, types.TaskListOptions{Filters: filter})
  62. if err != nil {
  63. errs = append(errs, err.Error())
  64. continue
  65. }
  66. tasks = append(tasks, nodeTasks...)
  67. }
  68. if err := task.Print(dockerCli, ctx, tasks, idresolver.New(client, opts.noResolve), opts.noTrunc); err != nil {
  69. errs = append(errs, err.Error())
  70. }
  71. if len(errs) > 0 {
  72. return fmt.Errorf("%s", strings.Join(errs, "\n"))
  73. }
  74. return nil
  75. }