8 "github.com/docker/distribution/reference"
9 "github.com/docker/docker/api/errors"
10 "github.com/docker/docker/api/types"
11 "github.com/docker/docker/container"
12 "github.com/docker/docker/image"
13 "github.com/docker/docker/pkg/stringid"
19 conflictDependentChild conflictType = (1 << iota)
20 conflictRunningContainer
21 conflictActiveReference
22 conflictStoppedContainer
23 conflictHard = conflictDependentChild | conflictRunningContainer
24 conflictSoft = conflictActiveReference | conflictStoppedContainer
27 // ImageDelete deletes the image referenced by the given imageRef from this
28 // daemon. The given imageRef can be an image ID, ID prefix, or a repository
29 // reference (with an optional tag or digest, defaulting to the tag name
30 // "latest"). There is differing behavior depending on whether the given
31 // imageRef is a repository reference or not.
33 // If the given imageRef is a repository reference then that repository
34 // reference will be removed. However, if there exists any containers which
35 // were created using the same image reference then the repository reference
36 // cannot be removed unless either there are other repository references to the
37 // same image or force is true. Following removal of the repository reference,
38 // the referenced image itself will attempt to be deleted as described below
39 // but quietly, meaning any image delete conflicts will cause the image to not
40 // be deleted and the conflict will not be reported.
42 // There may be conflicts preventing deletion of an image and these conflicts
43 // are divided into two categories grouped by their severity:
46 // - a pull or build using the image.
47 // - any descendant image.
48 // - any running container using the image.
51 // - any stopped container using the image.
52 // - any repository tag or digest references to the image.
54 // The image cannot be removed if there are any hard conflicts and can be
55 // removed if there are soft conflicts only if force is true.
57 // If prune is true, ancestor images will each attempt to be deleted quietly,
58 // meaning any delete conflicts will cause the image to not be deleted and the
59 // conflict will not be reported.
61 // FIXME: remove ImageDelete's dependency on Daemon, then move to the graph
62 // package. This would require that we no longer need the daemon to determine
63 // whether images are being used by a stopped or running container.
64 func (daemon *Daemon) ImageDelete(imageRef string, force, prune bool) ([]types.ImageDeleteResponseItem, error) {
66 records := []types.ImageDeleteResponseItem{}
68 imgID, platform, err := daemon.GetImageIDAndPlatform(imageRef)
70 return nil, daemon.imageNotExistToErrcode(err)
73 repoRefs := daemon.stores[platform].referenceStore.References(imgID.Digest())
75 var removedRepositoryRef bool
76 if !isImageIDPrefix(imgID.String(), imageRef) {
77 // A repository reference was given and should be removed
78 // first. We can only remove this reference if either force is
79 // true, there are multiple repository references to this
80 // image, or there are no containers using the given reference.
81 if !force && isSingleReference(repoRefs) {
82 if container := daemon.getContainerUsingImage(imgID); container != nil {
83 // If we removed the repository reference then
84 // this image would remain "dangling" and since
85 // we really want to avoid that the client must
86 // explicitly force its removal.
87 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()))
88 return nil, errors.NewRequestConflictError(err)
92 parsedRef, err := reference.ParseNormalizedNamed(imageRef)
97 parsedRef, err = daemon.removeImageRef(platform, parsedRef)
102 untaggedRecord := types.ImageDeleteResponseItem{Untagged: reference.FamiliarString(parsedRef)}
104 daemon.LogImageEvent(imgID.String(), imgID.String(), "untag")
105 records = append(records, untaggedRecord)
107 repoRefs = daemon.stores[platform].referenceStore.References(imgID.Digest())
109 // If a tag reference was removed and the only remaining
110 // references to the same repository are digest references,
111 // then clean up those digest references.
112 if _, isCanonical := parsedRef.(reference.Canonical); !isCanonical {
113 foundRepoTagRef := false
114 for _, repoRef := range repoRefs {
115 if _, repoRefIsCanonical := repoRef.(reference.Canonical); !repoRefIsCanonical && parsedRef.Name() == repoRef.Name() {
116 foundRepoTagRef = true
120 if !foundRepoTagRef {
121 // Remove canonical references from same repository
122 remainingRefs := []reference.Named{}
123 for _, repoRef := range repoRefs {
124 if _, repoRefIsCanonical := repoRef.(reference.Canonical); repoRefIsCanonical && parsedRef.Name() == repoRef.Name() {
125 if _, err := daemon.removeImageRef(platform, repoRef); err != nil {
129 untaggedRecord := types.ImageDeleteResponseItem{Untagged: reference.FamiliarString(repoRef)}
130 records = append(records, untaggedRecord)
132 remainingRefs = append(remainingRefs, repoRef)
136 repoRefs = remainingRefs
140 // If it has remaining references then the untag finished the remove
141 if len(repoRefs) > 0 {
145 removedRepositoryRef = true
147 // If an ID reference was given AND there is at most one tag
148 // reference to the image AND all references are within one
149 // repository, then remove all references.
150 if isSingleReference(repoRefs) {
153 c |= conflictSoft &^ conflictActiveReference
155 if conflict := daemon.checkImageDeleteConflict(imgID, platform, c); conflict != nil {
159 for _, repoRef := range repoRefs {
160 parsedRef, err := daemon.removeImageRef(platform, repoRef)
165 untaggedRecord := types.ImageDeleteResponseItem{Untagged: reference.FamiliarString(parsedRef)}
167 daemon.LogImageEvent(imgID.String(), imgID.String(), "untag")
168 records = append(records, untaggedRecord)
173 if err := daemon.imageDeleteHelper(imgID, platform, &records, force, prune, removedRepositoryRef); err != nil {
177 imageActions.WithValues("delete").UpdateSince(start)
182 // isSingleReference returns true when all references are from one repository
183 // and there is at most one tag. Returns false for empty input.
184 func isSingleReference(repoRefs []reference.Named) bool {
185 if len(repoRefs) <= 1 {
186 return len(repoRefs) == 1
188 var singleRef reference.Named
189 canonicalRefs := map[string]struct{}{}
190 for _, repoRef := range repoRefs {
191 if _, isCanonical := repoRef.(reference.Canonical); isCanonical {
192 canonicalRefs[repoRef.Name()] = struct{}{}
193 } else if singleRef == nil {
199 if singleRef == nil {
200 // Just use first canonical ref
201 singleRef = repoRefs[0]
203 _, ok := canonicalRefs[singleRef.Name()]
204 return len(canonicalRefs) == 1 && ok
207 // isImageIDPrefix returns whether the given possiblePrefix is a prefix of the
209 func isImageIDPrefix(imageID, possiblePrefix string) bool {
210 if strings.HasPrefix(imageID, possiblePrefix) {
214 if i := strings.IndexRune(imageID, ':'); i >= 0 {
215 return strings.HasPrefix(imageID[i+1:], possiblePrefix)
221 // getContainerUsingImage returns a container that was created using the given
222 // imageID. Returns nil if there is no such container.
223 func (daemon *Daemon) getContainerUsingImage(imageID image.ID) *container.Container {
224 return daemon.containers.First(func(c *container.Container) bool {
225 return c.ImageID == imageID
229 // removeImageRef attempts to parse and remove the given image reference from
230 // this daemon's store of repository tag/digest references. The given
231 // repositoryRef must not be an image ID but a repository name followed by an
232 // optional tag or digest reference. If tag or digest is omitted, the default
233 // tag is used. Returns the resolved image reference and an error.
234 func (daemon *Daemon) removeImageRef(platform string, ref reference.Named) (reference.Named, error) {
235 ref = reference.TagNameOnly(ref)
237 // Ignore the boolean value returned, as far as we're concerned, this
238 // is an idempotent operation and it's okay if the reference didn't
239 // exist in the first place.
240 _, err := daemon.stores[platform].referenceStore.Delete(ref)
245 // removeAllReferencesToImageID attempts to remove every reference to the given
246 // imgID from this daemon's store of repository tag/digest references. Returns
247 // on the first encountered error. Removed references are logged to this
248 // daemon's event service. An "Untagged" types.ImageDeleteResponseItem is added to the
249 // given list of records.
250 func (daemon *Daemon) removeAllReferencesToImageID(imgID image.ID, platform string, records *[]types.ImageDeleteResponseItem) error {
251 imageRefs := daemon.stores[platform].referenceStore.References(imgID.Digest())
253 for _, imageRef := range imageRefs {
254 parsedRef, err := daemon.removeImageRef(platform, imageRef)
259 untaggedRecord := types.ImageDeleteResponseItem{Untagged: reference.FamiliarString(parsedRef)}
261 daemon.LogImageEvent(imgID.String(), imgID.String(), "untag")
262 *records = append(*records, untaggedRecord)
268 // ImageDeleteConflict holds a soft or hard conflict and an associated error.
269 // Implements the error interface.
270 type imageDeleteConflict struct {
277 func (idc *imageDeleteConflict) Error() string {
280 forceMsg = "cannot be forced"
282 forceMsg = "must be forced"
285 return fmt.Sprintf("conflict: unable to delete %s (%s) - %s", stringid.TruncateID(idc.imgID.String()), forceMsg, idc.message)
288 // imageDeleteHelper attempts to delete the given image from this daemon. If
289 // the image has any hard delete conflicts (child images or running containers
290 // using the image) then it cannot be deleted. If the image has any soft delete
291 // conflicts (any tags/digests referencing the image or any stopped container
292 // using the image) then it can only be deleted if force is true. If the delete
293 // succeeds and prune is true, the parent images are also deleted if they do
294 // not have any soft or hard delete conflicts themselves. Any deleted images
295 // and untagged references are appended to the given records. If any error or
296 // conflict is encountered, it will be returned immediately without deleting
297 // the image. If quiet is true, any encountered conflicts will be ignored and
298 // the function will return nil immediately without deleting the image.
299 func (daemon *Daemon) imageDeleteHelper(imgID image.ID, platform string, records *[]types.ImageDeleteResponseItem, force, prune, quiet bool) error {
300 // First, determine if this image has any conflicts. Ignore soft conflicts
306 if conflict := daemon.checkImageDeleteConflict(imgID, platform, c); conflict != nil {
307 if quiet && (!daemon.imageIsDangling(imgID, platform) || conflict.used) {
308 // Ignore conflicts UNLESS the image is "dangling" or not being used in
309 // which case we want the user to know.
313 // There was a conflict and it's either a hard conflict OR we are not
314 // forcing deletion on soft conflicts.
318 parent, err := daemon.stores[platform].imageStore.GetParent(imgID)
320 // There may be no parent
324 // Delete all repository tag/digest references to this image.
325 if err := daemon.removeAllReferencesToImageID(imgID, platform, records); err != nil {
329 removedLayers, err := daemon.stores[platform].imageStore.Delete(imgID)
334 daemon.LogImageEvent(imgID.String(), imgID.String(), "delete")
335 *records = append(*records, types.ImageDeleteResponseItem{Deleted: imgID.String()})
336 for _, removedLayer := range removedLayers {
337 *records = append(*records, types.ImageDeleteResponseItem{Deleted: removedLayer.ChainID.String()})
340 if !prune || parent == "" {
344 // We need to prune the parent image. This means delete it if there are
345 // no tags/digests referencing it and there are no containers using it (
346 // either running or stopped).
347 // Do not force prunings, but do so quietly (stopping on any encountered
349 return daemon.imageDeleteHelper(parent, platform, records, false, true, true)
352 // checkImageDeleteConflict determines whether there are any conflicts
353 // preventing deletion of the given image from this daemon. A hard conflict is
354 // any image which has the given image as a parent or any running container
355 // using the image. A soft conflict is any tags/digest referencing the given
356 // image or any stopped container using the image. If ignoreSoftConflicts is
357 // true, this function will not check for soft conflict conditions.
358 func (daemon *Daemon) checkImageDeleteConflict(imgID image.ID, platform string, mask conflictType) *imageDeleteConflict {
359 // Check if the image has any descendant images.
360 if mask&conflictDependentChild != 0 && len(daemon.stores[platform].imageStore.Children(imgID)) > 0 {
361 return &imageDeleteConflict{
364 message: "image has dependent child images",
368 if mask&conflictRunningContainer != 0 {
369 // Check if any running container is using the image.
370 running := func(c *container.Container) bool {
371 return c.IsRunning() && c.ImageID == imgID
373 if container := daemon.containers.First(running); container != nil {
374 return &imageDeleteConflict{
378 message: fmt.Sprintf("image is being used by running container %s", stringid.TruncateID(container.ID)),
383 // Check if any repository tags/digest reference this image.
384 if mask&conflictActiveReference != 0 && len(daemon.stores[platform].referenceStore.References(imgID.Digest())) > 0 {
385 return &imageDeleteConflict{
387 message: "image is referenced in multiple repositories",
391 if mask&conflictStoppedContainer != 0 {
392 // Check if any stopped containers reference this image.
393 stopped := func(c *container.Container) bool {
394 return !c.IsRunning() && c.ImageID == imgID
396 if container := daemon.containers.First(stopped); container != nil {
397 return &imageDeleteConflict{
400 message: fmt.Sprintf("image is being used by stopped container %s", stringid.TruncateID(container.ID)),
408 // imageIsDangling returns whether the given image is "dangling" which means
409 // that there are no repository references to the given image and it has no
411 func (daemon *Daemon) imageIsDangling(imgID image.ID, platform string) bool {
412 return !(len(daemon.stores[platform].referenceStore.References(imgID.Digest())) > 0 || len(daemon.stores[platform].imageStore.Children(imgID)) > 0)