image_delete.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  1. package images // import "github.com/docker/docker/daemon/images"
  2. import (
  3. "context"
  4. "fmt"
  5. "strings"
  6. "time"
  7. "github.com/distribution/reference"
  8. "github.com/docker/docker/api/types/events"
  9. imagetypes "github.com/docker/docker/api/types/image"
  10. "github.com/docker/docker/container"
  11. "github.com/docker/docker/errdefs"
  12. "github.com/docker/docker/image"
  13. "github.com/docker/docker/pkg/stringid"
  14. "github.com/pkg/errors"
  15. )
  16. type conflictType int
  17. const (
  18. conflictDependentChild conflictType = 1 << iota
  19. conflictRunningContainer
  20. conflictActiveReference
  21. conflictStoppedContainer
  22. conflictHard = conflictDependentChild | conflictRunningContainer
  23. conflictSoft = conflictActiveReference | conflictStoppedContainer
  24. )
  25. // ImageDelete deletes the image referenced by the given imageRef from this
  26. // daemon. The given imageRef can be an image ID, ID prefix, or a repository
  27. // reference (with an optional tag or digest, defaulting to the tag name
  28. // "latest"). There is differing behavior depending on whether the given
  29. // imageRef is a repository reference or not.
  30. //
  31. // If the given imageRef is a repository reference then that repository
  32. // reference will be removed. However, if there exists any containers which
  33. // were created using the same image reference then the repository reference
  34. // cannot be removed unless either there are other repository references to the
  35. // same image or force is true. Following removal of the repository reference,
  36. // the referenced image itself will attempt to be deleted as described below
  37. // but quietly, meaning any image delete conflicts will cause the image to not
  38. // be deleted and the conflict will not be reported.
  39. //
  40. // There may be conflicts preventing deletion of an image and these conflicts
  41. // are divided into two categories grouped by their severity:
  42. //
  43. // Hard Conflict:
  44. // - a pull or build using the image.
  45. // - any descendant image.
  46. // - any running container using the image.
  47. //
  48. // Soft Conflict:
  49. // - any stopped container using the image.
  50. // - any repository tag or digest references to the image.
  51. //
  52. // The image cannot be removed if there are any hard conflicts and can be
  53. // removed if there are soft conflicts only if force is true.
  54. //
  55. // If prune is true, ancestor images will each attempt to be deleted quietly,
  56. // meaning any delete conflicts will cause the image to not be deleted and the
  57. // conflict will not be reported.
  58. func (i *ImageService) ImageDelete(ctx context.Context, imageRef string, force, prune bool) ([]imagetypes.DeleteResponse, error) {
  59. start := time.Now()
  60. records := []imagetypes.DeleteResponse{}
  61. img, err := i.GetImage(ctx, imageRef, imagetypes.GetImageOpts{})
  62. if err != nil {
  63. return nil, err
  64. }
  65. imgID := img.ID()
  66. repoRefs := i.referenceStore.References(imgID.Digest())
  67. using := func(c *container.Container) bool {
  68. return c.ImageID == imgID
  69. }
  70. var removedRepositoryRef bool
  71. if !isImageIDPrefix(imgID.String(), imageRef) {
  72. // A repository reference was given and should be removed
  73. // first. We can only remove this reference if either force is
  74. // true, there are multiple repository references to this
  75. // image, or there are no containers using the given reference.
  76. if !force && isSingleReference(repoRefs) {
  77. if ctr := i.containers.First(using); ctr != nil {
  78. // If we removed the repository reference then
  79. // this image would remain "dangling" and since
  80. // we really want to avoid that the client must
  81. // explicitly force its removal.
  82. err := errors.Errorf("conflict: unable to remove repository reference %q (must force) - container %s is using its referenced image %s", imageRef, stringid.TruncateID(ctr.ID), stringid.TruncateID(imgID.String()))
  83. return nil, errdefs.Conflict(err)
  84. }
  85. }
  86. parsedRef, err := reference.ParseNormalizedNamed(imageRef)
  87. if err != nil {
  88. return nil, err
  89. }
  90. parsedRef, err = i.removeImageRef(parsedRef)
  91. if err != nil {
  92. return nil, err
  93. }
  94. untaggedRecord := imagetypes.DeleteResponse{Untagged: reference.FamiliarString(parsedRef)}
  95. i.LogImageEvent(imgID.String(), imgID.String(), events.ActionUnTag)
  96. records = append(records, untaggedRecord)
  97. repoRefs = i.referenceStore.References(imgID.Digest())
  98. // If a tag reference was removed and the only remaining
  99. // references to the same repository are digest references,
  100. // then clean up those digest references.
  101. if _, isCanonical := parsedRef.(reference.Canonical); !isCanonical {
  102. foundRepoTagRef := false
  103. for _, repoRef := range repoRefs {
  104. if _, repoRefIsCanonical := repoRef.(reference.Canonical); !repoRefIsCanonical && parsedRef.Name() == repoRef.Name() {
  105. foundRepoTagRef = true
  106. break
  107. }
  108. }
  109. if !foundRepoTagRef {
  110. // Remove canonical references from same repository
  111. var remainingRefs []reference.Named
  112. for _, repoRef := range repoRefs {
  113. if _, repoRefIsCanonical := repoRef.(reference.Canonical); repoRefIsCanonical && parsedRef.Name() == repoRef.Name() {
  114. if _, err := i.removeImageRef(repoRef); err != nil {
  115. return records, err
  116. }
  117. records = append(records, imagetypes.DeleteResponse{Untagged: reference.FamiliarString(repoRef)})
  118. } else {
  119. remainingRefs = append(remainingRefs, repoRef)
  120. }
  121. }
  122. repoRefs = remainingRefs
  123. }
  124. }
  125. // If it has remaining references then the untag finished the remove
  126. if len(repoRefs) > 0 {
  127. return records, nil
  128. }
  129. removedRepositoryRef = true
  130. } else {
  131. // If an ID reference was given AND there is at most one tag
  132. // reference to the image AND all references are within one
  133. // repository, then remove all references.
  134. if isSingleReference(repoRefs) {
  135. c := conflictHard
  136. if !force {
  137. c |= conflictSoft &^ conflictActiveReference
  138. }
  139. if conflict := i.checkImageDeleteConflict(imgID, c); conflict != nil {
  140. return nil, conflict
  141. }
  142. for _, repoRef := range repoRefs {
  143. parsedRef, err := i.removeImageRef(repoRef)
  144. if err != nil {
  145. return nil, err
  146. }
  147. i.LogImageEvent(imgID.String(), imgID.String(), events.ActionUnTag)
  148. records = append(records, imagetypes.DeleteResponse{Untagged: reference.FamiliarString(parsedRef)})
  149. }
  150. }
  151. }
  152. if err := i.imageDeleteHelper(imgID, &records, force, prune, removedRepositoryRef); err != nil {
  153. return nil, err
  154. }
  155. imageActions.WithValues("delete").UpdateSince(start)
  156. return records, nil
  157. }
  158. // isSingleReference returns true when all references are from one repository
  159. // and there is at most one tag. Returns false for empty input.
  160. func isSingleReference(repoRefs []reference.Named) bool {
  161. if len(repoRefs) <= 1 {
  162. return len(repoRefs) == 1
  163. }
  164. var singleRef reference.Named
  165. canonicalRefs := map[string]struct{}{}
  166. for _, repoRef := range repoRefs {
  167. if _, isCanonical := repoRef.(reference.Canonical); isCanonical {
  168. canonicalRefs[repoRef.Name()] = struct{}{}
  169. } else if singleRef == nil {
  170. singleRef = repoRef
  171. } else {
  172. return false
  173. }
  174. }
  175. if singleRef == nil {
  176. // Just use first canonical ref
  177. singleRef = repoRefs[0]
  178. }
  179. _, ok := canonicalRefs[singleRef.Name()]
  180. return len(canonicalRefs) == 1 && ok
  181. }
  182. // isImageIDPrefix returns whether the given possiblePrefix is a prefix of the
  183. // given imageID.
  184. func isImageIDPrefix(imageID, possiblePrefix string) bool {
  185. if strings.HasPrefix(imageID, possiblePrefix) {
  186. return true
  187. }
  188. if i := strings.IndexRune(imageID, ':'); i >= 0 {
  189. return strings.HasPrefix(imageID[i+1:], possiblePrefix)
  190. }
  191. return false
  192. }
  193. // removeImageRef attempts to parse and remove the given image reference from
  194. // this daemon's store of repository tag/digest references. The given
  195. // repositoryRef must not be an image ID but a repository name followed by an
  196. // optional tag or digest reference. If tag or digest is omitted, the default
  197. // tag is used. Returns the resolved image reference and an error.
  198. func (i *ImageService) removeImageRef(ref reference.Named) (reference.Named, error) {
  199. ref = reference.TagNameOnly(ref)
  200. // Ignore the boolean value returned, as far as we're concerned, this
  201. // is an idempotent operation and it's okay if the reference didn't
  202. // exist in the first place.
  203. _, err := i.referenceStore.Delete(ref)
  204. return ref, err
  205. }
  206. // removeAllReferencesToImageID attempts to remove every reference to the given
  207. // imgID from this daemon's store of repository tag/digest references. Returns
  208. // on the first encountered error. Removed references are logged to this
  209. // daemon's event service. An "Untagged" types.ImageDeleteResponseItem is added to the
  210. // given list of records.
  211. func (i *ImageService) removeAllReferencesToImageID(imgID image.ID, records *[]imagetypes.DeleteResponse) error {
  212. for _, imageRef := range i.referenceStore.References(imgID.Digest()) {
  213. parsedRef, err := i.removeImageRef(imageRef)
  214. if err != nil {
  215. return err
  216. }
  217. i.LogImageEvent(imgID.String(), imgID.String(), events.ActionUnTag)
  218. *records = append(*records, imagetypes.DeleteResponse{
  219. Untagged: reference.FamiliarString(parsedRef),
  220. })
  221. }
  222. return nil
  223. }
  224. // ImageDeleteConflict holds a soft or hard conflict and an associated error.
  225. // Implements the error interface.
  226. type imageDeleteConflict struct {
  227. hard bool
  228. used bool
  229. imgID image.ID
  230. message string
  231. }
  232. func (idc *imageDeleteConflict) Error() string {
  233. var forceMsg string
  234. if idc.hard {
  235. forceMsg = "cannot be forced"
  236. } else {
  237. forceMsg = "must be forced"
  238. }
  239. return fmt.Sprintf("conflict: unable to delete %s (%s) - %s", stringid.TruncateID(idc.imgID.String()), forceMsg, idc.message)
  240. }
  241. func (idc *imageDeleteConflict) Conflict() {}
  242. // imageDeleteHelper attempts to delete the given image from this daemon. If
  243. // the image has any hard delete conflicts (child images or running containers
  244. // using the image) then it cannot be deleted. If the image has any soft delete
  245. // conflicts (any tags/digests referencing the image or any stopped container
  246. // using the image) then it can only be deleted if force is true. If the delete
  247. // succeeds and prune is true, the parent images are also deleted if they do
  248. // not have any soft or hard delete conflicts themselves. Any deleted images
  249. // and untagged references are appended to the given records. If any error or
  250. // conflict is encountered, it will be returned immediately without deleting
  251. // the image. If quiet is true, any encountered conflicts will be ignored and
  252. // the function will return nil immediately without deleting the image.
  253. func (i *ImageService) imageDeleteHelper(imgID image.ID, records *[]imagetypes.DeleteResponse, force, prune, quiet bool) error {
  254. // First, determine if this image has any conflicts. Ignore soft conflicts
  255. // if force is true.
  256. c := conflictHard
  257. if !force {
  258. c |= conflictSoft
  259. }
  260. if conflict := i.checkImageDeleteConflict(imgID, c); conflict != nil {
  261. if quiet && (!i.imageIsDangling(imgID) || conflict.used) {
  262. // Ignore conflicts UNLESS the image is "dangling" or not being used in
  263. // which case we want the user to know.
  264. return nil
  265. }
  266. // There was a conflict and it's either a hard conflict OR we are not
  267. // forcing deletion on soft conflicts.
  268. return conflict
  269. }
  270. parent, err := i.imageStore.GetParent(imgID)
  271. if err != nil {
  272. // There may be no parent
  273. parent = ""
  274. }
  275. // Delete all repository tag/digest references to this image.
  276. if err := i.removeAllReferencesToImageID(imgID, records); err != nil {
  277. return err
  278. }
  279. removedLayers, err := i.imageStore.Delete(imgID)
  280. if err != nil {
  281. return err
  282. }
  283. i.LogImageEvent(imgID.String(), imgID.String(), events.ActionDelete)
  284. *records = append(*records, imagetypes.DeleteResponse{Deleted: imgID.String()})
  285. for _, removedLayer := range removedLayers {
  286. *records = append(*records, imagetypes.DeleteResponse{Deleted: removedLayer.ChainID.String()})
  287. }
  288. if !prune || parent == "" {
  289. return nil
  290. }
  291. // We need to prune the parent image. This means delete it if there are
  292. // no tags/digests referencing it and there are no containers using it (
  293. // either running or stopped).
  294. // Do not force prunings, but do so quietly (stopping on any encountered
  295. // conflicts).
  296. return i.imageDeleteHelper(parent, records, false, true, true)
  297. }
  298. // checkImageDeleteConflict determines whether there are any conflicts
  299. // preventing deletion of the given image from this daemon. A hard conflict is
  300. // any image which has the given image as a parent or any running container
  301. // using the image. A soft conflict is any tags/digest referencing the given
  302. // image or any stopped container using the image. If ignoreSoftConflicts is
  303. // true, this function will not check for soft conflict conditions.
  304. func (i *ImageService) checkImageDeleteConflict(imgID image.ID, mask conflictType) *imageDeleteConflict {
  305. // Check if the image has any descendant images.
  306. if mask&conflictDependentChild != 0 && len(i.imageStore.Children(imgID)) > 0 {
  307. return &imageDeleteConflict{
  308. hard: true,
  309. imgID: imgID,
  310. message: "image has dependent child images",
  311. }
  312. }
  313. if mask&conflictRunningContainer != 0 {
  314. // Check if any running container is using the image.
  315. running := func(c *container.Container) bool {
  316. return c.ImageID == imgID && c.IsRunning()
  317. }
  318. if ctr := i.containers.First(running); ctr != nil {
  319. return &imageDeleteConflict{
  320. imgID: imgID,
  321. hard: true,
  322. used: true,
  323. message: fmt.Sprintf("image is being used by running container %s", stringid.TruncateID(ctr.ID)),
  324. }
  325. }
  326. }
  327. // Check if any repository tags/digest reference this image.
  328. if mask&conflictActiveReference != 0 && len(i.referenceStore.References(imgID.Digest())) > 0 {
  329. return &imageDeleteConflict{
  330. imgID: imgID,
  331. message: "image is referenced in multiple repositories",
  332. }
  333. }
  334. if mask&conflictStoppedContainer != 0 {
  335. // Check if any stopped containers reference this image.
  336. stopped := func(c *container.Container) bool {
  337. return !c.IsRunning() && c.ImageID == imgID
  338. }
  339. if ctr := i.containers.First(stopped); ctr != nil {
  340. return &imageDeleteConflict{
  341. imgID: imgID,
  342. used: true,
  343. message: fmt.Sprintf("image is being used by stopped container %s", stringid.TruncateID(ctr.ID)),
  344. }
  345. }
  346. }
  347. return nil
  348. }
  349. // imageIsDangling returns whether the given image is "dangling" which means
  350. // that there are no repository references to the given image and it has no
  351. // child images.
  352. func (i *ImageService) imageIsDangling(imgID image.ID) bool {
  353. return !(len(i.referenceStore.References(imgID.Digest())) > 0 || len(i.imageStore.Children(imgID)) > 0)
  354. }