-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy paths3_bucket.go
1467 lines (1290 loc) · 40 KB
/
s3_bucket.go
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
995
996
997
998
999
1000
package pail
import (
"archive/tar"
"compress/gzip"
"context"
"io"
"net/http"
"os"
"path/filepath"
"regexp"
"strings"
"time"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/credentials"
"github.com/aws/aws-sdk-go-v2/credentials/stscreds"
s3Manager "github.com/aws/aws-sdk-go-v2/feature/s3/manager"
"github.com/aws/aws-sdk-go-v2/service/s3"
s3Types "github.com/aws/aws-sdk-go-v2/service/s3/types"
"github.com/aws/aws-sdk-go-v2/service/sts"
"github.com/aws/smithy-go"
"github.com/evergreen-ci/utility"
"github.com/mongodb/grip"
"github.com/mongodb/grip/message"
"github.com/pkg/errors"
)
const compressionEncoding = "gzip"
// S3Permissions is a type that describes the object canned ACL from S3.
type S3Permissions string
// Valid S3 permissions.
const (
S3PermissionsPrivate S3Permissions = S3Permissions(string(s3Types.ObjectCannedACLPrivate))
S3PermissionsPublicRead S3Permissions = S3Permissions(string(s3Types.ObjectCannedACLPublicRead))
S3PermissionsPublicReadWrite S3Permissions = S3Permissions(string(s3Types.ObjectCannedACLPublicReadWrite))
S3PermissionsAuthenticatedRead S3Permissions = S3Permissions(string(s3Types.ObjectCannedACLAuthenticatedRead))
S3PermissionsAWSExecRead S3Permissions = S3Permissions(string(s3Types.ObjectCannedACLAwsExecRead))
S3PermissionsBucketOwnerRead S3Permissions = S3Permissions(string(s3Types.ObjectCannedACLBucketOwnerRead))
S3PermissionsBucketOwnerFullControl S3Permissions = S3Permissions(string(s3Types.ObjectCannedACLBucketOwnerFullControl))
)
// Validate checks that the S3Permissions string is valid.
func (p S3Permissions) Validate() error {
switch p {
case S3PermissionsPublicRead, S3PermissionsPublicReadWrite:
return nil
case S3PermissionsPrivate, S3PermissionsAuthenticatedRead, S3PermissionsAWSExecRead:
return nil
case S3PermissionsBucketOwnerRead, S3PermissionsBucketOwnerFullControl:
return nil
default:
return errors.New("invalid S3 permissions type specified")
}
}
type s3BucketSmall struct {
s3Bucket
}
type s3BucketLarge struct {
s3Bucket
minPartSize int
}
type s3Bucket struct {
dryRun bool
deleteOnPush bool
deleteOnPull bool
singleFileChecksums bool
compress bool
verbose bool
batchSize int
svc *s3.Client
name string
prefix string
permissions S3Permissions
contentType string
}
// S3Options support the use and creation of S3 backed buckets.
type S3Options struct {
// DryRun enables running in a mode that will not execute any
// operations that modify the bucket.
DryRun bool
// DeleteOnSync will delete all objects from the target that do not
// exist in the destination after the completion of a sync operation
// (Push/Pull).
DeleteOnSync bool
// DeleteOnPush will delete all objects from the target that do not
// exist in the source after the completion of Push.
DeleteOnPush bool
// DeleteOnPull will delete all objects from the target that do not
// exist in the source after the completion of Pull.
DeleteOnPull bool
// Compress enables gzipping of uploaded objects. For downloading, objects
// that are compressed with gzip are automatically decoded.
Compress bool
// UseSingleFileChecksums forces the bucket to checksum files before
// running uploads and download operation (rather than doing these
// operations independently.) Useful for large files, particularly in
// coordination with the parallel sync bucket implementations.
UseSingleFileChecksums bool
// Verbose sets the logging mode to "debug".
Verbose bool
// MaxRetries sets the number of retry attempts for S3 operations.
// By default it defers to the AWS SDK's default.
MaxRetries *int
// Credentials allows the passing in of explicit AWS credentials. These
// will override the default credentials chain. (Optional)
Credentials aws.CredentialsProvider
// SharedCredentialsFilepath, when not empty, will override the default
// credentials chain and the Credentials value (see above). (Optional)
SharedCredentialsFilepath string
// SharedCredentialsProfile, when not empty, will fetch the given
// credentials profile from the shared credentials file. (Optional)
SharedCredentialsProfile string
// AssumeRoleARN specifies an IAM role ARN. When not empty, it will be
// used to assume the given role for this session. See
// `https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles.html` for
// more information. (Optional)
AssumeRoleARN string
// AssumeRoleOptions provide a mechanism to override defaults by
// applying changes to the AssumeRoleProvider struct created with this
// session. This field is ignored if AssumeRoleARN is not set.
// (Optional)
AssumeRoleOptions []func(*stscreds.AssumeRoleOptions)
// Region specifies the AWS region.
Region string
// Name specifies the name of the bucket.
Name string
// Prefix specifies the prefix to use. (Optional)
Prefix string
// Permissions sets the S3 permissions to use for each object. Defaults
// to FULL_CONTROL. See
// `https://docs.aws.amazon.com/AmazonS3/latest/dev/acl-overview.html`
// for more information.
Permissions S3Permissions
// ContentType sets the standard MIME type of the object data. Defaults
// to nil. See
//`https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.17`
// for more information.
ContentType string
}
// CreateAWSCredentials is a wrapper for creating static AWS credentials.
func CreateAWSCredentials(awsKey, awsPassword, awsToken string) aws.CredentialsProvider {
return credentials.NewStaticCredentialsProvider(awsKey, awsPassword, awsToken)
}
func (s *s3Bucket) normalizeKey(key string) string { return s.Join(s.prefix, key) }
func (s *s3Bucket) denormalizeKey(key string) string { return consistentTrimPrefix(key, s.prefix) }
func newS3BucketBase(ctx context.Context, client *http.Client, options S3Options) (*s3Bucket, error) {
if options.Permissions != "" {
if err := options.Permissions.Validate(); err != nil {
return nil, errors.WithStack(err)
}
}
if (options.DeleteOnPush != options.DeleteOnPull) && options.DeleteOnSync {
return nil, errors.New("ambiguous delete on sync options set")
}
config := configOpts{
region: options.Region,
maxRetries: aws.ToInt(options.MaxRetries),
client: client,
sharedCredentialsFilepath: options.SharedCredentialsFilepath,
sharedCredentialsProfile: options.SharedCredentialsProfile,
}
cfg, err := getCachedConfig(ctx, config)
if err != nil {
return nil, errors.Wrap(err, "getting AWS config")
}
var s3Opts []func(*s3.Options)
if options.Credentials != nil {
s3Opts = append(s3Opts, func(opts *s3.Options) {
opts.Credentials = options.Credentials
})
} else if options.AssumeRoleARN != "" {
s3Opts = append(s3Opts, func(opts *s3.Options) {
assumeRoleClient := sts.NewFromConfig(*cfg)
opts.Credentials = stscreds.NewAssumeRoleProvider(assumeRoleClient, options.AssumeRoleARN, options.AssumeRoleOptions...)
})
}
svc := s3.NewFromConfig(*cfg, s3Opts...)
return &s3Bucket{
name: options.Name,
prefix: options.Prefix,
compress: options.Compress,
singleFileChecksums: options.UseSingleFileChecksums,
verbose: options.Verbose,
svc: svc,
permissions: options.Permissions,
contentType: options.ContentType,
dryRun: options.DryRun,
batchSize: 1000,
deleteOnPush: options.DeleteOnPush || options.DeleteOnSync,
deleteOnPull: options.DeleteOnPull || options.DeleteOnSync,
}, nil
}
var configCache = make(map[configOpts]*aws.Config)
type configOpts struct {
region string
maxRetries int
sharedCredentialsFilepath string
sharedCredentialsProfile string
expiry time.Duration
client *http.Client
}
func getCachedConfig(ctx context.Context, cfgOpts configOpts) (*aws.Config, error) {
isDefault := cfgOpts.client == nil &&
cfgOpts.sharedCredentialsFilepath == "" &&
cfgOpts.sharedCredentialsProfile == ""
if isDefault && configCache[cfgOpts] != nil {
return configCache[cfgOpts], nil
}
var newCfgOpts []func(*config.LoadOptions) error
if cfgOpts.maxRetries != 0 {
newCfgOpts = append(newCfgOpts, config.WithRetryMaxAttempts(cfgOpts.maxRetries))
}
if cfgOpts.region != "" {
newCfgOpts = append(newCfgOpts, config.WithRegion(cfgOpts.region))
}
if cfgOpts.client != nil {
newCfgOpts = append(newCfgOpts, config.WithHTTPClient(cfgOpts.client))
}
if cfgOpts.sharedCredentialsFilepath != "" {
newCfgOpts = append(newCfgOpts, config.WithSharedCredentialsFiles([]string{cfgOpts.sharedCredentialsFilepath}))
}
if cfgOpts.sharedCredentialsProfile != "" {
newCfgOpts = append(newCfgOpts, config.WithSharedConfigProfile(cfgOpts.sharedCredentialsProfile))
}
if cfgOpts.expiry != 0 {
newCfgOpts = append(newCfgOpts, config.WithCredentialsCacheOptions(func(cco *aws.CredentialsCacheOptions) {
cco.ExpiryWindow = cfgOpts.expiry
}))
}
newCfg, err := config.LoadDefaultConfig(ctx, newCfgOpts...)
if err != nil {
return nil, errors.Wrap(err, "creating new session")
}
if isDefault {
configCache[cfgOpts] = &newCfg
}
return &newCfg, nil
}
// NewS3Bucket returns a Bucket implementation backed by S3. This
// implementation does not support multipart uploads, if you would like to add
// objects larger than 5 gigabytes see NewS3MultiPartBucket.
func NewS3Bucket(ctx context.Context, options S3Options) (Bucket, error) {
bucket, err := newS3BucketBase(ctx, nil, options)
if err != nil {
return nil, err
}
return &s3BucketSmall{s3Bucket: *bucket}, nil
}
// NewS3BucketWithHTTPClient returns a Bucket implementation backed by S3 with
// an existing HTTP client connection. This implementation does not support
// multipart uploads, if you would like to add objects larger than 5
// gigabytes see NewS3MultiPartBucket.
func NewS3BucketWithHTTPClient(ctx context.Context, client *http.Client, options S3Options) (Bucket, error) {
bucket, err := newS3BucketBase(ctx, client, options)
if err != nil {
return nil, err
}
return &s3BucketSmall{s3Bucket: *bucket}, nil
}
// NewS3MultiPartBucket returns a Bucket implementation backed by S3
// that supports multipart uploads for large objects.
func NewS3MultiPartBucket(ctx context.Context, options S3Options) (Bucket, error) {
bucket, err := newS3BucketBase(ctx, nil, options)
if err != nil {
return nil, err
}
// 5MB is the minimum size for a multipart upload, so buffer needs to
// be at least that big.
return &s3BucketLarge{s3Bucket: *bucket, minPartSize: 1024 * 1024 * 5}, nil
}
// NewS3MultiPartBucketWithHTTPClient returns a Bucket implementation backed
// by S3 with an existing HTTP client connection that supports multipart
// uploads for large objects.
func NewS3MultiPartBucketWithHTTPClient(ctx context.Context, client *http.Client, options S3Options) (Bucket, error) {
bucket, err := newS3BucketBase(ctx, client, options)
if err != nil {
return nil, err
}
// 5MB is the minimum size for a multipart upload, so buffer needs to
// be at least that big.
return &s3BucketLarge{s3Bucket: *bucket, minPartSize: 1024 * 1024 * 5}, nil
}
func (s *s3Bucket) String() string { return s.name }
func (s *s3Bucket) Check(ctx context.Context) error {
input := &s3.HeadBucketInput{
Bucket: aws.String(s.name),
}
_, err := s.svc.HeadBucket(ctx, input)
// Aside from a 404 Not Found error, HEAD bucket returns a 403
// Forbidden error. If the latter is the case, that is OK because
// we know the bucket exists and the given credentials may have
// access to a sub-bucket. See
// https://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketHEAD.html
// for more information.
if err != nil {
var apiErr smithy.APIError
if errors.As(err, &apiErr) {
if apiErr.ErrorCode() == "NotFound" {
return errors.Wrap(err, "finding bucket")
}
}
}
return nil
}
func (s *s3Bucket) Exists(ctx context.Context, key string) (bool, error) {
_, err := s.svc.HeadObject(ctx, &s3.HeadObjectInput{
Bucket: aws.String(s.name),
Key: aws.String(s.normalizeKey(key)),
})
if err != nil {
var apiErr smithy.APIError
if errors.As(err, &apiErr) {
if apiErr.ErrorCode() == "NotFound" {
return false, nil
}
}
return false, errors.Wrap(err, "getting S3 head object")
}
return true, nil
}
func (s *s3Bucket) Join(elems ...string) string { return consistentJoin(elems) }
type smallWriteCloser struct {
isClosed bool
dryRun bool
compress bool
verbose bool
svc *s3.Client
buffer []byte
name string
ctx context.Context
key string
permissions S3Permissions
contentType string
}
type largeWriteCloser struct {
isCreated bool
isClosed bool
compress bool
dryRun bool
verbose bool
partNumber int32
minSize int
svc *s3.Client
ctx context.Context
buffer []byte
completedParts []s3Types.CompletedPart
name string
key string
permissions S3Permissions
contentType string
uploadID string
}
func (w *largeWriteCloser) create() error {
grip.DebugWhen(w.verbose, message.Fields{
"type": "s3",
"dry_run": w.dryRun,
"operation": "large writer create",
"bucket": w.name,
"key": w.key,
})
if !w.dryRun {
input := &s3.CreateMultipartUploadInput{
Bucket: aws.String(w.name),
Key: aws.String(w.key),
ACL: s3Types.ObjectCannedACL(string(w.permissions)),
ContentType: aws.String(w.contentType),
}
if w.compress {
input.ContentEncoding = aws.String(compressionEncoding)
}
result, err := w.svc.CreateMultipartUpload(w.ctx, input)
if err != nil {
return errors.Wrap(err, "creating a multipart upload")
}
w.uploadID = *result.UploadId
}
w.isCreated = true
w.partNumber++
return nil
}
func (w *largeWriteCloser) complete() error {
grip.DebugWhen(w.verbose, message.Fields{
"type": "s3",
"dry_run": w.dryRun,
"operation": "large writer complete",
"bucket": w.name,
"key": w.key,
})
if !w.dryRun {
input := &s3.CompleteMultipartUploadInput{
Bucket: aws.String(w.name),
Key: aws.String(w.key),
MultipartUpload: &s3Types.CompletedMultipartUpload{
Parts: w.completedParts,
},
UploadId: aws.String(w.uploadID),
}
_, err := w.svc.CompleteMultipartUpload(w.ctx, input)
if err != nil {
abortErr := w.abort()
if abortErr != nil {
return errors.Wrap(abortErr, "aborting multipart upload")
}
return errors.Wrap(err, "completing multipart upload")
}
}
return nil
}
func (w *largeWriteCloser) abort() error {
grip.DebugWhen(w.verbose, message.Fields{
"type": "s3",
"dry_run": w.dryRun,
"operation": "large writer abort",
"bucket": w.name,
"key": w.key,
})
input := &s3.AbortMultipartUploadInput{
Bucket: aws.String(w.name),
Key: aws.String(w.key),
UploadId: aws.String(w.uploadID),
}
_, err := w.svc.AbortMultipartUpload(w.ctx, input)
return err
}
func (w *largeWriteCloser) flush() error {
grip.DebugWhen(w.verbose, message.Fields{
"type": "s3",
"dry_run": w.dryRun,
"operation": "large writer flush",
"bucket": w.name,
"key": w.key,
})
if !w.isCreated {
err := w.create()
if err != nil {
return err
}
}
if !w.dryRun {
input := &s3.UploadPartInput{
Body: s3Manager.ReadSeekCloser(strings.NewReader(string(w.buffer))),
Bucket: aws.String(w.name),
Key: aws.String(w.key),
PartNumber: aws.Int32(w.partNumber),
UploadId: aws.String(w.uploadID),
}
result, err := w.svc.UploadPart(w.ctx, input)
if err != nil {
abortErr := w.abort()
if abortErr != nil {
return errors.Wrap(abortErr, "aborting multipart upload")
}
return errors.Wrap(err, "uploading part")
}
w.completedParts = append(w.completedParts, s3Types.CompletedPart{
ETag: result.ETag,
PartNumber: aws.Int32(w.partNumber),
})
}
w.buffer = []byte{}
w.partNumber++
return nil
}
func (w *smallWriteCloser) Write(p []byte) (int, error) {
grip.DebugWhen(w.verbose, message.Fields{
"type": "s3",
"dry_run": w.dryRun,
"operation": "small writer write",
"bucket": w.name,
"key": w.key,
})
if w.isClosed {
return 0, errors.New("writer already closed")
}
w.buffer = append(w.buffer, p...)
return len(p), nil
}
func (w *largeWriteCloser) Write(p []byte) (int, error) {
grip.DebugWhen(w.verbose, message.Fields{
"type": "s3",
"dry_run": w.dryRun,
"operation": "large writer write",
"bucket": w.name,
"key": w.key,
})
if w.isClosed {
return 0, errors.New("writer already closed")
}
w.buffer = append(w.buffer, p...)
if len(w.buffer) > w.minSize {
err := w.flush()
if err != nil {
return 0, err
}
}
return len(p), nil
}
func (w *smallWriteCloser) Close() error {
grip.DebugWhen(w.verbose, message.Fields{
"type": "s3",
"dry_run": w.dryRun,
"operation": "small writer close",
"bucket": w.name,
"key": w.key,
})
if w.isClosed {
return errors.New("writer already closed")
}
if w.dryRun {
return nil
}
input := &s3.PutObjectInput{
Body: s3Manager.ReadSeekCloser(strings.NewReader(string(w.buffer))),
Bucket: aws.String(w.name),
Key: aws.String(w.key),
ACL: s3Types.ObjectCannedACL(string(w.permissions)),
ContentType: aws.String(w.contentType),
}
if w.compress {
input.ContentEncoding = aws.String(compressionEncoding)
}
_, err := w.svc.PutObject(w.ctx, input)
return errors.Wrap(err, "copying data to file")
}
func (w *largeWriteCloser) Close() error {
grip.DebugWhen(w.verbose, message.Fields{
"type": "s3",
"dry_run": w.dryRun,
"operation": "large writer close",
"bucket": w.name,
"key": w.key,
})
if w.isClosed {
return errors.New("writer already closed")
}
if len(w.buffer) > 0 || w.partNumber == 0 {
err := w.flush()
if err != nil {
return err
}
}
err := w.complete()
return err
}
type compressingWriteCloser struct {
gzipWriter io.WriteCloser
s3Writer io.WriteCloser
}
func (w *compressingWriteCloser) Write(p []byte) (int, error) {
return w.gzipWriter.Write(p)
}
func (w *compressingWriteCloser) Close() error {
catcher := grip.NewBasicCatcher()
catcher.Add(w.gzipWriter.Close())
catcher.Add(w.s3Writer.Close())
return catcher.Resolve()
}
func (s *s3BucketSmall) Writer(ctx context.Context, key string) (io.WriteCloser, error) {
grip.DebugWhen(s.verbose, message.Fields{
"type": "s3",
"dry_run": s.dryRun,
"operation": "small writer",
"bucket": s.name,
"bucket_prefix": s.prefix,
"key": key,
})
writer := &smallWriteCloser{
name: s.name,
svc: s.svc,
ctx: ctx,
key: s.normalizeKey(key),
permissions: s.permissions,
contentType: s.contentType,
dryRun: s.dryRun,
compress: s.compress,
}
if s.compress {
return &compressingWriteCloser{
gzipWriter: gzip.NewWriter(writer),
s3Writer: writer,
}, nil
}
return writer, nil
}
func (s *s3BucketLarge) Writer(ctx context.Context, key string) (io.WriteCloser, error) {
grip.DebugWhen(s.verbose, message.Fields{
"type": "s3",
"dry_run": s.dryRun,
"operation": "large writer",
"bucket": s.name,
"bucket_prefix": s.prefix,
"key": key,
})
writer := &largeWriteCloser{
minSize: s.minPartSize,
name: s.name,
svc: s.svc,
ctx: ctx,
key: s.normalizeKey(key),
permissions: s.permissions,
contentType: s.contentType,
dryRun: s.dryRun,
compress: s.compress,
verbose: s.verbose,
}
if s.compress {
return &compressingWriteCloser{
gzipWriter: gzip.NewWriter(writer),
s3Writer: writer,
}, nil
}
return writer, nil
}
func (s *s3Bucket) Reader(ctx context.Context, key string) (io.ReadCloser, error) {
grip.DebugWhen(s.verbose, message.Fields{
"type": "s3",
"operation": "reader",
"bucket": s.name,
"bucket_prefix": s.prefix,
"key": key,
})
input := &s3.GetObjectInput{
Bucket: aws.String(s.name),
Key: aws.String(s.normalizeKey(key)),
}
result, err := s.svc.GetObject(ctx, input)
if err != nil {
var apiErr smithy.APIError
if errors.As(err, &apiErr) {
if apiErr.ErrorCode() == "NoSuchKey" {
return nil, MakeKeyNotFoundError(err)
}
}
return nil, err
}
if aws.ToString(result.ContentEncoding) == "gzip" {
return gzip.NewReader(result.Body)
}
return result.Body, nil
}
func putHelper(ctx context.Context, b Bucket, key string, r io.Reader) error {
f, err := b.Writer(ctx, key)
if err != nil {
return errors.WithStack(err)
}
_, err = io.Copy(f, r)
if err != nil {
_ = f.Close()
return errors.Wrap(err, "copying data to file")
}
return errors.WithStack(f.Close())
}
func (s *s3BucketSmall) Put(ctx context.Context, key string, r io.Reader) error {
grip.DebugWhen(s.verbose, message.Fields{
"type": "s3",
"dry_run": s.dryRun,
"operation": "put",
"bucket": s.name,
"bucket_prefix": s.prefix,
"key": key,
})
return putHelper(ctx, s, key, r)
}
func (s *s3BucketLarge) Put(ctx context.Context, key string, r io.Reader) error {
grip.DebugWhen(s.verbose, message.Fields{
"type": "s3",
"dry_run": s.dryRun,
"operation": "put",
"bucket": s.name,
"bucket_prefix": s.prefix,
"key": key,
})
return putHelper(ctx, s, key, r)
}
func (s *s3Bucket) Get(ctx context.Context, key string) (io.ReadCloser, error) {
grip.DebugWhen(s.verbose, message.Fields{
"type": "s3",
"operation": "get",
"bucket": s.name,
"bucket_prefix": s.prefix,
"key": key,
})
return s.Reader(ctx, key)
}
func (s *s3Bucket) s3WithUploadChecksumHelper(ctx context.Context, target, file string) (bool, error) {
localmd5, err := utility.MD5SumFile(file)
if err != nil {
return false, errors.Wrapf(err, "checksumming '%s'", file)
}
input := &s3.HeadObjectInput{
Bucket: aws.String(s.name),
Key: aws.String(target),
IfMatch: aws.String(localmd5),
}
_, err = s.svc.HeadObject(ctx, input)
var apiErr smithy.APIError
if errors.As(err, &apiErr) {
if apiErr.ErrorCode() == "PreconditionFailed" || apiErr.ErrorCode() == "NotFound" {
return true, nil
}
}
return false, errors.Wrapf(err, "checking if object '%s' exists", target)
}
func doUpload(ctx context.Context, b Bucket, key, path string) error {
f, err := os.Open(path)
if err != nil {
return errors.Wrapf(err, "opening file '%s'", path)
}
defer f.Close()
return errors.WithStack(b.Put(ctx, key, f))
}
func (s *s3Bucket) uploadHelper(ctx context.Context, b Bucket, key, path string) error {
grip.DebugWhen(s.verbose, message.Fields{
"type": "s3",
"dry_run": s.dryRun,
"operation": "upload",
"bucket": s.name,
"bucket_prefix": s.prefix,
"key": key,
"path": path,
})
if s.singleFileChecksums {
shouldUpload, err := s.s3WithUploadChecksumHelper(ctx, key, path)
if err != nil {
return errors.WithStack(err)
}
if !shouldUpload {
return nil
}
}
return errors.WithStack(doUpload(ctx, b, key, path))
}
func (s *s3BucketLarge) Upload(ctx context.Context, key, path string) error {
return s.uploadHelper(ctx, s, key, path)
}
func (s *s3BucketSmall) Upload(ctx context.Context, key, path string) error {
return s.uploadHelper(ctx, s, key, path)
}
func doDownload(ctx context.Context, b Bucket, key, path string) error {
reader, err := b.Reader(ctx, key)
if err != nil {
return errors.WithStack(err)
}
if err = os.MkdirAll(filepath.Dir(path), 0700); err != nil {
return errors.Wrapf(err, "creating enclosing directory for file '%s'", path)
}
f, err := os.Create(path)
if err != nil {
return errors.Wrapf(err, "creating file '%s'", path)
}
_, err = io.Copy(f, reader)
if err != nil {
_ = f.Close()
return errors.Wrap(err, "copying data")
}
return errors.WithStack(f.Close())
}
func s3DownloadWithChecksum(ctx context.Context, b Bucket, item BucketItem, local string) error {
localmd5, err := utility.MD5SumFile(local)
if os.IsNotExist(errors.Cause(err)) {
if err = doDownload(ctx, b, item.Name(), local); err != nil {
return errors.WithStack(err)
}
} else if err != nil {
return errors.WithStack(err)
}
if localmd5 != item.Hash() {
if err = doDownload(ctx, b, item.Name(), local); err != nil {
return errors.WithStack(err)
}
}
return nil
}
func (s *s3Bucket) downloadHelper(ctx context.Context, b Bucket, key, path string) error {
grip.DebugWhen(s.verbose, message.Fields{
"type": "s3",
"operation": "download",
"bucket": s.name,
"bucket_prefix": s.prefix,
"key": key,
"path": path,
})
if s.singleFileChecksums {
iter, err := s.listHelper(ctx, b, s.normalizeKey(key))
if err != nil {
return errors.WithStack(err)
}
if !iter.Next(ctx) {
return errors.New("no results found")
}
return s3DownloadWithChecksum(ctx, b, iter.Item(), path)
}
return doDownload(ctx, b, key, path)
}
func (s *s3BucketSmall) Download(ctx context.Context, key, path string) error {
return s.downloadHelper(ctx, s, key, path)
}
func (s *s3BucketLarge) Download(ctx context.Context, key, path string) error {
return s.downloadHelper(ctx, s, key, path)
}
func (s *s3Bucket) pushHelper(ctx context.Context, b Bucket, opts SyncOptions) error {
grip.DebugWhen(s.verbose, message.Fields{
"type": "s3",
"dry_run": s.dryRun,
"operation": "push",
"bucket": s.name,
"bucket_prefix": s.prefix,
"remote": opts.Remote,
"local": opts.Local,
"exclude": opts.Exclude,
})
var re *regexp.Regexp
var err error
if opts.Exclude != "" {
re, err = regexp.Compile(opts.Exclude)
if err != nil {
return errors.Wrap(err, "compiling exclude regex")
}
}
files, err := walkLocalTree(ctx, opts.Local)
if err != nil {
return errors.WithStack(err)
}
for _, fn := range files {
if re != nil && re.MatchString(fn) {
continue
}
target := s.Join(opts.Remote, fn)
file := filepath.Join(opts.Local, fn)
shouldUpload, err := s.s3WithUploadChecksumHelper(ctx, target, file)
if err != nil {
return errors.WithStack(err)
}
if !shouldUpload {
continue
}
if err = doUpload(ctx, b, target, file); err != nil {
return errors.WithStack(err)
}
}
if s.deleteOnPush && !s.dryRun {
return errors.Wrap(deleteOnPush(ctx, files, opts.Remote, b), "deleting on sync after push")
}
return nil
}
func (s *s3BucketSmall) Push(ctx context.Context, opts SyncOptions) error {
return s.pushHelper(ctx, s, opts)
}
func (s *s3BucketLarge) Push(ctx context.Context, opts SyncOptions) error {
return s.pushHelper(ctx, s, opts)
}
func (s *s3Bucket) pullHelper(ctx context.Context, b Bucket, opts SyncOptions) error {
grip.DebugWhen(s.verbose, message.Fields{
"type": "s3",
"operation": "pull",
"bucket": s.name,
"bucket_prefix": s.prefix,
"remote": opts.Remote,
"local": opts.Local,
"exclude": opts.Exclude,
})
var re *regexp.Regexp
var err error
if opts.Exclude != "" {
re, err = regexp.Compile(opts.Exclude)
if err != nil {
return errors.Wrap(err, "compiling exclude regex")
}
}
iter, err := b.List(ctx, opts.Remote)
if err != nil {
return errors.WithStack(err)
}
keys := []string{}
for iter.Next(ctx) {
if iter.Err() != nil {
return errors.Wrap(err, "iterating bucket")
}
if re != nil && re.MatchString(iter.Item().Name()) {
continue
}
localName, err := filepath.Rel(opts.Remote, iter.Item().Name())
if err != nil {
return errors.Wrap(err, "getting relative filepath")
}
keys = append(keys, localName)
if err := s3DownloadWithChecksum(ctx, b, iter.Item(), filepath.Join(opts.Local, localName)); err != nil {
return errors.WithStack(err)