rm.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. package container
  2. import (
  3. "fmt"
  4. "strings"
  5. "golang.org/x/net/context"
  6. "github.com/docker/docker/api/client"
  7. "github.com/docker/docker/cli"
  8. "github.com/docker/engine-api/types"
  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 *client.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 *client.DockerCli, opts *rmOptions) error {
  36. ctx := context.Background()
  37. var errs []string
  38. for _, name := range opts.containers {
  39. if name == "" {
  40. return fmt.Errorf("Container name cannot be empty")
  41. }
  42. name = strings.Trim(name, "/")
  43. if err := removeContainer(dockerCli, ctx, name, opts.rmVolumes, opts.rmLink, opts.force); err != nil {
  44. errs = append(errs, err.Error())
  45. } else {
  46. fmt.Fprintf(dockerCli.Out(), "%s\n", name)
  47. }
  48. }
  49. if len(errs) > 0 {
  50. return fmt.Errorf("%s", strings.Join(errs, "\n"))
  51. }
  52. return nil
  53. }
  54. func removeContainer(dockerCli *client.DockerCli, ctx context.Context, container string, removeVolumes, removeLinks, force bool) error {
  55. options := types.ContainerRemoveOptions{
  56. RemoveVolumes: removeVolumes,
  57. RemoveLinks: removeLinks,
  58. Force: force,
  59. }
  60. if err := dockerCli.Client().ContainerRemove(ctx, container, options); err != nil {
  61. return err
  62. }
  63. return nil
  64. }