image_delete.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413
  1. package daemon
  2. import (
  3. "fmt"
  4. "strings"
  5. "time"
  6. "github.com/docker/distribution/reference"
  7. "github.com/docker/docker/api/errors"
  8. "github.com/docker/docker/api/types"
  9. "github.com/docker/docker/container"
  10. "github.com/docker/docker/image"
  11. "github.com/docker/docker/pkg/stringid"
  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, err := daemon.GetImageID(imageRef)
  63. if err != nil {
  64. return nil, daemon.imageNotExistToErrcode(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 := fmt.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, errors.NewRequestConflictError(err)
  81. }
  82. }
  83. parsedRef, err := reference.ParseNormalizedNamed(imageRef)
  84. if err != nil {
  85. return nil, err
  86. }
  87. parsedRef, err = daemon.removeImageRef(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(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, c); conflict != nil {
  138. return nil, conflict
  139. }
  140. for _, repoRef := range repoRefs {
  141. parsedRef, err := daemon.removeImageRef(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, &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(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, records *[]types.ImageDeleteResponseItem) error {
  218. imageRefs := daemon.referenceStore.References(imgID.Digest())
  219. for _, imageRef := range imageRefs {
  220. parsedRef, err := daemon.removeImageRef(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. // imageDeleteHelper attempts to delete the given image from this daemon. If
  248. // the image has any hard delete conflicts (child images or running containers
  249. // using the image) then it cannot be deleted. If the image has any soft delete
  250. // conflicts (any tags/digests referencing the image or any stopped container
  251. // using the image) then it can only be deleted if force is true. If the delete
  252. // succeeds and prune is true, the parent images are also deleted if they do
  253. // not have any soft or hard delete conflicts themselves. Any deleted images
  254. // and untagged references are appended to the given records. If any error or
  255. // conflict is encountered, it will be returned immediately without deleting
  256. // the image. If quiet is true, any encountered conflicts will be ignored and
  257. // the function will return nil immediately without deleting the image.
  258. func (daemon *Daemon) imageDeleteHelper(imgID image.ID, records *[]types.ImageDeleteResponseItem, force, prune, quiet bool) error {
  259. // First, determine if this image has any conflicts. Ignore soft conflicts
  260. // if force is true.
  261. c := conflictHard
  262. if !force {
  263. c |= conflictSoft
  264. }
  265. if conflict := daemon.checkImageDeleteConflict(imgID, c); conflict != nil {
  266. if quiet && (!daemon.imageIsDangling(imgID) || conflict.used) {
  267. // Ignore conflicts UNLESS the image is "dangling" or not being used in
  268. // which case we want the user to know.
  269. return nil
  270. }
  271. // There was a conflict and it's either a hard conflict OR we are not
  272. // forcing deletion on soft conflicts.
  273. return conflict
  274. }
  275. parent, err := daemon.imageStore.GetParent(imgID)
  276. if err != nil {
  277. // There may be no parent
  278. parent = ""
  279. }
  280. // Delete all repository tag/digest references to this image.
  281. if err := daemon.removeAllReferencesToImageID(imgID, records); err != nil {
  282. return err
  283. }
  284. removedLayers, err := daemon.imageStore.Delete(imgID)
  285. if err != nil {
  286. return err
  287. }
  288. daemon.LogImageEvent(imgID.String(), imgID.String(), "delete")
  289. *records = append(*records, types.ImageDeleteResponseItem{Deleted: imgID.String()})
  290. for _, removedLayer := range removedLayers {
  291. *records = append(*records, types.ImageDeleteResponseItem{Deleted: removedLayer.ChainID.String()})
  292. }
  293. if !prune || parent == "" {
  294. return nil
  295. }
  296. // We need to prune the parent image. This means delete it if there are
  297. // no tags/digests referencing it and there are no containers using it (
  298. // either running or stopped).
  299. // Do not force prunings, but do so quietly (stopping on any encountered
  300. // conflicts).
  301. return daemon.imageDeleteHelper(parent, records, false, true, true)
  302. }
  303. // checkImageDeleteConflict determines whether there are any conflicts
  304. // preventing deletion of the given image from this daemon. A hard conflict is
  305. // any image which has the given image as a parent or any running container
  306. // using the image. A soft conflict is any tags/digest referencing the given
  307. // image or any stopped container using the image. If ignoreSoftConflicts is
  308. // true, this function will not check for soft conflict conditions.
  309. func (daemon *Daemon) checkImageDeleteConflict(imgID image.ID, mask conflictType) *imageDeleteConflict {
  310. // Check if the image has any descendant images.
  311. if mask&conflictDependentChild != 0 && len(daemon.imageStore.Children(imgID)) > 0 {
  312. return &imageDeleteConflict{
  313. hard: true,
  314. imgID: imgID,
  315. message: "image has dependent child images",
  316. }
  317. }
  318. if mask&conflictRunningContainer != 0 {
  319. // Check if any running container is using the image.
  320. running := func(c *container.Container) bool {
  321. return c.IsRunning() && c.ImageID == imgID
  322. }
  323. if container := daemon.containers.First(running); container != nil {
  324. return &imageDeleteConflict{
  325. imgID: imgID,
  326. hard: true,
  327. used: true,
  328. message: fmt.Sprintf("image is being used by running container %s", stringid.TruncateID(container.ID)),
  329. }
  330. }
  331. }
  332. // Check if any repository tags/digest reference this image.
  333. if mask&conflictActiveReference != 0 && len(daemon.referenceStore.References(imgID.Digest())) > 0 {
  334. return &imageDeleteConflict{
  335. imgID: imgID,
  336. message: "image is referenced in multiple repositories",
  337. }
  338. }
  339. if mask&conflictStoppedContainer != 0 {
  340. // Check if any stopped containers reference this image.
  341. stopped := func(c *container.Container) bool {
  342. return !c.IsRunning() && c.ImageID == imgID
  343. }
  344. if container := daemon.containers.First(stopped); container != nil {
  345. return &imageDeleteConflict{
  346. imgID: imgID,
  347. used: true,
  348. message: fmt.Sprintf("image is being used by stopped container %s", stringid.TruncateID(container.ID)),
  349. }
  350. }
  351. }
  352. return nil
  353. }
  354. // imageIsDangling returns whether the given image is "dangling" which means
  355. // that there are no repository references to the given image and it has no
  356. // child images.
  357. func (daemon *Daemon) imageIsDangling(imgID image.ID) bool {
  358. return !(len(daemon.referenceStore.References(imgID.Digest())) > 0 || len(daemon.imageStore.Children(imgID)) > 0)
  359. }