rm.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. package container
  2. import (
  3. "errors"
  4. "fmt"
  5. "strings"
  6. "github.com/docker/docker/api/types"
  7. "github.com/docker/docker/cli"
  8. "github.com/docker/docker/cli/command"
  9. "github.com/spf13/cobra"
  10. "golang.org/x/net/context"
  11. )
  12. type rmOptions struct {
  13. rmVolumes bool
  14. rmLink bool
  15. force bool
  16. containers []string
  17. }
  18. // NewRmCommand creates a new cobra.Command for `docker rm`
  19. func NewRmCommand(dockerCli *command.DockerCli) *cobra.Command {
  20. var opts rmOptions
  21. cmd := &cobra.Command{
  22. Use: "rm [OPTIONS] CONTAINER [CONTAINER...]",
  23. Short: "Remove one or more containers",
  24. Args: cli.RequiresMinArgs(1),
  25. RunE: func(cmd *cobra.Command, args []string) error {
  26. opts.containers = args
  27. return runRm(dockerCli, &opts)
  28. },
  29. }
  30. flags := cmd.Flags()
  31. flags.BoolVarP(&opts.rmVolumes, "volumes", "v", false, "Remove the volumes associated with the container")
  32. flags.BoolVarP(&opts.rmLink, "link", "l", false, "Remove the specified link")
  33. flags.BoolVarP(&opts.force, "force", "f", false, "Force the removal of a running container (uses SIGKILL)")
  34. return cmd
  35. }
  36. func runRm(dockerCli *command.DockerCli, opts *rmOptions) error {
  37. ctx := context.Background()
  38. var errs []string
  39. options := types.ContainerRemoveOptions{
  40. RemoveVolumes: opts.rmVolumes,
  41. RemoveLinks: opts.rmLink,
  42. Force: opts.force,
  43. }
  44. errChan := parallelOperation(ctx, opts.containers, func(ctx context.Context, container string) error {
  45. container = strings.Trim(container, "/")
  46. if container == "" {
  47. return errors.New("Container name cannot be empty")
  48. }
  49. return dockerCli.Client().ContainerRemove(ctx, container, options)
  50. })
  51. for _, name := range opts.containers {
  52. if err := <-errChan; err != nil {
  53. errs = append(errs, err.Error())
  54. continue
  55. }
  56. fmt.Fprintln(dockerCli.Out(), name)
  57. }
  58. if len(errs) > 0 {
  59. return errors.New(strings.Join(errs, "\n"))
  60. }
  61. return nil
  62. }