Debian Codegraph @

buildkit/cache/remotecache/s3/s3.go

raw
1 package s3
2
3 import (
4 "bytes"
5 "context"
6 "encoding/json"
7 "fmt"
8 "io"
9 "os"
10 "strconv"
11 "strings"
12 "time"
13
14 "github.com/aws/aws-sdk-go-v2/aws"
15 aws_config "github.com/aws/aws-sdk-go-v2/config"
16 "github.com/aws/aws-sdk-go-v2/credentials"
17 "github.com/aws/aws-sdk-go-v2/feature/s3/manager"
18 "github.com/aws/aws-sdk-go-v2/service/s3"
19 s3types "github.com/aws/aws-sdk-go-v2/service/s3/types"
20 "github.com/containerd/containerd/v2/core/content"
21 "github.com/containerd/containerd/v2/pkg/labels"
22 "github.com/moby/buildkit/cache/remotecache"
23 v1 "github.com/moby/buildkit/cache/remotecache/v1"
24 "github.com/moby/buildkit/session"
25 "github.com/moby/buildkit/solver"
26 "github.com/moby/buildkit/util/compression"
27 "github.com/moby/buildkit/util/progress"
28 "github.com/moby/buildkit/worker"
29 digest "github.com/opencontainers/go-digest"
30 ocispecs "github.com/opencontainers/image-spec/specs-go/v1"
31 "github.com/pkg/errors"
32 "golang.org/x/sync/errgroup"
33 )
34
35 const (
36 attrBucket = "bucket"
37 attrRegion = "region"
38 attrPrefix = "prefix"
39 attrManifestsPrefix = "manifests_prefix"
40 attrBlobsPrefix = "blobs_prefix"
41 attrName = "name"
42 attrTouchRefresh = "touch_refresh"
43 attrEndpointURL = "endpoint_url"
44 attrAccessKeyID = "access_key_id"
45 attrSecretAccessKey = "secret_access_key"
46 attrSessionToken = "session_token"
47 attrUsePathStyle = "use_path_style"
48 attrUploadParallelism = "upload_parallelism"
49 maxCopyObjectSize = 5 * 1024 * 1024 * 1024
50 )
51
52 type Config struct {
53 Bucket string
54 Region string
55 Prefix string
56 ManifestsPrefix string
57 BlobsPrefix string
58 Names []string
59 TouchRefresh time.Duration
60 EndpointURL string
61 AccessKeyID string
62 SecretAccessKey string
63 SessionToken string
64 UsePathStyle bool
65 UploadParallelism int
66 }
67
68 func getConfig(attrs map[string]string) (Config, error) {
69 bucket, ok := attrs[attrBucket]
70 if !ok {
71 bucket, ok = os.LookupEnv("AWS_BUCKET")
72 if !ok {
73 return Config{}, errors.Errorf("bucket ($AWS_BUCKET) not set for s3 cache")
74 }
75 }
76
77 region, ok := attrs[attrRegion]
78 if !ok {
79 region, ok = os.LookupEnv("AWS_REGION")
80 if !ok {
81 return Config{}, errors.Errorf("region ($AWS_REGION) not set for s3 cache")
82 }
83 }
84
85 prefix := attrs[attrPrefix]
86
87 manifestsPrefix, ok := attrs[attrManifestsPrefix]
88 if !ok {
89 manifestsPrefix = "manifests/"
90 }
91
92 blobsPrefix, ok := attrs[attrBlobsPrefix]
93 if !ok {
94 blobsPrefix = "blobs/"
95 }
96
97 names := []string{"buildkit"}
98 name, ok := attrs[attrName]
99 if ok {
100 splittedNames := strings.Split(name, ";")
101 if len(splittedNames) > 0 {
102 names = splittedNames
103 }
104 }
105
106 touchRefresh := 24 * time.Hour
107
108 touchRefreshStr, ok := attrs[attrTouchRefresh]
109 if ok {
110 touchRefreshFromUser, err := time.ParseDuration(touchRefreshStr)
111 if err == nil {
112 touchRefresh = touchRefreshFromUser
113 }
114 }
115
116 endpointURL := attrs[attrEndpointURL]
117 accessKeyID := attrs[attrAccessKeyID]
118 secretAccessKey := attrs[attrSecretAccessKey]
119 sessionToken := attrs[attrSessionToken]
120
121 usePathStyle := false
122 usePathStyleStr, ok := attrs[attrUsePathStyle]
123 if ok {
124 usePathStyleUser, err := strconv.ParseBool(usePathStyleStr)
125 if err == nil {
126 usePathStyle = usePathStyleUser
127 }
128 }
129
130 uploadParallelism := 4
131 uploadParallelismStr, ok := attrs[attrUploadParallelism]
132 if ok {
133 uploadParallelismInt, err := strconv.Atoi(uploadParallelismStr)
134 if err != nil {
135 return Config{}, errors.Errorf("upload_parallelism must be a positive integer")
136 }
137 if uploadParallelismInt <= 0 {
138 return Config{}, errors.Errorf("upload_parallelism must be a positive integer")
139 }
140 uploadParallelism = uploadParallelismInt
141 }
142
143 return Config{
144 Bucket: bucket,
145 Region: region,
146 Prefix: prefix,
147 ManifestsPrefix: manifestsPrefix,
148 BlobsPrefix: blobsPrefix,
149 Names: names,
150 TouchRefresh: touchRefresh,
151 EndpointURL: endpointURL,
152 AccessKeyID: accessKeyID,
153 SecretAccessKey: secretAccessKey,
154 SessionToken: sessionToken,
155 UsePathStyle: usePathStyle,
156 UploadParallelism: uploadParallelism,
157 }, nil
158 }
159
160 // ResolveCacheExporterFunc for s3 cache exporter.
161 func ResolveCacheExporterFunc() remotecache.ResolveCacheExporterFunc {
162 return func(ctx context.Context, g session.Group, attrs map[string]string) (remotecache.Exporter, error) {
163 config, err := getConfig(attrs)
164 if err != nil {
165 return nil, err
166 }
167
168 s3Client, err := newS3Client(ctx, config)
169 if err != nil {
170 return nil, err
171 }
172 cc := v1.NewCacheChains()
173 return &exporter{CacheExporterTarget: cc, chains: cc, s3Client: s3Client, config: config}, nil
174 }
175 }
176
177 type exporter struct {
178 solver.CacheExporterTarget
179 chains *v1.CacheChains
180 s3Client *s3Client
181 config Config
182 }
183
184 func (*exporter) Name() string {
185 return "exporting cache to Amazon S3"
186 }
187
188 func (e *exporter) Config() remotecache.Config {
189 return remotecache.Config{
190 Compression: compression.New(compression.Default),
191 }
192 }
193
194 type nopCloserSectionReader struct {
195 *io.SectionReader
196 }
197
198 func (*nopCloserSectionReader) Close() error { return nil }
199
200 func (e *exporter) Finalize(ctx context.Context) (map[string]string, error) {
201 cacheConfig, descs, err := e.chains.Marshal(ctx)
202 if err != nil {
203 return nil, err
204 }
205
206 eg, groupCtx := errgroup.WithContext(ctx)
207 tasks := make(chan int, e.config.UploadParallelism)
208
209 go func() {
210 for i := range cacheConfig.Layers {
211 tasks <- i
212 }
213 close(tasks)
214 }()
215
216 for range e.config.UploadParallelism {
217 eg.Go(func() error {
218 for index := range tasks {
219 blob := cacheConfig.Layers[index].Blob
220 dgstPair, ok := descs[blob]
221 if !ok {
222 return errors.Errorf("missing blob %s", blob)
223 }
224 if dgstPair.Descriptor.Annotations == nil {
225 return errors.Errorf("invalid descriptor without annotations")
226 }
227 v, ok := dgstPair.Descriptor.Annotations[labels.LabelUncompressed]
228 if !ok {
229 return errors.Errorf("invalid descriptor without uncompressed annotation")
230 }
231 diffID, err := digest.Parse(v)
232 if err != nil {
233 return errors.Wrapf(err, "failed to parse uncompressed annotation")
234 }
235
236 key := e.s3Client.blobKey(dgstPair.Descriptor.Digest)
237 exists, size, err := e.s3Client.exists(groupCtx, key)
238 if err != nil {
239 return errors.Wrapf(err, "failed to check file presence in cache")
240 }
241 if exists != nil {
242 if time.Since(*exists) > e.config.TouchRefresh {
243 err = e.s3Client.touch(groupCtx, key, size)
244 if err != nil {
245 return errors.Wrapf(err, "failed to touch file")
246 }
247 }
248 } else {
249 layerDone := progress.OneOff(groupCtx, fmt.Sprintf("writing layer %s", blob))
250 // TODO: once buildkit uses v2, start using
251 // https://github.com/containerd/containerd/pull/9657
252 // currently inline data should never happen.
253 ra, err := dgstPair.Provider.ReaderAt(groupCtx, dgstPair.Descriptor)
254 if err != nil {
255 return layerDone(errors.Wrap(err, "error reading layer blob from provider"))
256 }
257 defer ra.Close()
258 if err := e.s3Client.saveMutableAt(groupCtx, key, &nopCloserSectionReader{io.NewSectionReader(ra, 0, ra.Size())}); err != nil {
259 return layerDone(errors.Wrap(err, "error writing layer blob"))
260 }
261 layerDone(nil)
262 }
263
264 la := &v1.LayerAnnotations{
265 DiffID: diffID,
266 Size: dgstPair.Descriptor.Size,
267 MediaType: dgstPair.Descriptor.MediaType,
268 }
269 if v, ok := dgstPair.Descriptor.Annotations["buildkit/createdat"]; ok {
270 var t time.Time
271 if err := (&t).UnmarshalText([]byte(v)); err != nil {
272 return err
273 }
274 la.CreatedAt = t.UTC()
275 }
276 cacheConfig.Layers[index].Annotations = la
277 }
278 return nil
279 })
280 }
281
282 if err := eg.Wait(); err != nil {
283 return nil, err
284 }
285
286 dt, err := json.Marshal(cacheConfig)
287 if err != nil {
288 return nil, err
289 }
290
291 for _, name := range e.config.Names {
292 if err := e.s3Client.saveMutableAt(ctx, e.s3Client.manifestKey(name), bytes.NewReader(dt)); err != nil {
293 return nil, errors.Wrapf(err, "error writing manifest: %s", name)
294 }
295 }
296 return nil, nil
297 }
298
299 // ResolveCacheImporterFunc for s3 cache importer.
300 func ResolveCacheImporterFunc() remotecache.ResolveCacheImporterFunc {
301 return func(ctx context.Context, _ session.Group, attrs map[string]string) (remotecache.Importer, ocispecs.Descriptor, error) {
302 config, err := getConfig(attrs)
303 if err != nil {
304 return nil, ocispecs.Descriptor{}, err
305 }
306 s3Client, err := newS3Client(ctx, config)
307 if err != nil {
308 return nil, ocispecs.Descriptor{}, err
309 }
310 return &importer{s3Client, config}, ocispecs.Descriptor{}, nil
311 }
312 }
313
314 type importer struct {
315 s3Client *s3Client
316 config Config
317 }
318
319 func (i *importer) makeDescriptorProviderPair(l v1.CacheLayer) (*v1.DescriptorProviderPair, error) {
320 if l.Annotations == nil {
321 return nil, errors.Errorf("cache layer with missing annotations")
322 }
323 if l.Annotations.DiffID == "" {
324 return nil, errors.Errorf("cache layer with missing diffid")
325 }
326 annotations := map[string]string{}
327 annotations[labels.LabelUncompressed] = l.Annotations.DiffID.String()
328 if !l.Annotations.CreatedAt.IsZero() {
329 txt, err := l.Annotations.CreatedAt.MarshalText()
330 if err != nil {
331 return nil, err
332 }
333 annotations["buildkit/createdat"] = string(txt)
334 }
335 return &v1.DescriptorProviderPair{
336 Provider: i.s3Client,
337 Descriptor: ocispecs.Descriptor{
338 MediaType: l.Annotations.MediaType,
339 Digest: l.Blob,
340 Size: l.Annotations.Size,
341 Annotations: annotations,
342 },
343 }, nil
344 }
345
346 func (i *importer) load(ctx context.Context) (*v1.CacheChains, error) {
347 var config v1.CacheConfig
348 found, err := i.s3Client.getManifest(ctx, i.s3Client.manifestKey(i.config.Names[0]), &config)
349 if err != nil {
350 return nil, err
351 }
352 if !found {
353 return v1.NewCacheChains(), nil
354 }
355
356 allLayers := v1.DescriptorProvider{}
357
358 for _, l := range config.Layers {
359 dpp, err := i.makeDescriptorProviderPair(l)
360 if err != nil {
361 return nil, err
362 }
363 allLayers[l.Blob] = *dpp
364 }
365
366 cc := v1.NewCacheChains()
367 if err := v1.ParseConfig(config, allLayers, cc); err != nil {
368 return nil, err
369 }
370 return cc, nil
371 }
372
373 func (i *importer) Resolve(ctx context.Context, _ ocispecs.Descriptor, id string, w worker.Worker) (solver.CacheManager, error) {
374 cc, err := i.load(ctx)
375 if err != nil {
376 return nil, err
377 }
378
379 keysStorage, resultStorage, err := v1.NewCacheKeyStorage(cc, w)
380 if err != nil {
381 return nil, err
382 }
383
384 return solver.NewCacheManager(ctx, id, keysStorage, resultStorage), nil
385 }
386
387 type readerAt struct {
388 ReaderAtCloser
389 size int64
390 }
391
392 func (r *readerAt) Size() int64 {
393 return r.size
394 }
395
396 type s3Client struct {
397 *s3.Client
398 *manager.Uploader
399 bucket string
400 prefix string
401 blobsPrefix string
402 manifestsPrefix string
403 }
404
405 func newS3Client(ctx context.Context, config Config) (*s3Client, error) {
406 cfg, err := aws_config.LoadDefaultConfig(ctx, aws_config.WithRegion(config.Region))
407 if err != nil {
408 return nil, errors.Errorf("Unable to load AWS SDK config, %v", err)
409 }
410 client := s3.NewFromConfig(cfg, func(options *s3.Options) {
411 if config.AccessKeyID != "" && config.SecretAccessKey != "" {
412 options.Credentials = credentials.NewStaticCredentialsProvider(config.AccessKeyID, config.SecretAccessKey, config.SessionToken)
413 }
414 if config.EndpointURL != "" {
415 options.UsePathStyle = config.UsePathStyle
416 options.BaseEndpoint = aws.String(config.EndpointURL)
417 }
418 })
419
420 return &s3Client{
421 Client: client,
422 Uploader: manager.NewUploader(client),
423 bucket: config.Bucket,
424 prefix: config.Prefix,
425 blobsPrefix: config.BlobsPrefix,
426 manifestsPrefix: config.ManifestsPrefix,
427 }, nil
428 }
429
430 func (s3Client *s3Client) getManifest(ctx context.Context, key string, config *v1.CacheConfig) (bool, error) {
431 input := &s3.GetObjectInput{
432 Bucket: &s3Client.bucket,
433 Key: &key,
434 }
435
436 output, err := s3Client.GetObject(ctx, input)
437 if err != nil {
438 if isNotFound(err) {
439 return false, nil
440 }
441 return false, err
442 }
443 defer output.Body.Close()
444
445 decoder := json.NewDecoder(output.Body)
446 if err := decoder.Decode(config); err != nil {
447 return false, errors.WithStack(err)
448 }
449 if _, err := decoder.Token(); !errors.Is(err, io.EOF) {
450 return false, errors.Errorf("unexpected data after JSON object")
451 }
452
453 return true, nil
454 }
455
456 func (s3Client *s3Client) getReader(ctx context.Context, key string, offset int64) (io.ReadCloser, error) {
457 input := &s3.GetObjectInput{
458 Bucket: &s3Client.bucket,
459 Key: &key,
460 }
461 if offset > 0 {
462 input.Range = aws.String(fmt.Sprintf("bytes=%d-", offset))
463 }
464
465 output, err := s3Client.GetObject(ctx, input)
466 if err != nil {
467 return nil, err
468 }
469 return output.Body, nil
470 }
471
472 func (s3Client *s3Client) saveMutableAt(ctx context.Context, key string, body io.Reader) error {
473 input := &s3.PutObjectInput{
474 Bucket: &s3Client.bucket,
475 Key: &key,
476 Body: body,
477 }
478 _, err := s3Client.Upload(ctx, input)
479 return err
480 }
481
482 func (s3Client *s3Client) exists(ctx context.Context, key string) (*time.Time, *int64, error) {
483 input := &s3.HeadObjectInput{
484 Bucket: &s3Client.bucket,
485 Key: &key,
486 }
487
488 head, err := s3Client.HeadObject(ctx, input)
489 if err != nil {
490 if isNotFound(err) {
491 return nil, nil, nil
492 }
493 return nil, nil, err
494 }
495 return head.LastModified, head.ContentLength, nil
496 }
497
498 func buildCopySourceRange(start int64, objectSize int64) string {
499 end := start + maxCopyObjectSize - 1
500 if end > objectSize {
501 end = objectSize - 1
502 }
503 startRange := strconv.FormatInt(start, 10)
504 stopRange := strconv.FormatInt(end, 10)
505 return "bytes=" + startRange + "-" + stopRange
506 }
507
508 func (s3Client *s3Client) touch(ctx context.Context, key string, size *int64) (err error) {
509 copySource := fmt.Sprintf("%s/%s", s3Client.bucket, key)
510
511 // CopyObject does not support files > 5GB
512 if *size < maxCopyObjectSize {
513 cp := &s3.CopyObjectInput{
514 Bucket: &s3Client.bucket,
515 CopySource: &copySource,
516 Key: &key,
517 Metadata: map[string]string{"updated-at": time.Now().String()},
518 MetadataDirective: "REPLACE",
519 }
520
521 _, err := s3Client.CopyObject(ctx, cp)
522
523 return err
524 }
525 input := &s3.CreateMultipartUploadInput{
526 Bucket: &s3Client.bucket,
527 Key: &key,
528 }
529
530 output, err := s3Client.CreateMultipartUpload(ctx, input)
531 if err != nil {
532 return err
533 }
534
535 defer func() {
536 abortIn := s3.AbortMultipartUploadInput{
537 Bucket: &s3Client.bucket,
538 Key: &key,
539 UploadId: output.UploadId,
540 }
541 if err != nil {
542 s3Client.AbortMultipartUpload(ctx, &abortIn)
543 }
544 }()
545
546 var currentPartNumber int32 = 1
547 var currentPosition int64
548 var completedParts []s3types.CompletedPart
549
550 for currentPosition < *size {
551 copyRange := buildCopySourceRange(currentPosition, *size)
552 partInput := s3.UploadPartCopyInput{
553 Bucket: &s3Client.bucket,
554 CopySource: &copySource,
555 CopySourceRange: &copyRange,
556 Key: &key,
557 PartNumber: &currentPartNumber,
558 UploadId: output.UploadId,
559 }
560 uploadPartCopyResult, err := s3Client.UploadPartCopy(ctx, &partInput)
561 if err != nil {
562 return err
563 }
564 partNumber := new(int32)
565 *partNumber = currentPartNumber
566 completedParts = append(completedParts, s3types.CompletedPart{
567 ETag: uploadPartCopyResult.CopyPartResult.ETag,
568 PartNumber: partNumber,
569 })
570
571 currentPartNumber++
572 currentPosition += maxCopyObjectSize
573 }
574
575 completeMultipartUploadInput := &s3.CompleteMultipartUploadInput{
576 Bucket: &s3Client.bucket,
577 Key: &key,
578 UploadId: output.UploadId,
579 MultipartUpload: &s3types.CompletedMultipartUpload{
580 Parts: completedParts,
581 },
582 }
583
584 if _, err := s3Client.CompleteMultipartUpload(ctx, completeMultipartUploadInput); err != nil {
585 return err
586 }
587
588 return nil
589 }
590
591 func (s3Client *s3Client) ReaderAt(ctx context.Context, desc ocispecs.Descriptor) (content.ReaderAt, error) {
592 readerAtCloser := toReaderAtCloser(func(offset int64) (io.ReadCloser, error) {
593 return s3Client.getReader(ctx, s3Client.blobKey(desc.Digest), offset)
594 })
595 return &readerAt{ReaderAtCloser: readerAtCloser, size: desc.Size}, nil
596 }
597
598 func (s3Client *s3Client) manifestKey(name string) string {
599 return s3Client.prefix + s3Client.manifestsPrefix + name
600 }
601
602 func (s3Client *s3Client) blobKey(dgst digest.Digest) string {
603 return s3Client.prefix + s3Client.blobsPrefix + dgst.String()
604 }
605
606 func isNotFound(err error) bool {
607 var nf *s3types.NotFound
608 var nsk *s3types.NoSuchKey
609 return errors.As(err, &nf) || errors.As(err, &nsk)
610 }