Repository navigation
Expand file tree
/
Copy paths3store.go
More file actions
994 lines (855 loc) · 29.4 KB
/
Copy paths3store.go
File metadata and controls
994 lines (855 loc) · 29.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
package dstore
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"net"
"net/http"
"net/url"
"os"
"path"
"path/filepath"
"strconv"
"strings"
"sync"
"time"
"unicode/utf8"
"github.com/aws/aws-sdk-go-v2/aws"
awsconfig "github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/credentials"
"github.com/aws/aws-sdk-go-v2/feature/s3/manager"
"github.com/aws/aws-sdk-go-v2/service/s3"
"github.com/aws/aws-sdk-go-v2/service/s3/types"
"github.com/aws/smithy-go"
"github.com/aws/smithy-go/encoding/httpbinding"
"go.uber.org/zap"
"golang.org/x/net/http2"
)
type s3ReadCloser struct {
outer io.ReadCloser
httpBody io.ReadCloser
}
func (s *s3ReadCloser) Read(p []byte) (int, error) {
return s.outer.Read(p)
}
func (s *s3ReadCloser) Close() error {
// Drain the raw HTTP body BEFORE closing the outer reader chain. If outer
// closes httpBody first (which it does when there is no compression layer),
// the subsequent drain becomes a no-op and the connection is never returned
// to the pool.
io.Copy(io.Discard, s.httpBody)
return s.outer.Close()
}
var retryS3PushLocalFilesDelay time.Duration
var s3ReadAttempts = 1
var bufferedS3Read bool
var s3MaxIdleConns = 100
var s3MaxIdleConnsPerHost = 10
var s3IdleConnTimeout = 90 * time.Second
var sharedTransport http.RoundTripper
var sharedTransportOnce sync.Once
func getSharedTransport() http.RoundTripper {
sharedTransportOnce.Do(func() {
t := &http.Transport{
ForceAttemptHTTP2: true,
MaxIdleConns: s3MaxIdleConns,
MaxIdleConnsPerHost: s3MaxIdleConnsPerHost,
IdleConnTimeout: s3IdleConnTimeout,
ResponseHeaderTimeout: 30 * time.Second,
TLSHandshakeTimeout: 10 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
DialContext: (&net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second,
}).DialContext,
}
if t2, err := http2.ConfigureTransports(t); err == nil {
t2.ReadIdleTimeout = 31 * time.Second
t2.PingTimeout = 15 * time.Second
}
sharedTransport = t
})
return sharedTransport
}
func init() {
retry := os.Getenv("DSTORE_S3_RETRY_PUSH_DELAY")
if retry != "" {
retryS3PushLocalFilesDelay, _ = time.ParseDuration(retry)
}
if os.Getenv("DSTORE_S3_BUFFERED_READ") == "true" {
bufferedS3Read = true
}
readAttempts := os.Getenv("DSTORE_S3_READ_ATTEMPTS")
if readAttempts != "" {
attempts, _ := strconv.ParseUint(readAttempts, 10, 64)
if attempts > 0 {
s3ReadAttempts = int(attempts)
}
}
if v := os.Getenv("DSTORE_S3_MAX_IDLE_CONNS"); v != "" {
if n, err := strconv.Atoi(v); err == nil && n > 0 {
s3MaxIdleConns = n
}
}
if v := os.Getenv("DSTORE_S3_MAX_IDLE_CONNS_PER_HOST"); v != "" {
if n, err := strconv.Atoi(v); err == nil && n > 0 {
s3MaxIdleConnsPerHost = n
}
}
if v := os.Getenv("DSTORE_S3_IDLE_CONN_TIMEOUT"); v != "" {
if d, err := time.ParseDuration(v); err == nil {
s3IdleConnTimeout = d
}
}
zlog.Info("S3 storage configured",
zap.Bool("buffered_read", bufferedS3Read),
zap.Int("read_attempts", s3ReadAttempts),
zap.Duration("retry_push_local_files_delay", retryS3PushLocalFilesDelay),
zap.Int("max_idle_conns", s3MaxIdleConns),
zap.Int("max_idle_conns_per_host", s3MaxIdleConnsPerHost),
zap.Duration("idle_conn_timeout", s3IdleConnTimeout),
)
}
type S3Store struct {
baseURL *url.URL
bucket string
path string
storageClass string
client *s3.Client
uploader *manager.Uploader
downloader *manager.Downloader
context context.Context
*commonStore
}
func NewS3Store(baseURL *url.URL, extension, compressionType string, overwrite bool, opts ...Option) (*S3Store, error) {
ctx := context.Background()
return newS3StoreContext(ctx, baseURL, extension, compressionType, overwrite, opts...)
}
func newS3StoreContext(ctx context.Context, baseURL *url.URL, extension, compressionType string, overwrite bool, opts ...Option) (*S3Store, error) {
common, err := newCommonStore(baseURL, extension, compressionType, overwrite, opts...)
if err != nil {
return nil, err
}
s := &S3Store{
baseURL: baseURL,
commonStore: common,
context: ctx,
}
awsConfig, bucket, path, storageClass, err := ParseS3URL(baseURL)
if err != nil {
return nil, fmt.Errorf("invalid s3 url: %w", err)
}
awsConfig = append(awsConfig, awsconfig.WithHTTPClient(&http.Client{
Transport: getSharedTransport(),
}))
cfg, err := awsconfig.LoadDefaultConfig(ctx, awsConfig...)
if err != nil {
return nil, fmt.Errorf("error loading AWS config: %w", err)
}
s.client = s3.NewFromConfig(cfg, func(o *s3.Options) {
// Suppress flood of "Response has no supported checksum" warnings from the SDK.
// See https://github.com/aws/aws-sdk-go-v2/issues/3020
o.DisableLogOutputChecksumValidationSkipped = true
// Only compute request checksums when the operation requires it. As of
// service/s3 v1.73.0 the SDK computes CRC32 checksums on PUT/multipart by
// default, which breaks non-AWS S3-compatible backends (they reject the
// parts). This is the programmatic equivalent of setting the env var
// AWS_REQUEST_CHECKSUM_CALCULATION=when_required.
// See https://github.com/aws/aws-sdk-go-v2/discussions/2960
o.RequestChecksumCalculation = aws.RequestChecksumCalculationWhenRequired
})
s.uploader = manager.NewUploader(s.client)
s.downloader = manager.NewDownloader(s.client)
s.bucket = bucket
s.path = path
s.storageClass = storageClass
return s, nil
}
func (s *S3Store) Clone(ctx context.Context, opts ...Option) (Store, error) {
return newS3StoreContext(ctx, s.baseURL, s.extension, s.compressionType, s.overwrite, opts...)
}
func (s *S3Store) SubStore(subFolder string) (Store, error) {
url, err := url.Parse(s.baseURL.String())
if err != nil {
return nil, fmt.Errorf("s3 store parsing base url: %w", err)
}
url.Path = path.Join(url.Path, subFolder)
newPath := path.Join(s.path, subFolder)
return &S3Store{
baseURL: url,
commonStore: s.commonStore,
client: s.client,
uploader: s.uploader,
downloader: s.downloader,
bucket: s.bucket,
storageClass: s.storageClass,
path: newPath,
}, nil
}
func ParseS3URL(s3URL *url.URL) (configOptions []func(*awsconfig.LoadOptions) error, bucket, path, storageClass string, err error) {
region := s3URL.Query().Get("region")
if region == "" {
return nil, "", "", "", fmt.Errorf("specify s3 bucket like: s3://bucket/path?region=us-east-1")
}
configOptions = append(configOptions, awsconfig.WithRegion(region))
hasEndpoint := hasCustomEndpoint(s3URL)
if hasEndpoint {
endpoint := s3URL.Host
if s3URL.Query().Get("insecure") != "" {
endpoint = "http://" + endpoint
} else {
endpoint = "https://" + endpoint
}
configOptions = append(configOptions, awsconfig.WithEndpointResolverWithOptions(
aws.EndpointResolverWithOptionsFunc(func(service, region string, options ...interface{}) (aws.Endpoint, error) {
return aws.Endpoint{
URL: endpoint,
HostnameImmutable: true,
}, nil
}),
))
pathParts := strings.Split(strings.TrimLeft(s3URL.Path, "/"), "/")
bucket = pathParts[0]
path = strings.Replace(s3URL.Path, bucket, "", 1)
} else {
bucket = s3URL.Hostname()
path = s3URL.Path
}
accessKeyID := s3URL.Query().Get("access_key_id")
secretAccessKey := s3URL.Query().Get("secret_access_key")
if accessKeyID != "" && secretAccessKey != "" {
configOptions = append(configOptions, awsconfig.WithCredentialsProvider(
credentials.NewStaticCredentialsProvider(accessKeyID, secretAccessKey, ""),
))
}
if profile := s3URL.Query().Get("profile"); profile != "" {
configOptions = append(configOptions, awsconfig.WithSharedConfigProfile(profile))
}
return configOptions, bucket, strings.Trim(path, "/"), getStorageClass(s3URL.Query()), nil
}
func hasCustomEndpoint(s3URL *url.URL) bool {
// As soon as there is a port in the url, we are sure that's it's the
// hostname that should be configured, so move along
if s3URL.Port() != "" {
return true
}
// If there is no `.` in the hostname, we assume it's a bucket. It could still be
// problematic for `localhost`, we are expecting people to use `:<port>` to go
// in the condition above.
host := s3URL.Hostname()
if !strings.Contains(host, ".") {
return false
}
// Otherwise, by default we assume it's an hostname followed by the bucket. If
// operator really intent to use the bucket directly an it contains dot, the
// query parameter `infer_aws_endpoint=true` can be used to tell the store
// implementation that the hostname is the actual bucket
return s3URL.Query().Get("infer_aws_endpoint") == ""
}
func getStorageClass(q url.Values) string {
if v := q.Get("storage_class"); v != "" {
return v
}
if v := q.Get("storageClass"); v != "" {
zlog.Warn("query parameter 'storageClass' is deprecated, use 'storage_class' instead")
return v
}
return ""
}
func (s *S3Store) BaseURL() *url.URL {
return s.baseURL
}
func (s *S3Store) ObjectPath(name string) string {
return path.Join(s.path, s.pathWithExt(name))
}
func (s *S3Store) ObjectURL(name string) string {
return objectURL(s.baseURL, s.pathWithExt(name))
}
func (s *S3Store) WriteObject(ctx context.Context, base string, f io.Reader, metadataKeyValues ...string) (err error) {
ctx = withFileName(ctx, base)
ctx = withStoreType(ctx, "s3store")
ctx = withLogger(ctx, zlog, tracer)
// Parse metadataKeyValues array
if len(metadataKeyValues)%2 != 0 {
return fmt.Errorf("metadataKeyValues must have an even number of strings (key-value pairs), got %d", len(metadataKeyValues))
}
objPath := s.ObjectPath(base)
exists, err := s.FileExists(ctx, base)
if err != nil {
return err
}
if !s.overwrite && exists {
// We silently ignore when we ask not to overwrite, but we still must
// consume the reader so that pipe-based producers (e.g. an io.Pipe fed
// by a goroutine) don't block forever waiting for a consumer that
// will never come.
_, _ = io.Copy(io.Discard, f)
return nil
}
pr, pw := io.Pipe()
writeDone := make(chan error, 1)
ctx, cancel := context.WithCancel(ctx)
wg := sync.WaitGroup{}
wg.Add(1)
go func(ctx context.Context) {
defer wg.Done()
err := s.compressedCopy(ctx, pw, f)
writeDone <- err
// The error, not a plain EOF, must reach the uploader: on EOF it completes the upload
// with what it has read so far, and the cancel below can come too late to stop it.
pw.CloseWithError(err)
if err != nil {
cancel()
}
}(ctx)
uploadInput := &s3.PutObjectInput{
Bucket: aws.String(s.bucket),
Key: aws.String(objPath),
Body: pr,
}
if s.storageClass != "" {
uploadInput.StorageClass = types.StorageClass(s.storageClass)
}
// Add metadata if provided
if len(metadataKeyValues) > 0 {
metadata := make(map[string]string)
for i := 0; i < len(metadataKeyValues); i += 2 {
key := metadataKeyValues[i]
value := metadataKeyValues[i+1]
metadata[key] = value
}
uploadInput.Metadata = metadata
}
_, err = s.uploader.Upload(ctx, uploadInput)
if err != nil {
select {
case err2 := <-writeDone:
if err2 != nil {
return fmt.Errorf("writing through pipe: %w", err2)
}
default:
// error was generated in the Upload (s3 or context timeout), compressedCopy is not finished,
// we make it fail. double closing is safe here
pw.Close()
}
return fmt.Errorf("uploading to S3 through manager: %w", err)
}
wg.Wait()
if err := <-writeDone; err != nil {
return fmt.Errorf("writing through pipe: %w", err)
}
return nil
}
// S3 refuses a single CopyObject call above 5 GiB, bigger objects must be copied part by part.
var s3MaxSingleCopySize int64 = 5 * 1024 * 1024 * 1024
// Size of each part of a multipart copy, within the 5 MiB to 5 GiB range S3 accepts for a part.
var s3CopyPartSize int64 = 1024 * 1024 * 1024
// CopyObject copies an object within the store's bucket without moving its bytes through the
// client: the service reads the source and writes the destination itself, so nothing is
// decompressed and recompressed on the way. A backend with no copy operation of its own is
// served by streaming the object through the client instead.
func (s *S3Store) CopyObject(ctx context.Context, src, dest string) error {
srcPath := s.ObjectPath(src)
destPath := s.ObjectPath(dest)
head, err := s.client.HeadObject(ctx, &s3.HeadObjectInput{
Bucket: aws.String(s.bucket),
Key: aws.String(srcPath),
})
if err != nil {
var notFound *types.NotFound
var noSuchKey *types.NoSuchKey
if errors.As(err, ¬Found) || errors.As(err, &noSuchKey) {
return fmt.Errorf("source object %q: %w", srcPath, ErrNotFound)
}
return fmt.Errorf("reading attributes of source object %q: %w", srcPath, err)
}
if !s.overwrite {
exists, err := s.FileExists(ctx, dest)
if err != nil {
return err
}
if exists {
return nil
}
}
var size int64
if head.ContentLength != nil {
size = *head.ContentLength
}
copySource := s3CopySource(s.bucket, srcPath)
if size > s3MaxSingleCopySize {
err = s.multipartCopyObject(ctx, copySource, srcPath, destPath, size)
} else {
err = s.singleCopyObject(ctx, copySource, srcPath, destPath)
}
if err != nil && isServerSideCopyUnsupported(err) {
zlog.Debug("backend does not support server-side copy, streaming the object through the client instead",
zap.String("bucket", s.bucket),
zap.String("source", srcPath),
zap.String("destination", destPath),
zap.Error(err),
)
return s.copyObjectStreaming(ctx, src, dest)
}
return err
}
// s3CopySource builds the "bucket/key" the SDK expects as a copy source, escaped with the very
// encoder the SDK puts request paths through, separators left alone.
func s3CopySource(bucket, key string) string {
return httpbinding.EscapePath(bucket+"/"+key, false)
}
// isServerSideCopyUnsupported reports whether the backend answered that it has no copy
// operation at all, the one failure a client-side copy can still recover from.
func isServerSideCopyUnsupported(err error) bool {
var apiErr smithy.APIError
if !errors.As(err, &apiErr) {
return false
}
switch apiErr.ErrorCode() {
case "NotImplemented", "MethodNotAllowed":
return true
}
return false
}
// copyObjectStreaming reads the source and writes the destination through the client, the only
// way left when the backend has no server-side copy.
func (s *S3Store) copyObjectStreaming(ctx context.Context, src, dest string) error {
reader, err := s.OpenObject(ctx, src)
if err != nil {
return err
}
defer reader.Close()
return s.WriteObject(ctx, dest, reader)
}
func (s *S3Store) singleCopyObject(ctx context.Context, copySource, srcPath, destPath string) error {
input := &s3.CopyObjectInput{
Bucket: aws.String(s.bucket),
Key: aws.String(destPath),
CopySource: aws.String(copySource),
}
if s.storageClass != "" {
input.StorageClass = types.StorageClass(s.storageClass)
}
if _, err := s.client.CopyObject(ctx, input); err != nil {
return fmt.Errorf("copying %q to %q: %w", srcPath, destPath, err)
}
return nil
}
func (s *S3Store) multipartCopyObject(ctx context.Context, copySource, srcPath, destPath string, size int64) error {
createInput := &s3.CreateMultipartUploadInput{
Bucket: aws.String(s.bucket),
Key: aws.String(destPath),
}
if s.storageClass != "" {
createInput.StorageClass = types.StorageClass(s.storageClass)
}
created, err := s.client.CreateMultipartUpload(ctx, createInput)
if err != nil {
return fmt.Errorf("starting multipart copy of %q to %q: %w", srcPath, destPath, err)
}
parts := make([]types.CompletedPart, 0, (size+s3CopyPartSize-1)/s3CopyPartSize)
for start, partNumber := int64(0), int32(1); start < size; start, partNumber = start+s3CopyPartSize, partNumber+1 {
end := start + s3CopyPartSize - 1
if end >= size {
end = size - 1
}
// The range bounds are both inclusive.
copied, err := s.client.UploadPartCopy(ctx, &s3.UploadPartCopyInput{
Bucket: aws.String(s.bucket),
Key: aws.String(destPath),
CopySource: aws.String(copySource),
CopySourceRange: aws.String(fmt.Sprintf("bytes=%d-%d", start, end)),
PartNumber: aws.Int32(partNumber),
UploadId: created.UploadId,
})
if err != nil {
s.abortMultipartUpload(ctx, destPath, created.UploadId)
return fmt.Errorf("copying bytes %d-%d of %q to %q: %w", start, end, srcPath, destPath, err)
}
part := types.CompletedPart{PartNumber: aws.Int32(partNumber)}
if copied.CopyPartResult != nil {
part.ETag = copied.CopyPartResult.ETag
}
parts = append(parts, part)
}
_, err = s.client.CompleteMultipartUpload(ctx, &s3.CompleteMultipartUploadInput{
Bucket: aws.String(s.bucket),
Key: aws.String(destPath),
UploadId: created.UploadId,
MultipartUpload: &types.CompletedMultipartUpload{Parts: parts},
})
if err != nil {
s.abortMultipartUpload(ctx, destPath, created.UploadId)
return fmt.Errorf("completing multipart copy of %q to %q: %w", srcPath, destPath, err)
}
return nil
}
// abortMultipartUpload releases the parts already copied, which the bucket keeps billing
// until the upload is either completed or aborted. It runs even when ctx is done, since
// a cancelled copy is exactly when the leftovers need to go.
func (s *S3Store) abortMultipartUpload(ctx context.Context, destPath string, uploadID *string) {
_, err := s.client.AbortMultipartUpload(context.WithoutCancel(ctx), &s3.AbortMultipartUploadInput{
Bucket: aws.String(s.bucket),
Key: aws.String(destPath),
UploadId: uploadID,
})
if err != nil {
zlog.Warn("unable to abort multipart copy, parts already copied may linger in the bucket",
zap.String("bucket", s.bucket),
zap.String("key", destPath),
zap.Stringp("upload_id", uploadID),
zap.Error(err),
)
}
}
func (s *S3Store) FileExists(ctx context.Context, base string) (bool, error) {
path := s.ObjectPath(base)
_, err := s.client.HeadObject(ctx, &s3.HeadObjectInput{
Bucket: aws.String(s.bucket),
Key: aws.String(path),
})
if err != nil {
var notFound *types.NotFound
var noSuchKey *types.NoSuchKey
if errors.As(err, ¬Found) || errors.As(err, &noSuchKey) {
return false, nil
}
return false, err
}
return true, nil
}
func (s *S3Store) ObjectAttributes(ctx context.Context, base string) (*ObjectAttributes, error) {
path := s.ObjectPath(base)
output, err := s.client.HeadObject(ctx, &s3.HeadObjectInput{
Bucket: aws.String(s.bucket),
Key: aws.String(path),
})
if err != nil {
return nil, err
}
return &ObjectAttributes{
LastModified: *output.LastModified,
Size: *output.ContentLength,
Metadata: output.Metadata,
}, nil
}
func (s *S3Store) SetMetadata(ctx context.Context, base string, metadata map[string]string) error {
path := s.ObjectPath(base)
// Use CopyObject to update metadata (copy to itself with new metadata)
copySource := fmt.Sprintf("%s/%s", s.bucket, path)
_, err := s.client.CopyObject(ctx, &s3.CopyObjectInput{
Bucket: aws.String(s.bucket),
Key: aws.String(path),
CopySource: aws.String(copySource),
Metadata: metadata,
MetadataDirective: types.MetadataDirectiveReplace,
})
return err
}
func (s *S3Store) OpenObject(ctx context.Context, name string) (out io.ReadCloser, err error) {
ctx = withStoreType(ctx, "s3store")
ctx = withLogger(ctx, zlog, tracer)
path := s.ObjectPath(name)
ctx = withFileName(ctx, path)
if tracer.Enabled() {
zlog.Debug("opening dstore file", zap.String("path", path))
}
for i := 0; i < s3ReadAttempts; i++ {
if i > 0 { // small wait on retry
zlog.Debug("got an error on s3 OpenObject, retrying",
zap.Error(err),
zap.Int("attempt", i),
zap.Int("max_attempts", s3ReadAttempts),
zap.String("name", name),
zap.String("path", path),
)
time.Sleep(500 * time.Millisecond)
}
var reader *s3.GetObjectOutput
reader, err = s.client.GetObject(ctx, &s3.GetObjectInput{
Bucket: aws.String(s.bucket),
Key: aws.String(path),
})
if err != nil {
var noSuchBucket *types.NoSuchBucket
var noSuchKey *types.NoSuchKey
if errors.As(err, &noSuchBucket) {
err = fmt.Errorf("s3 bucket %s does not exist", s.bucket)
} else if errors.As(err, &noSuchKey) {
err = ErrNotFound
}
continue
}
if bufferedS3Read {
var data []byte
data, err = io.ReadAll(reader.Body)
if err != nil {
continue
}
if err = reader.Body.Close(); err != nil {
continue
}
out, err = s.uncompressedReader(ctx, io.NopCloser(bytes.NewReader(data)))
} else {
httpBody := reader.Body
out, err = s.uncompressedReader(ctx, httpBody)
if err == nil {
out = &s3ReadCloser{outer: out, httpBody: httpBody}
}
}
if tracer.Enabled() {
out = wrapReadCloser(out, func() {
zlog.Debug("closing dstore file", zap.String("path", path))
})
}
return out, err
}
return nil, fmt.Errorf("s3 open object (%d attempts, buffered_read: %v): %w", s3ReadAttempts, bufferedS3Read, err)
}
func (s *S3Store) WalkFrom(ctx context.Context, prefix, startingPoint string, f func(filename string) (err error)) error {
return s.WalkFromTo(ctx, prefix, startingPoint, "", f)
}
func (s *S3Store) WalkFromTo(ctx context.Context, prefix, startingPoint, exclusiveEndPoint string, f func(filename string) (err error)) error {
targetPrefix := s.path
if targetPrefix != "" {
targetPrefix += "/"
}
if prefix != "" {
targetPrefix = filepath.Join(targetPrefix, prefix)
if prefix[len(prefix)-1:] == "/" {
targetPrefix += "/"
}
}
input := &s3.ListObjectsV2Input{
Bucket: aws.String(s.bucket),
Prefix: aws.String(targetPrefix),
}
if startingPoint != "" {
if !strings.HasPrefix(startingPoint, prefix) {
return fmt.Errorf("starting point %q must start with prefix %q", startingPoint, prefix)
}
// "startingPoint" is known to start with "prefix" (checked above), but our the prefix received do
// not contain the "baseURL" which is required because it contains the "path" of the store. So we remove the
// "original prefix" from the "startingPoint" and append it to the real "final" prefix instead.
relativeStartingPoint := strings.TrimPrefix(startingPoint, prefix)
// StartAfter is exclusive, so it gets the key right before the starting point:
// 'helloworld.html' is walked from 'helloworld.htmk'. The walk still filters, because
// keys between the two ('helloworld.htmk0') are returned by that bound.
// StartAfter is also known as 'marker' within S3 compatible layer
if startAfter := keyBefore(targetPrefix + relativeStartingPoint); startAfter != "" {
input.StartAfter = aws.String(startAfter)
}
}
if exclusiveEndPoint != "" && !strings.HasPrefix(exclusiveEndPoint, prefix) {
return fmt.Errorf("exclusive end point %q must start with prefix %q", exclusiveEndPoint, prefix)
}
if tracer.Enabled() {
zlog.Info("walking files from", zap.String("original_prefix", targetPrefix), zap.String("prefix", targetPrefix), zap.Stringp("start_after", input.StartAfter))
}
paginator := s3.NewListObjectsV2Paginator(s.client, input)
for paginator.HasMorePages() {
page, err := paginator.NextPage(ctx)
if err != nil {
return fmt.Errorf("listing objects: %w", err)
}
for _, obj := range page.Contents {
filename := s.toBaseName(*obj.Key)
if filename == "" {
zlog.Debug("got an empty filename from s3 store, ignoring it", zap.String("key", *obj.Key))
continue
}
if startingPoint != "" && filename < startingPoint {
continue
}
// Keys come back sorted, so the first one at or past the bound ends the whole listing.
if exclusiveEndPoint != "" && filename >= exclusiveEndPoint {
return nil
}
if err := f(filename); err != nil {
if errors.Is(err, StopIteration) {
return nil
}
return fmt.Errorf("processing object list: %w", err)
}
}
}
return nil
}
func (s *S3Store) Walk(ctx context.Context, prefix string, f func(filename string) (err error)) error {
return s.WalkFrom(ctx, prefix, "", f)
}
// keyBefore returns the largest key that sorts before target, as far as one rune can take it:
// the last rune is decremented, or dropped when there is nothing below it. The result is the
// tightest StartAfter that still returns target itself, and it stays valid UTF-8, which a bare
// byte decrement would not.
func keyBefore(target string) string {
if target == "" {
return ""
}
lastRune, size := utf8.DecodeLastRuneInString(target)
head := target[0 : len(target)-size]
if lastRune == utf8.RuneError && size <= 1 {
return head // not valid UTF-8, the whole rune goes
}
if lastRune <= ' ' {
return head
}
previous := lastRune - 1
if previous == 0xDFFF {
previous = 0xD7FF // surrogates are not valid runes
}
return head + string(previous)
}
func (s *S3Store) toBaseName(filename string) string {
return strings.TrimPrefix(strings.TrimSuffix(filename, s.pathWithExt("")), s.path+"/")
}
func (s *S3Store) DeleteObject(ctx context.Context, base string) error {
path := s.ObjectPath(base)
_, err := s.client.DeleteObject(ctx, &s3.DeleteObjectInput{
Bucket: aws.String(s.bucket),
Key: aws.String(path),
})
if err != nil {
var noSuchKey *types.NoSuchKey
if errors.As(err, &noSuchKey) {
return ErrNotFound
}
}
return err
}
func (s *S3Store) PushLocalFile(ctx context.Context, localFile, toBaseName string) error {
remove, err := pushLocalFile(ctx, s, localFile, toBaseName)
if retryS3PushLocalFilesDelay != 0 {
time.Sleep(retryS3PushLocalFilesDelay)
exists, err := s.FileExists(ctx, toBaseName)
if err != nil {
zlog.Debug("just pushed file to dstore, but cannot check if it is still there after 500 milliseconds and retryS3PushLocalFiles is set", zap.Error(err))
return err
}
if !exists {
zlog.Debug("just pushed file to dstore, but it disappeared. Pushing again because retryS3PushLocalFiles is set", zap.String("dest basename", toBaseName))
rem, err := pushLocalFile(ctx, s, localFile, toBaseName)
if err != nil {
return err
}
return rem()
}
}
if err != nil {
return err
}
return remove()
}
func (s *S3Store) ListFiles(ctx context.Context, prefix string, max int) ([]string, error) {
return listFiles(ctx, s, prefix, max)
}
// WalkAttributes implements [AttributeWalker]: ListObjectsV2 returns the size and the
// modification time along with every key, so this costs exactly what Walk costs.
func (s *S3Store) WalkAttributes(ctx context.Context, prefix string, f func(entry ObjectEntry) error) error {
paginator := s3.NewListObjectsV2Paginator(s.client, &s3.ListObjectsV2Input{
Bucket: aws.String(s.bucket),
Prefix: aws.String(s.listingPrefix(prefix)),
})
for paginator.HasMorePages() {
page, err := paginator.NextPage(ctx)
if err != nil {
return fmt.Errorf("listing objects: %w", err)
}
for _, obj := range page.Contents {
filename := s.toBaseName(*obj.Key)
if filename == "" {
zlog.Debug("got an empty filename from s3 store, ignoring it", zap.String("key", *obj.Key))
continue
}
entry := ObjectEntry{Name: filename}
if obj.Size != nil {
entry.Size = *obj.Size
}
if obj.LastModified != nil {
entry.LastModified = *obj.LastModified
}
if err := f(entry); err != nil {
if errors.Is(err, StopIteration) {
return nil
}
return fmt.Errorf("processing object list: %w", err)
}
}
}
return nil
}
// ListFolders implements [FolderLister] with a delimited listing, which S3 answers with common
// prefixes without ever walking the objects nested under them.
func (s *S3Store) ListFolders(ctx context.Context, prefix string, max int) ([]string, error) {
return s.ListFoldersFromTo(ctx, prefix, "", "", max)
}
// ListFoldersFromTo starts the listing at the lower bound, which S3 honours server-side, and
// stops at the upper one, which it has no parameter for.
func (s *S3Store) ListFoldersFromTo(ctx context.Context, prefix, inclusiveFrom, exclusiveTo string, max int) ([]string, error) {
prefix = asFolderPrefix(prefix)
if err := checkFolderRange(prefix, inclusiveFrom, exclusiveTo); err != nil {
return nil, err
}
input := &s3.ListObjectsV2Input{
Bucket: aws.String(s.bucket),
Prefix: aws.String(s.listingPrefix(prefix)),
Delimiter: aws.String("/"),
}
if inclusiveFrom != "" {
// StartAfter is exclusive, and every folder key ends with a "/", so dropping that "/"
// gives the largest key the service may skip while still returning the folder itself.
if startAfter := strings.TrimSuffix(s.listingPrefix(prefix)+strings.TrimPrefix(inclusiveFrom, prefix), "/"); startAfter != "" {
input.StartAfter = aws.String(startAfter)
}
}
paginator := s3.NewListObjectsV2Paginator(s.client, input)
folders := newLimitedFolders(max)
if folders.full() {
return folders.folders, nil
}
for paginator.HasMorePages() {
page, err := paginator.NextPage(ctx)
if err != nil {
return nil, fmt.Errorf("listing folders: %w", err)
}
for _, commonPrefix := range page.CommonPrefixes {
if commonPrefix.Prefix == nil {
continue
}
folder := s.toBaseName(*commonPrefix.Prefix)
if folder == "" {
continue
}
// Common prefixes come back sorted, so the first one at or past the bound ends the listing.
if exclusiveTo != "" && folder >= exclusiveTo {
return folders.folders, nil
}
if !folderInRange(folder, inclusiveFrom, exclusiveTo) {
continue
}
if folders.full() {
return folders.folders, nil
}
folders.add(folder)
}
}
return folders.folders, nil
}
// listingPrefix turns a store-relative prefix into the absolute key prefix the bucket expects,
// keeping a trailing "/" that filepath.Join would eat.
func (s *S3Store) listingPrefix(prefix string) string {
targetPrefix := s.path
if targetPrefix != "" {
targetPrefix += "/"
}
if prefix == "" {
return targetPrefix
}
targetPrefix = path.Join(targetPrefix, prefix)
if strings.HasSuffix(prefix, "/") {
targetPrefix += "/"
}
return targetPrefix
}