delete.go 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  1. package daemon // import "github.com/docker/docker/daemon"
  2. import (
  3. "context"
  4. "fmt"
  5. "os"
  6. "path"
  7. "strings"
  8. "time"
  9. cerrdefs "github.com/containerd/containerd/errdefs"
  10. "github.com/containerd/containerd/leases"
  11. "github.com/containerd/log"
  12. "github.com/docker/docker/api/types/backend"
  13. containertypes "github.com/docker/docker/api/types/container"
  14. "github.com/docker/docker/api/types/events"
  15. "github.com/docker/docker/container"
  16. "github.com/docker/docker/daemon/config"
  17. "github.com/docker/docker/errdefs"
  18. "github.com/docker/docker/pkg/containerfs"
  19. "github.com/opencontainers/selinux/go-selinux"
  20. "github.com/pkg/errors"
  21. )
  22. // ContainerRm removes the container id from the filesystem. An error
  23. // is returned if the container is not found, or if the remove
  24. // fails. If the remove succeeds, the container name is released, and
  25. // network links are removed.
  26. func (daemon *Daemon) ContainerRm(name string, config *backend.ContainerRmConfig) error {
  27. return daemon.containerRm(&daemon.config().Config, name, config)
  28. }
  29. func (daemon *Daemon) containerRm(cfg *config.Config, name string, opts *backend.ContainerRmConfig) error {
  30. start := time.Now()
  31. ctr, err := daemon.GetContainer(name)
  32. if err != nil {
  33. return err
  34. }
  35. // Container state RemovalInProgress should be used to avoid races.
  36. if inProgress := ctr.SetRemovalInProgress(); inProgress {
  37. err := fmt.Errorf("removal of container %s is already in progress", name)
  38. return errdefs.Conflict(err)
  39. }
  40. defer ctr.ResetRemovalInProgress()
  41. // check if container wasn't deregistered by previous rm since Get
  42. if c := daemon.containers.Get(ctr.ID); c == nil {
  43. return nil
  44. }
  45. if opts.RemoveLink {
  46. return daemon.rmLink(cfg, ctr, name)
  47. }
  48. err = daemon.cleanupContainer(ctr, *opts)
  49. containerActions.WithValues("delete").UpdateSince(start)
  50. return err
  51. }
  52. func (daemon *Daemon) rmLink(cfg *config.Config, container *container.Container, name string) error {
  53. if name[0] != '/' {
  54. name = "/" + name
  55. }
  56. parent, n := path.Split(name)
  57. if parent == "/" {
  58. return fmt.Errorf("Conflict, cannot remove the default link name of the container")
  59. }
  60. parent = strings.TrimSuffix(parent, "/")
  61. pe, err := daemon.containersReplica.Snapshot().GetID(parent)
  62. if err != nil {
  63. return fmt.Errorf("Cannot get parent %s for link name %s", parent, name)
  64. }
  65. daemon.releaseName(name)
  66. parentContainer, _ := daemon.GetContainer(pe)
  67. if parentContainer != nil {
  68. daemon.linkIndex.unlink(name, container, parentContainer)
  69. if err := daemon.updateNetwork(cfg, parentContainer); err != nil {
  70. log.G(context.TODO()).Debugf("Could not update network to remove link %s: %v", n, err)
  71. }
  72. }
  73. return nil
  74. }
  75. // cleanupContainer unregisters a container from the daemon, stops stats
  76. // collection and cleanly removes contents and metadata from the filesystem.
  77. func (daemon *Daemon) cleanupContainer(container *container.Container, config backend.ContainerRmConfig) error {
  78. if container.IsRunning() {
  79. if !config.ForceRemove {
  80. if state := container.StateString(); state == "paused" {
  81. return errdefs.Conflict(fmt.Errorf("cannot remove container %q: container is %s and must be unpaused first", container.Name, state))
  82. } else {
  83. return errdefs.Conflict(fmt.Errorf("cannot remove container %q: container is %s: stop the container before removing or force remove", container.Name, state))
  84. }
  85. }
  86. if err := daemon.Kill(container); err != nil && !isNotRunning(err) {
  87. return fmt.Errorf("cannot remove container %q: could not kill: %w", container.Name, 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. if !cerrdefs.IsNotFound(err) {
  135. container.SetRemovalError(err)
  136. return err
  137. }
  138. }
  139. }
  140. }
  141. // Hold the container lock while deleting the container root directory
  142. // so that other goroutines don't attempt to concurrently open files
  143. // within it. Having any file open on Windows (without the
  144. // FILE_SHARE_DELETE flag) will block it from being deleted.
  145. container.Lock()
  146. err := containerfs.EnsureRemoveAll(container.Root)
  147. container.Unlock()
  148. if err != nil {
  149. err = errors.Wrapf(err, "unable to remove filesystem for %s", container.ID)
  150. container.SetRemovalError(err)
  151. return err
  152. }
  153. linkNames := daemon.linkIndex.delete(container)
  154. selinux.ReleaseLabel(container.ProcessLabel)
  155. daemon.containers.Delete(container.ID)
  156. daemon.containersReplica.Delete(container)
  157. if err := daemon.removeMountPoints(container, config.RemoveVolume); err != nil {
  158. log.G(context.TODO()).Error(err)
  159. }
  160. for _, name := range linkNames {
  161. daemon.releaseName(name)
  162. }
  163. container.SetRemoved()
  164. stateCtr.del(container.ID)
  165. daemon.LogContainerEvent(container, events.ActionDestroy)
  166. return nil
  167. }