/
client-s3.go
3074 lines (2798 loc) · 88.9 KB
/
client-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
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
// Copyright (c) 2015-2022 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
import (
"bytes"
"context"
"crypto/tls"
"encoding/json"
"errors"
"fmt"
"hash/fnv"
"io"
"math/rand"
"net"
"net/http"
"net/url"
"os"
"path"
"path/filepath"
"regexp"
"sort"
"strings"
"sync"
"time"
"github.com/klauspost/compress/gzhttp"
"github.com/minio/pkg/v2/env"
"github.com/minio/minio-go/v7"
"github.com/minio/minio-go/v7/pkg/credentials"
"github.com/minio/minio-go/v7/pkg/encrypt"
"github.com/minio/minio-go/v7/pkg/lifecycle"
"github.com/minio/minio-go/v7/pkg/notification"
"github.com/minio/minio-go/v7/pkg/policy"
"github.com/minio/minio-go/v7/pkg/replication"
"github.com/minio/minio-go/v7/pkg/s3utils"
"github.com/minio/minio-go/v7/pkg/sse"
"github.com/minio/minio-go/v7/pkg/tags"
"github.com/minio/pkg/v2/mimedb"
"github.com/minio/mc/pkg/deadlineconn"
"github.com/minio/mc/pkg/httptracer"
"github.com/minio/mc/pkg/limiter"
"github.com/minio/mc/pkg/probe"
)
// S3Client construct
type S3Client struct {
sync.Mutex
targetURL *ClientURL
api *minio.Client
virtualStyle bool
}
const (
amazonHostNameAccelerated = "s3-accelerate.amazonaws.com"
googleHostName = "storage.googleapis.com"
serverEncryptionKeyPrefix = "x-amz-server-side-encryption"
defaultRecordDelimiter = "\n"
defaultFieldDelimiter = ","
)
const (
recordDelimiterType = "recorddelimiter"
fieldDelimiterType = "fielddelimiter"
quoteCharacterType = "quotechar"
quoteEscapeCharacterType = "quoteescchar"
quoteFieldsType = "quotefields"
fileHeaderType = "fileheader"
commentCharType = "commentchar"
typeJSONType = "type"
// AmzObjectLockMode sets object lock mode
AmzObjectLockMode = "X-Amz-Object-Lock-Mode"
// AmzObjectLockRetainUntilDate sets object lock retain until date
AmzObjectLockRetainUntilDate = "X-Amz-Object-Lock-Retain-Until-Date"
// AmzObjectLockLegalHold sets object lock legal hold
AmzObjectLockLegalHold = "X-Amz-Object-Lock-Legal-Hold"
amzObjectSSEKMSKeyID = "X-Amz-Server-Side-Encryption-Aws-Kms-Key-Id"
amzObjectSSE = "X-Amz-Server-Side-Encryption"
)
type dialContext func(ctx context.Context, network, addr string) (net.Conn, error)
// newCustomDialContext setups a custom dialer for any external communication and proxies.
func newCustomDialContext(c *Config) dialContext {
return func(ctx context.Context, network, addr string) (net.Conn, error) {
dialer := &net.Dialer{
Timeout: 10 * time.Second,
KeepAlive: 15 * time.Second,
}
conn, err := dialer.DialContext(ctx, network, addr)
if err != nil {
return nil, err
}
dconn := deadlineconn.New(conn).
WithReadDeadline(c.ConnReadDeadline).
WithWriteDeadline(c.ConnWriteDeadline)
return dconn, nil
}
}
var timeSentinel = time.Unix(0, 0).UTC()
// getConfigHash returns the Hash for che *Config
func getConfigHash(config *Config) uint32 {
// Creates a parsed URL.
targetURL := newClientURL(config.HostURL)
// Save if target supports virtual host style.
hostName := targetURL.Host
// Generate a hash out of s3Conf.
confHash := fnv.New32a()
confHash.Write([]byte(hostName + config.AccessKey + config.SecretKey + config.SessionToken))
confSum := confHash.Sum32()
return confSum
}
// isHostTLS returns true if the Host URL is https
func isHostTLS(config *Config) bool {
// By default enable HTTPs.
useTLS := true
targetURL := newClientURL(config.HostURL)
if targetURL.Scheme == "http" {
useTLS = false
}
return useTLS
}
// getTransportForConfig returns a corresponding *http.Transport for the *Config
// set withS3v2 bool to true to add traceV2 tracer.
func getTransportForConfig(config *Config, withS3v2 bool) http.RoundTripper {
var transport http.RoundTripper
useTLS := isHostTLS(config)
if config.Transport != nil {
transport = config.Transport
} else {
tr := &http.Transport{
Proxy: http.ProxyFromEnvironment,
DialContext: newCustomDialContext(config),
MaxIdleConnsPerHost: 1024,
WriteBufferSize: 32 << 10, // 32KiB moving up from 4KiB default
ReadBufferSize: 32 << 10, // 32KiB moving up from 4KiB default
IdleConnTimeout: 90 * time.Second,
TLSHandshakeTimeout: 10 * time.Second,
ExpectContinueTimeout: 10 * time.Second,
// Set this value so that the underlying transport round-tripper
// doesn't try to auto decode the body of objects with
// content-encoding set to `gzip`.
//
// Refer:
// https://golang.org/src/net/http/transport.go?h=roundTrip#L1843
DisableCompression: true,
}
if useTLS {
// Keep TLS config.
tlsConfig := &tls.Config{
RootCAs: globalRootCAs,
// Can't use SSLv3 because of POODLE and BEAST
// Can't use TLSv1.0 because of POODLE and BEAST using CBC cipher
// Can't use TLSv1.1 because of RC4 cipher usage
MinVersion: tls.VersionTLS12,
}
if config.Insecure {
tlsConfig.InsecureSkipVerify = true
}
tr.TLSClientConfig = tlsConfig
// Because we create a custom TLSClientConfig, we have to opt-in to HTTP/2.
// See https://github.com/golang/go/issues/14275
//
// TODO: Enable http2.0 when upstream issues related to HTTP/2 are fixed.
//
// if e = http2.ConfigureTransport(tr); e != nil {
// return nil, probe.NewError(e)
// }
}
transport = tr
}
transport = limiter.New(config.UploadLimit, config.DownloadLimit, transport)
if config.Debug {
if strings.EqualFold(config.Signature, "S3v4") {
transport = httptracer.GetNewTraceTransport(newTraceV4(), transport)
} else if strings.EqualFold(config.Signature, "S3v2") && withS3v2 {
transport = httptracer.GetNewTraceTransport(newTraceV2(), transport)
}
}
transport = gzhttp.Transport(transport)
return transport
}
// getCredentialsChainForConfig returns an []credentials.Provider array for the config
// and the STS configuration (if present)
func getCredentialsChainForConfig(config *Config, transport http.RoundTripper) ([]credentials.Provider, *probe.Error) {
var credsChain []credentials.Provider
// if an STS endpoint is set, we will add that to the chain
if stsEndpoint := env.Get("MC_STS_ENDPOINT_"+config.Alias, ""); stsEndpoint != "" {
// set AWS_WEB_IDENTITY_TOKEN_FILE is MC_WEB_IDENTITY_TOKEN_FILE is set
if val := env.Get("MC_WEB_IDENTITY_TOKEN_FILE_"+config.Alias, ""); val != "" {
os.Setenv("AWS_WEB_IDENTITY_TOKEN_FILE", val)
if val := env.Get("MC_ROLE_ARN_"+config.Alias, ""); val != "" {
os.Setenv("AWS_ROLE_ARN", val)
}
if val := env.Get("MC_ROLE_SESSION_NAME_"+config.Alias, randString(32, rand.NewSource(time.Now().UnixNano()), "mc-session-name-")); val != "" {
os.Setenv("AWS_ROLE_SESSION_NAME", val)
}
}
stsEndpointURL, err := url.Parse(stsEndpoint)
if err != nil {
return nil, probe.NewError(fmt.Errorf("Error parsing sts endpoint: %v", err))
}
credsSts := &credentials.IAM{
Client: &http.Client{
Transport: transport,
},
Endpoint: stsEndpointURL.String(),
}
credsChain = append(credsChain, credsSts)
}
// V4 Credentials
credsV4 := &credentials.Static{
Value: credentials.Value{
AccessKeyID: config.AccessKey,
SecretAccessKey: config.SecretKey,
SessionToken: config.SessionToken,
SignerType: credentials.SignatureV4,
},
}
credsChain = append(credsChain, credsV4)
return credsChain, nil
}
// newFactory encloses New function with client cache.
func newFactory() func(config *Config) (Client, *probe.Error) {
clientCache := make(map[uint32]*minio.Client)
var mutex sync.Mutex
// Return New function.
return func(config *Config) (Client, *probe.Error) {
// Creates a parsed URL.
targetURL := newClientURL(config.HostURL)
// Save if target supports virtual host style.
hostName := targetURL.Host
confSum := getConfigHash(config)
useTLS := isHostTLS(config)
// Instantiate s3
s3Clnt := &S3Client{}
// Save the target URL.
s3Clnt.targetURL = targetURL
s3Clnt.virtualStyle = isVirtualHostStyle(hostName, config.Lookup)
isS3AcceleratedEndpoint := isAmazonAccelerated(hostName)
if s3Clnt.virtualStyle {
// If Google URL replace it with 'storage.googleapis.com'
if isGoogle(hostName) {
hostName = googleHostName
}
}
// Lookup previous cache by hash.
mutex.Lock()
defer mutex.Unlock()
var api *minio.Client
var found bool
if api, found = clientCache[confSum]; !found {
transport := getTransportForConfig(config, true)
credsChain, err := getCredentialsChainForConfig(config, transport)
if err != nil {
return nil, err
}
// V2 Credentials
credsV2 := &credentials.Static{
Value: credentials.Value{
AccessKeyID: config.AccessKey,
SecretAccessKey: config.SecretKey,
SessionToken: "",
SignerType: credentials.SignatureV2,
},
}
credsChain = append(credsChain, credsV2)
creds := credentials.NewChainCredentials(credsChain)
// Not found. Instantiate a new MinIO
var e error
options := minio.Options{
Creds: creds,
Secure: useTLS,
Region: env.Get("MC_REGION", env.Get("AWS_REGION", "")),
BucketLookup: config.Lookup,
Transport: transport,
}
api, e = minio.New(hostName, &options)
if e != nil {
return nil, probe.NewError(e)
}
// If Amazon Accelerated URL is requested enable it.
if isS3AcceleratedEndpoint {
api.SetS3TransferAccelerate(amazonHostNameAccelerated)
}
// Set app info.
api.SetAppInfo(config.AppName, config.AppVersion)
// Cache the new MinIO Client with hash of config as key.
clientCache[confSum] = api
}
// Store the new api object.
s3Clnt.api = api
return s3Clnt, nil
}
}
// S3New returns an initialized S3Client structure. If debug is enabled,
// it also enables an internal trace transport.
var S3New = newFactory()
// GetURL get url.
func (c *S3Client) GetURL() ClientURL {
return c.targetURL.Clone()
}
// AddNotificationConfig - Add bucket notification
func (c *S3Client) AddNotificationConfig(ctx context.Context, arn string, events []string, prefix, suffix string, ignoreExisting bool) *probe.Error {
bucket, _ := c.url2BucketAndObject()
accountArn, err := notification.NewArnFromString(arn)
if err != nil {
return probe.NewError(invalidArgumentErr(err)).Untrace()
}
nc := notification.NewConfig(accountArn)
// Get any enabled notification.
mb, e := c.api.GetBucketNotification(ctx, bucket)
if e != nil {
return probe.NewError(e)
}
// Configure events
for _, event := range events {
switch event {
case "put":
nc.AddEvents(notification.ObjectCreatedAll)
case "delete":
nc.AddEvents(notification.ObjectRemovedAll)
case "get":
nc.AddEvents(notification.ObjectAccessedAll)
case "replica":
nc.AddEvents(notification.EventType("s3:Replication:*"))
case "ilm":
nc.AddEvents(notification.EventType("s3:ObjectRestore:*"))
nc.AddEvents(notification.EventType("s3:ObjectTransition:*"))
case "scanner":
nc.AddEvents(notification.EventType("s3:Scanner:ManyVersions"))
nc.AddEvents(notification.EventType("s3:Scanner:BigPrefix"))
default:
return errInvalidArgument().Trace(events...)
}
}
if prefix != "" {
nc.AddFilterPrefix(prefix)
}
if suffix != "" {
nc.AddFilterSuffix(suffix)
}
switch accountArn.Service {
case "sns":
if !mb.AddTopic(nc) {
return errInvalidArgument().Trace("Overlapping Topic configs")
}
case "sqs":
if !mb.AddQueue(nc) {
return errInvalidArgument().Trace("Overlapping Queue configs")
}
case "lambda":
if !mb.AddLambda(nc) {
return errInvalidArgument().Trace("Overlapping lambda configs")
}
default:
return errInvalidArgument().Trace(accountArn.Service)
}
// Set the new bucket configuration
if err := c.api.SetBucketNotification(ctx, bucket, mb); err != nil {
if ignoreExisting && strings.Contains(err.Error(), "An object key name filtering rule defined with overlapping prefixes, overlapping suffixes, or overlapping combinations of prefixes and suffixes for the same event types") {
return nil
}
return probe.NewError(err)
}
return nil
}
// RemoveNotificationConfig - Remove bucket notification
func (c *S3Client) RemoveNotificationConfig(ctx context.Context, arn, event, prefix, suffix string) *probe.Error {
bucket, _ := c.url2BucketAndObject()
// Remove all notification configs if arn is empty
if arn == "" {
if err := c.api.RemoveAllBucketNotification(ctx, bucket); err != nil {
return probe.NewError(err)
}
return nil
}
mb, e := c.api.GetBucketNotification(ctx, bucket)
if e != nil {
return probe.NewError(e)
}
accountArn, err := notification.NewArnFromString(arn)
if err != nil {
return probe.NewError(invalidArgumentErr(err)).Untrace()
}
// if we are passed filters for either events, suffix or prefix, then only delete the single event that matches
// the arguments
if event != "" || suffix != "" || prefix != "" {
// Translate events to type events for comparison
events := strings.Split(event, ",")
var eventsTyped []notification.EventType
for _, e := range events {
switch e {
case "put":
eventsTyped = append(eventsTyped, notification.ObjectCreatedAll)
case "delete":
eventsTyped = append(eventsTyped, notification.ObjectRemovedAll)
case "get":
eventsTyped = append(eventsTyped, notification.ObjectAccessedAll)
case "replica":
eventsTyped = append(eventsTyped, notification.EventType("s3:Replication:*"))
case "ilm":
eventsTyped = append(eventsTyped, notification.EventType("s3:ObjectRestore:*"))
eventsTyped = append(eventsTyped, notification.EventType("s3:ObjectTransition:*"))
case "scanner":
eventsTyped = append(eventsTyped, notification.EventType("s3:Scanner:ManyVersions"))
eventsTyped = append(eventsTyped, notification.EventType("s3:Scanner:BigPrefix"))
default:
return errInvalidArgument().Trace(events...)
}
}
var err error
// based on the arn type, we'll look for the event in the corresponding sublist and delete it if there's a match
switch accountArn.Service {
case "sns":
err = mb.RemoveTopicByArnEventsPrefixSuffix(accountArn, eventsTyped, prefix, suffix)
case "sqs":
err = mb.RemoveQueueByArnEventsPrefixSuffix(accountArn, eventsTyped, prefix, suffix)
case "lambda":
err = mb.RemoveLambdaByArnEventsPrefixSuffix(accountArn, eventsTyped, prefix, suffix)
default:
return errInvalidArgument().Trace(accountArn.Service)
}
if err != nil {
return probe.NewError(err)
}
} else {
// remove all events for matching arn
switch accountArn.Service {
case "sns":
mb.RemoveTopicByArn(accountArn)
case "sqs":
mb.RemoveQueueByArn(accountArn)
case "lambda":
mb.RemoveLambdaByArn(accountArn)
default:
return errInvalidArgument().Trace(accountArn.Service)
}
}
// Set the new bucket configuration
if e := c.api.SetBucketNotification(ctx, bucket, mb); e != nil {
return probe.NewError(e)
}
return nil
}
// NotificationConfig notification config
type NotificationConfig struct {
ID string `json:"id"`
Arn string `json:"arn"`
Events []string `json:"events"`
Prefix string `json:"prefix"`
Suffix string `json:"suffix"`
}
// ListNotificationConfigs - List notification configs
func (c *S3Client) ListNotificationConfigs(ctx context.Context, arn string) ([]NotificationConfig, *probe.Error) {
var configs []NotificationConfig
bucket, _ := c.url2BucketAndObject()
mb, e := c.api.GetBucketNotification(ctx, bucket)
if e != nil {
return nil, probe.NewError(e)
}
// Generate pretty event names from event types
prettyEventNames := func(eventsTypes []notification.EventType) []string {
var result []string
for _, eventType := range eventsTypes {
result = append(result, string(eventType))
}
return result
}
getFilters := func(config notification.Config) (prefix, suffix string) {
if config.Filter == nil {
return
}
for _, filter := range config.Filter.S3Key.FilterRules {
if strings.ToLower(filter.Name) == "prefix" {
prefix = filter.Value
}
if strings.ToLower(filter.Name) == "suffix" {
suffix = filter.Value
}
}
return prefix, suffix
}
for _, config := range mb.TopicConfigs {
if arn != "" && config.Topic != arn {
continue
}
prefix, suffix := getFilters(config.Config)
configs = append(configs, NotificationConfig{
ID: config.ID,
Arn: config.Topic,
Events: prettyEventNames(config.Events),
Prefix: prefix,
Suffix: suffix,
})
}
for _, config := range mb.QueueConfigs {
if arn != "" && config.Queue != arn {
continue
}
prefix, suffix := getFilters(config.Config)
configs = append(configs, NotificationConfig{
ID: config.ID,
Arn: config.Queue,
Events: prettyEventNames(config.Events),
Prefix: prefix,
Suffix: suffix,
})
}
for _, config := range mb.LambdaConfigs {
if arn != "" && config.Lambda != arn {
continue
}
prefix, suffix := getFilters(config.Config)
configs = append(configs, NotificationConfig{
ID: config.ID,
Arn: config.Lambda,
Events: prettyEventNames(config.Events),
Prefix: prefix,
Suffix: suffix,
})
}
return configs, nil
}
// Supported content types
var supportedContentTypes = []string{
"csv",
"json",
"gzip",
"bzip2",
}
// set the SelectObjectOutputSerialization struct using options passed in by client. If unspecified,
// default S3 API specified defaults
func selectObjectOutputOpts(selOpts SelectObjectOpts, i minio.SelectObjectInputSerialization) minio.SelectObjectOutputSerialization {
var isOK bool
var recDelim, fldDelim, quoteChar, quoteEscChar, qf string
o := minio.SelectObjectOutputSerialization{}
if _, ok := selOpts.OutputSerOpts["json"]; ok {
jo := minio.JSONOutputOptions{}
if recDelim, isOK = selOpts.OutputSerOpts["json"][recordDelimiterType]; !isOK {
recDelim = "\n"
}
jo.SetRecordDelimiter(recDelim)
o.JSON = &jo
}
if _, ok := selOpts.OutputSerOpts["csv"]; ok {
ocsv := minio.CSVOutputOptions{}
if recDelim, isOK = selOpts.OutputSerOpts["csv"][recordDelimiterType]; !isOK {
recDelim = defaultRecordDelimiter
}
ocsv.SetRecordDelimiter(recDelim)
if fldDelim, isOK = selOpts.OutputSerOpts["csv"][fieldDelimiterType]; !isOK {
fldDelim = defaultFieldDelimiter
}
ocsv.SetFieldDelimiter(fldDelim)
if quoteChar, isOK = selOpts.OutputSerOpts["csv"][quoteCharacterType]; isOK {
ocsv.SetQuoteCharacter(quoteChar)
}
if quoteEscChar, isOK = selOpts.OutputSerOpts["csv"][quoteEscapeCharacterType]; isOK {
ocsv.SetQuoteEscapeCharacter(quoteEscChar)
}
if qf, isOK = selOpts.OutputSerOpts["csv"][quoteFieldsType]; isOK {
ocsv.SetQuoteFields(minio.CSVQuoteFields(qf))
}
o.CSV = &ocsv
}
// default to CSV output if options left unspecified
if o.CSV == nil && o.JSON == nil {
if i.JSON != nil {
j := minio.JSONOutputOptions{}
j.SetRecordDelimiter("\n")
o.JSON = &j
} else {
ocsv := minio.CSVOutputOptions{}
ocsv.SetRecordDelimiter(defaultRecordDelimiter)
ocsv.SetFieldDelimiter(defaultFieldDelimiter)
o.CSV = &ocsv
}
}
return o
}
func trimCompressionFileExts(name string) string {
return strings.TrimSuffix(strings.TrimSuffix(strings.TrimSuffix(name, ".gz"), ".bz"), ".bz2")
}
// set the SelectObjectInputSerialization struct using options passed in by client. If unspecified,
// default S3 API specified defaults
func selectObjectInputOpts(selOpts SelectObjectOpts, object string) minio.SelectObjectInputSerialization {
var isOK bool
var recDelim, fldDelim, quoteChar, quoteEscChar, fileHeader, commentChar, typ string
i := minio.SelectObjectInputSerialization{}
if _, ok := selOpts.InputSerOpts["parquet"]; ok {
iparquet := minio.ParquetInputOptions{}
i.Parquet = &iparquet
}
if _, ok := selOpts.InputSerOpts["json"]; ok {
j := minio.JSONInputOptions{}
if typ = selOpts.InputSerOpts["json"][typeJSONType]; typ != "" {
j.SetType(minio.JSONType(typ))
}
i.JSON = &j
}
if _, ok := selOpts.InputSerOpts["csv"]; ok {
icsv := minio.CSVInputOptions{}
icsv.SetRecordDelimiter(defaultRecordDelimiter)
if recDelim, isOK = selOpts.InputSerOpts["csv"][recordDelimiterType]; isOK {
icsv.SetRecordDelimiter(recDelim)
}
if fldDelim, isOK = selOpts.InputSerOpts["csv"][fieldDelimiterType]; isOK {
icsv.SetFieldDelimiter(fldDelim)
}
if quoteChar, isOK = selOpts.InputSerOpts["csv"][quoteCharacterType]; isOK {
icsv.SetQuoteCharacter(quoteChar)
}
if quoteEscChar, isOK = selOpts.InputSerOpts["csv"][quoteEscapeCharacterType]; isOK {
icsv.SetQuoteEscapeCharacter(quoteEscChar)
}
if fileHeader, isOK = selOpts.InputSerOpts["csv"][fileHeaderType]; isOK {
icsv.SetFileHeaderInfo(minio.CSVFileHeaderInfo(fileHeader))
}
if commentChar, isOK = selOpts.InputSerOpts["csv"][commentCharType]; isOK {
icsv.SetComments(commentChar)
}
i.CSV = &icsv
}
if i.CSV == nil && i.JSON == nil && i.Parquet == nil {
ext := filepath.Ext(trimCompressionFileExts(object))
if strings.Contains(ext, "csv") {
icsv := minio.CSVInputOptions{}
icsv.SetRecordDelimiter(defaultRecordDelimiter)
icsv.SetFieldDelimiter(defaultFieldDelimiter)
icsv.SetFileHeaderInfo(minio.CSVFileHeaderInfoUse)
i.CSV = &icsv
}
if strings.Contains(ext, "parquet") || strings.Contains(object, ".parquet") {
iparquet := minio.ParquetInputOptions{}
i.Parquet = &iparquet
}
if strings.Contains(ext, "json") {
ijson := minio.JSONInputOptions{}
ijson.SetType(minio.JSONLinesType)
i.JSON = &ijson
}
}
if i.CompressionType == "" {
i.CompressionType = selectCompressionType(selOpts, object)
}
return i
}
// get client specified compression type or default compression type from file extension
func selectCompressionType(selOpts SelectObjectOpts, object string) minio.SelectCompressionType {
ext := filepath.Ext(object)
contentType := mimedb.TypeByExtension(ext)
if selOpts.CompressionType != "" {
return selOpts.CompressionType
}
if strings.Contains(ext, "parquet") || strings.Contains(object, ".parquet") {
return minio.SelectCompressionNONE
}
if contentType != "" {
if strings.Contains(contentType, "gzip") {
return minio.SelectCompressionGZIP
} else if strings.Contains(contentType, "bzip") {
return minio.SelectCompressionBZIP
}
}
return minio.SelectCompressionNONE
}
// Select - select object content wrapper.
func (c *S3Client) Select(ctx context.Context, expression string, sse encrypt.ServerSide, selOpts SelectObjectOpts) (io.ReadCloser, *probe.Error) {
opts := minio.SelectObjectOptions{
Expression: expression,
ExpressionType: minio.QueryExpressionTypeSQL,
// Set any encryption headers
ServerSideEncryption: sse,
}
bucket, object := c.url2BucketAndObject()
opts.InputSerialization = selectObjectInputOpts(selOpts, object)
opts.OutputSerialization = selectObjectOutputOpts(selOpts, opts.InputSerialization)
reader, e := c.api.SelectObjectContent(ctx, bucket, object, opts)
if e != nil {
return nil, probe.NewError(e)
}
return reader, nil
}
func (c *S3Client) notificationToEventsInfo(ninfo notification.Info) []EventInfo {
eventsInfo := make([]EventInfo, len(ninfo.Records))
for i, record := range ninfo.Records {
bucketName := record.S3.Bucket.Name
var key string
// Unescape only if needed, look for URL encoded content.
if strings.Contains(record.S3.Object.Key, "%2F") {
var e error
key, e = url.QueryUnescape(record.S3.Object.Key)
if e != nil {
key = record.S3.Object.Key
}
} else {
key = record.S3.Object.Key
}
u := c.targetURL.Clone()
u.Path = path.Join(string(u.Separator), bucketName, key)
if strings.HasPrefix(record.EventName, "s3:ObjectCreated:") {
if strings.HasPrefix(record.EventName, "s3:ObjectCreated:Copy") {
eventsInfo[i] = EventInfo{
Time: record.EventTime,
Size: record.S3.Object.Size,
UserMetadata: record.S3.Object.UserMetadata,
Path: u.String(),
Type: notification.ObjectCreatedCopy,
Host: record.Source.Host,
Port: record.Source.Port,
UserAgent: record.Source.UserAgent,
}
} else if strings.HasPrefix(record.EventName, "s3:ObjectCreated:PutRetention") {
eventsInfo[i] = EventInfo{
Time: record.EventTime,
Size: record.S3.Object.Size,
UserMetadata: record.S3.Object.UserMetadata,
Path: u.String(),
Type: notification.EventType("s3:ObjectCreated:PutRetention"),
Host: record.Source.Host,
Port: record.Source.Port,
UserAgent: record.Source.UserAgent,
}
} else if strings.HasPrefix(record.EventName, "s3:ObjectCreated:PutLegalHold") {
eventsInfo[i] = EventInfo{
Time: record.EventTime,
Size: record.S3.Object.Size,
UserMetadata: record.S3.Object.UserMetadata,
Path: u.String(),
Type: notification.EventType("s3:ObjectCreated:PutLegalHold"),
Host: record.Source.Host,
Port: record.Source.Port,
UserAgent: record.Source.UserAgent,
}
} else {
eventsInfo[i] = EventInfo{
Time: record.EventTime,
Size: record.S3.Object.Size,
UserMetadata: record.S3.Object.UserMetadata,
Path: u.String(),
Type: notification.ObjectCreatedPut,
Host: record.Source.Host,
Port: record.Source.Port,
UserAgent: record.Source.UserAgent,
}
}
} else {
eventsInfo[i] = EventInfo{
Time: record.EventTime,
Size: record.S3.Object.Size,
UserMetadata: record.S3.Object.UserMetadata,
Path: u.String(),
Type: notification.EventType(record.EventName),
Host: record.Source.Host,
Port: record.Source.Port,
UserAgent: record.Source.UserAgent,
}
}
}
return eventsInfo
}
// Watch - Start watching on all bucket events for a given account ID.
func (c *S3Client) Watch(ctx context.Context, options WatchOptions) (*WatchObject, *probe.Error) {
// Extract bucket and object.
bucket, object := c.url2BucketAndObject()
// Validation
if bucket == "" && object != "" {
return nil, errInvalidArgument().Trace(bucket, object)
}
if object != "" && options.Prefix != "" {
return nil, errInvalidArgument().Trace(options.Prefix, object)
}
// Flag set to set the notification.
var events []string
for _, event := range options.Events {
switch event {
case "put":
events = append(events, string(notification.ObjectCreatedAll))
case "delete":
events = append(events, string(notification.ObjectRemovedAll))
case "get":
events = append(events, string(notification.ObjectAccessedAll))
case "replica":
events = append(events, "s3:Replication:*") // TODO: add it to minio-go as constant
case "ilm":
events = append(events, "s3:ObjectRestore:*", "s3:ObjectTransition:*") // TODO: add it to minio-go as constant
case "bucket-creation":
events = append(events, string(notification.BucketCreatedAll))
case "bucket-removal":
events = append(events, string(notification.BucketRemovedAll))
case "scanner":
events = append(events, "s3:Scanner:ManyVersions", "s3:Scanner:BigPrefix")
default:
return nil, errInvalidArgument().Trace(event)
}
}
wo := &WatchObject{
EventInfoChan: make(chan []EventInfo),
ErrorChan: make(chan *probe.Error),
DoneChan: make(chan struct{}),
}
listenCtx, listenCancel := context.WithCancel(ctx)
var eventsCh <-chan notification.Info
if bucket != "" {
if object != "" && options.Prefix == "" {
options.Prefix = object
}
eventsCh = c.api.ListenBucketNotification(listenCtx, bucket, options.Prefix, options.Suffix, events)
} else {
eventsCh = c.api.ListenNotification(listenCtx, "", "", events)
}
go func() {
defer close(wo.EventInfoChan)
defer close(wo.ErrorChan)
defer listenCancel()
for {
// Start listening on all bucket events.
select {
case notificationInfo, ok := <-eventsCh:
if !ok {
return
}
if notificationInfo.Err != nil {
var perr *probe.Error
if minio.ToErrorResponse(notificationInfo.Err).Code == "NotImplemented" {
perr = probe.NewError(APINotImplemented{
API: "Watch",
APIType: c.GetURL().String(),
})
} else {
perr = probe.NewError(notificationInfo.Err)
}
wo.Errors() <- perr
} else {
wo.Events() <- c.notificationToEventsInfo(notificationInfo)
}
case <-wo.DoneChan:
return
}
}
}()
return wo, nil
}
// Get - get object with GET options.
func (c *S3Client) Get(ctx context.Context, opts GetOptions) (io.ReadCloser, *ClientContent, *probe.Error) {
bucket, object := c.url2BucketAndObject()
o := minio.GetObjectOptions{
ServerSideEncryption: opts.SSE,
VersionID: opts.VersionID,
}
if opts.Zip {
o.Set("x-minio-extract", "true")
}
if opts.RangeStart != 0 {
err := o.SetRange(opts.RangeStart, 0)
if err != nil {
return nil, nil, probe.NewError(err)
}
}
// Disallow automatic decompression for some objects with content-encoding set.
o.Set("Accept-Encoding", "identity")
reader, e := c.api.GetObject(ctx, bucket, object, o)
if e != nil {
errResponse := minio.ToErrorResponse(e)
if errResponse.Code == "NoSuchBucket" {
return nil, nil, probe.NewError(BucketDoesNotExist{
Bucket: bucket,
})
}
if errResponse.Code == "InvalidBucketName" {
return nil, nil, probe.NewError(BucketInvalid{
Bucket: bucket,
})
}
if errResponse.Code == "NoSuchKey" {
return nil, nil, probe.NewError(ObjectMissing{})
}
return nil, nil, probe.NewError(e)
}
objStat, e := reader.Stat()
if e != nil {
errResponse := minio.ToErrorResponse(e)
if errResponse.Code == "NoSuchBucket" {
return nil, nil, probe.NewError(BucketDoesNotExist{
Bucket: bucket,
})
}
if errResponse.Code == "InvalidBucketName" {
return nil, nil, probe.NewError(BucketInvalid{
Bucket: bucket,
})
}
if errResponse.Code == "NoSuchKey" {
return nil, nil, probe.NewError(ObjectMissing{})
}
return nil, nil, probe.NewError(e)
}