github.com/kunnos/engine@v1.13.1/cli/command/stack/services.go (about)

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