github.1git.de/docker/cli@v26.1.3+incompatible/cli/command/node/ps.go (about) 1 package node 2 3 import ( 4 "context" 5 "strings" 6 7 "github.com/docker/cli/cli" 8 "github.com/docker/cli/cli/command" 9 "github.com/docker/cli/cli/command/completion" 10 "github.com/docker/cli/cli/command/idresolver" 11 "github.com/docker/cli/cli/command/task" 12 "github.com/docker/cli/opts" 13 "github.com/docker/docker/api/types" 14 "github.com/docker/docker/api/types/swarm" 15 "github.com/pkg/errors" 16 "github.com/spf13/cobra" 17 ) 18 19 type psOptions struct { 20 nodeIDs []string 21 noResolve bool 22 noTrunc bool 23 quiet bool 24 format string 25 filter opts.FilterOpt 26 } 27 28 func newPsCommand(dockerCli command.Cli) *cobra.Command { 29 options := psOptions{filter: opts.NewFilterOpt()} 30 31 cmd := &cobra.Command{ 32 Use: "ps [OPTIONS] [NODE...]", 33 Short: "List tasks running on one or more nodes, defaults to current node", 34 Args: cli.RequiresMinArgs(0), 35 RunE: func(cmd *cobra.Command, args []string) error { 36 options.nodeIDs = []string{"self"} 37 38 if len(args) != 0 { 39 options.nodeIDs = args 40 } 41 42 return runPs(cmd.Context(), dockerCli, options) 43 }, 44 ValidArgsFunction: completion.NoComplete, 45 } 46 flags := cmd.Flags() 47 flags.BoolVar(&options.noTrunc, "no-trunc", false, "Do not truncate output") 48 flags.BoolVar(&options.noResolve, "no-resolve", false, "Do not map IDs to Names") 49 flags.VarP(&options.filter, "filter", "f", "Filter output based on conditions provided") 50 flags.StringVar(&options.format, "format", "", "Pretty-print tasks using a Go template") 51 flags.BoolVarP(&options.quiet, "quiet", "q", false, "Only display task IDs") 52 53 return cmd 54 } 55 56 func runPs(ctx context.Context, dockerCli command.Cli, options psOptions) error { 57 client := dockerCli.Client() 58 59 var ( 60 errs []string 61 tasks []swarm.Task 62 ) 63 64 for _, nodeID := range options.nodeIDs { 65 nodeRef, err := Reference(ctx, client, nodeID) 66 if err != nil { 67 errs = append(errs, err.Error()) 68 continue 69 } 70 71 node, _, err := client.NodeInspectWithRaw(ctx, nodeRef) 72 if err != nil { 73 errs = append(errs, err.Error()) 74 continue 75 } 76 77 filter := options.filter.Value() 78 filter.Add("node", node.ID) 79 80 nodeTasks, err := client.TaskList(ctx, types.TaskListOptions{Filters: filter}) 81 if err != nil { 82 errs = append(errs, err.Error()) 83 continue 84 } 85 86 tasks = append(tasks, nodeTasks...) 87 } 88 89 format := options.format 90 if len(format) == 0 { 91 format = task.DefaultFormat(dockerCli.ConfigFile(), options.quiet) 92 } 93 94 if len(errs) == 0 || len(tasks) != 0 { 95 if err := task.Print(ctx, dockerCli, tasks, idresolver.New(client, options.noResolve), !options.noTrunc, options.quiet, format); err != nil { 96 errs = append(errs, err.Error()) 97 } 98 } 99 100 if len(errs) > 0 { 101 return errors.Errorf("%s", strings.Join(errs, "\n")) 102 } 103 104 return nil 105 }