github.com/containerd/nerdctl@v1.7.7/cmd/nerdctl/network_prune.go (about) 1 /* 2 Copyright The containerd Authors. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package main 18 19 import ( 20 "fmt" 21 "strings" 22 23 "github.com/containerd/nerdctl/pkg/api/types" 24 "github.com/containerd/nerdctl/pkg/clientutil" 25 "github.com/containerd/nerdctl/pkg/cmd/network" 26 "github.com/spf13/cobra" 27 ) 28 29 var networkDriversToKeep = []string{"host", "none", DefaultNetworkDriver} 30 31 func newNetworkPruneCommand() *cobra.Command { 32 networkPruneCommand := &cobra.Command{ 33 Use: "prune [flags]", 34 Short: "Remove all unused networks", 35 Args: cobra.NoArgs, 36 RunE: networkPruneAction, 37 SilenceUsage: true, 38 SilenceErrors: true, 39 } 40 networkPruneCommand.Flags().BoolP("force", "f", false, "Do not prompt for confirmation") 41 return networkPruneCommand 42 } 43 44 func networkPruneAction(cmd *cobra.Command, _ []string) error { 45 globalOptions, err := processRootCmdFlags(cmd) 46 if err != nil { 47 return err 48 } 49 force, err := cmd.Flags().GetBool("force") 50 if err != nil { 51 return err 52 } 53 54 if !force { 55 var confirm string 56 msg := "This will remove all custom networks not used by at least one container." 57 msg += "\nAre you sure you want to continue? [y/N] " 58 59 fmt.Fprintf(cmd.OutOrStdout(), "WARNING! %s", msg) 60 fmt.Fscanf(cmd.InOrStdin(), "%s", &confirm) 61 62 if strings.ToLower(confirm) != "y" { 63 return nil 64 } 65 } 66 options := types.NetworkPruneOptions{ 67 GOptions: globalOptions, 68 NetworkDriversToKeep: networkDriversToKeep, 69 Stdout: cmd.OutOrStdout(), 70 } 71 72 client, ctx, cancel, err := clientutil.NewClient(cmd.Context(), options.GOptions.Namespace, options.GOptions.Address) 73 if err != nil { 74 return err 75 } 76 defer cancel() 77 78 return network.Prune(ctx, client, options) 79 }