prune.go 1.8 KB

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