/
block_blob.go
1499 lines (1297 loc) · 50.8 KB
/
block_blob.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
/*
Licensed under the MIT License <http://opensource.org/licenses/MIT>.
Copyright © 2023-2024 Seagate Technology LLC and/or its Affiliates
Copyright © 2020-2024 Microsoft Corporation. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE
*/
package azstorage
import (
"bytes"
"context"
"encoding/base64"
"errors"
"math"
"net/url"
"os"
"path/filepath"
"reflect"
"runtime"
"strings"
"syscall"
"time"
"github.com/Seagate/cloudfuse/common"
"github.com/Seagate/cloudfuse/common/log"
"github.com/Seagate/cloudfuse/internal"
"github.com/Seagate/cloudfuse/internal/convertname"
"github.com/Seagate/cloudfuse/internal/stats_manager"
"github.com/Azure/azure-pipeline-go/pipeline"
"github.com/Azure/azure-storage-azcopy/v10/ste"
"github.com/Azure/azure-storage-blob-go/azblob"
)
const (
folderKey = "hdi_isfolder"
symlinkKey = "is_symlink"
max_context_timeout = 5
)
type BlockBlob struct {
AzStorageConnection
Auth azAuth
Service azblob.ServiceURL
Container azblob.ContainerURL
blobAccCond azblob.BlobAccessConditions
blobCPKOpt azblob.ClientProvidedKeyOptions
downloadOptions azblob.DownloadFromBlobOptions
listDetails azblob.BlobListingDetails
blockLocks common.KeyedMutex
}
// Verify that BlockBlob implements AzConnection interface
var _ AzConnection = &BlockBlob{}
const (
MaxBlocksSize = azblob.BlockBlobMaxStageBlockBytes * azblob.BlockBlobMaxBlocks
)
func (bb *BlockBlob) Configure(cfg AzStorageConfig) error {
bb.Config = cfg
bb.blobAccCond = azblob.BlobAccessConditions{}
if bb.Config.cpkEnabled {
bb.blobCPKOpt = azblob.ClientProvidedKeyOptions{
EncryptionKey: &bb.Config.cpkEncryptionKey,
EncryptionKeySha256: &bb.Config.cpkEncryptionKeySha256,
EncryptionAlgorithm: "AES256",
}
} else {
bb.blobCPKOpt = azblob.ClientProvidedKeyOptions{}
}
bb.downloadOptions = azblob.DownloadFromBlobOptions{
BlockSize: bb.Config.blockSize,
Parallelism: bb.Config.maxConcurrency,
ClientProvidedKeyOptions: bb.blobCPKOpt,
}
bb.listDetails = azblob.BlobListingDetails{
Metadata: true,
Deleted: false,
Snapshots: false,
}
return nil
}
// For dynamic config update the config here
func (bb *BlockBlob) UpdateConfig(cfg AzStorageConfig) error {
bb.Config.blockSize = cfg.blockSize
bb.Config.maxConcurrency = cfg.maxConcurrency
bb.Config.defaultTier = cfg.defaultTier
bb.Config.ignoreAccessModifiers = cfg.ignoreAccessModifiers
return nil
}
// NewCredentialKey : Update the credential key specified by the user
func (bb *BlockBlob) NewCredentialKey(key, value string) (err error) {
if key == "saskey" {
bb.Auth.setOption(key, value)
// Update the endpoint url from the credential
bb.Endpoint, err = url.Parse(bb.Auth.getEndpoint())
if err != nil {
log.Err("BlockBlob::NewCredentialKey : Failed to form base endpoint url [%s]", err.Error())
return errors.New("failed to form base endpoint url")
}
// Update the service url
bb.Service = azblob.NewServiceURL(*bb.Endpoint, bb.Pipeline)
// Update the container url
bb.Container = bb.Service.NewContainerURL(bb.Config.container)
}
return nil
}
// getCredential : Create the credential object
func (bb *BlockBlob) getCredential() azblob.Credential {
log.Trace("BlockBlob::getCredential : Getting credential")
bb.Auth = getAzAuth(bb.Config.authConfig)
if bb.Auth == nil {
log.Err("BlockBlob::getCredential : Failed to retrieve auth object")
return nil
}
cred := bb.Auth.getCredential()
if cred == nil {
log.Err("BlockBlob::getCredential : Failed to get credential")
return nil
}
return cred.(azblob.Credential)
}
// NewPipeline creates a Pipeline using the specified credentials and options.
func NewBlobPipeline(c azblob.Credential, o azblob.PipelineOptions, ro ste.XferRetryOptions) pipeline.Pipeline {
// Closest to API goes first; closest to the wire goes last
f := []pipeline.Factory{
azblob.NewTelemetryPolicyFactory(o.Telemetry),
azblob.NewUniqueRequestIDPolicyFactory(),
ste.NewBlobXferRetryPolicyFactory(ro),
}
f = append(f, c)
f = append(f,
pipeline.MethodFactoryMarker(), // indicates at what stage in the pipeline the method factory is invoked
ste.NewRequestLogPolicyFactory(ste.RequestLogOptions{
LogWarningIfTryOverThreshold: o.RequestLog.LogWarningIfTryOverThreshold,
SyslogDisabled: o.RequestLog.SyslogDisabled,
}))
return pipeline.NewPipeline(f, pipeline.Options{HTTPSender: o.HTTPSender, Log: o.Log})
}
// SetupPipeline : Based on the config setup the ***URLs
func (bb *BlockBlob) SetupPipeline() error {
log.Trace("BlockBlob::SetupPipeline : Setting up")
var err error
// Get the credential
cred := bb.getCredential()
if cred == nil {
log.Err("BlockBlob::SetupPipeline : Failed to get credential")
return errors.New("failed to get credential")
}
// Create a new pipeline
options, retryOptions := getAzBlobPipelineOptions(bb.Config)
bb.Pipeline = NewBlobPipeline(cred, options, retryOptions)
if bb.Pipeline == nil {
log.Err("BlockBlob::SetupPipeline : Failed to create pipeline object")
return errors.New("failed to create pipeline object")
}
// Get the endpoint url from the credential
bb.Endpoint, err = url.Parse(bb.Auth.getEndpoint())
if err != nil {
log.Err("BlockBlob::SetupPipeline : Failed to form base end point url [%s]", err.Error())
return errors.New("failed to form base end point url")
}
// Create the service url
bb.Service = azblob.NewServiceURL(*bb.Endpoint, bb.Pipeline)
// Create the container url
bb.Container = bb.Service.NewContainerURL(bb.Config.container)
return nil
}
// TestPipeline : Validate the credentials specified in the auth config
func (bb *BlockBlob) TestPipeline() error {
log.Trace("BlockBlob::TestPipeline : Validating")
if bb.Config.mountAllContainers {
return nil
}
if bb.Container.String() == "" {
log.Err("BlockBlob::TestPipeline : Container URL is not built, check your credentials")
return nil
}
marker := (azblob.Marker{})
listBlob, err := bb.Container.ListBlobsHierarchySegment(context.Background(), marker, "/",
azblob.ListBlobsSegmentOptions{MaxResults: 2,
Prefix: bb.Config.prefixPath,
})
if err != nil {
log.Err("BlockBlob::TestPipeline : Failed to validate account with given auth %s", err.Error)
return err
}
if listBlob == nil {
log.Info("BlockBlob::TestPipeline : Container is empty")
}
return nil
}
func (bb *BlockBlob) ListContainers() ([]string, error) {
log.Trace("BlockBlob::ListContainers : Listing containers")
cntList := make([]string, 0)
marker := azblob.Marker{}
for marker.NotDone() {
resp, err := bb.Service.ListContainersSegment(context.Background(), marker, azblob.ListContainersSegmentOptions{})
if err != nil {
log.Err("BlockBlob::ListContainers : Failed to get container list")
return cntList, err
}
for _, v := range resp.ContainerItems {
cntList = append(cntList, v.Name)
}
marker = resp.NextMarker
}
return cntList, nil
}
func (bb *BlockBlob) SetPrefixPath(path string) error {
log.Trace("BlockBlob::SetPrefixPath : path %s", path)
bb.Config.prefixPath = path
return nil
}
// CreateFile : Create a new file in the container/virtual directory
func (bb *BlockBlob) CreateFile(name string, mode os.FileMode) error {
log.Trace("BlockBlob::CreateFile : name %s", name)
var data []byte
return bb.WriteFromBuffer(name, nil, data)
}
// CreateDirectory : Create a new directory in the container/virtual directory
func (bb *BlockBlob) CreateDirectory(name string) error {
log.Trace("BlockBlob::CreateDirectory : name %s", name)
var data []byte
metadata := make(azblob.Metadata)
metadata[folderKey] = "true"
return bb.WriteFromBuffer(name, metadata, data)
}
// CreateLink : Create a symlink in the container/virtual directory
func (bb *BlockBlob) CreateLink(source string, target string) error {
log.Trace("BlockBlob::CreateLink : %s -> %s", source, target)
data := []byte(target)
metadata := make(azblob.Metadata)
metadata[symlinkKey] = "true"
return bb.WriteFromBuffer(source, metadata, data)
}
// DeleteFile : Delete a blob in the container/virtual directory
func (bb *BlockBlob) DeleteFile(name string) (err error) {
log.Trace("BlockBlob::DeleteFile : name %s", name)
blobURL := bb.getBlobURL(name)
_, err = blobURL.Delete(context.Background(), azblob.DeleteSnapshotsOptionInclude, bb.blobAccCond)
if err != nil {
serr := storeBlobErrToErr(err)
if serr == ErrFileNotFound {
log.Err("BlockBlob::DeleteFile : %s does not exist", name)
return syscall.ENOENT
} else if serr == BlobIsUnderLease {
log.Err("BlockBlob::DeleteFile : %s is under lease [%s]", name, err.Error())
return syscall.EIO
} else {
log.Err("BlockBlob::DeleteFile : Failed to delete blob %s [%s]", name, err.Error())
return err
}
}
return nil
}
// DeleteDirectory : Delete a virtual directory in the container/virtual directory
func (bb *BlockBlob) DeleteDirectory(name string) (err error) {
log.Trace("BlockBlob::DeleteDirectory : name %s", name)
for marker := (azblob.Marker{}); marker.NotDone(); {
listBlob, err := bb.Container.ListBlobsFlatSegment(context.Background(), marker,
azblob.ListBlobsSegmentOptions{MaxResults: common.MaxDirListCount,
Prefix: bb.getFormattedPath(name) + "/",
})
if err != nil {
log.Err("BlockBlob::DeleteDirectory : Failed to get list of blobs %s", err.Error)
return err
}
marker = listBlob.NextMarker
// Process the blobs returned in this result segment (if the segment is empty, the loop body won't execute)
for _, blobInfo := range listBlob.Segment.BlobItems {
err = bb.DeleteFile(split(bb.Config.prefixPath, blobInfo.Name))
if err != nil {
log.Err("BlockBlob::DeleteDirectory : Failed to delete file %s [%s]", blobInfo.Name, err.Error)
}
}
}
return bb.DeleteFile(name)
}
// RenameFile : Rename the file
func (bb *BlockBlob) RenameFile(source string, target string) error {
log.Trace("BlockBlob::RenameFile : %s -> %s", source, target)
blobURL := bb.getBlobURL(source)
newBlob := bb.getBlobURL(target)
prop, err := blobURL.GetProperties(context.Background(), bb.blobAccCond, bb.blobCPKOpt)
if err != nil {
serr := storeBlobErrToErr(err)
if serr == ErrFileNotFound {
log.Err("BlockBlob::RenameFile : %s does not exist", source)
return syscall.ENOENT
} else {
log.Err("BlockBlob::RenameFile : Failed to get blob properties for %s [%s]", source, err.Error())
return err
}
}
startCopy, err := newBlob.StartCopyFromURL(context.Background(), blobURL.URL(),
prop.NewMetadata(), azblob.ModifiedAccessConditions{}, azblob.BlobAccessConditions{}, bb.Config.defaultTier, nil)
if err != nil {
log.Err("BlockBlob::RenameFile : Failed to start copy of file %s [%s]", source, err.Error())
return err
}
copyStatus := startCopy.CopyStatus()
for copyStatus == azblob.CopyStatusPending {
time.Sleep(time.Second * 1)
prop, err = newBlob.GetProperties(context.Background(), bb.blobAccCond, bb.blobCPKOpt)
if err != nil {
log.Err("BlockBlob::RenameFile : CopyStats : Failed to get blob properties for %s [%s]", source, err.Error())
}
copyStatus = prop.CopyStatus()
}
log.Trace("BlockBlob::RenameFile : %s -> %s done", source, target)
// Copy of the file is done so now delete the older file
err = bb.DeleteFile(source)
for retry := 0; retry < 3 && err == syscall.ENOENT; retry++ {
// Sometimes backend is able to copy source file to destination but when we try to delete the
// source files it returns back with ENOENT. If file was just created on backend it might happen
// that it has not been synced yet at all layers and hence delete is not able to find the source file
log.Trace("BlockBlob::RenameFile : %s -> %s, unable to find source. Retrying %d", source, target, retry)
time.Sleep(1 * time.Second)
err = bb.DeleteFile(source)
}
if err == syscall.ENOENT {
// Even after 3 retries, 1 second apart if server returns 404 then source file no longer
// exists on the backend and its safe to assume rename was successful
err = nil
}
return err
}
// RenameDirectory : Rename the directory
func (bb *BlockBlob) RenameDirectory(source string, target string) error {
log.Trace("BlockBlob::RenameDirectory : %s -> %s", source, target)
srcDirPresent := false
for marker := (azblob.Marker{}); marker.NotDone(); {
listBlob, err := bb.Container.ListBlobsFlatSegment(context.Background(), marker,
azblob.ListBlobsSegmentOptions{MaxResults: common.MaxDirListCount,
Prefix: bb.getFormattedPath(source) + "/",
})
if err != nil {
log.Err("BlockBlob::RenameDirectory : Failed to get list of blobs %s", err.Error)
return err
}
marker = listBlob.NextMarker
// Process the blobs returned in this result segment (if the segment is empty, the loop body won't execute)
for _, blobInfo := range listBlob.Segment.BlobItems {
srcDirPresent = true
srcPath := split(bb.Config.prefixPath, blobInfo.Name)
err = bb.RenameFile(srcPath, strings.Replace(srcPath, source, target, 1))
if err != nil {
log.Err("BlockBlob::RenameDirectory : Failed to rename file %s [%s]", srcPath, err.Error)
}
}
}
err := bb.RenameFile(source, target)
// check if the marker blob for source directory does not exist but
// blobs were present in it, which were renamed earlier
if err == syscall.ENOENT && srcDirPresent {
err = nil
}
return err
}
func (bb *BlockBlob) getAttrUsingRest(name string) (attr *internal.ObjAttr, err error) {
log.Trace("BlockBlob::getAttrUsingRest : name %s", name)
blobURL := bb.getBlockBlobURL(name)
prop, err := blobURL.GetProperties(context.Background(), bb.blobAccCond, bb.blobCPKOpt)
if err != nil {
e := storeBlobErrToErr(err)
if e == ErrFileNotFound {
return attr, syscall.ENOENT
} else if e == InvalidPermission {
log.Err("BlockBlob::getAttrUsingRest : Insufficient permissions for %s [%s]", name, err.Error())
return attr, syscall.EACCES
} else {
log.Err("BlockBlob::getAttrUsingRest : Failed to get blob properties for %s [%s]", name, err.Error())
return attr, err
}
}
// Since block blob does not support acls, we set mode to 0 and FlagModeDefault to true so the fuse layer can return the default permission.
attr = &internal.ObjAttr{
Path: name, // We don't need to strip the prefixPath here since we pass the input name
Name: filepath.Base(name),
Size: prop.ContentLength(),
Mode: 0,
Mtime: prop.LastModified(),
Atime: prop.LastModified(),
Ctime: prop.LastModified(),
Crtime: prop.CreationTime(),
Flags: internal.NewFileBitMap(),
MD5: prop.ContentMD5(),
}
parseMetadata(attr, prop.NewMetadata())
attr.Flags.Set(internal.PropFlagMetadataRetrieved)
attr.Flags.Set(internal.PropFlagModeDefault)
return attr, nil
}
func (bb *BlockBlob) getAttrUsingList(name string) (attr *internal.ObjAttr, err error) {
log.Trace("BlockBlob::getAttrUsingList : name %s", name)
const maxFailCount = 20
failCount := 0
iteration := 0
var marker *string = nil
blobsRead := 0
for failCount < maxFailCount {
blobs, new_marker, err := bb.List(name, marker, bb.Config.maxResultsForList)
if err != nil {
e := storeBlobErrToErr(err)
if e == ErrFileNotFound {
return attr, syscall.ENOENT
} else if e == InvalidPermission {
log.Err("BlockBlob::getAttrUsingList : Insufficient permissions for %s [%s]", name, err.Error())
return attr, syscall.EACCES
} else {
log.Warn("BlockBlob::getAttrUsingList : Failed to list blob properties for %s [%s]", name, err.Error())
failCount++
continue
}
}
failCount = 0
for i, blob := range blobs {
log.Trace("BlockBlob::getAttrUsingList : Item %d Blob %s", i+blobsRead, blob.Name)
if blob.Path == name {
return blob, nil
}
}
marker = new_marker
iteration++
blobsRead += len(blobs)
log.Trace("BlockBlob::getAttrUsingList : So far retrieved %d objects in %d iterations", blobsRead, iteration)
if new_marker == nil || *new_marker == "" || failCount >= maxFailCount {
break
}
}
if err == nil {
log.Err("BlockBlob::getAttrUsingList : blob %s does not exist", name)
return nil, syscall.ENOENT
}
log.Err("BlockBlob::getAttrUsingList : Failed to list blob properties for %s [%s]", name, err.Error())
return nil, err
}
// GetAttr : Retrieve attributes of the blob
func (bb *BlockBlob) GetAttr(name string) (attr *internal.ObjAttr, err error) {
log.Trace("BlockBlob::GetAttr : name %s", name)
// To support virtual directories with no marker blob, we call list instead of get properties since list will not return a 404
if bb.Config.virtualDirectory {
return bb.getAttrUsingList(name)
}
return bb.getAttrUsingRest(name)
}
// List : Get a list of blobs matching the given prefix
// This fetches the list using a marker so the caller code should handle marker logic
// If count=0 - fetch max entries
func (bb *BlockBlob) List(prefix string, marker *string, count int32) ([]*internal.ObjAttr, *string, error) {
log.Trace("BlockBlob::List : prefix %s, marker %s", prefix, func(marker *string) string {
if marker != nil {
return *marker
} else {
return ""
}
}(marker))
blobList := make([]*internal.ObjAttr, 0)
if count == 0 {
count = common.MaxDirListCount
}
listPath := bb.getFormattedPath(prefix)
if (prefix != "" && prefix[len(prefix)-1] == '/') || (prefix == "" && bb.Config.prefixPath != "") {
listPath += "/"
}
// Get a result segment starting with the blob indicated by the current Marker.
listBlob, err := bb.Container.ListBlobsHierarchySegment(context.Background(), azblob.Marker{Val: marker}, "/",
azblob.ListBlobsSegmentOptions{MaxResults: count,
Prefix: listPath,
Details: bb.listDetails,
})
// Note: Since we make a list call with a prefix, we will not fail here for a non-existent directory.
// The blob service will not validate for us whether or not the path exists.
// This is different from ADLS Gen2 behavior.
// APIs that may be affected include IsDirEmpty, ReadDir and StreamDir
if err != nil {
log.Err("BlockBlob::List : Failed to list the container with the prefix %s", err.Error)
return blobList, nil, err
}
dereferenceTime := func(input *time.Time, defaultTime time.Time) time.Time {
if input == nil {
return defaultTime
} else {
return *input
}
}
// Process the blobs returned in this result segment (if the segment is empty, the loop body won't execute)
// Since block blob does not support acls, we set mode to 0 and FlagModeDefault to true so the fuse layer can return the default permission.
// For some directories 0 byte meta file may not exists so just create a map to figure out such directories
var dirList = make(map[string]bool)
for _, blobInfo := range listBlob.Segment.BlobItems {
// Convert the blob name to a filename
blobInfo.Name = bb.getFileName(blobInfo.Name)
attr := &internal.ObjAttr{
Path: split(bb.Config.prefixPath, blobInfo.Name),
Name: filepath.Base(blobInfo.Name),
Size: *blobInfo.Properties.ContentLength,
Mode: 0,
Mtime: blobInfo.Properties.LastModified,
Atime: dereferenceTime(blobInfo.Properties.LastAccessedOn, blobInfo.Properties.LastModified),
Ctime: blobInfo.Properties.LastModified,
Crtime: dereferenceTime(blobInfo.Properties.CreationTime, blobInfo.Properties.LastModified),
Flags: internal.NewFileBitMap(),
MD5: blobInfo.Properties.ContentMD5,
}
parseMetadata(attr, blobInfo.Metadata)
attr.Flags.Set(internal.PropFlagMetadataRetrieved)
attr.Flags.Set(internal.PropFlagModeDefault)
blobList = append(blobList, attr)
if attr.IsDir() {
// 0 byte meta found so mark this directory in map
dirList[blobInfo.Name+"/"] = true
attr.Size = 4096
}
}
// In case virtual directory exists but its corresponding 0 byte marker file is not there holding hdi_isfolder then just iterating
// over BlobItems will fail to identify that directory. In such cases BlobPrefixes help to list all directories
// dirList contains all dirs for which we got 0 byte meta file in this iteration, so exclude those and add rest to the list
// Note: Since listing is paginated, sometimes the marker file may come in a different iteration from the BlobPrefix. For such
// cases we manually call GetAttr to check the existence of the marker file.
for _, blobInfo := range listBlob.Segment.BlobPrefixes {
// Convert the blob name to a filename
blobInfo.Name = bb.getFileName(blobInfo.Name)
if _, ok := dirList[blobInfo.Name]; ok {
// marker file found in current iteration, skip adding the directory
continue
} else {
// marker file not found in current iteration, so we need to manually check attributes via REST
_, err := bb.getAttrUsingRest(blobInfo.Name)
// marker file also not found via manual check, safe to add to list
if err == syscall.ENOENT {
// For these dirs we get only the name and no other properties so hardcoding time to current time
name := strings.TrimSuffix(blobInfo.Name, "/")
attr := &internal.ObjAttr{
Path: split(bb.Config.prefixPath, name),
Name: filepath.Base(name),
Size: 4096,
Mode: os.ModeDir,
Mtime: time.Now(),
Flags: internal.NewDirBitMap(),
}
attr.Atime = attr.Mtime
attr.Crtime = attr.Mtime
attr.Ctime = attr.Mtime
attr.Flags.Set(internal.PropFlagMetadataRetrieved)
attr.Flags.Set(internal.PropFlagModeDefault)
blobList = append(blobList, attr)
}
}
}
// Clean up the temp map as its no more needed
clear(dirList)
return blobList, listBlob.NextMarker.Val, nil
}
// track the progress of download of blobs where every 100MB of data downloaded is being tracked. It also tracks the completion of download
func trackDownload(name string, bytesTransferred int64, count int64, downloadPtr *int64) {
if bytesTransferred >= (*downloadPtr)*100*common.MbToBytes || bytesTransferred == count {
(*downloadPtr)++
log.Debug("BlockBlob::trackDownload : Download: Blob = %v, Bytes transferred = %v, Size = %v", name, bytesTransferred, count)
// send the download progress as an event
azStatsCollector.PushEvents(downloadProgress, name, map[string]interface{}{bytesTfrd: bytesTransferred, size: count})
}
}
// ReadToFile : Download a blob to a local file
func (bb *BlockBlob) ReadToFile(name string, offset int64, count int64, fi *os.File) (err error) {
log.Trace("BlockBlob::ReadToFile : name %s, offset : %d, count %d", name, offset, count)
//defer exectime.StatTimeCurrentBlock("BlockBlob::ReadToFile")()
blobURL := bb.getBlobURL(name)
var downloadPtr *int64 = new(int64)
*downloadPtr = 1
if common.MonitorCfs() {
bb.downloadOptions.Progress = func(bytesTransferred int64) {
trackDownload(name, bytesTransferred, count, downloadPtr)
}
}
defer log.TimeTrack(time.Now(), "BlockBlob::ReadToFile", name)
err = azblob.DownloadBlobToFile(context.Background(), blobURL, offset, count, fi, bb.downloadOptions)
if err != nil {
e := storeBlobErrToErr(err)
if e == ErrFileNotFound {
return syscall.ENOENT
} else {
log.Err("BlockBlob::ReadToFile : Failed to download blob %s [%s]", name, err.Error())
return err
}
} else {
log.Debug("BlockBlob::ReadToFile : Download complete of blob %v", name)
// store total bytes downloaded so far
azStatsCollector.UpdateStats(stats_manager.Increment, bytesDownloaded, count)
}
if bb.Config.validateMD5 {
// Compute md5 of local file
fileMD5, err := getMD5(fi)
if err != nil {
log.Warn("BlockBlob::ReadToFile : Failed to generate MD5 Sum for %s", name)
} else {
// Get latest properties from container to get the md5 of blob
prop, err := blobURL.GetProperties(context.Background(), bb.blobAccCond, bb.blobCPKOpt)
if err != nil {
log.Warn("BlockBlob::ReadToFile : Failed to get properties of blob %s [%s]", name, err.Error())
} else {
blobMD5 := prop.ContentMD5()
if blobMD5 == nil {
log.Warn("BlockBlob::ReadToFile : Failed to get MD5 Sum for blob %s", name)
} else {
// compare md5 and fail is not match
if !reflect.DeepEqual(fileMD5, blobMD5) {
log.Err("BlockBlob::ReadToFile : MD5 Sum mismatch %s", name)
return errors.New("md5 sum mismatch on download")
}
}
}
}
}
return nil
}
// ReadBuffer : Download a specific range from a blob to a buffer
func (bb *BlockBlob) ReadBuffer(name string, offset int64, length int64) ([]byte, error) {
log.Trace("BlockBlob::ReadBuffer : name %s, offset %v, len %v", name, offset, length)
var buff []byte
if length == 0 {
attr, err := bb.GetAttr(name)
if err != nil {
return buff, err
}
length = attr.Size - offset
}
buff = make([]byte, length)
blobURL := bb.getBlobURL(name)
err := azblob.DownloadBlobToBuffer(context.Background(), blobURL, offset, length, buff, bb.downloadOptions)
if err != nil {
e := storeBlobErrToErr(err)
if e == ErrFileNotFound {
return buff, syscall.ENOENT
} else if e == InvalidRange {
return buff, syscall.ERANGE
}
log.Err("BlockBlob::ReadBuffer : Failed to download blob %s [%s]", name, err.Error())
return buff, err
}
return buff, nil
}
// ReadInBuffer : Download specific range from a file to a user provided buffer
func (bb *BlockBlob) ReadInBuffer(name string, offset int64, length int64, data []byte) error {
// log.Trace("BlockBlob::ReadInBuffer : name %s", name)
blobURL := bb.getBlobURL(name)
opt := bb.downloadOptions
opt.BlockSize = length
ctx, cancel := context.WithTimeout(context.Background(), max_context_timeout*time.Minute)
defer cancel()
err := azblob.DownloadBlobToBuffer(ctx, blobURL, offset, length, data, opt)
if err != nil {
e := storeBlobErrToErr(err)
if e == ErrFileNotFound {
return syscall.ENOENT
} else if e == InvalidRange {
return syscall.ERANGE
}
log.Err("BlockBlob::ReadInBuffer : Failed to download blob %s [%s]", name, err.Error())
return err
}
return nil
}
func (bb *BlockBlob) calculateBlockSize(name string, fileSize int64) (blockSize int64, err error) {
// If bufferSize > (BlockBlobMaxStageBlockBytes * BlockBlobMaxBlocks), then error
if fileSize > MaxBlocksSize {
log.Err("BlockBlob::calculateBlockSize : buffer is too large to upload to a block blob %s", name)
err = errors.New("buffer is too large to upload to a block blob")
return 0, err
}
// If bufferSize <= BlockBlobMaxUploadBlobBytes, then Upload should be used with just 1 I/O request
if fileSize <= azblob.BlockBlobMaxUploadBlobBytes {
// Files up to 256MB can be uploaded as a single block
blockSize = azblob.BlockBlobMaxUploadBlobBytes
} else {
// buffer / max blocks = block size to use all 50,000 blocks
blockSize = int64(math.Ceil(float64(fileSize) / azblob.BlockBlobMaxBlocks))
if blockSize < azblob.BlobDefaultDownloadBlockSize {
// Block size is smaller then 16MB then consider 16MB as default
blockSize = azblob.BlobDefaultDownloadBlockSize
} else {
if (blockSize & (-8)) != 0 {
// EXTRA : round off the block size to next higher multiple of 8.
// No reason to do so just the odd numbers in block size will not be good on server end is assumption
blockSize = (blockSize + 7) & (-8)
}
if blockSize > azblob.BlockBlobMaxStageBlockBytes {
// After rounding off the blockSize has become bigger then max allowed blocks.
log.Err("BlockBlob::calculateBlockSize : blockSize exceeds max allowed block size for %s", name)
err = errors.New("block-size is too large to upload to a block blob")
return 0, err
}
}
}
log.Info("BlockBlob::calculateBlockSize : %s size %v, blockSize %v", name, fileSize, blockSize)
return blockSize, nil
}
// track the progress of upload of blobs where every 100MB of data uploaded is being tracked. It also tracks the completion of upload
func trackUpload(name string, bytesTransferred int64, count int64, uploadPtr *int64) {
if bytesTransferred >= (*uploadPtr)*100*common.MbToBytes || bytesTransferred == count {
(*uploadPtr)++
log.Debug("BlockBlob::trackUpload : Upload: Blob = %v, Bytes transferred = %v, Size = %v", name, bytesTransferred, count)
// send upload progress as event
azStatsCollector.PushEvents(uploadProgress, name, map[string]interface{}{bytesTfrd: bytesTransferred, size: count})
}
}
// WriteFromFile : Upload local file to blob
func (bb *BlockBlob) WriteFromFile(name string, metadata map[string]string, fi *os.File) (err error) {
log.Trace("BlockBlob::WriteFromFile : name %s", name)
//defer exectime.StatTimeCurrentBlock("WriteFromFile::WriteFromFile")()
blobURL := bb.getBlockBlobURL(name)
defer log.TimeTrack(time.Now(), "BlockBlob::WriteFromFile", name)
var uploadPtr *int64 = new(int64)
*uploadPtr = 1
blockSize := bb.Config.blockSize
// get the size of the file
stat, err := fi.Stat()
if err != nil {
log.Err("BlockBlob::WriteFromFile : Failed to get file size %s [%s]", name, err.Error())
return err
}
// if the block size is not set then we configure it based on file size
if blockSize == 0 {
// based on file-size calculate block size
blockSize, err = bb.calculateBlockSize(name, stat.Size())
if err != nil {
return err
}
}
// Compute md5 of this file is requested by user
// If file is uploaded in one shot (no blocks created) then server is populating md5 on upload automatically.
// hence we take cost of calculating md5 only for files which are bigger in size and which will be converted to blocks.
md5sum := []byte{}
if bb.Config.updateMD5 && stat.Size() >= azblob.BlockBlobMaxUploadBlobBytes {
md5sum, err = getMD5(fi)
if err != nil {
// Md5 sum generation failed so set nil while uploading
log.Warn("BlockBlob::WriteFromFile : Failed to generate md5 of %s", name)
md5sum = []byte{0}
}
}
uploadOptions := azblob.UploadToBlockBlobOptions{
BlockSize: blockSize,
Parallelism: bb.Config.maxConcurrency,
Metadata: metadata,
BlobAccessTier: bb.Config.defaultTier,
BlobHTTPHeaders: azblob.BlobHTTPHeaders{
ContentType: getContentType(name),
ContentMD5: md5sum,
},
ClientProvidedKeyOptions: bb.blobCPKOpt,
}
if common.MonitorCfs() && stat.Size() > 0 {
uploadOptions.Progress = func(bytesTransferred int64) {
trackUpload(name, bytesTransferred, stat.Size(), uploadPtr)
}
}
_, err = azblob.UploadFileToBlockBlob(context.Background(), fi, blobURL, uploadOptions)
if err != nil {
serr := storeBlobErrToErr(err)
if serr == BlobIsUnderLease {
log.Err("BlockBlob::WriteFromFile : %s is under a lease, can not update file [%s]", name, err.Error())
return syscall.EIO
} else if serr == InvalidPermission {
log.Err("BlockBlob::WriteFromFile : Insufficient permissions for %s [%s]", name, err.Error())
return syscall.EACCES
} else {
log.Err("BlockBlob::WriteFromFile : Failed to upload blob %s [%s]", name, err.Error())
}
return err
} else {
log.Debug("BlockBlob::WriteFromFile : Upload complete of blob %v", name)
// store total bytes uploaded so far
if stat.Size() > 0 {
azStatsCollector.UpdateStats(stats_manager.Increment, bytesUploaded, stat.Size())
}
}
return nil
}
// WriteFromBuffer : Upload from a buffer to a blob
func (bb *BlockBlob) WriteFromBuffer(name string, metadata map[string]string, data []byte) error {
log.Trace("BlockBlob::WriteFromBuffer : name %s", name)
blobURL := bb.getBlockBlobURL(name)
defer log.TimeTrack(time.Now(), "BlockBlob::WriteFromBuffer", name)
_, err := azblob.UploadBufferToBlockBlob(context.Background(), data, blobURL, azblob.UploadToBlockBlobOptions{
BlockSize: bb.Config.blockSize,
Parallelism: bb.Config.maxConcurrency,
Metadata: metadata,
BlobAccessTier: bb.Config.defaultTier,
BlobHTTPHeaders: azblob.BlobHTTPHeaders{
ContentType: getContentType(name),
},
ClientProvidedKeyOptions: bb.blobCPKOpt,
})
if err != nil {
log.Err("BlockBlob::WriteFromBuffer : Failed to upload blob %s [%s]", name, err.Error())
return err
}
return nil
}
// GetFileBlockOffsets: store blocks ids and corresponding offsets
func (bb *BlockBlob) GetFileBlockOffsets(name string) (*common.BlockOffsetList, error) {
var blockOffset int64 = 0
blockList := common.BlockOffsetList{}
blobURL := bb.getBlockBlobURL(name)
storageBlockList, err := blobURL.GetBlockList(
context.Background(), azblob.BlockListCommitted, bb.blobAccCond.LeaseAccessConditions)
if err != nil {
log.Err("BlockBlob::GetFileBlockOffsets : Failed to get block list %s ", name, err.Error())
return &common.BlockOffsetList{}, err
}
// if block list empty its a small file
if len(storageBlockList.CommittedBlocks) == 0 {
blockList.Flags.Set(common.SmallFile)
return &blockList, nil
}
for _, block := range storageBlockList.CommittedBlocks {
blk := &common.Block{
Id: block.Name,
StartIndex: int64(blockOffset),
EndIndex: int64(blockOffset) + block.Size,
}
blockOffset += block.Size
blockList.BlockList = append(blockList.BlockList, blk)
}
// blockList.Etag = storageBlockList.ETag()
blockList.BlockIdLength = common.GetIdLength(blockList.BlockList[0].Id)
return &blockList, nil
}
func (bb *BlockBlob) createBlock(blockIdLength, startIndex, size int64) *common.Block {
newBlockId := base64.StdEncoding.EncodeToString(common.NewUUIDWithLength(blockIdLength))
newBlock := &common.Block{
Id: newBlockId,