forked from snowflakedb/gosnowflake
-
Notifications
You must be signed in to change notification settings - Fork 0
/
s3_storage_client.go
275 lines (252 loc) · 6.92 KB
/
s3_storage_client.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
// Copyright (c) 2021-2022 Snowflake Computing Inc. All rights reserved.
package gosnowflake
import (
"bytes"
"context"
"errors"
"fmt"
"os"
"strings"
"github.com/aws/aws-sdk-go-v2/aws"
"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/smithy-go"
)
const (
sfcDigest = "sfc-digest"
amzMatdesc = "x-amz-matdesc"
amzKey = "x-amz-key"
amzIv = "x-amz-iv"
notFound = "NotFound"
expiredToken = "ExpiredToken"
errNoWsaeconnaborted = "10053"
)
type snowflakeS3Client struct {
}
type s3Location struct {
bucketName string
s3Path string
}
func (util *snowflakeS3Client) createClient(info *execResponseStageInfo, useAccelerateEndpoint bool) (cloudClient, error) {
stageCredentials := info.Creds
var resolver s3.EndpointResolver
if info.EndPoint != "" {
resolver = s3.EndpointResolverFromURL("https://" + info.EndPoint) // FIPS endpoint
}
return s3.New(s3.Options{
Region: info.Region,
Credentials: aws.NewCredentialsCache(credentials.NewStaticCredentialsProvider(
stageCredentials.AwsKeyID,
stageCredentials.AwsSecretKey,
stageCredentials.AwsToken)),
EndpointResolver: resolver,
UseAccelerate: useAccelerateEndpoint,
}), nil
}
type s3HeaderAPI interface {
HeadObject(ctx context.Context, params *s3.HeadObjectInput, optFns ...func(*s3.Options)) (*s3.HeadObjectOutput, error)
}
// cloudUtil implementation
func (util *snowflakeS3Client) getFileHeader(meta *fileMetadata, filename string) (*fileHeader, error) {
headObjInput, err := util.getS3Object(meta, filename)
if err != nil {
return nil, err
}
var s3Cli s3HeaderAPI
s3Cli, ok := meta.client.(*s3.Client)
if !ok {
return nil, fmt.Errorf("could not parse client to s3.Client")
}
if meta.mockHeader != nil {
s3Cli = meta.mockHeader
}
out, err := s3Cli.HeadObject(context.Background(), headObjInput)
if err != nil {
var ae smithy.APIError
if errors.As(err, &ae) {
if ae.ErrorCode() == notFound {
meta.resStatus = notFoundFile
return &fileHeader{
digest: "",
contentLength: 0,
encryptionMetadata: nil,
}, nil
} else if ae.ErrorCode() == expiredToken {
meta.resStatus = renewToken
return nil, fmt.Errorf("received expired token. renewing")
}
meta.resStatus = errStatus
meta.lastError = err
return nil, fmt.Errorf("error while retrieving header")
}
}
meta.resStatus = uploaded
var encMeta encryptMetadata
if out.Metadata[amzKey] != "" {
encMeta = encryptMetadata{
out.Metadata[amzKey],
out.Metadata[amzIv],
out.Metadata[amzMatdesc],
}
}
return &fileHeader{
out.Metadata[sfcDigest],
out.ContentLength,
&encMeta,
}, nil
}
type s3UploadAPI interface {
Upload(ctx context.Context, params *s3.PutObjectInput, optFns ...func(*manager.Uploader)) (*manager.UploadOutput, error)
}
// cloudUtil implementation
func (util *snowflakeS3Client) uploadFile(
dataFile string,
meta *fileMetadata,
encryptMeta *encryptMetadata,
maxConcurrency int,
multiPartThreshold int64) error {
s3Meta := map[string]string{
httpHeaderContentType: httpHeaderValueOctetStream,
sfcDigest: meta.sha256Digest,
}
if encryptMeta != nil {
s3Meta[amzIv] = encryptMeta.iv
s3Meta[amzKey] = encryptMeta.key
s3Meta[amzMatdesc] = encryptMeta.matdesc
}
s3loc, err := util.extractBucketNameAndPath(meta.stageInfo.Location)
if err != nil {
return err
}
s3path := s3loc.s3Path + strings.TrimLeft(meta.dstFileName, "/")
client, ok := meta.client.(*s3.Client)
if !ok {
return &SnowflakeError{
Message: "failed to cast to s3 client",
}
}
var uploader s3UploadAPI
uploader = manager.NewUploader(client, func(u *manager.Uploader) {
u.Concurrency = maxConcurrency
u.PartSize = int64Max(multiPartThreshold, manager.DefaultUploadPartSize)
})
if meta.mockUploader != nil {
uploader = meta.mockUploader
}
if meta.srcStream != nil {
uploadStream := meta.srcStream
if meta.realSrcStream != nil {
uploadStream = meta.realSrcStream
}
_, err = uploader.Upload(context.Background(), &s3.PutObjectInput{
Bucket: &s3loc.bucketName,
Key: &s3path,
Body: bytes.NewBuffer(uploadStream.Bytes()),
Metadata: s3Meta,
})
} else {
var file *os.File
file, err = os.Open(dataFile)
if err != nil {
return err
}
_, err = uploader.Upload(context.Background(), &s3.PutObjectInput{
Bucket: &s3loc.bucketName,
Key: &s3path,
Body: file,
Metadata: s3Meta,
})
}
if err != nil {
var ae smithy.APIError
if errors.As(err, &ae) {
if ae.ErrorCode() == expiredToken {
meta.resStatus = renewToken
return err
} else if strings.Contains(ae.ErrorCode(), errNoWsaeconnaborted) {
meta.lastError = err
meta.resStatus = needRetryWithLowerConcurrency
return err
}
}
meta.lastError = err
meta.resStatus = needRetry
return err
}
meta.dstFileSize = meta.uploadSize
meta.resStatus = uploaded
return nil
}
// cloudUtil implementation
func (util *snowflakeS3Client) nativeDownloadFile(
meta *fileMetadata,
fullDstFileName string,
maxConcurrency int64) error {
s3Obj, _ := util.getS3Object(meta, meta.srcFileName)
client, ok := meta.client.(*s3.Client)
if !ok {
return &SnowflakeError{
Message: "failed to cast to s3 client",
}
}
f, err := os.OpenFile(fullDstFileName, os.O_CREATE|os.O_WRONLY, os.ModePerm)
if err != nil {
return err
}
defer f.Close()
downloader := manager.NewDownloader(client, func(u *manager.Downloader) {
u.Concurrency = int(maxConcurrency)
})
if _, err = downloader.Download(context.Background(), f, &s3.GetObjectInput{
Bucket: s3Obj.Bucket,
Key: s3Obj.Key,
}); err != nil {
var ae smithy.APIError
if errors.As(err, &ae) {
if ae.ErrorCode() == expiredToken {
meta.resStatus = renewToken
return err
} else if strings.Contains(ae.ErrorCode(), errNoWsaeconnaborted) {
meta.lastError = err
meta.resStatus = needRetryWithLowerConcurrency
return err
}
meta.lastError = err
meta.resStatus = errStatus
return err
}
meta.lastError = err
meta.resStatus = needRetry
return err
}
meta.resStatus = downloaded
return nil
}
func (util *snowflakeS3Client) extractBucketNameAndPath(location string) (*s3Location, error) {
stageLocation, err := expandUser(location)
if err != nil {
return nil, err
}
bucketName := stageLocation
s3Path := ""
if idx := strings.Index(stageLocation, "/"); idx >= 0 {
bucketName = stageLocation[0:idx]
s3Path = stageLocation[idx+1:]
if s3Path != "" && !strings.HasSuffix(s3Path, "/") {
s3Path += "/"
}
}
return &s3Location{bucketName, s3Path}, nil
}
func (util *snowflakeS3Client) getS3Object(meta *fileMetadata, filename string) (*s3.HeadObjectInput, error) {
s3loc, err := util.extractBucketNameAndPath(meta.stageInfo.Location)
if err != nil {
return nil, err
}
s3path := s3loc.s3Path + strings.TrimLeft(filename, "/")
return &s3.HeadObjectInput{
Bucket: &s3loc.bucketName,
Key: &s3path,
}, nil
}