prune.go 2.0 KB

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