|
| 1 | +package imageutils |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "errors" |
| 6 | + "fmt" |
| 7 | + |
| 8 | + "github.com/containers/common/pkg/retry" |
| 9 | + "github.com/containers/image/v5/image" |
| 10 | + "github.com/containers/image/v5/manifest" |
| 11 | + "github.com/containers/image/v5/types" |
| 12 | + "github.com/opencontainers/go-digest" |
| 13 | +) |
| 14 | + |
| 15 | +// GetImage retrieves a container image by name using the provided system context. |
| 16 | +// The returned ImageSource must be closed by the caller. |
| 17 | +func GetImage(ctx context.Context, sysCtx *types.SystemContext, imageName string, retryOpts *retry.RetryOptions) (types.Image, types.ImageSource, error) { |
| 18 | + ref, err := ParseImageName(imageName) |
| 19 | + if err != nil { |
| 20 | + return nil, nil, fmt.Errorf("error parsing image name %q: %w", imageName, err) |
| 21 | + } |
| 22 | + |
| 23 | + source, err := GetImageSourceFromReference(ctx, sysCtx, ref, retryOpts) |
| 24 | + if err != nil { |
| 25 | + return nil, nil, fmt.Errorf("error getting image source for %s: %w", imageName, err) |
| 26 | + } |
| 27 | + |
| 28 | + img, err := image.FromUnparsedImage(ctx, sysCtx, image.UnparsedInstance(source, nil)) |
| 29 | + if err != nil { |
| 30 | + return nil, nil, errors.Join(err, source.Close()) |
| 31 | + } |
| 32 | + |
| 33 | + return img, source, nil |
| 34 | +} |
| 35 | + |
| 36 | +// GetDigestFromImage computes and returns the manifest digest for the given image. |
| 37 | +// It includes retry logic to handle transient network errors. |
| 38 | +func GetDigestFromImage(ctx context.Context, image types.Image, retryOpts *retry.RetryOptions) (digest.Digest, error) { |
| 39 | + var ( |
| 40 | + rawManifest []byte |
| 41 | + err error |
| 42 | + ) |
| 43 | + if err = retry.IfNecessary(ctx, func() error { |
| 44 | + rawManifest, _, err = image.Manifest(ctx) |
| 45 | + return err |
| 46 | + }, retryOpts); err != nil { |
| 47 | + return "", fmt.Errorf("error retrieving manifest for image: %w", err) |
| 48 | + } |
| 49 | + return manifest.Digest(rawManifest) |
| 50 | +} |
| 51 | + |
| 52 | +// GetInspectInfoFromImage retrieves detailed inspection information for the given image. |
| 53 | +// It includes retry logic to handle transient network errors. |
| 54 | +func GetInspectInfoFromImage(ctx context.Context, image types.Image, retryOpts *retry.RetryOptions) (*types.ImageInspectInfo, error) { |
| 55 | + var ( |
| 56 | + imgInspect *types.ImageInspectInfo |
| 57 | + err error |
| 58 | + ) |
| 59 | + return imgInspect, retry.IfNecessary(ctx, func() error { |
| 60 | + imgInspect, err = image.Inspect(ctx) |
| 61 | + return err |
| 62 | + }, retryOpts) |
| 63 | +} |
| 64 | + |
| 65 | +// BulkInspectResult represents the result of inspecting a single image in a bulk operation. |
| 66 | +// It contains either the inspection information or an error if the inspection failed. |
| 67 | +type BulkInspectResult struct { |
| 68 | + Image string |
| 69 | + InspectInfo *types.ImageInspectInfo |
| 70 | + Error error |
| 71 | +} |
| 72 | + |
| 73 | +// BulkInspectorOptions configures the behavior of a BulkInspector. |
| 74 | +// RetryOpts specifies retry behavior for transient network errors. |
| 75 | +// FailOnErr determines whether to return immediately on the first error (true) |
| 76 | +// or to continue inspecting all images and collect all results (false). |
| 77 | +// Count limits the number of concurrent image inspections. If Count is 0 or |
| 78 | +// negative, no limit is applied and all images are inspected concurrently. |
| 79 | +type BulkInspectorOptions struct { |
| 80 | + RetryOpts *retry.RetryOptions |
| 81 | + FailOnErr bool |
| 82 | + Count int |
| 83 | +} |
| 84 | + |
| 85 | +// BulkInspector performs concurrent image inspections with optional rate limiting |
| 86 | +// and configurable error handling. |
| 87 | +type BulkInspector struct { |
| 88 | + retryOpts *retry.RetryOptions |
| 89 | + failOnErr bool |
| 90 | + count int |
| 91 | +} |
| 92 | + |
| 93 | +// NewBulkInspector creates a new BulkInspector with the provided options. |
| 94 | +// If opts is nil or RetryOpts is nil, sensible defaults are applied: |
| 95 | +// - RetryOpts.MaxRetry defaults to 2 |
| 96 | +// - FailOnErr defaults to false |
| 97 | +// - Count defaults to 0 (unlimited concurrency) |
| 98 | +func NewBulkInspector(opts *BulkInspectorOptions) *BulkInspector { |
| 99 | + if opts == nil { |
| 100 | + opts = &BulkInspectorOptions{} |
| 101 | + } |
| 102 | + if opts.RetryOpts == nil { |
| 103 | + opts.RetryOpts = &retry.RetryOptions{MaxRetry: 2} |
| 104 | + } |
| 105 | + return &BulkInspector{ |
| 106 | + retryOpts: opts.RetryOpts, |
| 107 | + failOnErr: opts.FailOnErr, |
| 108 | + count: opts.Count, |
| 109 | + } |
| 110 | +} |
| 111 | + |
| 112 | +// Inspect concurrently inspects multiple container images and returns their inspection results. |
| 113 | +// The inspection is performed with optional rate limiting based on the Count configuration. |
| 114 | +// If FailOnErr is true, the method returns immediately upon encountering the first error. |
| 115 | +// Otherwise, it inspects all images and returns results for all of them, with errors |
| 116 | +// recorded in individual BulkInspectResult entries. |
| 117 | +// Results are returned in completion order, not input order. Use the Image field to |
| 118 | +// correlate results with the input image names. |
| 119 | +func (i *BulkInspector) Inspect(ctx context.Context, sysCtx *types.SystemContext, images ...string) ([]BulkInspectResult, error) { |
| 120 | + imagesCount := len(images) |
| 121 | + if imagesCount == 0 { |
| 122 | + return []BulkInspectResult{}, nil |
| 123 | + } |
| 124 | + |
| 125 | + results := make(chan BulkInspectResult, imagesCount) |
| 126 | + var rateLimiterChannel chan struct{} |
| 127 | + if i.count > 0 { |
| 128 | + rateLimiterChannel = make(chan struct{}, i.count) |
| 129 | + } else { |
| 130 | + // No rate limiting - use a channel that never blocks |
| 131 | + rateLimiterChannel = make(chan struct{}, imagesCount) |
| 132 | + } |
| 133 | + |
| 134 | + childContext, cancel := context.WithCancel(ctx) |
| 135 | + // The deferred cancellation of the context will kill the tasks when exiting |
| 136 | + // Useful in case of error |
| 137 | + defer cancel() |
| 138 | + for _, imageName := range images { |
| 139 | + go func(img string) { |
| 140 | + select { |
| 141 | + case rateLimiterChannel <- struct{}{}: |
| 142 | + defer func() { <-rateLimiterChannel }() |
| 143 | + |
| 144 | + inspectInfo, err := i.inspectImage(childContext, sysCtx, img) |
| 145 | + results <- BulkInspectResult{Image: img, InspectInfo: inspectInfo, Error: err} |
| 146 | + case <-childContext.Done(): |
| 147 | + results <- BulkInspectResult{Error: childContext.Err(), Image: img, InspectInfo: nil} |
| 148 | + } |
| 149 | + }(imageName) |
| 150 | + } |
| 151 | + |
| 152 | + inspectInfos := make([]BulkInspectResult, imagesCount) |
| 153 | + for idx := range imagesCount { |
| 154 | + res := <-results |
| 155 | + if res.Error != nil && i.failOnErr { |
| 156 | + return nil, res.Error |
| 157 | + } |
| 158 | + inspectInfos[idx] = res |
| 159 | + } |
| 160 | + return inspectInfos, nil |
| 161 | +} |
| 162 | + |
| 163 | +func (i *BulkInspector) inspectImage(ctx context.Context, sysCtx *types.SystemContext, image string) (inspectInfo *types.ImageInspectInfo, err error) { |
| 164 | + img, imgSource, err := GetImage(ctx, sysCtx, image, i.retryOpts) |
| 165 | + if err != nil { |
| 166 | + return nil, err |
| 167 | + } |
| 168 | + defer func() { |
| 169 | + if imgSourceErr := imgSource.Close(); imgSourceErr != nil { |
| 170 | + err = errors.Join(err, imgSourceErr) |
| 171 | + } |
| 172 | + }() |
| 173 | + return GetInspectInfoFromImage(ctx, img, i.retryOpts) |
| 174 | +} |
0 commit comments