image_delete.go 15 KB

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