github.com/vieux/docker@v0.6.3-0.20161004191708-e097c2a938c7/cli/command/service/ps.go (about)

     1  package service
     2  
     3  import (
     4  	"github.com/docker/docker/api/types"
     5  	"github.com/docker/docker/cli"
     6  	"github.com/docker/docker/cli/command"
     7  	"github.com/docker/docker/cli/command/idresolver"
     8  	"github.com/docker/docker/cli/command/node"
     9  	"github.com/docker/docker/cli/command/task"
    10  	"github.com/docker/docker/opts"
    11  	"github.com/spf13/cobra"
    12  	"golang.org/x/net/context"
    13  )
    14  
    15  type psOptions struct {
    16  	serviceID string
    17  	noResolve bool
    18  	noTrunc   bool
    19  	filter    opts.FilterOpt
    20  }
    21  
    22  func newPsCommand(dockerCli *command.DockerCli) *cobra.Command {
    23  	opts := psOptions{filter: opts.NewFilterOpt()}
    24  
    25  	cmd := &cobra.Command{
    26  		Use:   "ps [OPTIONS] SERVICE",
    27  		Short: "List the tasks of a service",
    28  		Args:  cli.ExactArgs(1),
    29  		RunE: func(cmd *cobra.Command, args []string) error {
    30  			opts.serviceID = args[0]
    31  			return runPS(dockerCli, opts)
    32  		},
    33  	}
    34  	flags := cmd.Flags()
    35  	flags.BoolVar(&opts.noTrunc, "no-trunc", false, "Do not truncate output")
    36  	flags.BoolVar(&opts.noResolve, "no-resolve", false, "Do not map IDs to Names")
    37  	flags.VarP(&opts.filter, "filter", "f", "Filter output based on conditions provided")
    38  
    39  	return cmd
    40  }
    41  
    42  func runPS(dockerCli *command.DockerCli, opts psOptions) error {
    43  	client := dockerCli.Client()
    44  	ctx := context.Background()
    45  
    46  	service, _, err := client.ServiceInspectWithRaw(ctx, opts.serviceID)
    47  	if err != nil {
    48  		return err
    49  	}
    50  
    51  	filter := opts.filter.Value()
    52  	filter.Add("service", service.ID)
    53  	if filter.Include("node") {
    54  		nodeFilters := filter.Get("node")
    55  		for _, nodeFilter := range nodeFilters {
    56  			nodeReference, err := node.Reference(ctx, client, nodeFilter)
    57  			if err != nil {
    58  				return err
    59  			}
    60  			filter.Del("node", nodeFilter)
    61  			filter.Add("node", nodeReference)
    62  		}
    63  	}
    64  
    65  	tasks, err := client.TaskList(ctx, types.TaskListOptions{Filter: filter})
    66  	if err != nil {
    67  		return err
    68  	}
    69  
    70  	return task.Print(dockerCli, ctx, tasks, idresolver.New(client, opts.noResolve), opts.noTrunc)
    71  }