github.com/gravitational/moby@v1.13.1/daemon/image_delete.go (about)

     1  package daemon
     2  
     3  import (
     4  	"fmt"
     5  	"strings"
     6  	"time"
     7  
     8  	"github.com/docker/docker/api/errors"
     9  	"github.com/docker/docker/api/types"
    10  	"github.com/docker/docker/container"
    11  	"github.com/docker/docker/image"
    12  	"github.com/docker/docker/pkg/stringid"
    13  	"github.com/docker/docker/reference"
    14  )
    15  
    16  type conflictType int
    17  
    18  const (
    19  	conflictDependentChild conflictType = (1 << iota)
    20  	conflictRunningContainer
    21  	conflictActiveReference
    22  	conflictStoppedContainer
    23  	conflictHard = conflictDependentChild | conflictRunningContainer
    24  	conflictSoft = conflictActiveReference | conflictStoppedContainer
    25  )
    26  
    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.
    32  //
    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.
    41  //
    42  // There may be conflicts preventing deletion of an image and these conflicts
    43  // are divided into two categories grouped by their severity:
    44  //
    45  // Hard Conflict:
    46  // 	- a pull or build using the image.
    47  // 	- any descendant image.
    48  // 	- any running container using the image.
    49  //
    50  // Soft Conflict:
    51  // 	- any stopped container using the image.
    52  // 	- any repository tag or digest references to the image.
    53  //
    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.
    56  //
    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.
    60  //
    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.ImageDelete, error) {
    65  	start := time.Now()
    66  	records := []types.ImageDelete{}
    67  
    68  	imgID, err := daemon.GetImageID(imageRef)
    69  	if err != nil {
    70  		return nil, daemon.imageNotExistToErrcode(err)
    71  	}
    72  
    73  	repoRefs := daemon.referenceStore.References(imgID.Digest())
    74  
    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)
    89  			}
    90  		}
    91  
    92  		parsedRef, err := reference.ParseNamed(imageRef)
    93  		if err != nil {
    94  			return nil, err
    95  		}
    96  
    97  		parsedRef, err = daemon.removeImageRef(parsedRef)
    98  		if err != nil {
    99  			return nil, err
   100  		}
   101  
   102  		untaggedRecord := types.ImageDelete{Untagged: parsedRef.String()}
   103  
   104  		daemon.LogImageEvent(imgID.String(), imgID.String(), "untag")
   105  		records = append(records, untaggedRecord)
   106  
   107  		repoRefs = daemon.referenceStore.References(imgID.Digest())
   108  
   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
   117  					break
   118  				}
   119  			}
   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(repoRef); err != nil {
   126  							return records, err
   127  						}
   128  
   129  						untaggedRecord := types.ImageDelete{Untagged: repoRef.String()}
   130  						records = append(records, untaggedRecord)
   131  					} else {
   132  						remainingRefs = append(remainingRefs, repoRef)
   133  
   134  					}
   135  				}
   136  				repoRefs = remainingRefs
   137  			}
   138  		}
   139  
   140  		// If it has remaining references then the untag finished the remove
   141  		if len(repoRefs) > 0 {
   142  			return records, nil
   143  		}
   144  
   145  		removedRepositoryRef = true
   146  	} else {
   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) {
   151  			c := conflictHard
   152  			if !force {
   153  				c |= conflictSoft &^ conflictActiveReference
   154  			}
   155  			if conflict := daemon.checkImageDeleteConflict(imgID, c); conflict != nil {
   156  				return nil, conflict
   157  			}
   158  
   159  			for _, repoRef := range repoRefs {
   160  				parsedRef, err := daemon.removeImageRef(repoRef)
   161  				if err != nil {
   162  					return nil, err
   163  				}
   164  
   165  				untaggedRecord := types.ImageDelete{Untagged: parsedRef.String()}
   166  
   167  				daemon.LogImageEvent(imgID.String(), imgID.String(), "untag")
   168  				records = append(records, untaggedRecord)
   169  			}
   170  		}
   171  	}
   172  
   173  	if err := daemon.imageDeleteHelper(imgID, &records, force, prune, removedRepositoryRef); err != nil {
   174  		return nil, err
   175  	}
   176  
   177  	imageActions.WithValues("delete").UpdateSince(start)
   178  
   179  	return records, nil
   180  }
   181  
   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
   187  	}
   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 {
   194  			singleRef = repoRef
   195  		} else {
   196  			return false
   197  		}
   198  	}
   199  	if singleRef == nil {
   200  		// Just use first canonical ref
   201  		singleRef = repoRefs[0]
   202  	}
   203  	_, ok := canonicalRefs[singleRef.Name()]
   204  	return len(canonicalRefs) == 1 && ok
   205  }
   206  
   207  // isImageIDPrefix returns whether the given possiblePrefix is a prefix of the
   208  // given imageID.
   209  func isImageIDPrefix(imageID, possiblePrefix string) bool {
   210  	if strings.HasPrefix(imageID, possiblePrefix) {
   211  		return true
   212  	}
   213  
   214  	if i := strings.IndexRune(imageID, ':'); i >= 0 {
   215  		return strings.HasPrefix(imageID[i+1:], possiblePrefix)
   216  	}
   217  
   218  	return false
   219  }
   220  
   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
   226  	})
   227  }
   228  
   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(ref reference.Named) (reference.Named, error) {
   235  	ref = reference.WithDefaultTag(ref)
   236  	// Ignore the boolean value returned, as far as we're concerned, this
   237  	// is an idempotent operation and it's okay if the reference didn't
   238  	// exist in the first place.
   239  	_, err := daemon.referenceStore.Delete(ref)
   240  
   241  	return ref, err
   242  }
   243  
   244  // removeAllReferencesToImageID attempts to remove every reference to the given
   245  // imgID from this daemon's store of repository tag/digest references. Returns
   246  // on the first encountered error. Removed references are logged to this
   247  // daemon's event service. An "Untagged" types.ImageDelete is added to the
   248  // given list of records.
   249  func (daemon *Daemon) removeAllReferencesToImageID(imgID image.ID, records *[]types.ImageDelete) error {
   250  	imageRefs := daemon.referenceStore.References(imgID.Digest())
   251  
   252  	for _, imageRef := range imageRefs {
   253  		parsedRef, err := daemon.removeImageRef(imageRef)
   254  		if err != nil {
   255  			return err
   256  		}
   257  
   258  		untaggedRecord := types.ImageDelete{Untagged: parsedRef.String()}
   259  
   260  		daemon.LogImageEvent(imgID.String(), imgID.String(), "untag")
   261  		*records = append(*records, untaggedRecord)
   262  	}
   263  
   264  	return nil
   265  }
   266  
   267  // ImageDeleteConflict holds a soft or hard conflict and an associated error.
   268  // Implements the error interface.
   269  type imageDeleteConflict struct {
   270  	hard    bool
   271  	used    bool
   272  	imgID   image.ID
   273  	message string
   274  }
   275  
   276  func (idc *imageDeleteConflict) Error() string {
   277  	var forceMsg string
   278  	if idc.hard {
   279  		forceMsg = "cannot be forced"
   280  	} else {
   281  		forceMsg = "must be forced"
   282  	}
   283  
   284  	return fmt.Sprintf("conflict: unable to delete %s (%s) - %s", stringid.TruncateID(idc.imgID.String()), forceMsg, idc.message)
   285  }
   286  
   287  // imageDeleteHelper attempts to delete the given image from this daemon. If
   288  // the image has any hard delete conflicts (child images or running containers
   289  // using the image) then it cannot be deleted. If the image has any soft delete
   290  // conflicts (any tags/digests referencing the image or any stopped container
   291  // using the image) then it can only be deleted if force is true. If the delete
   292  // succeeds and prune is true, the parent images are also deleted if they do
   293  // not have any soft or hard delete conflicts themselves. Any deleted images
   294  // and untagged references are appended to the given records. If any error or
   295  // conflict is encountered, it will be returned immediately without deleting
   296  // the image. If quiet is true, any encountered conflicts will be ignored and
   297  // the function will return nil immediately without deleting the image.
   298  func (daemon *Daemon) imageDeleteHelper(imgID image.ID, records *[]types.ImageDelete, force, prune, quiet bool) error {
   299  	// First, determine if this image has any conflicts. Ignore soft conflicts
   300  	// if force is true.
   301  	c := conflictHard
   302  	if !force {
   303  		c |= conflictSoft
   304  	}
   305  	if conflict := daemon.checkImageDeleteConflict(imgID, c); conflict != nil {
   306  		if quiet && (!daemon.imageIsDangling(imgID) || conflict.used) {
   307  			// Ignore conflicts UNLESS the image is "dangling" or not being used in
   308  			// which case we want the user to know.
   309  			return nil
   310  		}
   311  
   312  		// There was a conflict and it's either a hard conflict OR we are not
   313  		// forcing deletion on soft conflicts.
   314  		return conflict
   315  	}
   316  
   317  	parent, err := daemon.imageStore.GetParent(imgID)
   318  	if err != nil {
   319  		// There may be no parent
   320  		parent = ""
   321  	}
   322  
   323  	// Delete all repository tag/digest references to this image.
   324  	if err := daemon.removeAllReferencesToImageID(imgID, records); err != nil {
   325  		return err
   326  	}
   327  
   328  	removedLayers, err := daemon.imageStore.Delete(imgID)
   329  	if err != nil {
   330  		return err
   331  	}
   332  
   333  	daemon.LogImageEvent(imgID.String(), imgID.String(), "delete")
   334  	*records = append(*records, types.ImageDelete{Deleted: imgID.String()})
   335  	for _, removedLayer := range removedLayers {
   336  		*records = append(*records, types.ImageDelete{Deleted: removedLayer.ChainID.String()})
   337  	}
   338  
   339  	if !prune || parent == "" {
   340  		return nil
   341  	}
   342  
   343  	// We need to prune the parent image. This means delete it if there are
   344  	// no tags/digests referencing it and there are no containers using it (
   345  	// either running or stopped).
   346  	// Do not force prunings, but do so quietly (stopping on any encountered
   347  	// conflicts).
   348  	return daemon.imageDeleteHelper(parent, records, false, true, true)
   349  }
   350  
   351  // checkImageDeleteConflict determines whether there are any conflicts
   352  // preventing deletion of the given image from this daemon. A hard conflict is
   353  // any image which has the given image as a parent or any running container
   354  // using the image. A soft conflict is any tags/digest referencing the given
   355  // image or any stopped container using the image. If ignoreSoftConflicts is
   356  // true, this function will not check for soft conflict conditions.
   357  func (daemon *Daemon) checkImageDeleteConflict(imgID image.ID, mask conflictType) *imageDeleteConflict {
   358  	// Check if the image has any descendant images.
   359  	if mask&conflictDependentChild != 0 && len(daemon.imageStore.Children(imgID)) > 0 {
   360  		return &imageDeleteConflict{
   361  			hard:    true,
   362  			imgID:   imgID,
   363  			message: "image has dependent child images",
   364  		}
   365  	}
   366  
   367  	if mask&conflictRunningContainer != 0 {
   368  		// Check if any running container is using the image.
   369  		running := func(c *container.Container) bool {
   370  			return c.IsRunning() && c.ImageID == imgID
   371  		}
   372  		if container := daemon.containers.First(running); container != nil {
   373  			return &imageDeleteConflict{
   374  				imgID:   imgID,
   375  				hard:    true,
   376  				used:    true,
   377  				message: fmt.Sprintf("image is being used by running container %s", stringid.TruncateID(container.ID)),
   378  			}
   379  		}
   380  	}
   381  
   382  	// Check if any repository tags/digest reference this image.
   383  	if mask&conflictActiveReference != 0 && len(daemon.referenceStore.References(imgID.Digest())) > 0 {
   384  		return &imageDeleteConflict{
   385  			imgID:   imgID,
   386  			message: "image is referenced in multiple repositories",
   387  		}
   388  	}
   389  
   390  	if mask&conflictStoppedContainer != 0 {
   391  		// Check if any stopped containers reference this image.
   392  		stopped := func(c *container.Container) bool {
   393  			return !c.IsRunning() && c.ImageID == imgID
   394  		}
   395  		if container := daemon.containers.First(stopped); container != nil {
   396  			return &imageDeleteConflict{
   397  				imgID:   imgID,
   398  				used:    true,
   399  				message: fmt.Sprintf("image is being used by stopped container %s", stringid.TruncateID(container.ID)),
   400  			}
   401  		}
   402  	}
   403  
   404  	return nil
   405  }
   406  
   407  // imageIsDangling returns whether the given image is "dangling" which means
   408  // that there are no repository references to the given image and it has no
   409  // child images.
   410  func (daemon *Daemon) imageIsDangling(imgID image.ID) bool {
   411  	return !(len(daemon.referenceStore.References(imgID.Digest())) > 0 || len(daemon.imageStore.Children(imgID)) > 0)
   412  }