prune.go 1.9 KB

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