image_pruner.go 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  1. package compose
  2. import (
  3. "context"
  4. "fmt"
  5. "sort"
  6. "sync"
  7. "github.com/compose-spec/compose-go/types"
  8. "github.com/distribution/distribution/v3/reference"
  9. moby "github.com/docker/docker/api/types"
  10. "github.com/docker/docker/api/types/filters"
  11. "github.com/docker/docker/client"
  12. "github.com/docker/docker/errdefs"
  13. "golang.org/x/sync/errgroup"
  14. "github.com/docker/compose/v2/pkg/api"
  15. )
  16. // ImagePruneMode controls how aggressively images associated with the project
  17. // are removed from the engine.
  18. type ImagePruneMode string
  19. const (
  20. // ImagePruneNone indicates that no project images should be removed.
  21. ImagePruneNone ImagePruneMode = ""
  22. // ImagePruneLocal indicates that only images built locally by Compose
  23. // should be removed.
  24. ImagePruneLocal ImagePruneMode = "local"
  25. // ImagePruneAll indicates that all project-associated images, including
  26. // remote images should be removed.
  27. ImagePruneAll ImagePruneMode = "all"
  28. )
  29. // ImagePruneOptions controls the behavior of image pruning.
  30. type ImagePruneOptions struct {
  31. Mode ImagePruneMode
  32. // RemoveOrphans will result in the removal of images that were built for
  33. // the project regardless of whether they are for a known service if true.
  34. RemoveOrphans bool
  35. }
  36. // ImagePruner handles image removal during Compose `down` operations.
  37. type ImagePruner struct {
  38. client client.ImageAPIClient
  39. project *types.Project
  40. }
  41. // NewImagePruner creates an ImagePruner object for a project.
  42. func NewImagePruner(imageClient client.ImageAPIClient, project *types.Project) *ImagePruner {
  43. return &ImagePruner{
  44. client: imageClient,
  45. project: project,
  46. }
  47. }
  48. // ImagesToPrune returns the set of images that should be removed.
  49. func (p *ImagePruner) ImagesToPrune(ctx context.Context, opts ImagePruneOptions) ([]string, error) {
  50. if opts.Mode == ImagePruneNone {
  51. return nil, nil
  52. } else if opts.Mode != ImagePruneLocal && opts.Mode != ImagePruneAll {
  53. return nil, fmt.Errorf("unsupported image prune mode: %s", opts.Mode)
  54. }
  55. var images []string
  56. if opts.Mode == ImagePruneAll {
  57. namedImages, err := p.namedImages(ctx)
  58. if err != nil {
  59. return nil, err
  60. }
  61. images = append(images, namedImages...)
  62. }
  63. projectImages, err := p.builtImagesForProject(ctx)
  64. if err != nil {
  65. return nil, err
  66. }
  67. for _, img := range projectImages {
  68. if len(img.RepoTags) == 0 {
  69. // currently, we're only removing the tagged references, but
  70. // if we start removing the dangling images and grouping by
  71. // service, we can remove this (and should rely on `Image::ID`)
  72. continue
  73. }
  74. removeImage := opts.RemoveOrphans
  75. if !removeImage {
  76. service, err := p.project.GetService(img.Labels[api.ServiceLabel])
  77. if err == nil && (opts.Mode == ImagePruneAll || service.Image == "") {
  78. removeImage = true
  79. }
  80. }
  81. if removeImage {
  82. images = append(images, img.RepoTags[0])
  83. }
  84. }
  85. fallbackImages, err := p.unlabeledLocalImages(ctx)
  86. if err != nil {
  87. return nil, err
  88. }
  89. images = append(images, fallbackImages...)
  90. images = normalizeAndDedupeImages(images)
  91. return images, nil
  92. }
  93. func (p *ImagePruner) builtImagesForProject(ctx context.Context) ([]moby.ImageSummary, error) {
  94. imageListOpts := moby.ImageListOptions{
  95. Filters: filters.NewArgs(
  96. projectFilter(p.project.Name),
  97. // TODO(milas): we should really clean up the dangling images as
  98. // well (historically we have NOT); need to refactor this to handle
  99. // it gracefully without producing confusing CLI output, i.e. we
  100. // do not want to print out a bunch of untagged/dangling image IDs,
  101. // they should be grouped into a logical operation for the relevant
  102. // service
  103. filters.Arg("dangling", "false"),
  104. ),
  105. }
  106. projectImages, err := p.client.ImageList(ctx, imageListOpts)
  107. if err != nil {
  108. return nil, err
  109. }
  110. return projectImages, nil
  111. }
  112. func (p *ImagePruner) namedImages(ctx context.Context) ([]string, error) {
  113. var images []string
  114. for _, service := range p.project.Services {
  115. if service.Image == "" {
  116. continue
  117. }
  118. images = append(images, service.Image)
  119. }
  120. return p.filterImagesByExistence(ctx, images)
  121. }
  122. func (p *ImagePruner) filterImagesByExistence(ctx context.Context, imageNames []string) ([]string, error) {
  123. var mu sync.Mutex
  124. var ret []string
  125. eg, ctx := errgroup.WithContext(ctx)
  126. for _, img := range imageNames {
  127. img := img
  128. eg.Go(func() error {
  129. _, _, err := p.client.ImageInspectWithRaw(ctx, img)
  130. if errdefs.IsNotFound(err) {
  131. // err on the side of caution: only skip if we successfully
  132. // queried the API and got back a definitive "not exists"
  133. return nil
  134. }
  135. mu.Lock()
  136. defer mu.Unlock()
  137. ret = append(ret, img)
  138. return nil
  139. })
  140. }
  141. if err := eg.Wait(); err != nil {
  142. return nil, err
  143. }
  144. return ret, nil
  145. }
  146. func (p *ImagePruner) unlabeledLocalImages(ctx context.Context) ([]string, error) {
  147. var images []string
  148. for _, service := range p.project.Services {
  149. if service.Image != "" {
  150. continue
  151. }
  152. img := api.GetImageNameOrDefault(service, p.project.Name)
  153. images = append(images, img)
  154. }
  155. return p.filterImagesByExistence(ctx, images)
  156. }
  157. func normalizeAndDedupeImages(images []string) []string {
  158. seen := make(map[string]struct{}, len(images))
  159. for _, img := range images {
  160. // since some references come from user input (service.image) and some
  161. // come from the engine API, we standardize them, opting for the
  162. // familiar name format since they'll also be displayed in the CLI
  163. ref, err := reference.ParseNormalizedNamed(img)
  164. if err == nil {
  165. ref = reference.TagNameOnly(ref)
  166. img = reference.FamiliarString(ref)
  167. }
  168. seen[img] = struct{}{}
  169. }
  170. ret := make([]string, 0, len(seen))
  171. for v := range seen {
  172. ret = append(ret, v)
  173. }
  174. sort.Strings(ret)
  175. return ret
  176. }