forked from peak/s5cmd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
s3.go
938 lines (785 loc) · 22 KB
/
s3.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
package storage
import (
"context"
"crypto/tls"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
urlpkg "net/url"
"os"
"strconv"
"strings"
"sync"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/client"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/endpoints"
"github.com/aws/aws-sdk-go/aws/request"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3"
"github.com/aws/aws-sdk-go/service/s3/s3iface"
"github.com/aws/aws-sdk-go/service/s3/s3manager"
"github.com/aws/aws-sdk-go/service/s3/s3manager/s3manageriface"
"github.com/spansh/s5cmd/log"
"github.com/spansh/s5cmd/storage/url"
)
var sentinelURL = urlpkg.URL{}
const (
// deleteObjectsMax is the max allowed objects to be deleted on single HTTP
// request.
deleteObjectsMax = 1000
// Amazon Accelerated Transfer endpoint
transferAccelEndpoint = "s3-accelerate.amazonaws.com"
// Google Cloud Storage endpoint
gcsEndpoint = "storage.googleapis.com"
)
// Re-used AWS sessions dramatically improve performance.
var globalSessionCache = &SessionCache{
sessions: map[Options]*session.Session{},
}
// S3 is a storage type which interacts with S3API, DownloaderAPI and
// UploaderAPI.
type S3 struct {
api s3iface.S3API
downloader s3manageriface.DownloaderAPI
uploader s3manageriface.UploaderAPI
endpointURL urlpkg.URL
dryRun bool
}
func parseEndpoint(endpoint string) (urlpkg.URL, error) {
if endpoint == "" {
return sentinelURL, nil
}
// add a scheme to correctly parse the endpoint. Without a scheme,
// url.Parse will put the host information in path"
if !strings.HasPrefix(endpoint, "http") {
endpoint = "http://" + endpoint
}
u, err := urlpkg.Parse(endpoint)
if err != nil {
return sentinelURL, fmt.Errorf("parse endpoint %q: %v", endpoint, err)
}
return *u, nil
}
// NewS3Storage creates new S3 session.
func newS3Storage(ctx context.Context, opts Options) (*S3, error) {
endpointURL, err := parseEndpoint(opts.Endpoint)
if err != nil {
return nil, err
}
awsSession, err := globalSessionCache.newSession(ctx, opts)
if err != nil {
return nil, err
}
return &S3{
api: s3.New(awsSession),
downloader: s3manager.NewDownloader(awsSession),
uploader: s3manager.NewUploader(awsSession),
endpointURL: endpointURL,
dryRun: opts.DryRun,
}, nil
}
// Stat retrieves metadata from S3 object without returning the object itself.
func (s *S3) Stat(ctx context.Context, url *url.URL) (*Object, error) {
output, err := s.api.HeadObjectWithContext(ctx, &s3.HeadObjectInput{
Bucket: aws.String(url.Bucket),
Key: aws.String(url.Path),
})
if err != nil {
if errHasCode(err, "NotFound") {
return nil, ErrGivenObjectNotFound
}
return nil, err
}
etag := aws.StringValue(output.ETag)
mod := aws.TimeValue(output.LastModified)
return &Object{
URL: url,
Etag: strings.Trim(etag, `"`),
ModTime: &mod,
Size: aws.Int64Value(output.ContentLength),
}, nil
}
// List is a non-blocking S3 list operation which paginates and filters S3
// keys. If no object found or an error is encountered during this period,
// it sends these errors to object channel.
func (s *S3) List(ctx context.Context, url *url.URL, _ bool) <-chan *Object {
if isGoogleEndpoint(s.endpointURL) {
return s.listObjects(ctx, url)
}
return s.listObjectsV2(ctx, url)
}
func (s *S3) listObjectsV2(ctx context.Context, url *url.URL) <-chan *Object {
listInput := s3.ListObjectsV2Input{
Bucket: aws.String(url.Bucket),
Prefix: aws.String(url.Prefix),
}
if url.Delimiter != "" {
listInput.SetDelimiter(url.Delimiter)
}
objCh := make(chan *Object)
go func() {
defer close(objCh)
objectFound := false
var now time.Time
err := s.api.ListObjectsV2PagesWithContext(ctx, &listInput, func(p *s3.ListObjectsV2Output, lastPage bool) bool {
for _, c := range p.CommonPrefixes {
prefix := aws.StringValue(c.Prefix)
if !url.Match(prefix) {
continue
}
newurl := url.Clone()
newurl.Path = prefix
objCh <- &Object{
URL: newurl,
Type: ObjectType{os.ModeDir},
}
objectFound = true
}
// track the instant object iteration began,
// so it can be used to bypass objects created after this instant
if now.IsZero() {
now = time.Now().UTC()
}
for _, c := range p.Contents {
key := aws.StringValue(c.Key)
if !url.Match(key) {
continue
}
mod := aws.TimeValue(c.LastModified).UTC()
if mod.After(now) {
objectFound = true
continue
}
var objtype os.FileMode
if strings.HasSuffix(key, "/") {
objtype = os.ModeDir
}
newurl := url.Clone()
newurl.Path = aws.StringValue(c.Key)
etag := aws.StringValue(c.ETag)
objCh <- &Object{
URL: newurl,
Etag: strings.Trim(etag, `"`),
ModTime: &mod,
Type: ObjectType{objtype},
Size: aws.Int64Value(c.Size),
StorageClass: StorageClass(aws.StringValue(c.StorageClass)),
}
objectFound = true
}
return !lastPage
})
if err != nil {
objCh <- &Object{Err: err}
return
}
if !objectFound {
objCh <- &Object{Err: ErrNoObjectFound}
}
}()
return objCh
}
// listObjects is used for cloud services that does not support S3
// ListObjectsV2 API. I'm looking at you GCS.
func (s *S3) listObjects(ctx context.Context, url *url.URL) <-chan *Object {
listInput := s3.ListObjectsInput{
Bucket: aws.String(url.Bucket),
Prefix: aws.String(url.Prefix),
}
if url.Delimiter != "" {
listInput.SetDelimiter(url.Delimiter)
}
objCh := make(chan *Object)
go func() {
defer close(objCh)
objectFound := false
var now time.Time
err := s.api.ListObjectsPagesWithContext(ctx, &listInput, func(p *s3.ListObjectsOutput, lastPage bool) bool {
for _, c := range p.CommonPrefixes {
prefix := aws.StringValue(c.Prefix)
if !url.Match(prefix) {
continue
}
newurl := url.Clone()
newurl.Path = prefix
objCh <- &Object{
URL: newurl,
Type: ObjectType{os.ModeDir},
}
objectFound = true
}
// track the instant object iteration began,
// so it can be used to bypass objects created after this instant
if now.IsZero() {
now = time.Now().UTC()
}
for _, c := range p.Contents {
key := aws.StringValue(c.Key)
if !url.Match(key) {
continue
}
mod := aws.TimeValue(c.LastModified).UTC()
if mod.After(now) {
objectFound = true
continue
}
var objtype os.FileMode
if strings.HasSuffix(key, "/") {
objtype = os.ModeDir
}
newurl := url.Clone()
newurl.Path = aws.StringValue(c.Key)
etag := aws.StringValue(c.ETag)
objCh <- &Object{
URL: newurl,
Etag: strings.Trim(etag, `"`),
ModTime: &mod,
Type: ObjectType{objtype},
Size: aws.Int64Value(c.Size),
StorageClass: StorageClass(aws.StringValue(c.StorageClass)),
}
objectFound = true
}
return !lastPage
})
if err != nil {
objCh <- &Object{Err: err}
return
}
if !objectFound {
objCh <- &Object{Err: ErrNoObjectFound}
}
}()
return objCh
}
// Copy is a single-object copy operation which copies objects to S3
// destination from another S3 source.
func (s *S3) Copy(ctx context.Context, from, to *url.URL, metadata Metadata) error {
if s.dryRun {
return nil
}
// SDK expects CopySource like "bucket[/key]"
copySource := from.EscapedPath()
input := &s3.CopyObjectInput{
Bucket: aws.String(to.Bucket),
Key: aws.String(to.Path),
CopySource: aws.String(copySource),
}
storageClass := metadata.StorageClass()
if storageClass != "" {
input.StorageClass = aws.String(storageClass)
}
sseEncryption := metadata.SSE()
if sseEncryption != "" {
input.ServerSideEncryption = aws.String(sseEncryption)
sseKmsKeyID := metadata.SSEKeyID()
if sseKmsKeyID != "" {
input.SSEKMSKeyId = aws.String(sseKmsKeyID)
}
}
acl := metadata.ACL()
if acl != "" {
input.ACL = aws.String(acl)
}
cacheControl := metadata.CacheControl()
if cacheControl != "" {
input.CacheControl = aws.String(cacheControl)
}
expires := metadata.Expires()
if expires != "" {
t, err := time.Parse(time.RFC3339, expires)
if err != nil {
return err
}
input.Expires = aws.Time(t)
}
_, err := s.api.CopyObject(input)
return err
}
// Read fetches the remote object and returns its contents as an io.ReadCloser.
func (s *S3) Read(ctx context.Context, src *url.URL) (io.ReadCloser, error) {
resp, err := s.api.GetObjectWithContext(ctx, &s3.GetObjectInput{
Bucket: aws.String(src.Bucket),
Key: aws.String(src.Path),
})
if err != nil {
return nil, err
}
return resp.Body, nil
}
// Get is a multipart download operation which downloads S3 objects into any
// destination that implements io.WriterAt interface.
// Makes a single 'GetObject' call if 'concurrency' is 1 and ignores 'partSize'.
func (s *S3) Get(
ctx context.Context,
from *url.URL,
to io.WriterAt,
concurrency int,
partSize int64,
) (int64, error) {
if s.dryRun {
return 0, nil
}
return s.downloader.DownloadWithContext(ctx, to, &s3.GetObjectInput{
Bucket: aws.String(from.Bucket),
Key: aws.String(from.Path),
}, func(u *s3manager.Downloader) {
u.PartSize = partSize
u.Concurrency = concurrency
})
}
type SelectQuery struct {
ExpressionType string
Expression string
CompressionType string
}
func (s *S3) Select(ctx context.Context, url *url.URL, query *SelectQuery, resultCh chan<- json.RawMessage) error {
if s.dryRun {
return nil
}
input := &s3.SelectObjectContentInput{
Bucket: aws.String(url.Bucket),
Key: aws.String(url.Path),
ExpressionType: aws.String(query.ExpressionType),
Expression: aws.String(query.Expression),
InputSerialization: &s3.InputSerialization{
CompressionType: aws.String(query.CompressionType),
JSON: &s3.JSONInput{
Type: aws.String("Lines"),
},
},
OutputSerialization: &s3.OutputSerialization{
JSON: &s3.JSONOutput{},
},
}
resp, err := s.api.SelectObjectContentWithContext(ctx, input)
if err != nil {
return err
}
reader, writer := io.Pipe()
go func() {
defer writer.Close()
eventch := resp.EventStream.Reader.Events()
defer resp.EventStream.Close()
for {
select {
case <-ctx.Done():
return
case event, ok := <-eventch:
if !ok {
return
}
switch e := event.(type) {
case *s3.RecordsEvent:
writer.Write(e.Payload)
}
}
}
}()
decoder := json.NewDecoder(reader)
for {
var record json.RawMessage
err := decoder.Decode(&record)
if err == io.EOF {
break
}
if err != nil {
return err
}
resultCh <- record
}
return resp.EventStream.Reader.Err()
}
// Put is a multipart upload operation to upload resources, which implements
// io.Reader interface, into S3 destination.
func (s *S3) Put(
ctx context.Context,
reader io.Reader,
to *url.URL,
metadata Metadata,
concurrency int,
partSize int64,
) error {
if s.dryRun {
return nil
}
contentType := metadata.ContentType()
if contentType == "" {
contentType = "application/octet-stream"
}
input := &s3manager.UploadInput{
Bucket: aws.String(to.Bucket),
Key: aws.String(to.Path),
Body: reader,
ContentType: aws.String(contentType),
}
storageClass := metadata.StorageClass()
if storageClass != "" {
input.StorageClass = aws.String(storageClass)
}
acl := metadata.ACL()
if acl != "" {
input.ACL = aws.String(acl)
}
cacheControl := metadata.CacheControl()
if cacheControl != "" {
input.CacheControl = aws.String(cacheControl)
}
expires := metadata.Expires()
if expires != "" {
t, err := time.Parse(time.RFC3339, expires)
if err != nil {
return err
}
input.Expires = aws.Time(t)
}
sseEncryption := metadata.SSE()
if sseEncryption != "" {
input.ServerSideEncryption = aws.String(sseEncryption)
sseKmsKeyID := metadata.SSEKeyID()
if sseKmsKeyID != "" {
input.SSEKMSKeyId = aws.String(sseKmsKeyID)
}
}
_, err := s.uploader.UploadWithContext(ctx, input, func(u *s3manager.Uploader) {
u.PartSize = partSize
u.Concurrency = concurrency
})
return err
}
// chunk is an object identifier container which is used on MultiDelete
// operations. Since DeleteObjects API allows deleting objects up to 1000,
// splitting keys into multiple chunks is required.
type chunk struct {
Bucket string
Keys []*s3.ObjectIdentifier
}
// calculateChunks calculates chunks for given URL channel and returns
// read-only chunk channel.
func (s *S3) calculateChunks(ch <-chan *url.URL) <-chan chunk {
chunkch := make(chan chunk)
go func() {
defer close(chunkch)
var keys []*s3.ObjectIdentifier
initKeys := func() {
keys = make([]*s3.ObjectIdentifier, 0)
}
var bucket string
for url := range ch {
bucket = url.Bucket
objid := &s3.ObjectIdentifier{Key: aws.String(url.Path)}
keys = append(keys, objid)
if len(keys) == deleteObjectsMax {
chunkch <- chunk{
Bucket: bucket,
Keys: keys,
}
initKeys()
}
}
if len(keys) > 0 {
chunkch <- chunk{
Bucket: bucket,
Keys: keys,
}
}
}()
return chunkch
}
// Delete is a single object delete operation.
func (s *S3) Delete(ctx context.Context, url *url.URL) error {
chunk := chunk{
Bucket: url.Bucket,
Keys: []*s3.ObjectIdentifier{
{Key: aws.String(url.Path)},
},
}
resultch := make(chan *Object, 1)
defer close(resultch)
s.doDelete(ctx, chunk, resultch)
obj := <-resultch
return obj.Err
}
// doDelete deletes the given keys given by chunk. Results are piggybacked via
// the Object container.
func (s *S3) doDelete(ctx context.Context, chunk chunk, resultch chan *Object) {
if s.dryRun {
for _, k := range chunk.Keys {
key := fmt.Sprintf("s3://%v/%v", chunk.Bucket, aws.StringValue(k.Key))
url, _ := url.New(key)
resultch <- &Object{URL: url}
}
return
}
bucket := chunk.Bucket
o, err := s.api.DeleteObjectsWithContext(ctx, &s3.DeleteObjectsInput{
Bucket: aws.String(bucket),
Delete: &s3.Delete{Objects: chunk.Keys},
})
if err != nil {
resultch <- &Object{Err: err}
return
}
for _, d := range o.Deleted {
key := fmt.Sprintf("s3://%v/%v", bucket, aws.StringValue(d.Key))
url, _ := url.New(key)
resultch <- &Object{URL: url}
}
for _, e := range o.Errors {
key := fmt.Sprintf("s3://%v/%v", bucket, aws.StringValue(e.Key))
url, _ := url.New(key)
resultch <- &Object{
URL: url,
Err: fmt.Errorf(aws.StringValue(e.Message)),
}
}
}
// MultiDelete is a asynchronous removal operation for multiple objects.
// It reads given url channel, creates multiple chunks and run these
// chunks in parallel. Each chunk may have at most 1000 objects since DeleteObjects
// API has a limitation.
// See: https://docs.aws.amazon.com/AmazonS3/latest/API/API_DeleteObjects.html.
func (s *S3) MultiDelete(ctx context.Context, urlch <-chan *url.URL) <-chan *Object {
resultch := make(chan *Object)
go func() {
sem := make(chan bool, 10)
defer close(sem)
defer close(resultch)
chunks := s.calculateChunks(urlch)
var wg sync.WaitGroup
for chunk := range chunks {
chunk := chunk
wg.Add(1)
sem <- true
go func() {
defer wg.Done()
s.doDelete(ctx, chunk, resultch)
<-sem
}()
}
wg.Wait()
}()
return resultch
}
// ListBuckets is a blocking list-operation which gets bucket list and returns
// the buckets that match with given prefix.
func (s *S3) ListBuckets(ctx context.Context, prefix string) ([]Bucket, error) {
o, err := s.api.ListBucketsWithContext(ctx, &s3.ListBucketsInput{})
if err != nil {
return nil, err
}
var buckets []Bucket
for _, b := range o.Buckets {
bucketName := aws.StringValue(b.Name)
if prefix == "" || strings.HasPrefix(bucketName, prefix) {
buckets = append(buckets, Bucket{
CreationDate: aws.TimeValue(b.CreationDate),
Name: bucketName,
})
}
}
return buckets, nil
}
// MakeBucket creates an S3 bucket with the given name.
func (s *S3) MakeBucket(ctx context.Context, name string) error {
if s.dryRun {
return nil
}
_, err := s.api.CreateBucketWithContext(ctx, &s3.CreateBucketInput{
Bucket: aws.String(name),
})
return err
}
// RemoveBucket removes an S3 bucket with the given name.
func (s *S3) RemoveBucket(ctx context.Context, name string) error {
if s.dryRun {
return nil
}
_, err := s.api.DeleteBucketWithContext(ctx, &s3.DeleteBucketInput{
Bucket: aws.String(name),
})
return err
}
// SessionCache holds session.Session according to s3Opts and it synchronizes
// access/modification.
type SessionCache struct {
sync.Mutex
sessions map[Options]*session.Session
}
// newSession initializes a new AWS session with region fallback and custom
// options.
func (sc *SessionCache) newSession(ctx context.Context, opts Options) (*session.Session, error) {
sc.Lock()
defer sc.Unlock()
if sess, ok := sc.sessions[opts]; ok {
return sess, nil
}
awsCfg := aws.NewConfig()
if opts.NoSignRequest {
// do not sign requests when making service API calls
awsCfg.Credentials = credentials.AnonymousCredentials
}
endpointURL, err := parseEndpoint(opts.Endpoint)
if err != nil {
return nil, err
}
// use virtual-host-style if the endpoint is known to support it,
// otherwise use the path-style approach.
isVirtualHostStyle := isVirtualHostStyle(endpointURL)
useAccelerate := supportsTransferAcceleration(endpointURL)
// AWS SDK handles transfer acceleration automatically. Setting the
// Endpoint to a transfer acceleration endpoint would cause bucket
// operations fail.
if useAccelerate {
endpointURL = sentinelURL
}
var httpClient *http.Client
if opts.NoVerifySSL {
httpClient = insecureHTTPClient
}
awsCfg = awsCfg.
WithEndpoint(endpointURL.String()).
WithS3ForcePathStyle(!isVirtualHostStyle).
WithS3UseAccelerate(useAccelerate).
WithHTTPClient(httpClient)
awsCfg.Retryer = newCustomRetryer(opts.MaxRetries)
useSharedConfig := session.SharedConfigEnable
{
// Reverse of what the SDK does: if AWS_SDK_LOAD_CONFIG is 0 (or a
// falsy value) disable shared configs
loadCfg := os.Getenv("AWS_SDK_LOAD_CONFIG")
if loadCfg != "" {
if enable, _ := strconv.ParseBool(loadCfg); !enable {
useSharedConfig = session.SharedConfigDisable
}
}
}
sess, err := session.NewSessionWithOptions(
session.Options{
Config: *awsCfg,
SharedConfigState: useSharedConfig,
},
)
if err != nil {
return nil, err
}
// get region of the bucket and create session accordingly. if the region
// is not provided, it means we want region-independent session
// for operations such as listing buckets, making a new bucket etc.
// only get bucket region when it is not specified.
if opts.region != "" {
sess.Config.Region = aws.String(opts.region)
} else {
if err := setSessionRegion(ctx, sess, opts.bucket); err != nil {
return nil, err
}
}
sc.sessions[opts] = sess
return sess, nil
}
func (sc *SessionCache) clear() {
sc.Lock()
defer sc.Unlock()
sc.sessions = map[Options]*session.Session{}
}
func setSessionRegion(ctx context.Context, sess *session.Session, bucket string) error {
region := aws.StringValue(sess.Config.Region)
if region != "" {
return nil
}
// set default region
sess.Config.Region = aws.String(endpoints.UsEast1RegionID)
if bucket == "" {
return nil
}
// auto-detection
region, err := s3manager.GetBucketRegion(ctx, sess, bucket, "", func(r *request.Request) {
r.Config.Credentials = sess.Config.Credentials
})
if err != nil {
if errHasCode(err, "NotFound") {
return err
}
// don't deny any request to the service if region auto-fetching
// receives an error. Delegate error handling to command execution.
err = fmt.Errorf("session: fetching region failed: %v", err)
msg := log.ErrorMessage{Err: err.Error()}
log.Error(msg)
} else {
sess.Config.Region = aws.String(region)
}
return nil
}
// customRetryer wraps the SDK's built in DefaultRetryer adding additional
// error codes. Such as, retry for S3 InternalError code.
type customRetryer struct {
client.DefaultRetryer
}
func newCustomRetryer(maxRetries int) *customRetryer {
return &customRetryer{
DefaultRetryer: client.DefaultRetryer{
NumMaxRetries: maxRetries,
},
}
}
// ShouldRetry overrides SDK's built in DefaultRetryer, adding custom retry
// logics that are not included in the SDK.
func (c *customRetryer) ShouldRetry(req *request.Request) bool {
shouldRetry := errHasCode(req.Error, "InternalError") || errHasCode(req.Error, "RequestTimeTooSkewed") || strings.Contains(req.Error.Error(), "connection reset") || strings.Contains(req.Error.Error(), "connection timed out")
if !shouldRetry {
shouldRetry = c.DefaultRetryer.ShouldRetry(req)
}
// Errors related to tokens
if errHasCode(req.Error, "ExpiredToken") || errHasCode(req.Error, "ExpiredTokenException") || errHasCode(req.Error, "InvalidToken") {
return false
}
if shouldRetry && req.Error != nil {
err := fmt.Errorf("retryable error: %v", req.Error)
msg := log.DebugMessage{Err: err.Error()}
log.Debug(msg)
}
return shouldRetry
}
var insecureHTTPClient = &http.Client{
Transport: &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
},
}
func supportsTransferAcceleration(endpoint urlpkg.URL) bool {
return endpoint.Hostname() == transferAccelEndpoint
}
func isGoogleEndpoint(endpoint urlpkg.URL) bool {
return endpoint.Hostname() == gcsEndpoint
}
// isVirtualHostStyle reports whether the given endpoint supports S3 virtual
// host style bucket name resolving. If a custom S3 API compatible endpoint is
// given, resolve the bucketname from the URL path.
func isVirtualHostStyle(endpoint urlpkg.URL) bool {
return endpoint == sentinelURL || supportsTransferAcceleration(endpoint) || isGoogleEndpoint(endpoint)
}
func errHasCode(err error, code string) bool {
if err == nil || code == "" {
return false
}
var awsErr awserr.Error
if errors.As(err, &awsErr) {
if awsErr.Code() == code {
return true
}
}
var multiUploadErr s3manager.MultiUploadFailure
if errors.As(err, &multiUploadErr) {
return errHasCode(multiUploadErr.OrigErr(), code)
}
return false
}
// IsCancelationError reports whether given error is a storage related
// cancelation error.
func IsCancelationError(err error) bool {
return errHasCode(err, request.CanceledErrorCode)
}