image_delete.go 14 KB

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