-
Notifications
You must be signed in to change notification settings - Fork 342
/
adapter.go
464 lines (393 loc) · 13.8 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
package azure
import (
"context"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"time"
"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob"
"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/blob"
"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/bloberror"
"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/blockblob"
"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/sas"
"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/service"
"github.com/treeverse/lakefs/pkg/block"
"github.com/treeverse/lakefs/pkg/logging"
)
var ErrNotImplemented = errors.New("not implemented")
const (
sizeSuffix = "_size"
idSuffix = "_id"
_1MiB = 1024 * 1024
MaxBuffers = 1
defaultMaxRetryRequests = 0
URLTemplate = "https://%s.blob.core.windows.net/"
)
type Adapter struct {
client *service.Client
configurations configurations
preSignedURLDurationGenerator func() time.Time
}
type configurations struct {
retryReaderOptions azblob.RetryReaderOptions
}
func NewAdapter(client *service.Client, opts ...func(a *Adapter)) *Adapter {
a := &Adapter{
client: client,
configurations: configurations{retryReaderOptions: azblob.RetryReaderOptions{MaxRetries: defaultMaxRetryRequests}},
preSignedURLDurationGenerator: func() time.Time {
return time.Now().UTC().Add(block.DefaultPreSignExpiryDuration)
},
}
for _, opt := range opts {
opt(a)
}
return a
}
type BlobURLInfo struct {
ContainerURL string
ContainerName string
BlobURL string
}
type PrefixURLInfo struct {
ContainerURL string
ContainerName string
Prefix string
}
func ResolveBlobURLInfoFromURL(pathURL *url.URL) (BlobURLInfo, error) {
var qk BlobURLInfo
storageType, err := block.GetStorageType(pathURL)
if err != nil {
return qk, err
}
if storageType != block.StorageTypeAzure {
return qk, block.ErrInvalidNamespace
}
// In azure the first part of the path is part of the storage namespace
trimmedPath := strings.Trim(pathURL.Path, "/")
parts := strings.Split(trimmedPath, "/")
if len(parts) == 0 {
return qk, block.ErrInvalidNamespace
}
return BlobURLInfo{
ContainerURL: fmt.Sprintf("%s://%s/%s", pathURL.Scheme, pathURL.Host, parts[0]),
ContainerName: parts[0],
BlobURL: strings.Join(parts[1:], "/"),
}, nil
}
func resolveBlobURLInfo(obj block.ObjectPointer) (BlobURLInfo, error) {
key := obj.Identifier
defaultNamespace := obj.StorageNamespace
var qk BlobURLInfo
// check if the key is fully qualified
parsedKey, err := url.ParseRequestURI(key)
if err != nil {
// is not fully qualified, treat as key only
// if we don't have a trailing slash for the namespace, add it.
parsedNamespace, err := url.ParseRequestURI(defaultNamespace)
if err != nil {
return qk, err
}
qp, err := ResolveBlobURLInfoFromURL(parsedNamespace)
if err != nil {
return qk, err
}
info := BlobURLInfo{
ContainerURL: qp.ContainerURL,
ContainerName: qp.ContainerName,
BlobURL: qp.BlobURL + "/" + key,
}
if qp.BlobURL == "" {
info.BlobURL = key
}
return info, nil
}
return ResolveBlobURLInfoFromURL(parsedKey)
}
func resolveNamespacePrefix(lsOpts block.WalkOpts) (PrefixURLInfo, error) {
qualifiedPrefix, err := resolveBlobURLInfo(block.ObjectPointer{
StorageNamespace: lsOpts.StorageNamespace,
Identifier: lsOpts.Prefix,
})
if err != nil {
return PrefixURLInfo{}, err
}
return PrefixURLInfo{
ContainerURL: qualifiedPrefix.ContainerURL,
ContainerName: qualifiedPrefix.ContainerName,
Prefix: qualifiedPrefix.BlobURL,
}, 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) translatePutOpts(ctx context.Context, opts block.PutOpts) azblob.UploadStreamOptions {
res := azblob.UploadStreamOptions{}
if opts.StorageClass == nil {
return res
}
for _, t := range blob.PossibleAccessTierValues() {
if strings.EqualFold(*opts.StorageClass, string(t)) {
accessTier := t
res.AccessTier = &accessTier
break
}
}
if res.AccessTier == nil {
a.log(ctx).WithField("tier_type", *opts.StorageClass).Warn("Unknown Azure tier type")
}
return res
}
func (a *Adapter) log(ctx context.Context) logging.Logger {
return logging.FromContext(ctx)
}
func (a *Adapter) Put(ctx context.Context, obj block.ObjectPointer, sizeBytes int64, reader io.Reader, opts block.PutOpts) error {
var err error
defer reportMetrics("Put", time.Now(), &sizeBytes, &err)
qualifiedKey, err := resolveBlobURLInfo(obj)
if err != nil {
return err
}
o := a.translatePutOpts(ctx, opts)
_, err = a.client.NewContainerClient(qualifiedKey.ContainerName).NewBlockBlobClient(qualifiedKey.BlobURL).UploadStream(ctx, reader, &o)
return err
}
func (a *Adapter) Get(ctx context.Context, obj block.ObjectPointer, _ int64) (io.ReadCloser, error) {
var err error
defer reportMetrics("Get", time.Now(), nil, &err)
return a.Download(ctx, obj, 0, blockblob.CountToEnd)
}
func (a *Adapter) GetPreSignedURL(_ context.Context, obj block.ObjectPointer, mode block.PreSignMode) (string, error) {
permissions := sas.BlobPermissions{Read: true}
if mode == block.PreSignModeWrite {
permissions = sas.BlobPermissions{
Read: true,
Add: true,
Write: true,
}
}
return a.getPreSignedURL(obj, permissions)
}
func (a *Adapter) getPreSignedURL(obj block.ObjectPointer, permissions sas.BlobPermissions) (string, error) {
qualifiedKey, err := resolveBlobURLInfo(obj)
if err != nil {
return "", err
}
blobURL := a.client.NewContainerClient(qualifiedKey.ContainerName).NewBlobClient(qualifiedKey.BlobURL)
u, err := blobURL.GetSASURL(permissions, time.Time{}, a.preSignedURLDurationGenerator())
if err != nil {
return "", err
}
return u, 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)
return a.Download(ctx, obj, startPosition, endPosition-startPosition+1)
}
func (a *Adapter) Download(ctx context.Context, obj block.ObjectPointer, offset, count int64) (io.ReadCloser, error) {
qualifiedKey, err := resolveBlobURLInfo(obj)
if err != nil {
return nil, err
}
container := a.client.NewContainerClient(qualifiedKey.ContainerName)
blobURL := container.NewBlockBlobClient(qualifiedKey.BlobURL)
downloadResponse, err := blobURL.DownloadStream(ctx, &azblob.DownloadStreamOptions{
RangeGetContentMD5: nil,
Range: blob.HTTPRange{
Offset: offset,
Count: count,
},
})
if bloberror.HasCode(err, bloberror.BlobNotFound) {
return nil, block.ErrDataNotFound
}
if err != nil {
a.log(ctx).WithError(err).Errorf("failed to get azure blob from container %s key %s", container, blobURL)
return nil, err
}
return downloadResponse.Body, nil
}
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
}
containerURL := a.client.NewContainerClient(qualifiedPrefix.ContainerName)
var marker *string
for {
listBlob := containerURL.NewListBlobsFlatPager(&azblob.ListBlobsFlatOptions{
Prefix: &qualifiedPrefix.Prefix,
Marker: marker,
})
for listBlob.More() {
resp, err := listBlob.NextPage(ctx)
if err != nil {
return err
}
for _, blobInfo := range resp.Segment.BlobItems {
if err := walkFn(*blobInfo.Name); err != nil {
return err
}
}
if marker = resp.NextMarker; marker == nil {
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 := resolveBlobURLInfo(obj)
if err != nil {
return false, err
}
blobURL := a.client.NewContainerClient(qualifiedKey.ContainerName).NewBlobClient(qualifiedKey.BlobURL)
_, err = blobURL.GetProperties(ctx, nil)
if bloberror.HasCode(err, bloberror.BlobNotFound) {
return false, nil
}
if err != nil {
return false, err
}
return true, nil
}
func (a *Adapter) GetProperties(ctx context.Context, obj block.ObjectPointer) (block.Properties, error) {
var err error
defer reportMetrics("GetProperties", time.Now(), nil, &err)
qualifiedKey, err := resolveBlobURLInfo(obj)
if err != nil {
return block.Properties{}, err
}
container := a.client.NewContainerClient(qualifiedKey.ContainerName)
blobURL := container.NewBlobClient(qualifiedKey.BlobURL)
props, err := blobURL.GetProperties(ctx, nil)
if err != nil {
return block.Properties{}, err
}
return block.Properties{StorageClass: props.AccessTier}, nil
}
func (a *Adapter) Remove(ctx context.Context, obj block.ObjectPointer) error {
var err error
defer reportMetrics("Remove", time.Now(), nil, &err)
qualifiedKey, err := resolveBlobURLInfo(obj)
if err != nil {
return err
}
container := a.client.NewContainerClient(qualifiedKey.ContainerName)
blobURL := container.NewBlobClient(qualifiedKey.BlobURL)
_, err = blobURL.Delete(ctx, nil)
return err
}
func (a *Adapter) Copy(ctx context.Context, sourceObj, destinationObj block.ObjectPointer) error {
var err error
defer reportMetrics("Copy", time.Now(), nil, &err)
qualifiedDestinationKey, err := resolveBlobURLInfo(destinationObj)
if err != nil {
return err
}
qualifiedSourceKey, err := resolveBlobURLInfo(sourceObj)
if err != nil {
return err
}
destClient := a.client.NewContainerClient(qualifiedDestinationKey.ContainerName).NewBlobClient(qualifiedDestinationKey.BlobURL)
sourceClient := a.client.NewContainerClient(qualifiedSourceKey.ContainerName).NewBlobClient(qualifiedSourceKey.BlobURL)
sasKey, err := sourceClient.GetSASURL(sas.BlobPermissions{
Read: true,
}, time.Time{}, a.preSignedURLDurationGenerator())
if err != nil {
return err
}
// TODO (niro): copy is limited to 256MB, should we handle it somehow?
_, err = destClient.CopyFromURL(ctx, sasKey, nil)
return err
}
func (a *Adapter) CreateMultiPartUpload(_ context.Context, obj block.ObjectPointer, _ *http.Request, _ block.CreateMultiPartUploadOpts) (*block.CreateMultiPartUploadResponse, error) {
// Azure has no create multipart upload
var err error
defer reportMetrics("CreateMultiPartUpload", time.Now(), nil, &err)
qualifiedKey, err := resolveBlobURLInfo(obj)
if err != nil {
return nil, err
}
return &block.CreateMultiPartUploadResponse{
UploadID: qualifiedKey.BlobURL,
}, nil
}
func (a *Adapter) UploadPart(ctx context.Context, obj block.ObjectPointer, _ int64, reader io.Reader, _ string, _ int) (*block.UploadPartResponse, error) {
var err error
defer reportMetrics("UploadPart", time.Now(), nil, &err)
qualifiedKey, err := resolveBlobURLInfo(obj)
if err != nil {
return nil, err
}
container := a.client.NewContainerClient(qualifiedKey.ContainerName)
hashReader := block.NewHashingReader(reader, block.HashFunctionMD5)
multipartBlockWriter := NewMultipartBlockWriter(hashReader, *container, qualifiedKey.BlobURL)
_, err = copyFromReader(ctx, hashReader, multipartBlockWriter, blockblob.UploadStreamOptions{
BlockSize: _1MiB,
Concurrency: MaxBuffers,
})
if err != nil {
return nil, err
}
return &block.UploadPartResponse{
ETag: strings.Trim(multipartBlockWriter.etag, `"`),
}, nil
}
func (a *Adapter) UploadCopyPart(ctx context.Context, sourceObj, destinationObj block.ObjectPointer, _ string, _ int) (*block.UploadPartResponse, error) {
var err error
defer reportMetrics("UploadPart", time.Now(), nil, &err)
return a.copyPartRange(ctx, sourceObj, destinationObj, 0, blockblob.CountToEnd)
}
func (a *Adapter) UploadCopyPartRange(ctx context.Context, sourceObj, destinationObj block.ObjectPointer, _ string, _ int, startPosition, endPosition int64) (*block.UploadPartResponse, error) {
var err error
defer reportMetrics("UploadPart", time.Now(), nil, &err)
return a.copyPartRange(ctx, sourceObj, destinationObj, startPosition, endPosition-startPosition+1)
}
func (a *Adapter) copyPartRange(ctx context.Context, sourceObj, destinationObj block.ObjectPointer, startPosition, count int64) (*block.UploadPartResponse, error) {
qualifiedSourceKey, err := resolveBlobURLInfo(sourceObj)
if err != nil {
return nil, err
}
qualifiedDestinationKey, err := resolveBlobURLInfo(destinationObj)
if err != nil {
return nil, err
}
destinationContainer := a.client.NewContainerClient(qualifiedDestinationKey.ContainerName)
sourceContainer := a.client.NewContainerClient(qualifiedSourceKey.ContainerName)
sourceBlobURL := sourceContainer.NewBlockBlobClient(qualifiedSourceKey.BlobURL)
return copyPartRange(ctx, *destinationContainer, qualifiedDestinationKey.BlobURL, *sourceBlobURL, startPosition, count)
}
func (a *Adapter) AbortMultiPartUpload(_ context.Context, _ block.ObjectPointer, _ string) error {
// Azure has no abort, in case of commit, uncommitted parts are erased, otherwise staged data is erased after 7 days
return nil
}
func (a *Adapter) BlockstoreType() string {
return block.BlockstoreTypeAzure
}
func (a *Adapter) CompleteMultiPartUpload(ctx context.Context, obj block.ObjectPointer, _ string, multipartList *block.MultipartUploadCompletion) (*block.CompleteMultiPartUploadResponse, error) {
var err error
defer reportMetrics("CompleteMultiPartUpload", time.Now(), nil, &err)
qualifiedKey, err := resolveBlobURLInfo(obj)
if err != nil {
return nil, err
}
containerURL := a.client.NewContainerClient(qualifiedKey.ContainerName)
return completeMultipart(ctx, multipartList.Part, *containerURL, qualifiedKey.BlobURL)
}
func (a *Adapter) GetStorageNamespaceInfo() block.StorageNamespaceInfo {
return block.StorageNamespaceInfo{
ValidityRegex: `^https?://`,
Example: "https://mystorageaccount.blob.core.windows.net/mycontainer/",
}
}
func (a *Adapter) RuntimeStats() map[string]string {
return nil
}