|
| 1 | +package network |
| 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/cli" |
| 10 | + "github.com/docker/docker/cli/command" |
| 11 | + "github.com/spf13/cobra" |
| 12 | +) |
| 13 | + |
| 14 | +type pruneOptions struct { |
| 15 | + force bool |
| 16 | +} |
| 17 | + |
| 18 | +// NewPruneCommand returns a new cobra prune command for networks |
| 19 | +func NewPruneCommand(dockerCli *command.DockerCli) *cobra.Command { |
| 20 | + var opts pruneOptions |
| 21 | + |
| 22 | + cmd := &cobra.Command{ |
| 23 | + Use: "prune [OPTIONS]", |
| 24 | + Short: "Remove all unused networks", |
| 25 | + Args: cli.NoArgs, |
| 26 | + RunE: func(cmd *cobra.Command, args []string) error { |
| 27 | + output, err := runPrune(dockerCli, opts) |
| 28 | + if err != nil { |
| 29 | + return err |
| 30 | + } |
| 31 | + if output != "" { |
| 32 | + fmt.Fprintln(dockerCli.Out(), output) |
| 33 | + } |
| 34 | + return nil |
| 35 | + }, |
| 36 | + } |
| 37 | + |
| 38 | + flags := cmd.Flags() |
| 39 | + flags.BoolVarP(&opts.force, "force", "f", false, "Do not prompt for confirmation") |
| 40 | + |
| 41 | + return cmd |
| 42 | +} |
| 43 | + |
| 44 | +const warning = `WARNING! This will remove all networks not used by at least one container. |
| 45 | +Are you sure you want to continue?` |
| 46 | + |
| 47 | +func runPrune(dockerCli *command.DockerCli, opts pruneOptions) (output string, err error) { |
| 48 | + if !opts.force && !command.PromptForConfirmation(dockerCli.In(), dockerCli.Out(), warning) { |
| 49 | + return |
| 50 | + } |
| 51 | + |
| 52 | + report, err := dockerCli.Client().NetworksPrune(context.Background(), types.NetworksPruneConfig{}) |
| 53 | + if err != nil { |
| 54 | + return |
| 55 | + } |
| 56 | + |
| 57 | + if len(report.NetworksDeleted) > 0 { |
| 58 | + output = "Deleted Networks:\n" |
| 59 | + for _, id := range report.NetworksDeleted { |
| 60 | + output += id + "\n" |
| 61 | + } |
| 62 | + } |
| 63 | + |
| 64 | + return |
| 65 | +} |
| 66 | + |
| 67 | +// RunPrune calls the Network Prune API |
| 68 | +// This returns the amount of space reclaimed and a detailed output string |
| 69 | +func RunPrune(dockerCli *command.DockerCli) (uint64, string, error) { |
| 70 | + output, err := runPrune(dockerCli, pruneOptions{force: true}) |
| 71 | + return 0, output, err |
| 72 | +} |
0 commit comments