prune.go 2.1 KB

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