image_delete.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  1. package containerd
  2. import (
  3. "context"
  4. "fmt"
  5. "sort"
  6. "strings"
  7. "github.com/containerd/containerd/images"
  8. "github.com/containerd/log"
  9. "github.com/distribution/reference"
  10. "github.com/docker/docker/api/types/events"
  11. imagetypes "github.com/docker/docker/api/types/image"
  12. "github.com/docker/docker/container"
  13. "github.com/docker/docker/image"
  14. "github.com/docker/docker/internal/compatcontext"
  15. "github.com/docker/docker/pkg/stringid"
  16. "github.com/opencontainers/go-digest"
  17. ocispec "github.com/opencontainers/image-spec/specs-go/v1"
  18. )
  19. // ImageDelete deletes the image referenced by the given imageRef from this
  20. // daemon. The given imageRef can be an image ID, ID prefix, or a repository
  21. // reference (with an optional tag or digest, defaulting to the tag name
  22. // "latest"). There is differing behavior depending on whether the given
  23. // imageRef is a repository reference or not.
  24. //
  25. // If the given imageRef is a repository reference then that repository
  26. // reference will be removed. However, if there exists any containers which
  27. // were created using the same image reference then the repository reference
  28. // cannot be removed unless either there are other repository references to the
  29. // same image or force is true. Following removal of the repository reference,
  30. // the referenced image itself will attempt to be deleted as described below
  31. // but quietly, meaning any image delete conflicts will cause the image to not
  32. // be deleted and the conflict will not be reported.
  33. //
  34. // There may be conflicts preventing deletion of an image and these conflicts
  35. // are divided into two categories grouped by their severity:
  36. //
  37. // Hard Conflict:
  38. // - any running container using the image.
  39. //
  40. // Soft Conflict:
  41. // - any stopped container using the image.
  42. // - any repository tag or digest references to the image.
  43. //
  44. // The image cannot be removed if there are any hard conflicts and can be
  45. // removed if there are soft conflicts only if force is true.
  46. //
  47. // If prune is true, ancestor images will each attempt to be deleted quietly,
  48. // meaning any delete conflicts will cause the image to not be deleted and the
  49. // conflict will not be reported.
  50. //
  51. // TODO(thaJeztah): image delete should send prometheus counters; see https://github.com/moby/moby/issues/45268
  52. func (i *ImageService) ImageDelete(ctx context.Context, imageRef string, force, prune bool) ([]imagetypes.DeleteResponse, error) {
  53. parsedRef, err := reference.ParseNormalizedNamed(imageRef)
  54. if err != nil {
  55. return nil, err
  56. }
  57. img, err := i.resolveImage(ctx, imageRef)
  58. if err != nil {
  59. return nil, err
  60. }
  61. imgID := image.ID(img.Target.Digest)
  62. explicitDanglingRef := strings.HasPrefix(imageRef, imageNameDanglingPrefix) && isDanglingImage(img)
  63. if isImageIDPrefix(imgID.String(), imageRef) || explicitDanglingRef {
  64. return i.deleteAll(ctx, img, force, prune)
  65. }
  66. singleRef, err := i.isSingleReference(ctx, img)
  67. if err != nil {
  68. return nil, err
  69. }
  70. if !singleRef {
  71. err := i.client.ImageService().Delete(ctx, img.Name)
  72. if err != nil {
  73. return nil, err
  74. }
  75. i.LogImageEvent(imgID.String(), imgID.String(), events.ActionUnTag)
  76. records := []imagetypes.DeleteResponse{{Untagged: reference.FamiliarString(reference.TagNameOnly(parsedRef))}}
  77. return records, nil
  78. }
  79. using := func(c *container.Container) bool {
  80. return c.ImageID == imgID
  81. }
  82. ctr := i.containers.First(using)
  83. if ctr != nil {
  84. if !force {
  85. // If we removed the repository reference then
  86. // this image would remain "dangling" and since
  87. // we really want to avoid that the client must
  88. // explicitly force its removal.
  89. refString := reference.FamiliarString(reference.TagNameOnly(parsedRef))
  90. err := &imageDeleteConflict{
  91. reference: refString,
  92. used: true,
  93. message: fmt.Sprintf("container %s is using its referenced image %s",
  94. stringid.TruncateID(ctr.ID),
  95. stringid.TruncateID(imgID.String())),
  96. }
  97. return nil, err
  98. }
  99. err := i.softImageDelete(ctx, img)
  100. if err != nil {
  101. return nil, err
  102. }
  103. i.LogImageEvent(imgID.String(), imgID.String(), events.ActionUnTag)
  104. records := []imagetypes.DeleteResponse{{Untagged: reference.FamiliarString(reference.TagNameOnly(parsedRef))}}
  105. return records, nil
  106. }
  107. return i.deleteAll(ctx, img, force, prune)
  108. }
  109. // deleteAll deletes the image from the daemon, and if prune is true,
  110. // also deletes dangling parents if there is no conflict in doing so.
  111. // Parent images are removed quietly, and if there is any issue/conflict
  112. // it is logged but does not halt execution/an error is not returned.
  113. func (i *ImageService) deleteAll(ctx context.Context, img images.Image, force, prune bool) ([]imagetypes.DeleteResponse, error) {
  114. var records []imagetypes.DeleteResponse
  115. // Workaround for: https://github.com/moby/buildkit/issues/3797
  116. possiblyDeletedConfigs := map[digest.Digest]struct{}{}
  117. err := i.walkPresentChildren(ctx, img.Target, func(_ context.Context, d ocispec.Descriptor) error {
  118. if images.IsConfigType(d.MediaType) {
  119. possiblyDeletedConfigs[d.Digest] = struct{}{}
  120. }
  121. return nil
  122. })
  123. if err != nil {
  124. return nil, err
  125. }
  126. defer func() {
  127. if err := i.unleaseSnapshotsFromDeletedConfigs(compatcontext.WithoutCancel(ctx), possiblyDeletedConfigs); err != nil {
  128. log.G(ctx).WithError(err).Warn("failed to unlease snapshots")
  129. }
  130. }()
  131. imgID := img.Target.Digest.String()
  132. var parents []imageWithRootfs
  133. if prune {
  134. parents, err = i.parents(ctx, image.ID(imgID))
  135. if err != nil {
  136. log.G(ctx).WithError(err).Warn("failed to get image parents")
  137. }
  138. sortParentsByAffinity(parents)
  139. }
  140. imageRefs, err := i.client.ImageService().List(ctx, "target.digest=="+imgID)
  141. if err != nil {
  142. return nil, err
  143. }
  144. for _, imageRef := range imageRefs {
  145. if err := i.imageDeleteHelper(ctx, imageRef, &records, force); err != nil {
  146. return records, err
  147. }
  148. }
  149. i.LogImageEvent(imgID, imgID, events.ActionDelete)
  150. records = append(records, imagetypes.DeleteResponse{Deleted: imgID})
  151. for _, parent := range parents {
  152. if !isDanglingImage(parent.img) {
  153. break
  154. }
  155. err = i.imageDeleteHelper(ctx, parent.img, &records, false)
  156. if err != nil {
  157. log.G(ctx).WithError(err).Warn("failed to remove image parent")
  158. break
  159. }
  160. parentID := parent.img.Target.Digest.String()
  161. i.LogImageEvent(parentID, parentID, events.ActionDelete)
  162. records = append(records, imagetypes.DeleteResponse{Deleted: parentID})
  163. }
  164. return records, nil
  165. }
  166. // isImageIDPrefix returns whether the given
  167. // possiblePrefix is a prefix of the given imageID.
  168. func isImageIDPrefix(imageID, possiblePrefix string) bool {
  169. if strings.HasPrefix(imageID, possiblePrefix) {
  170. return true
  171. }
  172. if i := strings.IndexRune(imageID, ':'); i >= 0 {
  173. return strings.HasPrefix(imageID[i+1:], possiblePrefix)
  174. }
  175. return false
  176. }
  177. func sortParentsByAffinity(parents []imageWithRootfs) {
  178. sort.Slice(parents, func(i, j int) bool {
  179. lenRootfsI := len(parents[i].rootfs.DiffIDs)
  180. lenRootfsJ := len(parents[j].rootfs.DiffIDs)
  181. if lenRootfsI == lenRootfsJ {
  182. return isDanglingImage(parents[i].img)
  183. }
  184. return lenRootfsI > lenRootfsJ
  185. })
  186. }
  187. // isSingleReference returns true if there are no other images in the
  188. // daemon targeting the same content as `img` that are not dangling.
  189. func (i *ImageService) isSingleReference(ctx context.Context, img images.Image) (bool, error) {
  190. refs, err := i.client.ImageService().List(ctx, "target.digest=="+img.Target.Digest.String())
  191. if err != nil {
  192. return false, err
  193. }
  194. for _, ref := range refs {
  195. if !isDanglingImage(ref) && ref.Name != img.Name {
  196. return false, nil
  197. }
  198. }
  199. return true, nil
  200. }
  201. type conflictType int
  202. const (
  203. conflictRunningContainer conflictType = 1 << iota
  204. conflictActiveReference
  205. conflictStoppedContainer
  206. conflictHard = conflictRunningContainer
  207. conflictSoft = conflictActiveReference | conflictStoppedContainer
  208. )
  209. // imageDeleteHelper attempts to delete the given image from this daemon.
  210. // If the image has any hard delete conflicts (running containers using
  211. // the image) then it cannot be deleted. If the image has any soft delete
  212. // conflicts (any tags/digests referencing the image or any stopped container
  213. // using the image) then it can only be deleted if force is true. Any deleted
  214. // images and untagged references are appended to the given records. If any
  215. // error or conflict is encountered, it will be returned immediately without
  216. // deleting the image.
  217. func (i *ImageService) imageDeleteHelper(ctx context.Context, img images.Image, records *[]imagetypes.DeleteResponse, force bool) error {
  218. // First, determine if this image has any conflicts. Ignore soft conflicts
  219. // if force is true.
  220. c := conflictHard
  221. if !force {
  222. c |= conflictSoft
  223. }
  224. imgID := image.ID(img.Target.Digest)
  225. err := i.checkImageDeleteConflict(ctx, imgID, c)
  226. if err != nil {
  227. return err
  228. }
  229. untaggedRef, err := reference.ParseAnyReference(img.Name)
  230. if err != nil {
  231. return err
  232. }
  233. err = i.client.ImageService().Delete(ctx, img.Name, images.SynchronousDelete())
  234. if err != nil {
  235. return err
  236. }
  237. if !isDanglingImage(img) {
  238. i.LogImageEvent(imgID.String(), imgID.String(), events.ActionUnTag)
  239. *records = append(*records, imagetypes.DeleteResponse{Untagged: reference.FamiliarString(untaggedRef)})
  240. }
  241. return nil
  242. }
  243. // ImageDeleteConflict holds a soft or hard conflict and associated
  244. // error. A hard conflict represents a running container using the
  245. // image, while a soft conflict is any tags/digests referencing the
  246. // given image or any stopped container using the image.
  247. // Implements the error interface.
  248. type imageDeleteConflict struct {
  249. hard bool
  250. used bool
  251. reference string
  252. message string
  253. }
  254. func (idc *imageDeleteConflict) Error() string {
  255. var forceMsg string
  256. if idc.hard {
  257. forceMsg = "cannot be forced"
  258. } else {
  259. forceMsg = "must be forced"
  260. }
  261. return fmt.Sprintf("conflict: unable to delete %s (%s) - %s", idc.reference, forceMsg, idc.message)
  262. }
  263. func (imageDeleteConflict) Conflict() {}
  264. // checkImageDeleteConflict returns a conflict representing
  265. // any issue preventing deletion of the given image ID, and
  266. // nil if there are none. It takes a bitmask representing a
  267. // filter for which conflict types the caller cares about,
  268. // and will only check for these conflict types.
  269. func (i *ImageService) checkImageDeleteConflict(ctx context.Context, imgID image.ID, mask conflictType) error {
  270. if mask&conflictRunningContainer != 0 {
  271. running := func(c *container.Container) bool {
  272. return c.ImageID == imgID && c.IsRunning()
  273. }
  274. if ctr := i.containers.First(running); ctr != nil {
  275. return &imageDeleteConflict{
  276. reference: stringid.TruncateID(imgID.String()),
  277. hard: true,
  278. used: true,
  279. message: fmt.Sprintf("image is being used by running container %s", stringid.TruncateID(ctr.ID)),
  280. }
  281. }
  282. }
  283. if mask&conflictStoppedContainer != 0 {
  284. stopped := func(c *container.Container) bool {
  285. return !c.IsRunning() && c.ImageID == imgID
  286. }
  287. if ctr := i.containers.First(stopped); ctr != nil {
  288. return &imageDeleteConflict{
  289. reference: stringid.TruncateID(imgID.String()),
  290. used: true,
  291. message: fmt.Sprintf("image is being used by stopped container %s", stringid.TruncateID(ctr.ID)),
  292. }
  293. }
  294. }
  295. if mask&conflictActiveReference != 0 {
  296. refs, err := i.client.ImageService().List(ctx, "target.digest=="+imgID.String())
  297. if err != nil {
  298. return err
  299. }
  300. if len(refs) > 1 {
  301. return &imageDeleteConflict{
  302. reference: stringid.TruncateID(imgID.String()),
  303. message: "image is referenced in multiple repositories",
  304. }
  305. }
  306. }
  307. return nil
  308. }