-
Notifications
You must be signed in to change notification settings - Fork 231
/
Copy pathscenario_helpers.go
1181 lines (989 loc) · 42.8 KB
/
scenario_helpers.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
// Copyright © Microsoft <wastore@microsoft.com>
//
// 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.
// TODO this file was forked from the cmd package, it needs to cleaned to keep only the necessary part
package e2etest
import (
"bytes"
"context"
"crypto/md5"
"encoding/base64"
"fmt"
"github.com/google/uuid"
"io"
"net/url"
"os"
"path"
"path/filepath"
"runtime"
"strconv"
"strings"
"time"
"github.com/Azure/azure-storage-azcopy/v10/azbfs"
"github.com/Azure/azure-storage-azcopy/v10/sddl"
"github.com/minio/minio-go"
"github.com/Azure/azure-storage-azcopy/v10/common"
"github.com/Azure/azure-storage-blob-go/azblob"
"github.com/Azure/azure-storage-file-go/azfile"
)
const defaultFileSize = 1024
const defaultStringFileSize = "1k"
type scenarioHelper struct{}
var specialNames = []string{
"打麻将.txt",
"wow such space so much space",
"打%%#%@#%麻将.txt",
// "saywut.pdf?yo=bla&WUWUWU=foo&sig=yyy", // TODO this breaks on windows, figure out a way to add it only for tests on Unix
"coração",
"আপনার নাম কি",
"%4509%4254$85140&",
"Donaudampfschifffahrtselektrizitätenhauptbetriebswerkbauunterbeamtengesellschaft",
"お名前は何ですか",
"Adın ne",
"як вас звати",
}
// note: this is to emulate the list-of-files flag
func (scenarioHelper) generateListOfFiles(c asserter, fileList []string) (path string) {
parentDirName, err := os.MkdirTemp("", "AzCopyLocalTest")
c.AssertNoErr(err)
// create the file
path = common.GenerateFullPath(parentDirName, generateName(c, "listy", 0))
err = os.MkdirAll(filepath.Dir(path), os.ModePerm)
c.AssertNoErr(err)
// pipe content into it
content := strings.Join(fileList, "\n")
err = os.WriteFile(path, []byte(content), common.DEFAULT_FILE_PERM)
c.AssertNoErr(err)
return
}
func (scenarioHelper) generateLocalDirectory(c asserter) (dstDirName string) {
dstDirName, err := os.MkdirTemp("", "AzCopyLocalTest")
c.AssertNoErr(err)
return
}
// create a test file
func (scenarioHelper) generateLocalFile(filePath string, fileSize int, body []byte) ([]byte, error) {
if body == nil {
// generate random data
_, body = getRandomDataAndReader(fileSize)
}
// create all parent directories
err := os.MkdirAll(filepath.Dir(filePath), os.ModePerm)
if err != nil {
return nil, err
}
// write to file and return the data
err = os.WriteFile(filePath, body, common.DEFAULT_FILE_PERM)
return body, err
}
type generateLocalFilesFromList struct {
dirPath string
generateFromListOptions
}
func (s scenarioHelper) generateLocalFilesFromList(c asserter, options *generateLocalFilesFromList) {
for _, file := range options.fs {
var err error
destFile := filepath.Join(options.dirPath, file.name)
if file.isFolder() {
err = os.MkdirAll(destFile, os.ModePerm)
c.AssertNoErr(err)
// TODO: You'll need to set up things like attributes, and other relevant things from
// file.creationProperties here. (Use all the properties of file.creationProperties that are supported
// // by local files. E.g. not contentHeaders or metadata).
if file.creationProperties.smbPermissionsSddl != nil {
osScenarioHelper{}.setFileSDDLString(c, filepath.Join(options.dirPath, file.name), *file.creationProperties.smbPermissionsSddl)
}
if file.creationProperties.lastWriteTime != nil {
c.AssertNoErr(os.Chtimes(destFile, time.Now(), *file.creationProperties.lastWriteTime), "set times")
}
} else if file.creationProperties.entityType == common.EEntityType.File() {
var mode uint32
if file.creationProperties.posixProperties != nil && file.creationProperties.posixProperties.mode != nil {
mode = *file.creationProperties.posixProperties.mode
}
switch {
case mode & common.S_IFIFO == common.S_IFIFO || mode & common.S_IFSOCK == common.S_IFSOCK:
osScenarioHelper{}.Mknod(c, destFile, mode, 0)
default:
sourceData, err := s.generateLocalFile(
destFile,
file.creationProperties.sizeBytes(c, options.defaultSize), file.body)
if file.creationProperties.contentHeaders == nil {
file.creationProperties.contentHeaders = &contentHeaders{}
}
if file.creationProperties.contentHeaders.contentMD5 == nil {
contentMD5 := md5.Sum(sourceData)
file.creationProperties.contentHeaders.contentMD5 = contentMD5[:]
}
c.AssertNoErr(err)
}
// TODO: You'll need to set up things like attributes, and other relevant things from
// file.creationProperties here. (Use all the properties of file.creationProperties that are supported
// by local files. E.g. not contentHeaders or metadata).
if file.creationProperties.smbPermissionsSddl != nil {
osScenarioHelper{}.setFileSDDLString(c, destFile, *file.creationProperties.smbPermissionsSddl)
}
if file.creationProperties.lastWriteTime != nil {
c.AssertNoErr(os.Chtimes(destFile, time.Now(), *file.creationProperties.lastWriteTime), "set times")
}
} else if file.creationProperties.entityType == common.EEntityType.Symlink() {
c.Assert(file.creationProperties.symlinkTarget, notEquals(), nil)
oldName := filepath.Join(options.dirPath, *file.creationProperties.symlinkTarget)
c.AssertNoErr(os.Symlink(oldName, destFile))
}
}
// sleep a bit so that the files' lmts are guaranteed to be in the past
time.Sleep(time.Millisecond * 1050)
}
// Enumerates all local files and their properties, with the given dirpath
func (s scenarioHelper) enumerateLocalProperties(a asserter, dirpath string) map[string]*objectProperties {
result := make(map[string]*objectProperties)
err := filepath.Walk(dirpath, func(fullpath string, info os.FileInfo, err error) error {
a.AssertNoErr(err) // we don't expect any errors walking the local file system
relPath := strings.Replace(fullpath, dirpath, "", 1)
if runtime.GOOS == "windows" {
// For windows based system
relPath = strings.TrimPrefix(relPath, "\\")
} else {
// For Linux based system
relPath = strings.TrimPrefix(relPath, "/")
}
size := info.Size()
lastWriteTime := info.ModTime()
var pCreationTime *time.Time
var pSmbAttributes *uint32
var pSmbPermissionsSddl *string
if runtime.GOOS == "windows" {
var creationTime time.Time
lastWriteTime, creationTime = osScenarioHelper{}.getFileDates(a, fullpath)
pCreationTime = &creationTime
pSmbAttributes = osScenarioHelper{}.getFileAttrs(a, fullpath)
pSmbPermissionsSddl = osScenarioHelper{}.getFileSDDLString(a, fullpath)
}
entityType := common.EEntityType.File()
if info.IsDir() {
entityType = common.EEntityType.Folder()
} else if info.Mode()&os.ModeSymlink == os.ModeSymlink {
entityType = common.EEntityType.Symlink()
}
props := objectProperties{
entityType: entityType,
size: &size,
creationTime: pCreationTime,
lastWriteTime: &lastWriteTime,
smbAttributes: pSmbAttributes,
smbPermissionsSddl: pSmbPermissionsSddl,
// contentHeaders don't exist on local file system
// nameValueMetadata doesn't exist on local file system
}
result[relPath] = &props
return nil
})
a.AssertNoErr(err)
return result
}
func (s scenarioHelper) generateCommonRemoteScenarioForLocal(c asserter, dirPath string, prefix string) (fileList []string) {
fileList = make([]string, 50)
for i := 0; i < 10; i++ {
batch := []string{
generateName(c, prefix+"top", 0),
generateName(c, prefix+"sub1/", 0),
generateName(c, prefix+"sub2/", 0),
generateName(c, prefix+"sub1/sub3/sub5/", 0),
generateName(c, prefix+specialNames[i], 0),
}
for j, name := range batch {
fileList[5*i+j] = name
_, err := s.generateLocalFile(filepath.Join(dirPath, name), defaultFileSize, nil)
c.AssertNoErr(err)
}
}
// sleep a bit so that the files' lmts are guaranteed to be in the past
time.Sleep(time.Millisecond * 1050)
return
}
func (scenarioHelper) generateCommonRemoteScenarioForBlob(c asserter, containerURL azblob.ContainerURL, prefix string) (blobList []string) {
// make 50 blobs with random names
// 10 of them at the top level
// 10 of them in sub dir "sub1"
// 10 of them in sub dir "sub2"
// 10 of them in deeper sub dir "sub1/sub3/sub5"
// 10 of them with special characters
blobList = make([]string, 50)
for i := 0; i < 10; i++ {
_, blobName1 := createNewBlockBlob(c, containerURL, prefix+"top")
_, blobName2 := createNewBlockBlob(c, containerURL, prefix+"sub1/")
_, blobName3 := createNewBlockBlob(c, containerURL, prefix+"sub2/")
_, blobName4 := createNewBlockBlob(c, containerURL, prefix+"sub1/sub3/sub5/")
_, blobName5 := createNewBlockBlob(c, containerURL, prefix+specialNames[i])
blobList[5*i] = blobName1
blobList[5*i+1] = blobName2
blobList[5*i+2] = blobName3
blobList[5*i+3] = blobName4
blobList[5*i+4] = blobName5
}
// sleep a bit so that the blobs' lmts are guaranteed to be in the past
time.Sleep(time.Millisecond * 1050)
return
}
func (scenarioHelper) generateCommonRemoteScenarioForBlobFS(c asserter, filesystemURL azbfs.FileSystemURL, prefix string) (pathList []string) {
pathList = make([]string, 50)
for i := 0; i < 10; i++ {
_, pathName1 := createNewBfsFile(c, filesystemURL, prefix+"top")
_, pathName2 := createNewBfsFile(c, filesystemURL, prefix+"sub1/")
_, pathName3 := createNewBfsFile(c, filesystemURL, prefix+"sub2/")
_, pathName4 := createNewBfsFile(c, filesystemURL, prefix+"sub1/sub3/sub5")
_, pathName5 := createNewBfsFile(c, filesystemURL, prefix+specialNames[i])
pathList[5*i] = pathName1
pathList[5*i+1] = pathName2
pathList[5*i+2] = pathName3
pathList[5*i+3] = pathName4
pathList[5*i+4] = pathName5
}
// sleep a bit so that the paths' lmts are guaranteed to be in the past
time.Sleep(time.Millisecond * 1500)
return
}
func (scenarioHelper) generateCommonRemoteScenarioForAzureFile(c asserter, shareURL azfile.ShareURL, prefix string) (fileList []string) {
fileList = make([]string, 50)
for i := 0; i < 10; i++ {
_, fileName1 := createNewAzureFile(c, shareURL, prefix+"top")
_, fileName2 := createNewAzureFile(c, shareURL, prefix+"sub1/")
_, fileName3 := createNewAzureFile(c, shareURL, prefix+"sub2/")
_, fileName4 := createNewAzureFile(c, shareURL, prefix+"sub1/sub3/sub5/")
_, fileName5 := createNewAzureFile(c, shareURL, prefix+specialNames[i])
fileList[5*i] = fileName1
fileList[5*i+1] = fileName2
fileList[5*i+2] = fileName3
fileList[5*i+3] = fileName4
fileList[5*i+4] = fileName5
}
// sleep a bit so that the blobs' lmts are guaranteed to be in the past
time.Sleep(time.Millisecond * 1050)
return
}
func (s scenarioHelper) generateBlobContainersAndBlobsFromLists(c asserter, serviceURL azblob.ServiceURL, containerList []string, blobList []*testObject) {
for _, containerName := range containerList {
curl := serviceURL.NewContainerURL(containerName)
_, err := curl.Create(ctx, azblob.Metadata{}, azblob.PublicAccessNone)
c.AssertNoErr(err)
s.generateBlobsFromList(c, &generateBlobFromListOptions{
containerURL: curl,
generateFromListOptions: generateFromListOptions{
fs: blobList,
defaultSize: defaultStringFileSize,
},
})
}
}
func (s scenarioHelper) generateFileSharesAndFilesFromLists(c asserter, serviceURL azfile.ServiceURL, shareList []string, fileList []*testObject) {
for _, shareName := range shareList {
sURL := serviceURL.NewShareURL(shareName)
_, err := sURL.Create(ctx, azfile.Metadata{}, 0)
c.AssertNoErr(err)
s.generateAzureFilesFromList(c, &generateAzureFilesFromListOptions{
shareURL: sURL,
fileList: fileList,
defaultSize: defaultStringFileSize,
})
}
}
func (s scenarioHelper) generateFilesystemsAndFilesFromLists(c asserter, serviceURL azbfs.ServiceURL, fsList []string, fileList []string, data string) {
for _, filesystemName := range fsList {
fsURL := serviceURL.NewFileSystemURL(filesystemName)
_, err := fsURL.Create(ctx)
c.AssertNoErr(err)
s.generateBFSPathsFromList(c, fsURL, fileList)
}
}
func (s scenarioHelper) generateS3BucketsAndObjectsFromLists(c asserter, s3Client *minio.Client, bucketList []string, objectList []string, data string) {
for _, bucketName := range bucketList {
err := s3Client.MakeBucket(bucketName, "")
c.AssertNoErr(err)
s.generateObjects(c, s3Client, bucketName, objectList)
}
}
type generateFromListOptions struct {
fs []*testObject
defaultSize string
preservePosixProperties bool
accountType AccountType
}
type generateBlobFromListOptions struct {
rawSASURL url.URL
containerURL azblob.ContainerURL
cpkInfo common.CpkInfo
cpkScopeInfo common.CpkScopeInfo
accessTier azblob.AccessTierType
generateFromListOptions
}
// create the demanded blobs
func (scenarioHelper) generateBlobsFromList(c asserter, options *generateBlobFromListOptions) {
for _, b := range options.fs {
switch b.creationProperties.entityType {
case common.EEntityType.Folder(): // it's fine to create folders even when we're not explicitly testing them, UNLESS we're testing CPK-- AzCopy can't properly pick that up!
if !options.cpkInfo.Empty() || b.name == "" {
continue // can't write root, and can't handle dirs with CPK
}
if b.creationProperties.nameValueMetadata == nil {
b.creationProperties.nameValueMetadata = map[string]string{}
}
b.body = make([]byte, 0)
b.creationProperties.nameValueMetadata[common.POSIXFolderMeta] = "true"
mode := uint64(os.FileMode(common.DEFAULT_FILE_PERM) | os.ModeDir)
b.creationProperties.nameValueMetadata[common.POSIXModeMeta] = strconv.FormatUint(mode, 10)
b.creationProperties.posixProperties.AddToMetadata(b.creationProperties.nameValueMetadata)
case common.EEntityType.Symlink():
if b.creationProperties.nameValueMetadata == nil {
b.creationProperties.nameValueMetadata = map[string]string{}
}
b.body = []byte(*b.creationProperties.symlinkTarget)
b.creationProperties.nameValueMetadata[common.POSIXSymlinkMeta] = "true"
mode := uint64(os.FileMode(common.DEFAULT_FILE_PERM) | os.ModeSymlink)
b.creationProperties.nameValueMetadata[common.POSIXModeMeta] = strconv.FormatUint(mode, 10)
b.creationProperties.posixProperties.AddToMetadata(b.creationProperties.nameValueMetadata)
default:
if b.creationProperties.nameValueMetadata == nil {
b.creationProperties.nameValueMetadata = map[string]string{}
}
b.creationProperties.posixProperties.AddToMetadata(b.creationProperties.nameValueMetadata)
if b.creationProperties.posixProperties != nil && b.creationProperties.posixProperties.mode != nil {
mode := *b.creationProperties.posixProperties.mode
// todo: support for device rep files may be difficult in a testing environment.
if mode & common.S_IFSOCK == common.S_IFSOCK || mode & common.S_IFIFO == common.S_IFIFO {
b.body = make([]byte, 0)
}
}
}
ad := blobResourceAdapter{b}
var reader *bytes.Reader
var sourceData []byte
if b.body != nil {
reader = bytes.NewReader(b.body)
sourceData = b.body
} else {
reader, sourceData = getRandomDataAndReader(b.creationProperties.sizeBytes(c, options.defaultSize))
b.body = sourceData // set body
}
// Setting content MD5
if ad.obj.creationProperties.contentHeaders == nil {
b.creationProperties.contentHeaders = &contentHeaders{}
}
if ad.obj.creationProperties.contentHeaders.contentMD5 == nil {
contentMD5 := md5.Sum(sourceData)
ad.obj.creationProperties.contentHeaders.contentMD5 = contentMD5[:]
}
tags := ad.toBlobTags()
if options.accountType == EAccountType.HierarchicalNamespaceEnabled() {
tags = nil
}
headers := ad.toHeaders()
var err error
switch b.creationProperties.blobType {
case common.EBlobType.BlockBlob(), common.EBlobType.Detect():
bb := options.containerURL.NewBlockBlobURL(b.name)
if options.accessTier == "" {
options.accessTier = azblob.DefaultAccessTier
}
if reader.Size() > 0 {
// to prevent the service from erroring out with an improper MD5, we opt to commit a block, then the list.
blockID := base64.StdEncoding.EncodeToString([]byte(uuid.NewString()))
sResp, err := bb.StageBlock(ctx,
blockID,
reader,
azblob.LeaseAccessConditions{},
nil,
common.ToClientProvidedKeyOptions(options.cpkInfo, options.cpkScopeInfo))
c.AssertNoErr(err)
c.Assert(sResp.StatusCode(), equals(), 201)
cResp, err := bb.CommitBlockList(ctx,
[]string{blockID},
headers,
ad.toMetadata(),
azblob.BlobAccessConditions{},
options.accessTier,
ad.toBlobTags(),
common.ToClientProvidedKeyOptions(options.cpkInfo, options.cpkScopeInfo),
azblob.ImmutabilityPolicyOptions{},
)
c.AssertNoErr(err)
c.Assert(cResp.StatusCode(), equals(), 201)
} else { // todo: invalid MD5 on empty blob is impossible like this, but it's doubtful we'll need to support it.
// handle empty blobs
cResp, err := bb.Upload(ctx,
reader,
headers,
ad.toMetadata(),
azblob.BlobAccessConditions{},
options.accessTier,
ad.toBlobTags(),
common.ToClientProvidedKeyOptions(options.cpkInfo, options.cpkScopeInfo),
azblob.ImmutabilityPolicyOptions{})
c.AssertNoErr(err)
c.Assert(cResp.StatusCode(), equals(), 201)
}
case common.EBlobType.PageBlob():
pb := options.containerURL.NewPageBlobURL(b.name)
cResp, err := pb.Create(ctx, reader.Size(), 0, headers, ad.toMetadata(), azblob.BlobAccessConditions{}, azblob.DefaultPremiumBlobAccessTier, tags, common.ToClientProvidedKeyOptions(options.cpkInfo, options.cpkScopeInfo), azblob.ImmutabilityPolicyOptions{})
c.AssertNoErr(err)
c.Assert(cResp.StatusCode(), equals(), 201)
pbUpResp, err := pb.UploadPages(ctx, 0, reader, azblob.PageBlobAccessConditions{}, nil, common.ToClientProvidedKeyOptions(options.cpkInfo, options.cpkScopeInfo))
c.AssertNoErr(err)
c.Assert(pbUpResp.StatusCode(), equals(), 201)
case common.EBlobType.AppendBlob():
ab := options.containerURL.NewAppendBlobURL(b.name)
cResp, err := ab.Create(ctx, headers, ad.toMetadata(), azblob.BlobAccessConditions{}, tags, common.ToClientProvidedKeyOptions(options.cpkInfo, options.cpkScopeInfo), azblob.ImmutabilityPolicyOptions{})
c.AssertNoErr(err)
c.Assert(cResp.StatusCode(), equals(), 201)
abUpResp, err := ab.AppendBlock(ctx, reader, azblob.AppendBlobAccessConditions{}, nil, common.ToClientProvidedKeyOptions(options.cpkInfo, options.cpkScopeInfo))
c.AssertNoErr(err)
c.Assert(abUpResp.StatusCode(), equals(), 201)
}
if b.creationProperties.adlsPermissionsACL != nil {
bfsURLParts := azbfs.NewBfsURLParts(options.rawSASURL)
bfsURLParts.Host = strings.Replace(bfsURLParts.Host, ".blob", ".dfs", 1)
bfsContainer := azbfs.NewFileSystemURL(bfsURLParts.URL(), azbfs.NewPipeline(azbfs.NewAnonymousCredential(), azbfs.PipelineOptions{}))
var updateResp *azbfs.PathUpdateResponse
if b.isFolder() {
dirURL := bfsContainer.NewDirectoryURL(b.name)
updateResp, err = dirURL.SetAccessControl(ctx, azbfs.BlobFSAccessControl{
ACL: *b.creationProperties.adlsPermissionsACL,
})
} else {
d, f := path.Split(b.name)
dirURL := bfsContainer.NewDirectoryURL(d)
fileURL := dirURL.NewFileURL(f)
updateResp, err = fileURL.SetAccessControl(ctx, azbfs.BlobFSAccessControl{
ACL: *b.creationProperties.adlsPermissionsACL,
})
}
c.AssertNoErr(err)
c.Assert(updateResp.StatusCode(), equals(), 200)
}
}
// sleep a bit so that the blobs' lmts are guaranteed to be in the past
// TODO: can we make it so that this sleeping only happens when we really need it to?
time.Sleep(time.Millisecond * 1050)
}
func (s scenarioHelper) enumerateContainerBlobProperties(a asserter, containerURL azblob.ContainerURL) map[string]*objectProperties {
result := make(map[string]*objectProperties)
for marker := (azblob.Marker{}); marker.NotDone(); {
listBlob, err := containerURL.ListBlobsFlatSegment(context.TODO(), marker, azblob.ListBlobsSegmentOptions{Details: azblob.BlobListingDetails{Metadata: true, Tags: true}})
a.AssertNoErr(err)
for _, blobInfo := range listBlob.Segment.BlobItems {
relativePath := blobInfo.Name // need to change this when we support working on virtual directories down inside containers
bp := blobInfo.Properties
h := contentHeaders{
cacheControl: bp.CacheControl,
contentDisposition: bp.ContentDisposition,
contentEncoding: bp.ContentEncoding,
contentLanguage: bp.ContentLanguage,
contentType: bp.ContentType,
contentMD5: bp.ContentMD5,
}
md := map[string]string(blobInfo.Metadata)
props := objectProperties{
entityType: common.EEntityType.File(), // todo: posix properties includes folders
size: bp.ContentLength,
contentHeaders: &h,
nameValueMetadata: md,
creationTime: bp.CreationTime,
lastWriteTime: &bp.LastModified,
cpkInfo: &common.CpkInfo{EncryptionKeySha256: bp.CustomerProvidedKeySha256},
cpkScopeInfo: &common.CpkScopeInfo{EncryptionScope: bp.EncryptionScope},
adlsPermissionsACL: bp.ACL,
// smbAttributes and smbPermissions don't exist in blob
}
if blobInfo.BlobTags != nil {
blobTagsMap := common.BlobTags{}
for _, blobTag := range blobInfo.BlobTags.BlobTagSet {
blobTagsMap[url.QueryEscape(blobTag.Key)] = url.QueryEscape(blobTag.Value)
}
props.blobTags = blobTagsMap
}
props.blobType = common.FromAzBlobType(blobInfo.Properties.BlobType)
result[relativePath] = &props
}
marker = listBlob.NextMarker
}
return result
}
func (s scenarioHelper) downloadBlobContent(a asserter, options downloadContentOptions) []byte {
blobURL := options.containerURL.NewBlobURL(options.resourceRelPath)
cpk := common.ToClientProvidedKeyOptions(options.cpkInfo, options.cpkScopeInfo)
downloadResp, err := blobURL.Download(ctx, 0, azblob.CountToEnd, azblob.BlobAccessConditions{}, false, cpk)
a.AssertNoErr(err)
retryReader := downloadResp.Body(azblob.RetryReaderOptions{})
defer retryReader.Close()
destData, err := io.ReadAll(retryReader)
a.AssertNoErr(err)
return destData[:]
}
func (scenarioHelper) generatePageBlobsFromList(c asserter, containerURL azblob.ContainerURL, blobList []string, data string) {
for _, blobName := range blobList {
// Create the blob (PUT blob)
blob := containerURL.NewPageBlobURL(blobName)
cResp, err := blob.Create(ctx,
int64(len(data)),
0,
azblob.BlobHTTPHeaders{
ContentType: "text/random",
},
azblob.Metadata{},
azblob.BlobAccessConditions{},
azblob.DefaultPremiumBlobAccessTier,
nil,
azblob.ClientProvidedKeyOptions{},
azblob.ImmutabilityPolicyOptions{},
)
c.AssertNoErr(err)
c.Assert(cResp.StatusCode(), equals(), 201)
// Create the page (PUT page)
uResp, err := blob.UploadPages(ctx,
0,
strings.NewReader(data),
azblob.PageBlobAccessConditions{},
nil,
azblob.ClientProvidedKeyOptions{},
)
c.AssertNoErr(err)
c.Assert(uResp.StatusCode(), equals(), 201)
}
// sleep a bit so that the blobs' lmts are guaranteed to be in the past
time.Sleep(time.Millisecond * 1050)
}
func (scenarioHelper) generateAppendBlobsFromList(c asserter, containerURL azblob.ContainerURL, blobList []string, data string) {
for _, blobName := range blobList {
// Create the blob (PUT blob)
blob := containerURL.NewAppendBlobURL(blobName)
cResp, err := blob.Create(ctx,
azblob.BlobHTTPHeaders{
ContentType: "text/random",
},
azblob.Metadata{},
azblob.BlobAccessConditions{},
nil,
azblob.ClientProvidedKeyOptions{},
azblob.ImmutabilityPolicyOptions{},
)
c.AssertNoErr(err)
c.Assert(cResp.StatusCode(), equals(), 201)
// Append a block (PUT block)
uResp, err := blob.AppendBlock(ctx,
strings.NewReader(data),
azblob.AppendBlobAccessConditions{},
nil, azblob.ClientProvidedKeyOptions{})
c.AssertNoErr(err)
c.Assert(uResp.StatusCode(), equals(), 201)
}
// sleep a bit so that the blobs' lmts are guaranteed to be in the past
time.Sleep(time.Millisecond * 1050)
}
func (scenarioHelper) generateBlockBlobWithAccessTier(c asserter, containerURL azblob.ContainerURL, blobName string, accessTier azblob.AccessTierType) {
blob := containerURL.NewBlockBlobURL(blobName)
cResp, err := blob.Upload(ctx, strings.NewReader(blockBlobDefaultData), azblob.BlobHTTPHeaders{},
nil, azblob.BlobAccessConditions{}, accessTier, nil, azblob.ClientProvidedKeyOptions{}, azblob.ImmutabilityPolicyOptions{})
c.AssertNoErr(err)
c.Assert(cResp.StatusCode(), equals(), 201)
}
// create the demanded objects
func (scenarioHelper) generateObjects(c asserter, client *minio.Client, bucketName string, objectList []string) {
size := int64(len(objectDefaultData))
for _, objectName := range objectList {
n, err := client.PutObjectWithContext(ctx, bucketName, objectName, strings.NewReader(objectDefaultData), size, minio.PutObjectOptions{})
c.AssertNoErr(err)
c.Assert(n, equals(), size)
}
}
// create the demanded files
func (scenarioHelper) generateFlatFiles(c asserter, shareURL azfile.ShareURL, fileList []string) {
for _, fileName := range fileList {
file := shareURL.NewRootDirectoryURL().NewFileURL(fileName)
err := azfile.UploadBufferToAzureFile(ctx, []byte(fileDefaultData), file, azfile.UploadToAzureFileOptions{})
c.AssertNoErr(err)
}
// sleep a bit so that the blobs' lmts are guaranteed to be in the past
time.Sleep(time.Millisecond * 1050)
}
func (scenarioHelper) generateCommonRemoteScenarioForS3(c asserter, client *minio.Client, bucketName string, prefix string, returnObjectListWithBucketName bool) (objectList []string) {
// make 50 objects with random names
// 10 of them at the top level
// 10 of them in sub dir "sub1"
// 10 of them in sub dir "sub2"
// 10 of them in deeper sub dir "sub1/sub3/sub5"
// 10 of them with special characters
objectList = make([]string, 50)
for i := 0; i < 10; i++ {
objectName1 := createNewObject(c, client, bucketName, prefix+"top")
objectName2 := createNewObject(c, client, bucketName, prefix+"sub1/")
objectName3 := createNewObject(c, client, bucketName, prefix+"sub2/")
objectName4 := createNewObject(c, client, bucketName, prefix+"sub1/sub3/sub5/")
objectName5 := createNewObject(c, client, bucketName, prefix+specialNames[i])
// Note: common.AZCOPY_PATH_SEPARATOR_STRING is added before bucket or objectName, as in the change minimize JobPartPlan file size,
// transfer.Source & transfer.Destination(after trimming the SourceRoot and DestinationRoot) are with AZCOPY_PATH_SEPARATOR_STRING suffix,
// when user provided source & destination are without / suffix, which is the case for scenarioHelper generated URL.
bucketPath := ""
if returnObjectListWithBucketName {
bucketPath = common.AZCOPY_PATH_SEPARATOR_STRING + bucketName
}
objectList[5*i] = bucketPath + common.AZCOPY_PATH_SEPARATOR_STRING + objectName1
objectList[5*i+1] = bucketPath + common.AZCOPY_PATH_SEPARATOR_STRING + objectName2
objectList[5*i+2] = bucketPath + common.AZCOPY_PATH_SEPARATOR_STRING + objectName3
objectList[5*i+3] = bucketPath + common.AZCOPY_PATH_SEPARATOR_STRING + objectName4
objectList[5*i+4] = bucketPath + common.AZCOPY_PATH_SEPARATOR_STRING + objectName5
}
// sleep a bit so that the blobs' lmts are guaranteed to be in the past
time.Sleep(time.Millisecond * 1050)
return
}
type generateAzureFilesFromListOptions struct {
shareURL azfile.ShareURL
fileList []*testObject
defaultSize string
}
// create the demanded azure files
func (scenarioHelper) generateAzureFilesFromList(c asserter, options *generateAzureFilesFromListOptions) {
for _, f := range options.fileList {
ad := filesResourceAdapter{f}
if f.isFolder() {
// make sure the dir exists
file := options.shareURL.NewRootDirectoryURL().NewFileURL(path.Join(f.name, "dummyChild"))
generateParentsForAzureFile(c, file)
dir := options.shareURL.NewRootDirectoryURL().NewDirectoryURL(f.name)
// set its metadata if any
if f.creationProperties.nameValueMetadata != nil {
_, err := dir.SetMetadata(context.TODO(), ad.toMetadata())
c.AssertNoErr(err)
}
if f.creationProperties.smbPermissionsSddl != nil || f.creationProperties.smbAttributes != nil || f.creationProperties.lastWriteTime != nil {
_, err := dir.SetProperties(ctx, ad.toHeaders(c, options.shareURL).SMBProperties)
c.AssertNoErr(err)
if f.creationProperties.smbPermissionsSddl != nil {
prop, err := dir.GetProperties(ctx)
c.AssertNoErr(err)
perm, err := options.shareURL.GetPermission(ctx, prop.FilePermissionKey())
c.AssertNoErr(err)
dest, _ := sddl.ParseSDDL(perm.Permission)
source, _ := sddl.ParseSDDL(*f.creationProperties.smbPermissionsSddl)
c.Assert(dest.Compare(source), equals(), true)
}
}
// set other properties
// TODO: do we need a SetProperties method on dir...? Discuss with zezha-msft
if f.creationProperties.creationTime != nil {
panic("setting these properties isn't implemented yet for folders in the test harness")
// TODO: nakulkar-msft the attributes stuff will need to be implemented here before attributes can be tested on Azure Files
}
// TODO: I'm pretty sure we don't prserve lastWritetime or contentProperties (headers) for folders, so the above if statement doesn't test those
// Is that the correct decision?
} else if f.creationProperties.entityType == common.EEntityType.File() {
file := options.shareURL.NewRootDirectoryURL().NewFileURL(f.name)
// create parents first
generateParentsForAzureFile(c, file)
// create the file itself
fileSize := int64(f.creationProperties.sizeBytes(c, options.defaultSize))
var contentR *bytes.Reader
var contentD []byte
if f.body != nil {
contentR = bytes.NewReader(f.body)
contentD = f.body
fileSize = contentR.Size()
} else {
contentR, contentD = getRandomDataAndReader(int(fileSize))
f.body = contentD
}
if f.creationProperties.contentHeaders == nil {
f.creationProperties.contentHeaders = &contentHeaders{}
}
if f.creationProperties.contentHeaders.contentMD5 == nil {
contentMD5 := md5.Sum(contentD)
f.creationProperties.contentHeaders.contentMD5 = contentMD5[:]
}
headers := ad.toHeaders(c, options.shareURL)
cResp, err := file.Create(ctx, fileSize, headers, ad.toMetadata())
c.AssertNoErr(err)
c.Assert(cResp.StatusCode(), equals(), 201)
_, err = file.UploadRange(context.Background(), 0, contentR, nil)
if err == nil {
c.Failed()
}
if f.creationProperties.smbPermissionsSddl != nil || f.creationProperties.smbAttributes != nil || f.creationProperties.lastWriteTime != nil {
/*
via Jason Shay:
Providing securityKey/SDDL during 'PUT File' and 'PUT Properties' can and will provide different results/semantics.
This is true for the REST PUT commands, as well as locally when providing a SECURITY_DESCRIPTOR in the SECURITY_ATTRIBUTES structure in the CreateFile() call.
In both cases of file creation (CreateFile() and REST PUT File), the actual security descriptor applied to the file can undergo some changes as compared to the input.
SetProperties() (and NtSetSecurityObject) use update semantics, so it should store what you provide it (with a couple exceptions).
And on the cloud share, you would need 'Set Properties' to be called as a final step, to save the final ACLs with 'update' semantics.
*/
_, err := file.SetHTTPHeaders(ctx, headers)
c.AssertNoErr(err)
if f.creationProperties.smbPermissionsSddl != nil {
prop, err := file.GetProperties(ctx)
c.AssertNoErr(err)
perm, err := options.shareURL.GetPermission(ctx, prop.FilePermissionKey())
c.AssertNoErr(err)
dest, _ := sddl.ParseSDDL(perm.Permission)
source, _ := sddl.ParseSDDL(*f.creationProperties.smbPermissionsSddl)
c.Assert(dest.Compare(source), equals(), true)
}
}
// TODO: do we want to put some random content into it?
} else {
panic(fmt.Sprintf("file %s unsupported entity type %s", f.name, f.creationProperties.entityType.String()))
}
}
// sleep a bit so that the files' lmts are guaranteed to be in the past
time.Sleep(time.Millisecond * 1050)
}
func (s scenarioHelper) enumerateShareFileProperties(a asserter, shareURL azfile.ShareURL) map[string]*objectProperties {
var dirQ []azfile.DirectoryURL
result := make(map[string]*objectProperties)
root := shareURL.NewRootDirectoryURL()
rootProps, err := root.GetProperties(ctx)
a.AssertNoErr(err)
rootAttr := uint32(azfile.ParseFileAttributeFlagsString(rootProps.FileAttributes()))
var rootPerm *string
if permKey := rootProps.FilePermissionKey(); permKey != "" {
sharePerm, err := shareURL.GetPermission(ctx, permKey)
a.AssertNoErr(err, "Failed to get permissions from key")
rootPerm = &sharePerm.Permission
}
result[""] = &objectProperties{
entityType: common.EEntityType.Folder(),
smbPermissionsSddl: rootPerm,
smbAttributes: &rootAttr,
}
dirQ = append(dirQ, root)
for i := 0; i < len(dirQ); i++ {
currentDirURL := dirQ[i]
for marker := (azfile.Marker{}); marker.NotDone(); {
lResp, err := currentDirURL.ListFilesAndDirectoriesSegment(context.TODO(), marker, azfile.ListFilesAndDirectoriesOptions{})
a.AssertNoErr(err)
// Process the files and folders we listed
for _, fileInfo := range lResp.FileItems {
fileURL := currentDirURL.NewFileURL(fileInfo.Name)
fProps, err := fileURL.GetProperties(context.TODO())
a.AssertNoErr(err)
// Construct the properties object
fileSize := fProps.ContentLength()
creationTime, err := time.Parse(azfile.ISO8601, fProps.FileCreationTime())
a.AssertNoErr(err)
lastWriteTime, err := time.Parse(azfile.ISO8601, fProps.FileLastWriteTime())
a.AssertNoErr(err)
contentHeader := fProps.NewHTTPHeaders()
h := contentHeaders{
cacheControl: &contentHeader.CacheControl,
contentDisposition: &contentHeader.ContentDisposition,
contentEncoding: &contentHeader.ContentEncoding,
contentLanguage: &contentHeader.ContentLanguage,
contentType: &contentHeader.ContentType,
contentMD5: contentHeader.ContentMD5,
}
fileAttrs := uint32(azfile.ParseFileAttributeFlagsString(fProps.FileAttributes()))
permissionKey := fProps.FilePermissionKey()
var perm string
if permissionKey != "" {
sharePerm, err := shareURL.GetPermission(ctx, permissionKey)
a.AssertNoErr(err, "Failed to get permissions from key")
perm = sharePerm.Permission
}
props := objectProperties{
entityType: common.EEntityType.File(), // only enumerating files in list call
size: &fileSize,
nameValueMetadata: fProps.NewMetadata(),
contentHeaders: &h,
creationTime: &creationTime,
lastWriteTime: &lastWriteTime,
smbAttributes: &fileAttrs,
smbPermissionsSddl: &perm,
}
relativePath := lResp.DirectoryPath + "/"
if relativePath == "/" {
relativePath = ""
}
result[relativePath+fileInfo.Name] = &props
}
for _, dirInfo := range lResp.DirectoryItems {
dirURL := currentDirURL.NewDirectoryURL(dirInfo.Name)
dProps, err := dirURL.GetProperties(context.TODO())
a.AssertNoErr(err)
// Construct the properties object
creationTime, err := time.Parse(azfile.ISO8601, dProps.FileCreationTime())
a.AssertNoErr(err)
lastWriteTime, err := time.Parse(azfile.ISO8601, dProps.FileLastWriteTime())
a.AssertNoErr(err)
// Grab the permissions
permKey := dProps.FilePermissionKey()
var perm string
if permKey != "" {
permResp, err := shareURL.GetPermission(ctx, permKey)
a.AssertNoErr(err, "Failed to get permissions from key")
perm = permResp.Permission
}
// Set up properties
props := objectProperties{
entityType: common.EEntityType.Folder(), // Only enumerating directories in list call
nameValueMetadata: dProps.NewMetadata(),
creationTime: &creationTime,
lastWriteTime: &lastWriteTime,
smbPermissionsSddl: &perm,
}