image_delete.go 15 KB

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