image_delete.go 11 KB

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