/
s3.go
519 lines (437 loc) · 14.8 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
/*
Copyright 2019 The Vitess Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Package s3backupstorage implements the BackupStorage interface for AWS S3.
//
// AWS access credentials are configured via standard AWS means, such as:
// - AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY environment variables
// - credentials file at ~/.aws/credentials
// - if running on an EC2 instance, an IAM role
// See details at http://blogs.aws.amazon.com/security/post/Tx3D6U6WSFGOK2H/A-New-and-Standardized-Way-to-Manage-Credentials-in-the-AWS-SDKs
package s3backupstorage
import (
"context"
"crypto/md5"
"crypto/tls"
"encoding/base64"
"fmt"
"io"
"math"
"net/http"
"os"
"sort"
"strings"
"sync"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/client"
"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/spf13/pflag"
"vitess.io/vitess/go/vt/concurrency"
"vitess.io/vitess/go/vt/log"
stats "vitess.io/vitess/go/vt/mysqlctl/backupstats"
"vitess.io/vitess/go/vt/mysqlctl/backupstorage"
"vitess.io/vitess/go/vt/servenv"
)
var (
// AWS API region
region string
// AWS request retries
retryCount int
// AWS endpoint, defaults to amazonaws.com but appliances may use a different location
endpoint string
// bucket is where the backups will go.
bucket string
// root is a prefix added to all object names.
root string
// forcePath is used to ensure that the certificate and path used match the endpoint + region
forcePath bool
tlsSkipVerifyCert bool
// verboseLogging provides more verbose logging of AWS actions
requiredLogLevel string
// sse is the server-side encryption algorithm used when storing this object in S3
sse string
// path component delimiter
delimiter = "/"
)
func registerFlags(fs *pflag.FlagSet) {
fs.StringVar(®ion, "s3_backup_aws_region", "us-east-1", "AWS region to use.")
fs.IntVar(&retryCount, "s3_backup_aws_retries", -1, "AWS request retries.")
fs.StringVar(&endpoint, "s3_backup_aws_endpoint", "", "endpoint of the S3 backend (region must be provided).")
fs.StringVar(&bucket, "s3_backup_storage_bucket", "", "S3 bucket to use for backups.")
fs.StringVar(&root, "s3_backup_storage_root", "", "root prefix for all backup-related object names.")
fs.BoolVar(&forcePath, "s3_backup_force_path_style", false, "force the s3 path style.")
fs.BoolVar(&tlsSkipVerifyCert, "s3_backup_tls_skip_verify_cert", false, "skip the 'certificate is valid' check for SSL connections.")
fs.StringVar(&requiredLogLevel, "s3_backup_log_level", "LogOff", "determine the S3 loglevel to use from LogOff, LogDebug, LogDebugWithSigning, LogDebugWithHTTPBody, LogDebugWithRequestRetries, LogDebugWithRequestErrors.")
fs.StringVar(&sse, "s3_backup_server_side_encryption", "", "server-side encryption algorithm (e.g., AES256, aws:kms, sse_c:/path/to/key/file).")
}
func init() {
servenv.OnParseFor("vtbackup", registerFlags)
servenv.OnParseFor("vtctl", registerFlags)
servenv.OnParseFor("vtctld", registerFlags)
servenv.OnParseFor("vttablet", registerFlags)
}
type logNameToLogLevel map[string]aws.LogLevelType
var logNameMap logNameToLogLevel
const sseCustomerPrefix = "sse_c:"
// S3BackupHandle implements the backupstorage.BackupHandle interface.
type S3BackupHandle struct {
client s3iface.S3API
bs *S3BackupStorage
dir string
name string
readOnly bool
errors concurrency.AllErrorRecorder
waitGroup sync.WaitGroup
}
// Directory is part of the backupstorage.BackupHandle interface.
func (bh *S3BackupHandle) Directory() string {
return bh.dir
}
// Name is part of the backupstorage.BackupHandle interface.
func (bh *S3BackupHandle) Name() string {
return bh.name
}
// RecordError is part of the concurrency.ErrorRecorder interface.
func (bh *S3BackupHandle) RecordError(err error) {
bh.errors.RecordError(err)
}
// HasErrors is part of the concurrency.ErrorRecorder interface.
func (bh *S3BackupHandle) HasErrors() bool {
return bh.errors.HasErrors()
}
// Error is part of the concurrency.ErrorRecorder interface.
func (bh *S3BackupHandle) Error() error {
return bh.errors.Error()
}
// AddFile is part of the backupstorage.BackupHandle interface.
func (bh *S3BackupHandle) AddFile(ctx context.Context, filename string, filesize int64) (io.WriteCloser, error) {
if bh.readOnly {
return nil, fmt.Errorf("AddFile cannot be called on read-only backup")
}
// Calculate s3 upload part size using the source filesize
partSizeBytes := s3manager.DefaultUploadPartSize
if filesize > 0 {
minimumPartSize := float64(filesize) / float64(s3manager.MaxUploadParts)
// Round up to ensure large enough partsize
calculatedPartSizeBytes := int64(math.Ceil(minimumPartSize))
if calculatedPartSizeBytes > partSizeBytes {
partSizeBytes = calculatedPartSizeBytes
}
}
reader, writer := io.Pipe()
bh.waitGroup.Add(1)
go func() {
defer bh.waitGroup.Done()
uploader := s3manager.NewUploaderWithClient(bh.client, func(u *s3manager.Uploader) {
u.PartSize = partSizeBytes
})
object := objName(bh.dir, bh.name, filename)
sendStats := bh.bs.params.Stats.Scope(stats.Operation("AWS:Request:Send"))
// Using UploadWithContext breaks uploading to Minio and Ceph https://github.com/vitessio/vitess/issues/14188
_, err := uploader.Upload(&s3manager.UploadInput{
Bucket: &bucket,
Key: object,
Body: reader,
ServerSideEncryption: bh.bs.s3SSE.awsAlg,
SSECustomerAlgorithm: bh.bs.s3SSE.customerAlg,
SSECustomerKey: bh.bs.s3SSE.customerKey,
SSECustomerKeyMD5: bh.bs.s3SSE.customerMd5,
}, s3manager.WithUploaderRequestOptions(func(r *request.Request) {
r.Handlers.CompleteAttempt.PushBack(func(r *request.Request) {
sendStats.TimedIncrement(time.Since(r.AttemptTime))
})
}))
if err != nil {
reader.CloseWithError(err)
bh.RecordError(err)
}
}()
return writer, nil
}
// EndBackup is part of the backupstorage.BackupHandle interface.
func (bh *S3BackupHandle) EndBackup(ctx context.Context) error {
if bh.readOnly {
return fmt.Errorf("EndBackup cannot be called on read-only backup")
}
bh.waitGroup.Wait()
return bh.Error()
}
// AbortBackup is part of the backupstorage.BackupHandle interface.
func (bh *S3BackupHandle) AbortBackup(ctx context.Context) error {
if bh.readOnly {
return fmt.Errorf("AbortBackup cannot be called on read-only backup")
}
return bh.bs.RemoveBackup(ctx, bh.dir, bh.name)
}
// ReadFile is part of the backupstorage.BackupHandle interface.
func (bh *S3BackupHandle) ReadFile(ctx context.Context, filename string) (io.ReadCloser, error) {
if !bh.readOnly {
return nil, fmt.Errorf("ReadFile cannot be called on read-write backup")
}
object := objName(bh.dir, bh.name, filename)
sendStats := bh.bs.params.Stats.Scope(stats.Operation("AWS:Request:Send"))
out, err := bh.client.GetObjectWithContext(ctx, &s3.GetObjectInput{
Bucket: &bucket,
Key: object,
SSECustomerAlgorithm: bh.bs.s3SSE.customerAlg,
SSECustomerKey: bh.bs.s3SSE.customerKey,
SSECustomerKeyMD5: bh.bs.s3SSE.customerMd5,
}, func(r *request.Request) {
r.Handlers.CompleteAttempt.PushBack(func(r *request.Request) {
sendStats.TimedIncrement(time.Since(r.AttemptTime))
})
})
if err != nil {
return nil, err
}
return out.Body, nil
}
var _ backupstorage.BackupHandle = (*S3BackupHandle)(nil)
type S3ServerSideEncryption struct {
awsAlg *string
customerAlg *string
customerKey *string
customerMd5 *string
}
func (s3ServerSideEncryption *S3ServerSideEncryption) init() error {
s3ServerSideEncryption.reset()
if strings.HasPrefix(sse, sseCustomerPrefix) {
sseCustomerKeyFile := strings.TrimPrefix(sse, sseCustomerPrefix)
base64CodedKey, err := os.ReadFile(sseCustomerKeyFile)
if err != nil {
log.Errorf(err.Error())
return err
}
decodedKey, err := base64.StdEncoding.DecodeString(string(base64CodedKey))
if err != nil {
decodedKey = base64CodedKey
}
md5Hash := md5.Sum(decodedKey)
s3ServerSideEncryption.customerAlg = aws.String("AES256")
s3ServerSideEncryption.customerKey = aws.String(string(decodedKey))
s3ServerSideEncryption.customerMd5 = aws.String(base64.StdEncoding.EncodeToString(md5Hash[:]))
} else if sse != "" {
s3ServerSideEncryption.awsAlg = &sse
}
return nil
}
func (s3ServerSideEncryption *S3ServerSideEncryption) reset() {
s3ServerSideEncryption.awsAlg = nil
s3ServerSideEncryption.customerAlg = nil
s3ServerSideEncryption.customerKey = nil
s3ServerSideEncryption.customerMd5 = nil
}
// S3BackupStorage implements the backupstorage.BackupStorage interface.
type S3BackupStorage struct {
_client *s3.S3
mu sync.Mutex
s3SSE S3ServerSideEncryption
params backupstorage.Params
transport *http.Transport
}
func newS3BackupStorage() *S3BackupStorage {
// This initialises a new transport based off http.DefaultTransport the first time and returns the same
// transport on subsequent calls so connections can be reused as part of the same transport.
tlsClientConf := &tls.Config{InsecureSkipVerify: tlsSkipVerifyCert}
transport := http.DefaultTransport.(*http.Transport).Clone()
transport.TLSClientConfig = tlsClientConf
return &S3BackupStorage{params: backupstorage.NoParams(), transport: transport}
}
// ListBackups is part of the backupstorage.BackupStorage interface.
func (bs *S3BackupStorage) ListBackups(ctx context.Context, dir string) ([]backupstorage.BackupHandle, error) {
log.Infof("ListBackups: [s3] dir: %v, bucket: %v", dir, bucket)
c, err := bs.client()
if err != nil {
return nil, err
}
var searchPrefix *string
if dir == "/" {
searchPrefix = objName("")
} else {
searchPrefix = objName(dir, "")
}
log.Infof("objName: %v", *searchPrefix)
query := &s3.ListObjectsV2Input{
Bucket: &bucket,
Delimiter: &delimiter,
Prefix: searchPrefix,
}
var subdirs []string
for {
objs, err := c.ListObjectsV2(query)
if err != nil {
return nil, err
}
for _, prefix := range objs.CommonPrefixes {
subdir := strings.TrimPrefix(*prefix.Prefix, *searchPrefix)
subdir = strings.TrimSuffix(subdir, delimiter)
subdirs = append(subdirs, subdir)
}
if objs.NextContinuationToken == nil {
break
}
query.ContinuationToken = objs.NextContinuationToken
}
// Backups must be returned in order, oldest first.
sort.Strings(subdirs)
result := make([]backupstorage.BackupHandle, 0, len(subdirs))
for _, subdir := range subdirs {
result = append(result, &S3BackupHandle{
client: c,
bs: bs,
dir: dir,
name: subdir,
readOnly: true,
})
}
return result, nil
}
// StartBackup is part of the backupstorage.BackupStorage interface.
func (bs *S3BackupStorage) StartBackup(ctx context.Context, dir, name string) (backupstorage.BackupHandle, error) {
log.Infof("StartBackup: [s3] dir: %v, name: %v, bucket: %v", dir, name, bucket)
c, err := bs.client()
if err != nil {
return nil, err
}
return &S3BackupHandle{
client: c,
bs: bs,
dir: dir,
name: name,
readOnly: false,
}, nil
}
// RemoveBackup is part of the backupstorage.BackupStorage interface.
func (bs *S3BackupStorage) RemoveBackup(ctx context.Context, dir, name string) error {
log.Infof("RemoveBackup: [s3] dir: %v, name: %v, bucket: %v", dir, name, bucket)
c, err := bs.client()
if err != nil {
return err
}
query := &s3.ListObjectsV2Input{
Bucket: &bucket,
Prefix: objName(dir, name),
}
for {
objs, err := c.ListObjectsV2(query)
if err != nil {
return err
}
objIds := make([]*s3.ObjectIdentifier, 0, len(objs.Contents))
for _, obj := range objs.Contents {
objIds = append(objIds, &s3.ObjectIdentifier{
Key: obj.Key,
})
}
quiet := true // return less in the Delete response
out, err := c.DeleteObjects(&s3.DeleteObjectsInput{
Bucket: &bucket,
Delete: &s3.Delete{
Objects: objIds,
Quiet: &quiet,
},
})
if err != nil {
return err
}
for _, objError := range out.Errors {
return fmt.Errorf(objError.String())
}
if objs.NextContinuationToken == nil {
break
}
query.ContinuationToken = objs.NextContinuationToken
}
return nil
}
// Close is part of the backupstorage.BackupStorage interface.
func (bs *S3BackupStorage) Close() error {
bs.mu.Lock()
defer bs.mu.Unlock()
bs._client = nil
bs.s3SSE.reset()
return nil
}
func (bs *S3BackupStorage) WithParams(params backupstorage.Params) backupstorage.BackupStorage {
return &S3BackupStorage{params: params, transport: bs.transport}
}
var _ backupstorage.BackupStorage = (*S3BackupStorage)(nil)
// getLogLevel converts the string loglevel to an aws.LogLevelType
func getLogLevel() *aws.LogLevelType {
l := new(aws.LogLevelType)
*l = aws.LogOff // default setting
if level, found := logNameMap[requiredLogLevel]; found {
*l = level // adjust as required
}
return l
}
func (bs *S3BackupStorage) client() (*s3.S3, error) {
bs.mu.Lock()
defer bs.mu.Unlock()
if bs._client == nil {
logLevel := getLogLevel()
httpClient := &http.Client{Transport: bs.transport}
session, err := session.NewSession()
if err != nil {
return nil, err
}
awsConfig := aws.Config{
HTTPClient: httpClient,
LogLevel: logLevel,
Endpoint: aws.String(endpoint),
Region: aws.String(region),
S3ForcePathStyle: aws.Bool(forcePath),
}
if retryCount >= 0 {
awsConfig = *request.WithRetryer(&awsConfig, &ClosedConnectionRetryer{
awsRetryer: &client.DefaultRetryer{
NumMaxRetries: retryCount,
},
})
}
bs._client = s3.New(session, &awsConfig)
if len(bucket) == 0 {
return nil, fmt.Errorf("--s3_backup_storage_bucket required")
}
if _, err := bs._client.HeadBucket(&s3.HeadBucketInput{Bucket: &bucket}); err != nil {
return nil, err
}
if err := bs.s3SSE.init(); err != nil {
return nil, err
}
}
return bs._client, nil
}
func objName(parts ...string) *string {
res := ""
if root != "" {
res += root + delimiter
}
res += strings.Join(parts, delimiter)
return &res
}
func init() {
backupstorage.BackupStorageMap["s3"] = newS3BackupStorage()
logNameMap = logNameToLogLevel{
"LogOff": aws.LogOff,
"LogDebug": aws.LogDebug,
"LogDebugWithSigning": aws.LogDebugWithSigning,
"LogDebugWithHTTPBody": aws.LogDebugWithHTTPBody,
"LogDebugWithRequestRetries": aws.LogDebugWithRequestRetries,
"LogDebugWithRequestErrors": aws.LogDebugWithRequestErrors,
}
}