-
Notifications
You must be signed in to change notification settings - Fork 351
/
adapter.go
560 lines (512 loc) · 16.4 KB
/
adapter.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
package gs
import (
"context"
"errors"
"fmt"
"io"
"net/http"
"sort"
"time"
"cloud.google.com/go/storage"
"github.com/treeverse/lakefs/pkg/block"
"github.com/treeverse/lakefs/pkg/logging"
"google.golang.org/api/iterator"
)
const (
BlockstoreType = "gs"
MaxMultipartObjects = 10000
delimiter = "/"
partSuffix = ".part_"
markerSuffix = ".multipart"
)
var (
ErrNotImplemented = errors.New("not implemented")
ErrMissingPartNumber = errors.New("missing part number")
ErrMissingPartETag = errors.New("missing part ETag")
ErrMismatchPartETag = errors.New("mismatch part ETag")
ErrMismatchPartName = errors.New("mismatch part name")
ErrMaxMultipartObjects = errors.New("maximum multipart object reached")
ErrPartListMismatch = errors.New("multipart part list mismatch")
ErrMissingTargetAttrs = errors.New("missing target attributes")
)
type Adapter struct {
client *storage.Client
uploadIDTranslator block.UploadIDTranslator
}
func WithTranslator(t block.UploadIDTranslator) func(a *Adapter) {
return func(a *Adapter) {
a.uploadIDTranslator = t
}
}
func NewAdapter(client *storage.Client, opts ...func(a *Adapter)) *Adapter {
a := &Adapter{
client: client,
uploadIDTranslator: &block.NoOpTranslator{},
}
for _, opt := range opts {
opt(a)
}
return a
}
func (a *Adapter) log(ctx context.Context) logging.Logger {
return logging.FromContext(ctx)
}
func resolveNamespace(obj block.ObjectPointer) (block.QualifiedKey, error) {
qualifiedKey, err := block.ResolveNamespace(obj.StorageNamespace, obj.Identifier, obj.IdentifierType)
if err != nil {
return qualifiedKey, err
}
if qualifiedKey.StorageType != block.StorageTypeGS {
return qualifiedKey, block.ErrInvalidNamespace
}
return qualifiedKey, nil
}
func resolveNamespacePrefix(lsOpts block.WalkOpts) (block.QualifiedPrefix, error) {
qualifiedPrefix, err := block.ResolveNamespacePrefix(lsOpts.StorageNamespace, lsOpts.Prefix)
if err != nil {
return qualifiedPrefix, err
}
if qualifiedPrefix.StorageType != block.StorageTypeGS {
return qualifiedPrefix, block.ErrInvalidNamespace
}
return qualifiedPrefix, nil
}
func (a *Adapter) Put(ctx context.Context, obj block.ObjectPointer, sizeBytes int64, reader io.Reader, _ block.PutOpts) error {
var err error
defer reportMetrics("Put", time.Now(), &sizeBytes, &err)
qualifiedKey, err := resolveNamespace(obj)
if err != nil {
return err
}
w := a.client.
Bucket(qualifiedKey.StorageNamespace).
Object(qualifiedKey.Key).
NewWriter(ctx)
_, err = io.Copy(w, reader)
if err != nil {
return fmt.Errorf("io.Copy: %w", err)
}
err = w.Close()
if err != nil {
return fmt.Errorf("writer.Close: %w", err)
}
return nil
}
func (a *Adapter) Get(ctx context.Context, obj block.ObjectPointer, _ int64) (io.ReadCloser, error) {
var err error
defer reportMetrics("Get", time.Now(), nil, &err)
qualifiedKey, err := resolveNamespace(obj)
if err != nil {
return nil, err
}
r, err := a.client.Bucket(qualifiedKey.StorageNamespace).Object(qualifiedKey.Key).NewReader(ctx)
return r, err
}
func (a *Adapter) Walk(ctx context.Context, walkOpt block.WalkOpts, walkFn block.WalkFunc) error {
var err error
defer reportMetrics("Walk", time.Now(), nil, &err)
qualifiedPrefix, err := resolveNamespacePrefix(walkOpt)
if err != nil {
return err
}
iter := a.client.
Bucket(qualifiedPrefix.StorageNamespace).
Objects(ctx, &storage.Query{Prefix: qualifiedPrefix.Prefix})
for {
attrs, err := iter.Next()
if errors.Is(err, iterator.Done) {
break
}
if err != nil {
return fmt.Errorf("bucket(%s).Objects(): %w", qualifiedPrefix.StorageNamespace, err)
}
if err := walkFn(attrs.Name); err != nil {
return err
}
}
return nil
}
func (a *Adapter) Exists(ctx context.Context, obj block.ObjectPointer) (bool, error) {
var err error
defer reportMetrics("Exists", time.Now(), nil, &err)
qualifiedKey, err := resolveNamespace(obj)
if err != nil {
return false, err
}
_, err = a.client.Bucket(qualifiedKey.StorageNamespace).Object(qualifiedKey.Key).Attrs(ctx)
if errors.Is(err, storage.ErrObjectNotExist) {
return false, nil
}
if err != nil {
return false, err
}
return true, nil
}
func (a *Adapter) GetRange(ctx context.Context, obj block.ObjectPointer, startPosition int64, endPosition int64) (io.ReadCloser, error) {
var err error
defer reportMetrics("GetRange", time.Now(), nil, &err)
qualifiedKey, err := resolveNamespace(obj)
if err != nil {
return nil, err
}
r, err := a.client.
Bucket(qualifiedKey.StorageNamespace).
Object(qualifiedKey.Key).
NewRangeReader(ctx, startPosition, endPosition-startPosition+1)
if err != nil {
return nil, err
}
return r, nil
}
func (a *Adapter) GetProperties(ctx context.Context, obj block.ObjectPointer) (block.Properties, error) {
var err error
defer reportMetrics("GetProperties", time.Now(), nil, &err)
var props block.Properties
qualifiedKey, err := resolveNamespace(obj)
if err != nil {
return props, err
}
_, err = a.client.
Bucket(qualifiedKey.StorageNamespace).
Object(qualifiedKey.Key).
Attrs(ctx)
if err != nil {
return props, err
}
return props, nil
}
func (a *Adapter) Remove(ctx context.Context, obj block.ObjectPointer) error {
var err error
defer reportMetrics("Remove", time.Now(), nil, &err)
qualifiedKey, err := resolveNamespace(obj)
if err != nil {
return err
}
err = a.client.
Bucket(qualifiedKey.StorageNamespace).
Object(qualifiedKey.Key).
Delete(ctx)
if err != nil {
return fmt.Errorf("Object(%q).Delete: %w", qualifiedKey.Key, err)
}
return nil
}
func (a *Adapter) Copy(ctx context.Context, sourceObj, destinationObj block.ObjectPointer) error {
var err error
defer reportMetrics("Copy", time.Now(), nil, &err)
qualifiedDestinationKey, err := resolveNamespace(destinationObj)
if err != nil {
return fmt.Errorf("resolve destination: %w", err)
}
qualifiedSourceKey, err := resolveNamespace(sourceObj)
if err != nil {
return fmt.Errorf("resolve source: %w", err)
}
destinationObjectHandle := a.client.Bucket(qualifiedDestinationKey.StorageNamespace).Object(qualifiedDestinationKey.Key)
sourceObjectHandle := a.client.Bucket(qualifiedSourceKey.StorageNamespace).Object(qualifiedSourceKey.Key)
_, err = destinationObjectHandle.CopierFrom(sourceObjectHandle).Run(ctx)
if err != nil {
return fmt.Errorf("Copy: %w", err)
}
return nil
}
func (a *Adapter) CreateMultiPartUpload(ctx context.Context, obj block.ObjectPointer, r *http.Request, opts block.CreateMultiPartUploadOpts) (string, error) {
var err error
defer reportMetrics("CreateMultiPartUpload", time.Now(), nil, &err)
qualifiedKey, err := resolveNamespace(obj)
if err != nil {
return "", err
}
// we use the qualified key as the upload id
uploadID := a.uploadIDTranslator.SetUploadID(qualifiedKey.Key)
// we keep a marker file to identify multipart in progress
objName := formatMultipartMarkerFilename(uploadID)
o := a.client.
Bucket(qualifiedKey.StorageNamespace).
Object(objName)
w := o.NewWriter(ctx)
_, err = io.WriteString(w, qualifiedKey.Key)
if err != nil {
return "", fmt.Errorf("io.WriteString: %w", err)
}
err = w.Close()
if err != nil {
return "", fmt.Errorf("writer.Close: %w", err)
}
// log information
a.log(ctx).WithFields(logging.Fields{
"upload_id": uploadID,
"qualified_ns": qualifiedKey.StorageNamespace,
"qualified_key": qualifiedKey.Key,
"key": obj.Identifier,
}).Debug("created multipart upload")
return uploadID, nil
}
func (a *Adapter) UploadPart(ctx context.Context, obj block.ObjectPointer, sizeBytes int64, reader io.Reader, uploadID string, partNumber int64) (string, error) {
var err error
defer reportMetrics("UploadPart", time.Now(), &sizeBytes, &err)
qualifiedKey, err := resolveNamespace(obj)
if err != nil {
return "", err
}
uploadID = a.uploadIDTranslator.SetUploadID(uploadID)
objName := formatMultipartFilename(uploadID, partNumber)
o := a.client.
Bucket(qualifiedKey.StorageNamespace).
Object(objName)
w := o.NewWriter(ctx)
_, err = io.Copy(w, reader)
if err != nil {
return "", fmt.Errorf("io.Copy: %w", err)
}
err = w.Close()
if err != nil {
return "", fmt.Errorf("writer.Close: %w", err)
}
attrs, err := o.Attrs(ctx)
if err != nil {
return "", fmt.Errorf("object.Attrs: %w", err)
}
return attrs.Etag, nil
}
func (a *Adapter) UploadCopyPart(ctx context.Context, sourceObj, destinationObj block.ObjectPointer, uploadID string, partNumber int64) (string, error) {
var err error
defer reportMetrics("UploadCopyPart", time.Now(), nil, &err)
qualifiedKey, err := resolveNamespace(destinationObj)
if err != nil {
return "", err
}
uploadID = a.uploadIDTranslator.SetUploadID(uploadID)
objName := formatMultipartFilename(uploadID, partNumber)
o := a.client.
Bucket(qualifiedKey.StorageNamespace).
Object(objName)
qualifiedSourceKey, err := resolveNamespace(sourceObj)
if err != nil {
return "", fmt.Errorf("resolve source: %w", err)
}
sourceObjectHandle := a.client.Bucket(qualifiedSourceKey.StorageNamespace).Object(qualifiedSourceKey.Key)
attrs, err := o.CopierFrom(sourceObjectHandle).Run(ctx)
if err != nil {
return "", fmt.Errorf("CopierFrom: %w", err)
}
return attrs.Etag, nil
}
func (a *Adapter) UploadCopyPartRange(ctx context.Context, sourceObj, destinationObj block.ObjectPointer, uploadID string, partNumber, startPosition, endPosition int64) (string, error) {
var err error
defer reportMetrics("UploadCopyPartRange", time.Now(), nil, &err)
qualifiedKey, err := resolveNamespace(destinationObj)
if err != nil {
return "", err
}
uploadID = a.uploadIDTranslator.SetUploadID(uploadID)
objName := formatMultipartFilename(uploadID, partNumber)
o := a.client.
Bucket(qualifiedKey.StorageNamespace).
Object(objName)
reader, err := a.GetRange(ctx, sourceObj, startPosition, endPosition)
if err != nil {
return "", fmt.Errorf("GetRange: %w", err)
}
w := o.NewWriter(ctx)
_, err = io.Copy(w, reader)
if err != nil {
return "", fmt.Errorf("Copy: %w", err)
}
err = w.Close()
if err != nil {
_ = reader.Close()
return "", fmt.Errorf("WriterClose: %w", err)
}
err = reader.Close()
if err != nil {
return "", fmt.Errorf("ReaderClose: %w", err)
}
attrs, err := o.Attrs(ctx)
if err != nil {
return "", fmt.Errorf("object.Attrs: %w", err)
}
return attrs.Etag, nil
}
func (a *Adapter) AbortMultiPartUpload(ctx context.Context, obj block.ObjectPointer, uploadID string) error {
var err error
defer reportMetrics("AbortMultiPartUpload", time.Now(), nil, &err)
qualifiedKey, err := resolveNamespace(obj)
if err != nil {
return err
}
uploadID = a.uploadIDTranslator.TranslateUploadID(uploadID)
bucket := a.client.Bucket(qualifiedKey.StorageNamespace)
// delete all related files by listing the prefix
it := bucket.Objects(ctx, &storage.Query{
Prefix: uploadID,
Delimiter: delimiter,
})
for {
attrs, err := it.Next()
if errors.Is(err, iterator.Done) {
break
}
if err != nil {
return fmt.Errorf("bucket(%s).Objects(): %w", qualifiedKey.StorageNamespace, err)
}
if err := bucket.Object(attrs.Name).Delete(ctx); err != nil {
return fmt.Errorf("bucket(%s).object(%s).Delete(): %w", qualifiedKey.StorageNamespace, attrs.Name, err)
}
}
a.uploadIDTranslator.RemoveUploadID(uploadID)
return nil
}
func (a *Adapter) CompleteMultiPartUpload(ctx context.Context, obj block.ObjectPointer, uploadID string, multipartList *block.MultipartUploadCompletion) (*string, int64, error) {
var err error
defer reportMetrics("CompleteMultiPartUpload", time.Now(), nil, &err)
qualifiedKey, err := resolveNamespace(obj)
if err != nil {
return nil, 0, err
}
uploadID = a.uploadIDTranslator.TranslateUploadID(uploadID)
lg := a.log(ctx).WithFields(logging.Fields{
"upload_id": uploadID,
"qualified_ns": qualifiedKey.StorageNamespace,
"qualified_key": qualifiedKey.Key,
"key": obj.Identifier,
})
// list bucket parts and validate request match
bucketParts, err := a.listMultipartUploadParts(ctx, qualifiedKey.StorageNamespace, uploadID)
if err != nil {
return nil, 0, err
}
// validate bucketParts match the request multipartList
err = a.validateMultipartUploadParts(uploadID, multipartList, bucketParts)
if err != nil {
return nil, 0, err
}
// prepare names
parts := make([]string, len(bucketParts))
for i, part := range bucketParts {
parts[i] = part.Name
}
// compose target object
targetAttrs, err := a.composeMultipartUploadParts(ctx, qualifiedKey.StorageNamespace, uploadID, parts)
if err != nil {
lg.WithError(err).Error("CompleteMultipartUpload failed")
return nil, 0, err
}
// delete marker
bucket := a.client.Bucket(qualifiedKey.StorageNamespace)
objMarker := bucket.Object(formatMultipartMarkerFilename(uploadID))
if err := objMarker.Delete(ctx); err != nil {
a.log(ctx).WithError(err).Warn("Failed to delete multipart upload marker")
}
a.uploadIDTranslator.RemoveUploadID(uploadID)
lg.Debug("completed multipart upload")
return &targetAttrs.Etag, targetAttrs.Size, nil
}
func (a *Adapter) validateMultipartUploadParts(uploadID string, multipartList *block.MultipartUploadCompletion, bucketParts []*storage.ObjectAttrs) error {
if len(multipartList.Part) != len(bucketParts) {
return ErrPartListMismatch
}
for i, p := range multipartList.Part {
if p.PartNumber == nil {
return fmt.Errorf("invalid part at position %d: %w", i, ErrMissingPartNumber)
}
if p.ETag == nil {
return fmt.Errorf("invalid part at position %d: %w", i, ErrMissingPartETag)
}
objName := formatMultipartFilename(uploadID, *p.PartNumber)
if objName != bucketParts[i].Name {
return fmt.Errorf("invalid part at position %d: %w", i, ErrMismatchPartName)
}
if *p.ETag != bucketParts[i].Etag {
return fmt.Errorf("invalid part at position %d: %w", i, ErrMismatchPartETag)
}
}
return nil
}
func (a *Adapter) listMultipartUploadParts(ctx context.Context, bucketName string, uploadID string) ([]*storage.ObjectAttrs, error) {
bucket := a.client.Bucket(bucketName)
var bucketParts []*storage.ObjectAttrs
it := bucket.Objects(ctx, &storage.Query{
Delimiter: delimiter,
Prefix: uploadID + partSuffix,
})
for {
attrs, err := it.Next()
if errors.Is(err, iterator.Done) {
break
}
if err != nil {
return nil, fmt.Errorf("listing bucket '%s' upload '%s': %w", bucketName, uploadID, err)
}
bucketParts = append(bucketParts, attrs)
if len(bucketParts) > MaxMultipartObjects {
return nil, fmt.Errorf("listing bucket '%s' upload '%s': %w", bucketName, uploadID, ErrMaxMultipartObjects)
}
}
// sort by name - assume natual sort order
sort.Slice(bucketParts, func(i, j int) bool {
return bucketParts[i].Name < bucketParts[j].Name
})
return bucketParts, nil
}
func (a *Adapter) composeMultipartUploadParts(ctx context.Context, bucketName string, uploadID string, parts []string) (*storage.ObjectAttrs, error) {
// compose target from all parts
bucket := a.client.Bucket(bucketName)
var targetAttrs *storage.ObjectAttrs
err := ComposeAll(uploadID, parts, func(target string, parts []string) error {
objs := make([]*storage.ObjectHandle, len(parts))
for i := range parts {
objs[i] = bucket.Object(parts[i])
}
// compose target from parts
attrs, err := bucket.Object(target).ComposerFrom(objs...).Run(ctx)
if err != nil {
return err
}
if target == uploadID {
targetAttrs = attrs
}
// delete parts
for _, o := range objs {
if err := o.Delete(ctx); err != nil {
a.log(ctx).WithError(err).WithFields(logging.Fields{
"bucket": bucketName,
"parts": parts,
}).Warn("Failed to delete multipart upload part while compose")
}
}
return nil
})
if err == nil && targetAttrs == nil {
return nil, ErrMissingTargetAttrs
}
if err != nil {
return nil, err
}
return targetAttrs, nil
}
func (a *Adapter) ValidateConfiguration(ctx context.Context, _ string) error {
return nil
}
func (a *Adapter) GenerateInventory(_ context.Context, _ logging.Logger, _ string, _ bool, _ []string) (block.Inventory, error) {
return nil, fmt.Errorf("inventory %w", ErrNotImplemented)
}
func (a *Adapter) Close() error {
return a.client.Close()
}
func (a *Adapter) BlockstoreType() string {
return BlockstoreType
}
func (a *Adapter) GetStorageNamespaceInfo() block.StorageNamespaceInfo {
return block.DefaultStorageNamespaceInfo(BlockstoreType)
}
func (a *Adapter) RuntimeStats() map[string]string {
return nil
}
func formatMultipartFilename(uploadID string, partNumber int64) string {
// keep natural sort order with zero padding
return fmt.Sprintf("%s"+partSuffix+"%05d", uploadID, partNumber)
}
func formatMultipartMarkerFilename(uploadID string) string {
return uploadID + markerSuffix
}