github.com/portworx/docker@v1.12.1/api/client/stack/remove.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/cli"
    12  	"github.com/spf13/cobra"
    13  )
    14  
    15  type removeOptions struct {
    16  	namespace string
    17  }
    18  
    19  func newRemoveCommand(dockerCli *client.DockerCli) *cobra.Command {
    20  	var opts removeOptions
    21  
    22  	cmd := &cobra.Command{
    23  		Use:     "rm STACK",
    24  		Aliases: []string{"remove", "down"},
    25  		Short:   "Remove the stack",
    26  		Args:    cli.ExactArgs(1),
    27  		RunE: func(cmd *cobra.Command, args []string) error {
    28  			opts.namespace = args[0]
    29  			return runRemove(dockerCli, opts)
    30  		},
    31  	}
    32  	return cmd
    33  }
    34  
    35  func runRemove(dockerCli *client.DockerCli, opts removeOptions) error {
    36  	namespace := opts.namespace
    37  	client := dockerCli.Client()
    38  	stderr := dockerCli.Err()
    39  	ctx := context.Background()
    40  	hasError := false
    41  
    42  	services, err := getServices(ctx, client, namespace)
    43  	if err != nil {
    44  		return err
    45  	}
    46  	for _, service := range services {
    47  		fmt.Fprintf(stderr, "Removing service %s\n", service.Spec.Name)
    48  		if err := client.ServiceRemove(ctx, service.ID); err != nil {
    49  			hasError = true
    50  			fmt.Fprintf(stderr, "Failed to remove service %s: %s", service.ID, err)
    51  		}
    52  	}
    53  
    54  	networks, err := getNetworks(ctx, client, namespace)
    55  	if err != nil {
    56  		return err
    57  	}
    58  	for _, network := range networks {
    59  		fmt.Fprintf(stderr, "Removing network %s\n", network.Name)
    60  		if err := client.NetworkRemove(ctx, network.ID); err != nil {
    61  			hasError = true
    62  			fmt.Fprintf(stderr, "Failed to remove network %s: %s", network.ID, err)
    63  		}
    64  	}
    65  
    66  	if len(services) == 0 && len(networks) == 0 {
    67  		fmt.Fprintf(dockerCli.Out(), "Nothing found in stack: %s\n", namespace)
    68  		return nil
    69  	}
    70  
    71  	if hasError {
    72  		return fmt.Errorf("Failed to remove some resources")
    73  	}
    74  	return nil
    75  }