rm.go 1.8 KB

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