image_delete.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466
  1. package containerd
  2. import (
  3. "context"
  4. "fmt"
  5. "strings"
  6. "time"
  7. cerrdefs "github.com/containerd/containerd/errdefs"
  8. "github.com/containerd/containerd/images"
  9. containerdimages "github.com/containerd/containerd/images"
  10. "github.com/containerd/log"
  11. "github.com/distribution/reference"
  12. "github.com/docker/docker/api/types/events"
  13. imagetypes "github.com/docker/docker/api/types/image"
  14. "github.com/docker/docker/container"
  15. dimages "github.com/docker/docker/daemon/images"
  16. "github.com/docker/docker/image"
  17. "github.com/docker/docker/internal/compatcontext"
  18. "github.com/docker/docker/pkg/stringid"
  19. "github.com/opencontainers/go-digest"
  20. ocispec "github.com/opencontainers/image-spec/specs-go/v1"
  21. )
  22. // ImageDelete deletes the image referenced by the given imageRef from this
  23. // daemon. The given imageRef can be an image ID, ID prefix, or a repository
  24. // reference (with an optional tag or digest, defaulting to the tag name
  25. // "latest"). There is differing behavior depending on whether the given
  26. // imageRef is a repository reference or not.
  27. //
  28. // If the given imageRef is a repository reference then that repository
  29. // reference will be removed. However, if there exists any containers which
  30. // were created using the same image reference then the repository reference
  31. // cannot be removed unless either there are other repository references to the
  32. // same image or force is true. Following removal of the repository reference,
  33. // the referenced image itself will attempt to be deleted as described below
  34. // but quietly, meaning any image delete conflicts will cause the image to not
  35. // be deleted and the conflict will not be reported.
  36. //
  37. // There may be conflicts preventing deletion of an image and these conflicts
  38. // are divided into two categories grouped by their severity:
  39. //
  40. // Hard Conflict:
  41. // - any running container using the image.
  42. //
  43. // Soft Conflict:
  44. // - any stopped container using the image.
  45. // - any repository tag or digest references to the image.
  46. //
  47. // The image cannot be removed if there are any hard conflicts and can be
  48. // removed if there are soft conflicts only if force is true.
  49. //
  50. // If prune is true, ancestor images will each attempt to be deleted quietly,
  51. // meaning any delete conflicts will cause the image to not be deleted and the
  52. // conflict will not be reported.
  53. //
  54. // TODO(thaJeztah): image delete should send prometheus counters; see https://github.com/moby/moby/issues/45268
  55. func (i *ImageService) ImageDelete(ctx context.Context, imageRef string, force, prune bool) ([]imagetypes.DeleteResponse, error) {
  56. var c conflictType
  57. if !force {
  58. c |= conflictSoft
  59. }
  60. img, all, err := i.resolveAllReferences(ctx, imageRef)
  61. if err != nil {
  62. return nil, err
  63. }
  64. var imgID image.ID
  65. if img == nil {
  66. if len(all) == 0 {
  67. parsed, _ := reference.ParseAnyReference(imageRef)
  68. return nil, dimages.ErrImageDoesNotExist{Ref: parsed}
  69. }
  70. imgID = image.ID(all[0].Target.Digest)
  71. var named reference.Named
  72. if !isImageIDPrefix(imgID.String(), imageRef) {
  73. if nn, err := reference.ParseNormalizedNamed(imageRef); err == nil {
  74. named = nn
  75. }
  76. }
  77. sameRef, err := i.getSameReferences(ctx, named, all)
  78. if err != nil {
  79. return nil, err
  80. }
  81. if len(sameRef) == 0 && named != nil {
  82. return nil, dimages.ErrImageDoesNotExist{Ref: named}
  83. }
  84. if len(sameRef) == len(all) && !force {
  85. c &= ^conflictActiveReference
  86. }
  87. if named != nil && len(sameRef) > 0 && len(sameRef) != len(all) {
  88. var records []imagetypes.DeleteResponse
  89. for _, ref := range sameRef {
  90. // TODO: Add with target
  91. err := i.images.Delete(ctx, ref.Name)
  92. if err != nil {
  93. return nil, err
  94. }
  95. if nn, err := reference.ParseNormalizedNamed(ref.Name); err == nil {
  96. familiarRef := reference.FamiliarString(nn)
  97. i.logImageEvent(ref, familiarRef, events.ActionUnTag)
  98. records = append(records, imagetypes.DeleteResponse{Untagged: familiarRef})
  99. }
  100. }
  101. return records, nil
  102. }
  103. } else {
  104. imgID = image.ID(img.Target.Digest)
  105. explicitDanglingRef := strings.HasPrefix(imageRef, imageNameDanglingPrefix) && isDanglingImage(*img)
  106. if isImageIDPrefix(imgID.String(), imageRef) || explicitDanglingRef {
  107. return i.deleteAll(ctx, imgID, all, c, prune)
  108. }
  109. parsedRef, err := reference.ParseNormalizedNamed(img.Name)
  110. if err != nil {
  111. return nil, err
  112. }
  113. sameRef, err := i.getSameReferences(ctx, parsedRef, all)
  114. if err != nil {
  115. return nil, err
  116. }
  117. if len(sameRef) != len(all) {
  118. var records []imagetypes.DeleteResponse
  119. for _, ref := range sameRef {
  120. // TODO: Add with target
  121. err := i.images.Delete(ctx, ref.Name)
  122. if err != nil {
  123. return nil, err
  124. }
  125. if nn, err := reference.ParseNormalizedNamed(ref.Name); err == nil {
  126. familiarRef := reference.FamiliarString(nn)
  127. i.logImageEvent(ref, familiarRef, events.ActionUnTag)
  128. records = append(records, imagetypes.DeleteResponse{Untagged: familiarRef})
  129. }
  130. }
  131. return records, nil
  132. } else if len(all) > 1 && !force {
  133. // Since only a single used reference, remove all active
  134. // TODO: Consider keeping the conflict and changing active
  135. // reference calculation in image checker.
  136. c &= ^conflictActiveReference
  137. }
  138. using := func(c *container.Container) bool {
  139. return c.ImageID == imgID
  140. }
  141. // TODO: Should this also check parentage here?
  142. ctr := i.containers.First(using)
  143. if ctr != nil {
  144. familiarRef := reference.FamiliarString(parsedRef)
  145. if !force {
  146. // If we removed the repository reference then
  147. // this image would remain "dangling" and since
  148. // we really want to avoid that the client must
  149. // explicitly force its removal.
  150. err := &imageDeleteConflict{
  151. reference: familiarRef,
  152. used: true,
  153. message: fmt.Sprintf("container %s is using its referenced image %s",
  154. stringid.TruncateID(ctr.ID),
  155. stringid.TruncateID(imgID.String())),
  156. }
  157. return nil, err
  158. }
  159. // Delete all images
  160. err := i.softImageDelete(ctx, *img, all)
  161. if err != nil {
  162. return nil, err
  163. }
  164. i.logImageEvent(*img, familiarRef, events.ActionUnTag)
  165. records := []imagetypes.DeleteResponse{{Untagged: familiarRef}}
  166. return records, nil
  167. }
  168. }
  169. return i.deleteAll(ctx, imgID, all, c, prune)
  170. }
  171. // deleteAll deletes the image from the daemon, and if prune is true,
  172. // also deletes dangling parents if there is no conflict in doing so.
  173. // Parent images are removed quietly, and if there is any issue/conflict
  174. // it is logged but does not halt execution/an error is not returned.
  175. func (i *ImageService) deleteAll(ctx context.Context, imgID image.ID, all []images.Image, c conflictType, prune bool) (records []imagetypes.DeleteResponse, err error) {
  176. // Workaround for: https://github.com/moby/buildkit/issues/3797
  177. possiblyDeletedConfigs := map[digest.Digest]struct{}{}
  178. if len(all) > 0 && i.content != nil {
  179. handled := map[digest.Digest]struct{}{}
  180. for _, img := range all {
  181. if _, ok := handled[img.Target.Digest]; ok {
  182. continue
  183. } else {
  184. handled[img.Target.Digest] = struct{}{}
  185. }
  186. err := i.walkPresentChildren(ctx, img.Target, func(_ context.Context, d ocispec.Descriptor) error {
  187. if images.IsConfigType(d.MediaType) {
  188. possiblyDeletedConfigs[d.Digest] = struct{}{}
  189. }
  190. return nil
  191. })
  192. if err != nil {
  193. return nil, err
  194. }
  195. }
  196. }
  197. defer func() {
  198. if len(possiblyDeletedConfigs) > 0 {
  199. if err := i.unleaseSnapshotsFromDeletedConfigs(compatcontext.WithoutCancel(ctx), possiblyDeletedConfigs); err != nil {
  200. log.G(ctx).WithError(err).Warn("failed to unlease snapshots")
  201. }
  202. }
  203. }()
  204. var parents []containerdimages.Image
  205. if prune {
  206. // TODO(dmcgowan): Consider using GC labels to walk for deletion
  207. parents, err = i.parents(ctx, imgID)
  208. if err != nil {
  209. log.G(ctx).WithError(err).Warn("failed to get image parents")
  210. }
  211. }
  212. for _, imageRef := range all {
  213. if err := i.imageDeleteHelper(ctx, imageRef, all, &records, c); err != nil {
  214. return records, err
  215. }
  216. }
  217. i.LogImageEvent(imgID.String(), imgID.String(), events.ActionDelete)
  218. records = append(records, imagetypes.DeleteResponse{Deleted: imgID.String()})
  219. for _, parent := range parents {
  220. if !isDanglingImage(parent) {
  221. break
  222. }
  223. err = i.imageDeleteHelper(ctx, parent, all, &records, conflictSoft)
  224. if err != nil {
  225. log.G(ctx).WithError(err).Warn("failed to remove image parent")
  226. break
  227. }
  228. parentID := parent.Target.Digest.String()
  229. i.LogImageEvent(parentID, parentID, events.ActionDelete)
  230. records = append(records, imagetypes.DeleteResponse{Deleted: parentID})
  231. }
  232. return records, nil
  233. }
  234. // isImageIDPrefix returns whether the given
  235. // possiblePrefix is a prefix of the given imageID.
  236. func isImageIDPrefix(imageID, possiblePrefix string) bool {
  237. if strings.HasPrefix(imageID, possiblePrefix) {
  238. return true
  239. }
  240. if i := strings.IndexRune(imageID, ':'); i >= 0 {
  241. return strings.HasPrefix(imageID[i+1:], possiblePrefix)
  242. }
  243. return false
  244. }
  245. // getSameReferences returns the set of images which are the same as:
  246. // - the provided img if non-nil
  247. // - OR the first named image found in the provided image set
  248. // - OR the full set of provided images if no named references in the set
  249. //
  250. // References are considered the same if:
  251. // - Both contain the same name and tag
  252. // - Both contain the same name, one is untagged and no other differing tags in set
  253. // - One is dangling
  254. //
  255. // Note: All imgs should have the same target, only the image name will be considered
  256. // for determining whether images are the same.
  257. func (i *ImageService) getSameReferences(ctx context.Context, named reference.Named, imgs []images.Image) ([]images.Image, error) {
  258. var (
  259. tag string
  260. sameRef []images.Image
  261. digestRefs = []images.Image{}
  262. allTags bool
  263. )
  264. if named != nil {
  265. if tagged, ok := named.(reference.Tagged); ok {
  266. tag = tagged.Tag()
  267. } else if _, ok := named.(reference.Digested); ok {
  268. // If digest is explicitly provided, match all tags
  269. allTags = true
  270. }
  271. }
  272. for _, ref := range imgs {
  273. if !isDanglingImage(ref) {
  274. if repoRef, err := reference.ParseNamed(ref.Name); err == nil {
  275. if named == nil {
  276. named = repoRef
  277. if tagged, ok := named.(reference.Tagged); ok {
  278. tag = tagged.Tag()
  279. }
  280. } else if named.Name() != repoRef.Name() {
  281. continue
  282. } else if !allTags {
  283. if tagged, ok := repoRef.(reference.Tagged); ok {
  284. if tag == "" {
  285. tag = tagged.Tag()
  286. } else if tag != tagged.Tag() {
  287. // Same repo, different tag, do not include digest refs
  288. digestRefs = nil
  289. continue
  290. }
  291. } else {
  292. if digestRefs != nil {
  293. digestRefs = append(digestRefs, ref)
  294. }
  295. // Add digest refs at end if no other tags in the same name
  296. continue
  297. }
  298. }
  299. } else {
  300. // Ignore names which do not parse
  301. log.G(ctx).WithError(err).WithField("image", ref.Name).Info("failed to parse image name, ignoring")
  302. }
  303. }
  304. sameRef = append(sameRef, ref)
  305. }
  306. if digestRefs != nil {
  307. sameRef = append(sameRef, digestRefs...)
  308. }
  309. return sameRef, nil
  310. }
  311. type conflictType int
  312. const (
  313. conflictRunningContainer conflictType = 1 << iota
  314. conflictActiveReference
  315. conflictStoppedContainer
  316. conflictHard = conflictRunningContainer
  317. conflictSoft = conflictActiveReference | conflictStoppedContainer
  318. )
  319. // imageDeleteHelper attempts to delete the given image from this daemon.
  320. // If the image has any hard delete conflicts (running containers using
  321. // the image) then it cannot be deleted. If the image has any soft delete
  322. // conflicts (any tags/digests referencing the image or any stopped container
  323. // using the image) then it can only be deleted if force is true. Any deleted
  324. // images and untagged references are appended to the given records. If any
  325. // error or conflict is encountered, it will be returned immediately without
  326. // deleting the image.
  327. func (i *ImageService) imageDeleteHelper(ctx context.Context, img images.Image, all []images.Image, records *[]imagetypes.DeleteResponse, extra conflictType) error {
  328. // First, determine if this image has any conflicts. Ignore soft conflicts
  329. // if force is true.
  330. c := conflictHard | extra
  331. imgID := image.ID(img.Target.Digest)
  332. err := i.checkImageDeleteConflict(ctx, imgID, all, c)
  333. if err != nil {
  334. return err
  335. }
  336. untaggedRef, err := reference.ParseAnyReference(img.Name)
  337. if err != nil {
  338. return err
  339. }
  340. if !isDanglingImage(img) && len(all) == 1 && extra&conflictActiveReference != 0 {
  341. children, err := i.Children(ctx, imgID)
  342. if err != nil {
  343. return err
  344. }
  345. if len(children) > 0 {
  346. img := images.Image{
  347. Name: danglingImageName(img.Target.Digest),
  348. Target: img.Target,
  349. CreatedAt: time.Now(),
  350. Labels: img.Labels,
  351. }
  352. if _, err = i.images.Create(ctx, img); err != nil && !cerrdefs.IsAlreadyExists(err) {
  353. return fmt.Errorf("failed to create dangling image: %w", err)
  354. }
  355. }
  356. }
  357. // TODO: Add target option
  358. err = i.images.Delete(ctx, img.Name, images.SynchronousDelete())
  359. if err != nil {
  360. return err
  361. }
  362. if !isDanglingImage(img) {
  363. i.logImageEvent(img, reference.FamiliarString(untaggedRef), events.ActionUnTag)
  364. *records = append(*records, imagetypes.DeleteResponse{Untagged: reference.FamiliarString(untaggedRef)})
  365. }
  366. return nil
  367. }
  368. // ImageDeleteConflict holds a soft or hard conflict and associated
  369. // error. A hard conflict represents a running container using the
  370. // image, while a soft conflict is any tags/digests referencing the
  371. // given image or any stopped container using the image.
  372. // Implements the error interface.
  373. type imageDeleteConflict struct {
  374. hard bool
  375. used bool
  376. reference string
  377. message string
  378. }
  379. func (idc *imageDeleteConflict) Error() string {
  380. var forceMsg string
  381. if idc.hard {
  382. forceMsg = "cannot be forced"
  383. } else {
  384. forceMsg = "must be forced"
  385. }
  386. return fmt.Sprintf("conflict: unable to delete %s (%s) - %s", idc.reference, forceMsg, idc.message)
  387. }
  388. func (imageDeleteConflict) Conflict() {}
  389. // checkImageDeleteConflict returns a conflict representing
  390. // any issue preventing deletion of the given image ID, and
  391. // nil if there are none. It takes a bitmask representing a
  392. // filter for which conflict types the caller cares about,
  393. // and will only check for these conflict types.
  394. func (i *ImageService) checkImageDeleteConflict(ctx context.Context, imgID image.ID, all []images.Image, mask conflictType) error {
  395. if mask&conflictRunningContainer != 0 {
  396. running := func(c *container.Container) bool {
  397. return c.ImageID == imgID && c.IsRunning()
  398. }
  399. if ctr := i.containers.First(running); ctr != nil {
  400. return &imageDeleteConflict{
  401. reference: stringid.TruncateID(imgID.String()),
  402. hard: true,
  403. used: true,
  404. message: fmt.Sprintf("image is being used by running container %s", stringid.TruncateID(ctr.ID)),
  405. }
  406. }
  407. }
  408. if mask&conflictStoppedContainer != 0 {
  409. stopped := func(c *container.Container) bool {
  410. return !c.IsRunning() && c.ImageID == imgID
  411. }
  412. if ctr := i.containers.First(stopped); ctr != nil {
  413. return &imageDeleteConflict{
  414. reference: stringid.TruncateID(imgID.String()),
  415. used: true,
  416. message: fmt.Sprintf("image is being used by stopped container %s", stringid.TruncateID(ctr.ID)),
  417. }
  418. }
  419. }
  420. if mask&conflictActiveReference != 0 {
  421. // TODO: Count unexpired references...
  422. if len(all) > 1 {
  423. return &imageDeleteConflict{
  424. reference: stringid.TruncateID(imgID.String()),
  425. message: "image is referenced in multiple repositories",
  426. }
  427. }
  428. }
  429. return nil
  430. }