delete.go 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  1. package daemon // import "github.com/docker/docker/daemon"
  2. import (
  3. "context"
  4. "fmt"
  5. "os"
  6. "path"
  7. "strings"
  8. "time"
  9. "github.com/containerd/containerd/leases"
  10. "github.com/containerd/containerd/log"
  11. "github.com/docker/docker/api/types"
  12. containertypes "github.com/docker/docker/api/types/container"
  13. "github.com/docker/docker/container"
  14. "github.com/docker/docker/daemon/config"
  15. "github.com/docker/docker/errdefs"
  16. "github.com/docker/docker/pkg/containerfs"
  17. "github.com/opencontainers/selinux/go-selinux"
  18. "github.com/pkg/errors"
  19. )
  20. // ContainerRm removes the container id from the filesystem. An error
  21. // is returned if the container is not found, or if the remove
  22. // fails. If the remove succeeds, the container name is released, and
  23. // network links are removed.
  24. func (daemon *Daemon) ContainerRm(name string, config *types.ContainerRmConfig) error {
  25. return daemon.containerRm(&daemon.config().Config, name, config)
  26. }
  27. func (daemon *Daemon) containerRm(cfg *config.Config, name string, opts *types.ContainerRmConfig) error {
  28. start := time.Now()
  29. ctr, err := daemon.GetContainer(name)
  30. if err != nil {
  31. return err
  32. }
  33. // Container state RemovalInProgress should be used to avoid races.
  34. if inProgress := ctr.SetRemovalInProgress(); inProgress {
  35. err := fmt.Errorf("removal of container %s is already in progress", name)
  36. return errdefs.Conflict(err)
  37. }
  38. defer ctr.ResetRemovalInProgress()
  39. // check if container wasn't deregistered by previous rm since Get
  40. if c := daemon.containers.Get(ctr.ID); c == nil {
  41. return nil
  42. }
  43. if opts.RemoveLink {
  44. return daemon.rmLink(cfg, ctr, name)
  45. }
  46. err = daemon.cleanupContainer(ctr, *opts)
  47. containerActions.WithValues("delete").UpdateSince(start)
  48. return err
  49. }
  50. func (daemon *Daemon) rmLink(cfg *config.Config, container *container.Container, name string) error {
  51. if name[0] != '/' {
  52. name = "/" + name
  53. }
  54. parent, n := path.Split(name)
  55. if parent == "/" {
  56. return fmt.Errorf("Conflict, cannot remove the default link name of the container")
  57. }
  58. parent = strings.TrimSuffix(parent, "/")
  59. pe, err := daemon.containersReplica.Snapshot().GetID(parent)
  60. if err != nil {
  61. return fmt.Errorf("Cannot get parent %s for link name %s", parent, name)
  62. }
  63. daemon.releaseName(name)
  64. parentContainer, _ := daemon.GetContainer(pe)
  65. if parentContainer != nil {
  66. daemon.linkIndex.unlink(name, container, parentContainer)
  67. if err := daemon.updateNetwork(cfg, parentContainer); err != nil {
  68. log.G(context.TODO()).Debugf("Could not update network to remove link %s: %v", n, err)
  69. }
  70. }
  71. return nil
  72. }
  73. // cleanupContainer unregisters a container from the daemon, stops stats
  74. // collection and cleanly removes contents and metadata from the filesystem.
  75. func (daemon *Daemon) cleanupContainer(container *container.Container, config types.ContainerRmConfig) error {
  76. if container.IsRunning() {
  77. if !config.ForceRemove {
  78. state := container.StateString()
  79. procedure := "Stop the container before attempting removal or force remove"
  80. if state == "paused" {
  81. procedure = "Unpause and then " + strings.ToLower(procedure)
  82. }
  83. err := fmt.Errorf("You cannot remove a %s container %s. %s", state, container.ID, procedure)
  84. return errdefs.Conflict(err)
  85. }
  86. if err := daemon.Kill(container); err != nil {
  87. return fmt.Errorf("Could not kill running container %s, cannot remove - %v", container.ID, err)
  88. }
  89. }
  90. // stop collection of stats for the container regardless
  91. // if stats are currently getting collected.
  92. daemon.statsCollector.StopCollection(container)
  93. // stopTimeout is the number of seconds to wait for the container to stop
  94. // gracefully before forcibly killing it.
  95. //
  96. // Why 3 seconds? The timeout specified here was originally added in commit
  97. // 1615bb08c7c3fc6c4b22db0a633edda516f97cf0, which added a custom timeout to
  98. // some commands, but lacking an option for a timeout on "docker rm", was
  99. // hardcoded to 10 seconds. Commit 28fd289b448164b77affd8103c0d96fd8110daf9
  100. // later on updated this to 3 seconds (but no background on that change).
  101. //
  102. // If you arrived here and know the answer, you earned yourself a picture
  103. // of a cute animal of your own choosing.
  104. stopTimeout := 3
  105. if err := daemon.containerStop(context.TODO(), container, containertypes.StopOptions{Timeout: &stopTimeout}); err != nil {
  106. return err
  107. }
  108. // Mark container dead. We don't want anybody to be restarting it.
  109. container.Lock()
  110. container.Dead = true
  111. // Save container state to disk. So that if error happens before
  112. // container meta file got removed from disk, then a restart of
  113. // docker should not make a dead container alive.
  114. if err := container.CheckpointTo(daemon.containersReplica); err != nil && !os.IsNotExist(err) {
  115. log.G(context.TODO()).Errorf("Error saving dying container to disk: %v", err)
  116. }
  117. container.Unlock()
  118. // When container creation fails and `RWLayer` has not been created yet, we
  119. // do not call `ReleaseRWLayer`
  120. if container.RWLayer != nil {
  121. if err := daemon.imageService.ReleaseLayer(container.RWLayer); err != nil {
  122. err = errors.Wrapf(err, "container %s", container.ID)
  123. container.SetRemovalError(err)
  124. return err
  125. }
  126. container.RWLayer = nil
  127. } else {
  128. if daemon.UsesSnapshotter() {
  129. ls := daemon.containerdClient.LeasesService()
  130. lease := leases.Lease{
  131. ID: container.ID,
  132. }
  133. if err := ls.Delete(context.Background(), lease, leases.SynchronousDelete); err != nil {
  134. container.SetRemovalError(err)
  135. return err
  136. }
  137. }
  138. }
  139. // Hold the container lock while deleting the container root directory
  140. // so that other goroutines don't attempt to concurrently open files
  141. // within it. Having any file open on Windows (without the
  142. // FILE_SHARE_DELETE flag) will block it from being deleted.
  143. container.Lock()
  144. err := containerfs.EnsureRemoveAll(container.Root)
  145. container.Unlock()
  146. if err != nil {
  147. err = errors.Wrapf(err, "unable to remove filesystem for %s", container.ID)
  148. container.SetRemovalError(err)
  149. return err
  150. }
  151. linkNames := daemon.linkIndex.delete(container)
  152. selinux.ReleaseLabel(container.ProcessLabel)
  153. daemon.containers.Delete(container.ID)
  154. daemon.containersReplica.Delete(container)
  155. if err := daemon.removeMountPoints(container, config.RemoveVolume); err != nil {
  156. log.G(context.TODO()).Error(err)
  157. }
  158. for _, name := range linkNames {
  159. daemon.releaseName(name)
  160. }
  161. container.SetRemoved()
  162. stateCtr.del(container.ID)
  163. daemon.LogContainerEvent(container, "destroy")
  164. return nil
  165. }