github.com/brahmaroutu/docker@v1.2.1-0.20160809185609-eb28dde01f16/api/client/stack/services.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/service"
    12  	"github.com/docker/docker/cli"
    13  	"github.com/docker/docker/opts"
    14  	"github.com/docker/engine-api/types"
    15  	"github.com/docker/engine-api/types/filters"
    16  	"github.com/spf13/cobra"
    17  )
    18  
    19  const (
    20  	listItemFmt = "%s\t%s\t%s\t%s\t%s\n"
    21  )
    22  
    23  type servicesOptions struct {
    24  	quiet     bool
    25  	filter    opts.FilterOpt
    26  	namespace string
    27  }
    28  
    29  func newServicesCommand(dockerCli *client.DockerCli) *cobra.Command {
    30  	opts := servicesOptions{filter: opts.NewFilterOpt()}
    31  
    32  	cmd := &cobra.Command{
    33  		Use:   "services [OPTIONS] STACK",
    34  		Short: "List the services in the stack",
    35  		Args:  cli.ExactArgs(1),
    36  		RunE: func(cmd *cobra.Command, args []string) error {
    37  			opts.namespace = args[0]
    38  			return runServices(dockerCli, opts)
    39  		},
    40  	}
    41  	flags := cmd.Flags()
    42  	flags.BoolVarP(&opts.quiet, "quiet", "q", false, "Only display IDs")
    43  	flags.VarP(&opts.filter, "filter", "f", "Filter output based on conditions provided")
    44  
    45  	return cmd
    46  }
    47  
    48  func runServices(dockerCli *client.DockerCli, opts servicesOptions) error {
    49  	ctx := context.Background()
    50  	client := dockerCli.Client()
    51  
    52  	filter := opts.filter.Value()
    53  	filter.Add("label", labelNamespace+"="+opts.namespace)
    54  
    55  	services, err := client.ServiceList(ctx, types.ServiceListOptions{Filter: filter})
    56  	if err != nil {
    57  		return err
    58  	}
    59  
    60  	out := dockerCli.Out()
    61  
    62  	// if no services in this stack, print message and exit 0
    63  	if len(services) == 0 {
    64  		fmt.Fprintf(out, "Nothing found in stack: %s\n", opts.namespace)
    65  		return nil
    66  	}
    67  
    68  	if opts.quiet {
    69  		service.PrintQuiet(out, services)
    70  	} else {
    71  		taskFilter := filters.NewArgs()
    72  		for _, service := range services {
    73  			taskFilter.Add("service", service.ID)
    74  		}
    75  
    76  		tasks, err := client.TaskList(ctx, types.TaskListOptions{Filter: taskFilter})
    77  		if err != nil {
    78  			return err
    79  		}
    80  		nodes, err := client.NodeList(ctx, types.NodeListOptions{})
    81  		if err != nil {
    82  			return err
    83  		}
    84  		service.PrintNotQuiet(out, services, nodes, tasks)
    85  	}
    86  	return nil
    87  }