github.com/Heebron/moby@v0.0.0-20221111184709-6eab4f55faf7/daemon/images/image_delete.go (about)

     1  package images // import "github.com/docker/docker/daemon/images"
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"strings"
     7  	"time"
     8  
     9  	"github.com/docker/distribution/reference"
    10  	"github.com/docker/docker/api/types"
    11  	imagetypes "github.com/docker/docker/api/types/image"
    12  	"github.com/docker/docker/container"
    13  	"github.com/docker/docker/errdefs"
    14  	"github.com/docker/docker/image"
    15  	"github.com/docker/docker/pkg/stringid"
    16  	"github.com/pkg/errors"
    17  )
    18  
    19  type conflictType int
    20  
    21  const (
    22  	conflictDependentChild conflictType = 1 << iota
    23  	conflictRunningContainer
    24  	conflictActiveReference
    25  	conflictStoppedContainer
    26  	conflictHard = conflictDependentChild | conflictRunningContainer
    27  	conflictSoft = conflictActiveReference | conflictStoppedContainer
    28  )
    29  
    30  // ImageDelete deletes the image referenced by the given imageRef from this
    31  // daemon. The given imageRef can be an image ID, ID prefix, or a repository
    32  // reference (with an optional tag or digest, defaulting to the tag name
    33  // "latest"). There is differing behavior depending on whether the given
    34  // imageRef is a repository reference or not.
    35  //
    36  // If the given imageRef is a repository reference then that repository
    37  // reference will be removed. However, if there exists any containers which
    38  // were created using the same image reference then the repository reference
    39  // cannot be removed unless either there are other repository references to the
    40  // same image or force is true. Following removal of the repository reference,
    41  // the referenced image itself will attempt to be deleted as described below
    42  // but quietly, meaning any image delete conflicts will cause the image to not
    43  // be deleted and the conflict will not be reported.
    44  //
    45  // There may be conflicts preventing deletion of an image and these conflicts
    46  // are divided into two categories grouped by their severity:
    47  //
    48  // Hard Conflict:
    49  //   - a pull or build using the image.
    50  //   - any descendant image.
    51  //   - any running container using the image.
    52  //
    53  // Soft Conflict:
    54  //   - any stopped container using the image.
    55  //   - any repository tag or digest references to the image.
    56  //
    57  // The image cannot be removed if there are any hard conflicts and can be
    58  // removed if there are soft conflicts only if force is true.
    59  //
    60  // If prune is true, ancestor images will each attempt to be deleted quietly,
    61  // meaning any delete conflicts will cause the image to not be deleted and the
    62  // conflict will not be reported.
    63  func (i *ImageService) ImageDelete(ctx context.Context, imageRef string, force, prune bool) ([]types.ImageDeleteResponseItem, error) {
    64  	start := time.Now()
    65  	records := []types.ImageDeleteResponseItem{}
    66  
    67  	img, err := i.GetImage(ctx, imageRef, imagetypes.GetImageOpts{})
    68  	if err != nil {
    69  		return nil, err
    70  	}
    71  
    72  	imgID := img.ID()
    73  	repoRefs := i.referenceStore.References(imgID.Digest())
    74  
    75  	using := func(c *container.Container) bool {
    76  		return c.ImageID == imgID
    77  	}
    78  
    79  	var removedRepositoryRef bool
    80  	if !isImageIDPrefix(imgID.String(), imageRef) {
    81  		// A repository reference was given and should be removed
    82  		// first. We can only remove this reference if either force is
    83  		// true, there are multiple repository references to this
    84  		// image, or there are no containers using the given reference.
    85  		if !force && isSingleReference(repoRefs) {
    86  			if ctr := i.containers.First(using); ctr != nil {
    87  				// If we removed the repository reference then
    88  				// this image would remain "dangling" and since
    89  				// we really want to avoid that the client must
    90  				// explicitly force its removal.
    91  				err := errors.Errorf("conflict: unable to remove repository reference %q (must force) - container %s is using its referenced image %s", imageRef, stringid.TruncateID(ctr.ID), stringid.TruncateID(imgID.String()))
    92  				return nil, errdefs.Conflict(err)
    93  			}
    94  		}
    95  
    96  		parsedRef, err := reference.ParseNormalizedNamed(imageRef)
    97  		if err != nil {
    98  			return nil, err
    99  		}
   100  
   101  		parsedRef, err = i.removeImageRef(parsedRef)
   102  		if err != nil {
   103  			return nil, err
   104  		}
   105  
   106  		untaggedRecord := types.ImageDeleteResponseItem{Untagged: reference.FamiliarString(parsedRef)}
   107  
   108  		i.LogImageEvent(imgID.String(), imgID.String(), "untag")
   109  		records = append(records, untaggedRecord)
   110  
   111  		repoRefs = i.referenceStore.References(imgID.Digest())
   112  
   113  		// If a tag reference was removed and the only remaining
   114  		// references to the same repository are digest references,
   115  		// then clean up those digest references.
   116  		if _, isCanonical := parsedRef.(reference.Canonical); !isCanonical {
   117  			foundRepoTagRef := false
   118  			for _, repoRef := range repoRefs {
   119  				if _, repoRefIsCanonical := repoRef.(reference.Canonical); !repoRefIsCanonical && parsedRef.Name() == repoRef.Name() {
   120  					foundRepoTagRef = true
   121  					break
   122  				}
   123  			}
   124  			if !foundRepoTagRef {
   125  				// Remove canonical references from same repository
   126  				var remainingRefs []reference.Named
   127  				for _, repoRef := range repoRefs {
   128  					if _, repoRefIsCanonical := repoRef.(reference.Canonical); repoRefIsCanonical && parsedRef.Name() == repoRef.Name() {
   129  						if _, err := i.removeImageRef(repoRef); err != nil {
   130  							return records, err
   131  						}
   132  
   133  						untaggedRecord := types.ImageDeleteResponseItem{Untagged: reference.FamiliarString(repoRef)}
   134  						records = append(records, untaggedRecord)
   135  					} else {
   136  						remainingRefs = append(remainingRefs, repoRef)
   137  					}
   138  				}
   139  				repoRefs = remainingRefs
   140  			}
   141  		}
   142  
   143  		// If it has remaining references then the untag finished the remove
   144  		if len(repoRefs) > 0 {
   145  			return records, nil
   146  		}
   147  
   148  		removedRepositoryRef = true
   149  	} else {
   150  		// If an ID reference was given AND there is at most one tag
   151  		// reference to the image AND all references are within one
   152  		// repository, then remove all references.
   153  		if isSingleReference(repoRefs) {
   154  			c := conflictHard
   155  			if !force {
   156  				c |= conflictSoft &^ conflictActiveReference
   157  			}
   158  			if conflict := i.checkImageDeleteConflict(imgID, c); conflict != nil {
   159  				return nil, conflict
   160  			}
   161  
   162  			for _, repoRef := range repoRefs {
   163  				parsedRef, err := i.removeImageRef(repoRef)
   164  				if err != nil {
   165  					return nil, err
   166  				}
   167  
   168  				untaggedRecord := types.ImageDeleteResponseItem{Untagged: reference.FamiliarString(parsedRef)}
   169  
   170  				i.LogImageEvent(imgID.String(), imgID.String(), "untag")
   171  				records = append(records, untaggedRecord)
   172  			}
   173  		}
   174  	}
   175  
   176  	if err := i.imageDeleteHelper(imgID, &records, force, prune, removedRepositoryRef); err != nil {
   177  		return nil, err
   178  	}
   179  
   180  	imageActions.WithValues("delete").UpdateSince(start)
   181  
   182  	return records, nil
   183  }
   184  
   185  // isSingleReference returns true when all references are from one repository
   186  // and there is at most one tag. Returns false for empty input.
   187  func isSingleReference(repoRefs []reference.Named) bool {
   188  	if len(repoRefs) <= 1 {
   189  		return len(repoRefs) == 1
   190  	}
   191  	var singleRef reference.Named
   192  	canonicalRefs := map[string]struct{}{}
   193  	for _, repoRef := range repoRefs {
   194  		if _, isCanonical := repoRef.(reference.Canonical); isCanonical {
   195  			canonicalRefs[repoRef.Name()] = struct{}{}
   196  		} else if singleRef == nil {
   197  			singleRef = repoRef
   198  		} else {
   199  			return false
   200  		}
   201  	}
   202  	if singleRef == nil {
   203  		// Just use first canonical ref
   204  		singleRef = repoRefs[0]
   205  	}
   206  	_, ok := canonicalRefs[singleRef.Name()]
   207  	return len(canonicalRefs) == 1 && ok
   208  }
   209  
   210  // isImageIDPrefix returns whether the given possiblePrefix is a prefix of the
   211  // given imageID.
   212  func isImageIDPrefix(imageID, possiblePrefix string) bool {
   213  	if strings.HasPrefix(imageID, possiblePrefix) {
   214  		return true
   215  	}
   216  
   217  	if i := strings.IndexRune(imageID, ':'); i >= 0 {
   218  		return strings.HasPrefix(imageID[i+1:], possiblePrefix)
   219  	}
   220  
   221  	return false
   222  }
   223  
   224  // removeImageRef attempts to parse and remove the given image reference from
   225  // this daemon's store of repository tag/digest references. The given
   226  // repositoryRef must not be an image ID but a repository name followed by an
   227  // optional tag or digest reference. If tag or digest is omitted, the default
   228  // tag is used. Returns the resolved image reference and an error.
   229  func (i *ImageService) removeImageRef(ref reference.Named) (reference.Named, error) {
   230  	ref = reference.TagNameOnly(ref)
   231  
   232  	// Ignore the boolean value returned, as far as we're concerned, this
   233  	// is an idempotent operation and it's okay if the reference didn't
   234  	// exist in the first place.
   235  	_, err := i.referenceStore.Delete(ref)
   236  
   237  	return ref, err
   238  }
   239  
   240  // removeAllReferencesToImageID attempts to remove every reference to the given
   241  // imgID from this daemon's store of repository tag/digest references. Returns
   242  // on the first encountered error. Removed references are logged to this
   243  // daemon's event service. An "Untagged" types.ImageDeleteResponseItem is added to the
   244  // given list of records.
   245  func (i *ImageService) removeAllReferencesToImageID(imgID image.ID, records *[]types.ImageDeleteResponseItem) error {
   246  	imageRefs := i.referenceStore.References(imgID.Digest())
   247  
   248  	for _, imageRef := range imageRefs {
   249  		parsedRef, err := i.removeImageRef(imageRef)
   250  		if err != nil {
   251  			return err
   252  		}
   253  
   254  		untaggedRecord := types.ImageDeleteResponseItem{Untagged: reference.FamiliarString(parsedRef)}
   255  
   256  		i.LogImageEvent(imgID.String(), imgID.String(), "untag")
   257  		*records = append(*records, untaggedRecord)
   258  	}
   259  
   260  	return nil
   261  }
   262  
   263  // ImageDeleteConflict holds a soft or hard conflict and an associated error.
   264  // Implements the error interface.
   265  type imageDeleteConflict struct {
   266  	hard    bool
   267  	used    bool
   268  	imgID   image.ID
   269  	message string
   270  }
   271  
   272  func (idc *imageDeleteConflict) Error() string {
   273  	var forceMsg string
   274  	if idc.hard {
   275  		forceMsg = "cannot be forced"
   276  	} else {
   277  		forceMsg = "must be forced"
   278  	}
   279  
   280  	return fmt.Sprintf("conflict: unable to delete %s (%s) - %s", stringid.TruncateID(idc.imgID.String()), forceMsg, idc.message)
   281  }
   282  
   283  func (idc *imageDeleteConflict) Conflict() {}
   284  
   285  // imageDeleteHelper attempts to delete the given image from this daemon. If
   286  // the image has any hard delete conflicts (child images or running containers
   287  // using the image) then it cannot be deleted. If the image has any soft delete
   288  // conflicts (any tags/digests referencing the image or any stopped container
   289  // using the image) then it can only be deleted if force is true. If the delete
   290  // succeeds and prune is true, the parent images are also deleted if they do
   291  // not have any soft or hard delete conflicts themselves. Any deleted images
   292  // and untagged references are appended to the given records. If any error or
   293  // conflict is encountered, it will be returned immediately without deleting
   294  // the image. If quiet is true, any encountered conflicts will be ignored and
   295  // the function will return nil immediately without deleting the image.
   296  func (i *ImageService) imageDeleteHelper(imgID image.ID, records *[]types.ImageDeleteResponseItem, force, prune, quiet bool) error {
   297  	// First, determine if this image has any conflicts. Ignore soft conflicts
   298  	// if force is true.
   299  	c := conflictHard
   300  	if !force {
   301  		c |= conflictSoft
   302  	}
   303  	if conflict := i.checkImageDeleteConflict(imgID, c); conflict != nil {
   304  		if quiet && (!i.imageIsDangling(imgID) || conflict.used) {
   305  			// Ignore conflicts UNLESS the image is "dangling" or not being used in
   306  			// which case we want the user to know.
   307  			return nil
   308  		}
   309  
   310  		// There was a conflict and it's either a hard conflict OR we are not
   311  		// forcing deletion on soft conflicts.
   312  		return conflict
   313  	}
   314  
   315  	parent, err := i.imageStore.GetParent(imgID)
   316  	if err != nil {
   317  		// There may be no parent
   318  		parent = ""
   319  	}
   320  
   321  	// Delete all repository tag/digest references to this image.
   322  	if err := i.removeAllReferencesToImageID(imgID, records); err != nil {
   323  		return err
   324  	}
   325  
   326  	removedLayers, err := i.imageStore.Delete(imgID)
   327  	if err != nil {
   328  		return err
   329  	}
   330  
   331  	i.LogImageEvent(imgID.String(), imgID.String(), "delete")
   332  	*records = append(*records, types.ImageDeleteResponseItem{Deleted: imgID.String()})
   333  	for _, removedLayer := range removedLayers {
   334  		*records = append(*records, types.ImageDeleteResponseItem{Deleted: removedLayer.ChainID.String()})
   335  	}
   336  
   337  	if !prune || parent == "" {
   338  		return nil
   339  	}
   340  
   341  	// We need to prune the parent image. This means delete it if there are
   342  	// no tags/digests referencing it and there are no containers using it (
   343  	// either running or stopped).
   344  	// Do not force prunings, but do so quietly (stopping on any encountered
   345  	// conflicts).
   346  	return i.imageDeleteHelper(parent, records, false, true, true)
   347  }
   348  
   349  // checkImageDeleteConflict determines whether there are any conflicts
   350  // preventing deletion of the given image from this daemon. A hard conflict is
   351  // any image which has the given image as a parent or any running container
   352  // using the image. A soft conflict is any tags/digest referencing the given
   353  // image or any stopped container using the image. If ignoreSoftConflicts is
   354  // true, this function will not check for soft conflict conditions.
   355  func (i *ImageService) checkImageDeleteConflict(imgID image.ID, mask conflictType) *imageDeleteConflict {
   356  	// Check if the image has any descendant images.
   357  	if mask&conflictDependentChild != 0 && len(i.imageStore.Children(imgID)) > 0 {
   358  		return &imageDeleteConflict{
   359  			hard:    true,
   360  			imgID:   imgID,
   361  			message: "image has dependent child images",
   362  		}
   363  	}
   364  
   365  	if mask&conflictRunningContainer != 0 {
   366  		// Check if any running container is using the image.
   367  		running := func(c *container.Container) bool {
   368  			return c.ImageID == imgID && c.IsRunning()
   369  		}
   370  		if ctr := i.containers.First(running); ctr != nil {
   371  			return &imageDeleteConflict{
   372  				imgID:   imgID,
   373  				hard:    true,
   374  				used:    true,
   375  				message: fmt.Sprintf("image is being used by running container %s", stringid.TruncateID(ctr.ID)),
   376  			}
   377  		}
   378  	}
   379  
   380  	// Check if any repository tags/digest reference this image.
   381  	if mask&conflictActiveReference != 0 && len(i.referenceStore.References(imgID.Digest())) > 0 {
   382  		return &imageDeleteConflict{
   383  			imgID:   imgID,
   384  			message: "image is referenced in multiple repositories",
   385  		}
   386  	}
   387  
   388  	if mask&conflictStoppedContainer != 0 {
   389  		// Check if any stopped containers reference this image.
   390  		stopped := func(c *container.Container) bool {
   391  			return !c.IsRunning() && c.ImageID == imgID
   392  		}
   393  		if ctr := i.containers.First(stopped); ctr != nil {
   394  			return &imageDeleteConflict{
   395  				imgID:   imgID,
   396  				used:    true,
   397  				message: fmt.Sprintf("image is being used by stopped container %s", stringid.TruncateID(ctr.ID)),
   398  			}
   399  		}
   400  	}
   401  
   402  	return nil
   403  }
   404  
   405  // imageIsDangling returns whether the given image is "dangling" which means
   406  // that there are no repository references to the given image and it has no
   407  // child images.
   408  func (i *ImageService) imageIsDangling(imgID image.ID) bool {
   409  	return !(len(i.referenceStore.References(imgID.Digest())) > 0 || len(i.imageStore.Children(imgID)) > 0)
   410  }