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