daemon/image_delete.go
7a5e3df1
 package daemon
 
 import (
 	"fmt"
 	"strings"
3343d234
 	"time"
7a5e3df1
 
3a127939
 	"github.com/docker/distribution/reference"
91e197d6
 	"github.com/docker/docker/api/types"
6bb0d181
 	"github.com/docker/docker/container"
d453fe35
 	"github.com/docker/docker/errdefs"
9001ea26
 	"github.com/docker/docker/image"
b80fae73
 	"github.com/docker/docker/pkg/stringid"
0cba7740
 	"github.com/docker/docker/pkg/system"
ebcb7d6b
 	"github.com/pkg/errors"
7a5e3df1
 )
 
883be489
 type conflictType int
 
 const (
 	conflictDependentChild conflictType = (1 << iota)
 	conflictRunningContainer
 	conflictActiveReference
 	conflictStoppedContainer
 	conflictHard = conflictDependentChild | conflictRunningContainer
 	conflictSoft = conflictActiveReference | conflictStoppedContainer
 )
 
111d2f34
 // ImageDelete deletes the image referenced by the given imageRef from this
 // daemon. The given imageRef can be an image ID, ID prefix, or a repository
 // reference (with an optional tag or digest, defaulting to the tag name
 // "latest"). There is differing behavior depending on whether the given
 // imageRef is a repository reference or not.
 //
 // If the given imageRef is a repository reference then that repository
 // reference will be removed. However, if there exists any containers which
 // were created using the same image reference then the repository reference
 // cannot be removed unless either there are other repository references to the
 // same image or force is true. Following removal of the repository reference,
 // the referenced image itself will attempt to be deleted as described below
 // but quietly, meaning any image delete conflicts will cause the image to not
 // be deleted and the conflict will not be reported.
 //
 // There may be conflicts preventing deletion of an image and these conflicts
 // are divided into two categories grouped by their severity:
 //
 // Hard Conflict:
 // 	- a pull or build using the image.
99a39690
 // 	- any descendant image.
111d2f34
 // 	- any running container using the image.
 //
 // Soft Conflict:
 // 	- any stopped container using the image.
 // 	- any repository tag or digest references to the image.
 //
 // The image cannot be removed if there are any hard conflicts and can be
 // removed if there are soft conflicts only if force is true.
 //
 // If prune is true, ancestor images will each attempt to be deleted quietly,
 // meaning any delete conflicts will cause the image to not be deleted and the
 // conflict will not be reported.
 //
 // FIXME: remove ImageDelete's dependency on Daemon, then move to the graph
 // package. This would require that we no longer need the daemon to determine
 // whether images are being used by a stopped or running container.
5988b84e
 func (daemon *Daemon) ImageDelete(imageRef string, force, prune bool) ([]types.ImageDeleteResponseItem, error) {
3343d234
 	start := time.Now()
5988b84e
 	records := []types.ImageDeleteResponseItem{}
111d2f34
 
0cba7740
 	imgID, operatingSystem, err := daemon.GetImageIDAndOS(imageRef)
111d2f34
 	if err != nil {
ebcb7d6b
 		return nil, err
7a5e3df1
 	}
0cba7740
 	if !system.IsOSSupported(operatingSystem) {
 		return nil, errors.Errorf("unable to delete image: %q", system.ErrNotSupportedOperatingSystem)
 	}
111d2f34
 
7b9a8f46
 	repoRefs := daemon.referenceStore.References(imgID.Digest())
4352da78
 
111d2f34
 	var removedRepositoryRef bool
4352da78
 	if !isImageIDPrefix(imgID.String(), imageRef) {
111d2f34
 		// A repository reference was given and should be removed
 		// first. We can only remove this reference if either force is
 		// true, there are multiple repository references to this
 		// image, or there are no containers using the given reference.
1f7a9b1a
 		if !force && isSingleReference(repoRefs) {
4352da78
 			if container := daemon.getContainerUsingImage(imgID); container != nil {
111d2f34
 				// If we removed the repository reference then
 				// this image would remain "dangling" and since
 				// we really want to avoid that the client must
 				// explicitly force its removal.
ebcb7d6b
 				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()))
87a12421
 				return nil, errdefs.Conflict(err)
111d2f34
 			}
 		}
 
3a127939
 		parsedRef, err := reference.ParseNormalizedNamed(imageRef)
111d2f34
 		if err != nil {
 			return nil, err
 		}
 
ce8e529e
 		parsedRef, err = daemon.removeImageRef(parsedRef)
4352da78
 		if err != nil {
 			return nil, err
 		}
 
3a127939
 		untaggedRecord := types.ImageDeleteResponseItem{Untagged: reference.FamiliarString(parsedRef)}
111d2f34
 
72f1881d
 		daemon.LogImageEvent(imgID.String(), imgID.String(), "untag")
111d2f34
 		records = append(records, untaggedRecord)
 
7b9a8f46
 		repoRefs = daemon.referenceStore.References(imgID.Digest())
2f048f73
 
a281be1c
 		// If a tag reference was removed and the only remaining
 		// references to the same repository are digest references,
 		// then clean up those digest references.
2f048f73
 		if _, isCanonical := parsedRef.(reference.Canonical); !isCanonical {
a281be1c
 			foundRepoTagRef := false
2f048f73
 			for _, repoRef := range repoRefs {
a281be1c
 				if _, repoRefIsCanonical := repoRef.(reference.Canonical); !repoRefIsCanonical && parsedRef.Name() == repoRef.Name() {
 					foundRepoTagRef = true
2f048f73
 					break
 				}
 			}
a281be1c
 			if !foundRepoTagRef {
 				// Remove canonical references from same repository
 				remainingRefs := []reference.Named{}
2f048f73
 				for _, repoRef := range repoRefs {
a281be1c
 					if _, repoRefIsCanonical := repoRef.(reference.Canonical); repoRefIsCanonical && parsedRef.Name() == repoRef.Name() {
ce8e529e
 						if _, err := daemon.removeImageRef(repoRef); err != nil {
a281be1c
 							return records, err
 						}
 
3a127939
 						untaggedRecord := types.ImageDeleteResponseItem{Untagged: reference.FamiliarString(repoRef)}
a281be1c
 						records = append(records, untaggedRecord)
 					} else {
 						remainingRefs = append(remainingRefs, repoRef)
2f048f73
 
a281be1c
 					}
2f048f73
 				}
a281be1c
 				repoRefs = remainingRefs
2f048f73
 			}
 		}
 
 		// If it has remaining references then the untag finished the remove
 		if len(repoRefs) > 0 {
48e7f796
 			return records, nil
 		}
 
111d2f34
 		removedRepositoryRef = true
 	} else {
a281be1c
 		// If an ID reference was given AND there is at most one tag
 		// reference to the image AND all references are within one
 		// repository, then remove all references.
 		if isSingleReference(repoRefs) {
883be489
 			c := conflictHard
 			if !force {
 				c |= conflictSoft &^ conflictActiveReference
 			}
ce8e529e
 			if conflict := daemon.checkImageDeleteConflict(imgID, c); conflict != nil {
38a45eed
 				return nil, conflict
 			}
 
a281be1c
 			for _, repoRef := range repoRefs {
ce8e529e
 				parsedRef, err := daemon.removeImageRef(repoRef)
a281be1c
 				if err != nil {
 					return nil, err
 				}
111d2f34
 
3a127939
 				untaggedRecord := types.ImageDeleteResponseItem{Untagged: reference.FamiliarString(parsedRef)}
111d2f34
 
a281be1c
 				daemon.LogImageEvent(imgID.String(), imgID.String(), "untag")
 				records = append(records, untaggedRecord)
 			}
111d2f34
 		}
7a5e3df1
 	}
e4afc379
 
ce8e529e
 	if err := daemon.imageDeleteHelper(imgID, &records, force, prune, removedRepositoryRef); err != nil {
3343d234
 		return nil, err
 	}
 
 	imageActions.WithValues("delete").UpdateSince(start)
 
 	return records, nil
7a5e3df1
 }
 
a281be1c
 // isSingleReference returns true when all references are from one repository
 // and there is at most one tag. Returns false for empty input.
 func isSingleReference(repoRefs []reference.Named) bool {
 	if len(repoRefs) <= 1 {
 		return len(repoRefs) == 1
 	}
 	var singleRef reference.Named
 	canonicalRefs := map[string]struct{}{}
 	for _, repoRef := range repoRefs {
 		if _, isCanonical := repoRef.(reference.Canonical); isCanonical {
 			canonicalRefs[repoRef.Name()] = struct{}{}
 		} else if singleRef == nil {
 			singleRef = repoRef
 		} else {
 			return false
 		}
 	}
 	if singleRef == nil {
 		// Just use first canonical ref
 		singleRef = repoRefs[0]
 	}
 	_, ok := canonicalRefs[singleRef.Name()]
 	return len(canonicalRefs) == 1 && ok
 }
 
111d2f34
 // isImageIDPrefix returns whether the given possiblePrefix is a prefix of the
 // given imageID.
 func isImageIDPrefix(imageID, possiblePrefix string) bool {
4352da78
 	if strings.HasPrefix(imageID, possiblePrefix) {
 		return true
 	}
 
 	if i := strings.IndexRune(imageID, ':'); i >= 0 {
 		return strings.HasPrefix(imageID[i+1:], possiblePrefix)
 	}
111d2f34
 
4352da78
 	return false
111d2f34
 }
 
 // getContainerUsingImage returns a container that was created using the given
 // imageID. Returns nil if there is no such container.
6bb0d181
 func (daemon *Daemon) getContainerUsingImage(imageID image.ID) *container.Container {
3c82fad4
 	return daemon.containers.First(func(c *container.Container) bool {
 		return c.ImageID == imageID
 	})
111d2f34
 }
7a5e3df1
 
111d2f34
 // removeImageRef attempts to parse and remove the given image reference from
 // this daemon's store of repository tag/digest references. The given
 // repositoryRef must not be an image ID but a repository name followed by an
 // optional tag or digest reference. If tag or digest is omitted, the default
 // tag is used. Returns the resolved image reference and an error.
ce8e529e
 func (daemon *Daemon) removeImageRef(ref reference.Named) (reference.Named, error) {
3a127939
 	ref = reference.TagNameOnly(ref)
 
111d2f34
 	// Ignore the boolean value returned, as far as we're concerned, this
 	// is an idempotent operation and it's okay if the reference didn't
 	// exist in the first place.
7b9a8f46
 	_, err := daemon.referenceStore.Delete(ref)
111d2f34
 
4352da78
 	return ref, err
111d2f34
 }
 
 // removeAllReferencesToImageID attempts to remove every reference to the given
 // imgID from this daemon's store of repository tag/digest references. Returns
 // on the first encountered error. Removed references are logged to this
5988b84e
 // daemon's event service. An "Untagged" types.ImageDeleteResponseItem is added to the
111d2f34
 // given list of records.
ce8e529e
 func (daemon *Daemon) removeAllReferencesToImageID(imgID image.ID, records *[]types.ImageDeleteResponseItem) error {
7b9a8f46
 	imageRefs := daemon.referenceStore.References(imgID.Digest())
111d2f34
 
 	for _, imageRef := range imageRefs {
ce8e529e
 		parsedRef, err := daemon.removeImageRef(imageRef)
111d2f34
 		if err != nil {
 			return err
7a5e3df1
 		}
111d2f34
 
3a127939
 		untaggedRecord := types.ImageDeleteResponseItem{Untagged: reference.FamiliarString(parsedRef)}
111d2f34
 
72f1881d
 		daemon.LogImageEvent(imgID.String(), imgID.String(), "untag")
111d2f34
 		*records = append(*records, untaggedRecord)
 	}
 
 	return nil
 }
 
 // ImageDeleteConflict holds a soft or hard conflict and an associated error.
 // Implements the error interface.
 type imageDeleteConflict struct {
 	hard    bool
0bbc9f1d
 	used    bool
4352da78
 	imgID   image.ID
111d2f34
 	message string
 }
 
 func (idc *imageDeleteConflict) Error() string {
 	var forceMsg string
 	if idc.hard {
 		forceMsg = "cannot be forced"
7a5e3df1
 	} else {
111d2f34
 		forceMsg = "must be forced"
 	}
 
4352da78
 	return fmt.Sprintf("conflict: unable to delete %s (%s) - %s", stringid.TruncateID(idc.imgID.String()), forceMsg, idc.message)
111d2f34
 }
 
ebcb7d6b
 func (idc *imageDeleteConflict) Conflict() {}
 
111d2f34
 // imageDeleteHelper attempts to delete the given image from this daemon. If
 // the image has any hard delete conflicts (child images or running containers
 // using the image) then it cannot be deleted. If the image has any soft delete
 // conflicts (any tags/digests referencing the image or any stopped container
 // using the image) then it can only be deleted if force is true. If the delete
 // succeeds and prune is true, the parent images are also deleted if they do
 // not have any soft or hard delete conflicts themselves. Any deleted images
 // and untagged references are appended to the given records. If any error or
 // conflict is encountered, it will be returned immediately without deleting
 // the image. If quiet is true, any encountered conflicts will be ignored and
 // the function will return nil immediately without deleting the image.
ce8e529e
 func (daemon *Daemon) imageDeleteHelper(imgID image.ID, records *[]types.ImageDeleteResponseItem, force, prune, quiet bool) error {
111d2f34
 	// First, determine if this image has any conflicts. Ignore soft conflicts
 	// if force is true.
883be489
 	c := conflictHard
 	if !force {
 		c |= conflictSoft
 	}
ce8e529e
 	if conflict := daemon.checkImageDeleteConflict(imgID, c); conflict != nil {
 		if quiet && (!daemon.imageIsDangling(imgID) || conflict.used) {
0bbc9f1d
 			// Ignore conflicts UNLESS the image is "dangling" or not being used in
111d2f34
 			// which case we want the user to know.
 			return nil
 		}
 
 		// There was a conflict and it's either a hard conflict OR we are not
 		// forcing deletion on soft conflicts.
 		return conflict
 	}
 
ce8e529e
 	parent, err := daemon.imageStore.GetParent(imgID)
4352da78
 	if err != nil {
 		// There may be no parent
 		parent = ""
 	}
 
111d2f34
 	// Delete all repository tag/digest references to this image.
ce8e529e
 	if err := daemon.removeAllReferencesToImageID(imgID, records); err != nil {
111d2f34
 		return err
 	}
 
ce8e529e
 	removedLayers, err := daemon.imageStore.Delete(imgID)
4352da78
 	if err != nil {
111d2f34
 		return err
7a5e3df1
 	}
 
72f1881d
 	daemon.LogImageEvent(imgID.String(), imgID.String(), "delete")
5988b84e
 	*records = append(*records, types.ImageDeleteResponseItem{Deleted: imgID.String()})
4352da78
 	for _, removedLayer := range removedLayers {
5988b84e
 		*records = append(*records, types.ImageDeleteResponseItem{Deleted: removedLayer.ChainID.String()})
4352da78
 	}
111d2f34
 
4352da78
 	if !prune || parent == "" {
7a5e3df1
 		return nil
 	}
 
111d2f34
 	// We need to prune the parent image. This means delete it if there are
 	// no tags/digests referencing it and there are no containers using it (
 	// either running or stopped).
 	// Do not force prunings, but do so quietly (stopping on any encountered
 	// conflicts).
ce8e529e
 	return daemon.imageDeleteHelper(parent, records, false, true, true)
111d2f34
 }
 
 // checkImageDeleteConflict determines whether there are any conflicts
 // preventing deletion of the given image from this daemon. A hard conflict is
 // any image which has the given image as a parent or any running container
 // using the image. A soft conflict is any tags/digest referencing the given
 // image or any stopped container using the image. If ignoreSoftConflicts is
 // true, this function will not check for soft conflict conditions.
ce8e529e
 func (daemon *Daemon) checkImageDeleteConflict(imgID image.ID, mask conflictType) *imageDeleteConflict {
99a39690
 	// Check if the image has any descendant images.
ce8e529e
 	if mask&conflictDependentChild != 0 && len(daemon.imageStore.Children(imgID)) > 0 {
111d2f34
 		return &imageDeleteConflict{
 			hard:    true,
4352da78
 			imgID:   imgID,
111d2f34
 			message: "image has dependent child images",
7a5e3df1
 		}
 	}
 
883be489
 	if mask&conflictRunningContainer != 0 {
 		// Check if any running container is using the image.
3c82fad4
 		running := func(c *container.Container) bool {
 			return c.IsRunning() && c.ImageID == imgID
 		}
 		if container := daemon.containers.First(running); container != nil {
 			return &imageDeleteConflict{
 				imgID:   imgID,
 				hard:    true,
 				used:    true,
 				message: fmt.Sprintf("image is being used by running container %s", stringid.TruncateID(container.ID)),
111d2f34
 			}
7a5e3df1
 		}
 	}
111d2f34
 
 	// Check if any repository tags/digest reference this image.
7b9a8f46
 	if mask&conflictActiveReference != 0 && len(daemon.referenceStore.References(imgID.Digest())) > 0 {
111d2f34
 		return &imageDeleteConflict{
4352da78
 			imgID:   imgID,
f0988dd3
 			message: "image is referenced in multiple repositories",
111d2f34
 		}
1b67c38f
 	}
111d2f34
 
883be489
 	if mask&conflictStoppedContainer != 0 {
 		// Check if any stopped containers reference this image.
3c82fad4
 		stopped := func(c *container.Container) bool {
 			return !c.IsRunning() && c.ImageID == imgID
 		}
 		if container := daemon.containers.First(stopped); container != nil {
 			return &imageDeleteConflict{
 				imgID:   imgID,
 				used:    true,
 				message: fmt.Sprintf("image is being used by stopped container %s", stringid.TruncateID(container.ID)),
7a5e3df1
 			}
 		}
 	}
111d2f34
 
7a5e3df1
 	return nil
 }
111d2f34
 
 // imageIsDangling returns whether the given image is "dangling" which means
 // that there are no repository references to the given image and it has no
 // child images.
ce8e529e
 func (daemon *Daemon) imageIsDangling(imgID image.ID) bool {
 	return !(len(daemon.referenceStore.References(imgID.Digest())) > 0 || len(daemon.imageStore.Children(imgID)) > 0)
111d2f34
 }