github.com/portworx/docker@v1.12.1/api/client/stack/ps.go (about)

     1  // +build experimental
     2  
     3  package stack
     4  
     5  import (
     6  	"fmt"
     7  
     8  	"golang.org/x/net/context"
     9  
    10  	"github.com/docker/docker/api/client"
    11  	"github.com/docker/docker/api/client/idresolver"
    12  	"github.com/docker/docker/api/client/task"
    13  	"github.com/docker/docker/cli"
    14  	"github.com/docker/docker/opts"
    15  	"github.com/docker/engine-api/types"
    16  	"github.com/docker/engine-api/types/swarm"
    17  	"github.com/spf13/cobra"
    18  )
    19  
    20  type psOptions struct {
    21  	all       bool
    22  	filter    opts.FilterOpt
    23  	namespace string
    24  	noResolve bool
    25  }
    26  
    27  func newPSCommand(dockerCli *client.DockerCli) *cobra.Command {
    28  	opts := psOptions{filter: opts.NewFilterOpt()}
    29  
    30  	cmd := &cobra.Command{
    31  		Use:   "ps [OPTIONS] STACK",
    32  		Short: "List the tasks in the stack",
    33  		Args:  cli.ExactArgs(1),
    34  		RunE: func(cmd *cobra.Command, args []string) error {
    35  			opts.namespace = args[0]
    36  			return runPS(dockerCli, opts)
    37  		},
    38  	}
    39  	flags := cmd.Flags()
    40  	flags.BoolVarP(&opts.all, "all", "a", false, "Display all tasks")
    41  	flags.BoolVar(&opts.noResolve, "no-resolve", false, "Do not map IDs to Names")
    42  	flags.VarP(&opts.filter, "filter", "f", "Filter output based on conditions provided")
    43  
    44  	return cmd
    45  }
    46  
    47  func runPS(dockerCli *client.DockerCli, opts psOptions) error {
    48  	namespace := opts.namespace
    49  	client := dockerCli.Client()
    50  	ctx := context.Background()
    51  
    52  	filter := opts.filter.Value()
    53  	filter.Add("label", labelNamespace+"="+opts.namespace)
    54  	if !opts.all && !filter.Include("desired-state") {
    55  		filter.Add("desired-state", string(swarm.TaskStateRunning))
    56  		filter.Add("desired-state", string(swarm.TaskStateAccepted))
    57  	}
    58  
    59  	tasks, err := client.TaskList(ctx, types.TaskListOptions{Filter: filter})
    60  	if err != nil {
    61  		return err
    62  	}
    63  
    64  	if len(tasks) == 0 {
    65  		fmt.Fprintf(dockerCli.Out(), "Nothing found in stack: %s\n", namespace)
    66  		return nil
    67  	}
    68  
    69  	return task.Print(dockerCli, ctx, tasks, idresolver.New(client, opts.noResolve))
    70  }