delete.go 6.0 KB

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