-
Notifications
You must be signed in to change notification settings - Fork 234
/
Copy pathcopy.go
2172 lines (1895 loc) · 102 KB
/
copy.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 © 2017 Microsoft <[email protected]>
//
// 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 cmd
import (
"bufio"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"math"
"net/url"
"os"
"runtime"
"strconv"
"strings"
"sync"
"time"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/blob"
"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/blockblob"
"github.com/Azure/azure-storage-azcopy/v10/jobsAdmin"
"github.com/spf13/cobra"
"github.com/Azure/azure-storage-azcopy/v10/common"
"github.com/Azure/azure-storage-azcopy/v10/ste"
)
const pipingUploadParallelism = 5
const pipingDefaultBlockSize = 8 * 1024 * 1024
// For networking throughput in Mbps, (and only for networking), we divide by 1000*1000 (not 1024 * 1024) because
// networking is traditionally done in base 10 units (not base 2).
// E.g. "gigabit ethernet" means 10^9 bits/sec, not 2^30. So by using base 10 units
// we give the best correspondence to the sizing of the user's network pipes.
// See https://networkengineering.stackexchange.com/questions/3628/iec-or-si-units-binary-prefixes-used-for-network-measurement
// NOTE that for everything else in the app (e.g. sizes of files) we use the base 2 units (i.e. 1024 * 1024) because
// for RAM and disk file sizes, it is conventional to use the power-of-two-based units.
const base10Mega = 1000 * 1000
const pipeLocation = "~pipe~"
const PreservePermissionsFlag = "preserve-permissions"
// represents the raw copy command input from the user
type rawCopyCmdArgs struct {
// from arguments
src string
dst string
fromTo string
// blobUrlForRedirection string
// new include/exclude only apply to file names
// implemented for remove (and sync) only
include string
exclude string
includePath string // NOTE: This gets handled like list-of-files! It may LOOK like a bug, but it is not.
excludePath string
includeRegex string
excludeRegex string
includeFileAttributes string
excludeFileAttributes string
excludeContainer string
includeBefore string
includeAfter string
legacyInclude string // used only for warnings
legacyExclude string // used only for warnings
listOfVersionIDs string
// Indicates the user wants to upload the symlink itself, not the file on the other end
preserveSymlinks bool
// filters from flags
listOfFilesToCopy string
recursive bool
followSymlinks bool
autoDecompress bool
// forceWrite flag is used to define the User behavior
// to overwrite the existing blobs or not.
forceWrite string
forceIfReadOnly bool
// options from flags
blockSizeMB float64
putBlobSizeMB float64
metadata string
contentType string
contentEncoding string
contentDisposition string
contentLanguage string
cacheControl string
noGuessMimeType bool
preserveLastModifiedTime bool
putMd5 bool
md5ValidationOption string
CheckLength bool
deleteSnapshotsOption string
dryrun bool
blobTags string
// defines the type of the blob at the destination in case of upload / account to account copy
blobType string
blockBlobTier string
pageBlobTier string
output string // TODO: Is this unused now? replaced with param at root level?
// list of blobTypes to exclude while enumerating the transfer
excludeBlobType string
// Opt-in flag to persist SMB ACLs to Azure Files.
preserveSMBPermissions bool
preservePermissions bool // Separate flag so that we don't get funkiness with two "flags" targeting the same boolean
preserveOwner bool // works in conjunction with preserveSmbPermissions
// Default true; false indicates that the destination is the target directory, rather than something we'd put a directory under (e.g. a container)
asSubdir bool
// Opt-in flag to persist additional SMB properties to Azure Files. Named ...info instead of ...properties
// because the latter was similar enough to preserveSMBPermissions to induce user error
preserveSMBInfo bool
// Opt-in flag to persist additional POSIX properties
preservePOSIXProperties bool
// Opt-in flag to preserve the blob index tags during service to service transfer.
s2sPreserveBlobTags bool
// Flag to enable Window's special privileges
backupMode bool
// whether user wants to preserve full properties during service to service copy, the default value is true.
// For S3 and Azure File non-single file source, as list operation doesn't return full properties of objects/files,
// to preserve full properties AzCopy needs to send one additional request per object/file.
s2sPreserveProperties bool
// useful when preserveS3Properties set to true, enables get S3 objects' or Azure files' properties during s2s copy in backend, the default value is true
s2sGetPropertiesInBackend bool
// whether user wants to preserve access tier during service to service copy, the default value is true.
// In some case, e.g. target is a GPv1 storage account, access tier cannot be set properly.
// In such cases, use s2sPreserveAccessTier=false to bypass the access tier copy.
// For more details, please refer to https://docs.microsoft.com/en-us/azure/storage/blobs/storage-blob-storage-tiers
s2sPreserveAccessTier bool
// whether user wants to check if source has changed after enumerating, the default value is true.
// For S2S copy, as source is a remote resource, validating whether source has changed need additional request costs.
s2sSourceChangeValidation bool
// specify how user wants to handle invalid metadata.
s2sInvalidMetadataHandleOption string
// internal override to enforce strip-top-dir
internalOverrideStripTopDir bool
// whether to include blobs that have metadata 'hdi_isfolder = true'
includeDirectoryStubs bool
// whether to disable automatic decoding of illegal chars on Windows
disableAutoDecoding bool
// Optional flag to encrypt user data with user provided key.
// Key is provide in the REST request itself
// Provided key (EncryptionKey and EncryptionKeySHA256) and its hash will be fetched from environment variables
// Set EncryptionAlgorithm = "AES256" by default.
cpkInfo bool
// Key is present in AzureKeyVault and Azure KeyVault is linked with storage account.
// Provided key name will be fetched from Azure Key Vault and will be used to encrypt the data
cpkScopeInfo string
// Optional flag that permanently deletes soft-deleted snapshots/versions
permanentDeleteOption string
// Optional. Indicates the priority with which to rehydrate an archived blob. Valid values are High/Standard.
rehydratePriority string
// The priority setting can be changed from Standard to High by calling Set Blob Tier with this header set to High and setting x-ms-access-tier to the same value as previously set. The priority setting cannot be lowered from High to Standard.
trailingDot string
// when specified, AzCopy deletes the destination blob that has uncommitted blocks, not just the uncommitted blocks
deleteDestinationFileIfNecessary bool
}
func (raw *rawCopyCmdArgs) parsePatterns(pattern string) (cookedPatterns []string) {
cookedPatterns = make([]string, 0)
rawPatterns := strings.Split(pattern, ";")
for _, pattern := range rawPatterns {
// skip the empty patterns
if len(pattern) != 0 {
cookedPatterns = append(cookedPatterns, pattern)
}
}
return
}
// blocSizeInBytes converts a FLOATING POINT number of MiB, to a number of bytes
// A non-nil error is returned if the conversion is not possible to do accurately (e.g. it comes out of a fractional number of bytes)
// The purpose of using floating point is to allow specialist users (e.g. those who want small block sizes to tune their read IOPS)
// to use fractions of a MiB. E.g.
// 0.25 = 256 KiB
// 0.015625 = 16 KiB
func blockSizeInBytes(rawBlockSizeInMiB float64) (int64, error) {
if rawBlockSizeInMiB < 0 {
return 0, errors.New("negative block size not allowed")
}
rawSizeInBytes := rawBlockSizeInMiB * 1024 * 1024 // internally we use bytes, but users' convenience the command line uses MiB
if rawSizeInBytes > math.MaxInt64 {
return 0, errors.New("block size too big for int64")
}
const epsilon = 0.001 // arbitrarily using a tolerance of 1000th of a byte
_, frac := math.Modf(rawSizeInBytes)
isWholeNumber := frac < epsilon || frac > 1.0-epsilon // frac is very close to 0 or 1, so rawSizeInBytes is (very close to) an integer
if !isWholeNumber {
return 0, fmt.Errorf("while fractional numbers of MiB are allowed as the block size, the fraction must result to a whole number of bytes. %.12f MiB resolves to %.3f bytes", rawBlockSizeInMiB, rawSizeInBytes)
}
return int64(math.Round(rawSizeInBytes)), nil
}
// returns result of stripping and if striptopdir is enabled
// if nothing happens, the original source is returned
func (raw rawCopyCmdArgs) stripTrailingWildcardOnRemoteSource(location common.Location) (result string, stripTopDir bool, err error) {
result = raw.src
resourceURL, err := url.Parse(result)
gURLParts := common.NewGenericResourceURLParts(*resourceURL, location)
if err != nil {
err = fmt.Errorf("failed to parse url %s; %s", result, err)
return
}
if strings.Contains(gURLParts.GetContainerName(), "*") {
// Disallow container name search and object specifics
if gURLParts.GetObjectName() != "" {
err = errors.New("cannot combine a specific object name with an account-level search")
return
}
// Return immediately here because we know this will be safe.
return
}
// Trim the trailing /*.
if strings.HasSuffix(resourceURL.RawPath, "/*") {
resourceURL.RawPath = strings.TrimSuffix(resourceURL.RawPath, "/*")
resourceURL.Path = strings.TrimSuffix(resourceURL.Path, "/*")
stripTopDir = true
}
// Ensure there aren't any extra *s floating around.
if strings.Contains(resourceURL.RawPath, "*") {
err = errors.New("cannot use wildcards in the path section of the URL except in trailing \"/*\". If you wish to use * in your URL, manually encode it to %2A")
return
}
result = resourceURL.String()
return
}
func (raw rawCopyCmdArgs) cook() (CookedCopyCmdArgs, error) {
cooked := CookedCopyCmdArgs{
jobID: azcopyCurrentJobID,
}
// set up the front end scanning logger
azcopyScanningLogger = common.NewJobLogger(azcopyCurrentJobID, azcopyLogVerbosity, azcopyLogPathFolder, "-scanning")
azcopyScanningLogger.OpenLog()
glcm.RegisterCloseFunc(func() {
azcopyScanningLogger.CloseLog()
})
fromTo, err := ValidateFromTo(raw.src, raw.dst, raw.fromTo) // TODO: src/dst
if err != nil {
return cooked, err
}
var tempSrc string
tempDest := raw.dst
if strings.EqualFold(tempDest, common.Dev_Null) && runtime.GOOS == "windows" {
tempDest = common.Dev_Null // map all capitalization of "NUL"/"nul" to one because (on Windows) they all mean the same thing
}
// Check if source has a trailing wildcard on a URL
if fromTo.From().IsRemote() {
tempSrc, cooked.StripTopDir, err = raw.stripTrailingWildcardOnRemoteSource(fromTo.From())
if err != nil {
return cooked, err
}
} else {
tempSrc = raw.src
}
if raw.internalOverrideStripTopDir {
cooked.StripTopDir = true
}
// Strip the SAS from the source and destination whenever there is SAS exists in URL.
// Note: SAS could exists in source of S2S copy, even if the credential type is OAuth for destination.
cooked.Source, err = SplitResourceString(tempSrc, fromTo.From())
if err != nil {
return cooked, err
}
cooked.Destination, err = SplitResourceString(tempDest, fromTo.To())
if err != nil {
return cooked, err
}
cooked.FromTo = fromTo
cooked.Recursive = raw.recursive
cooked.ForceIfReadOnly = raw.forceIfReadOnly
if err = validateForceIfReadOnly(cooked.ForceIfReadOnly, cooked.FromTo); err != nil {
return cooked, err
}
if err = cooked.SymlinkHandling.Determine(raw.followSymlinks, raw.preserveSymlinks); err != nil {
return cooked, err
}
if err = validateSymlinkHandlingMode(cooked.SymlinkHandling, cooked.FromTo); err != nil {
return cooked, err
}
// copy&transform flags to type-safety
err = cooked.ForceWrite.Parse(raw.forceWrite)
if err != nil {
return cooked, err
}
allowAutoDecompress := fromTo == common.EFromTo.BlobLocal() || fromTo == common.EFromTo.FileLocal()
if raw.autoDecompress && !allowAutoDecompress {
return cooked, errors.New("automatic decompression is only supported for downloads from Blob and Azure Files") // as at Sept 2019, our ADLS Gen 2 Swagger does not include content-encoding for directory (path) listings so we can't support it there
}
cooked.autoDecompress = raw.autoDecompress
// cooked.StripTopDir is effectively a workaround for the lack of wildcards in remote sources.
// Local, however, still supports wildcards, and thus needs its top directory stripped whenever a wildcard is used.
// Thus, we check for wildcards and instruct the processor to strip the top dir later instead of repeatedly checking cca.Source for wildcards.
if fromTo.From() == common.ELocation.Local() && strings.Contains(cooked.Source.ValueLocal(), "*") {
cooked.StripTopDir = true
}
cooked.blockSize, err = blockSizeInBytes(raw.blockSizeMB)
if err != nil {
return cooked, err
}
cooked.putBlobSize, err = blockSizeInBytes(raw.putBlobSizeMB)
if err != nil {
return cooked, err
}
// parse the given blob type.
err = cooked.blobType.Parse(raw.blobType)
if err != nil {
return cooked, err
}
// If the given blobType is AppendBlob, block-size-mb should not be greater than
// common.MaxAppendBlobBlockSize.
if cookedSize, _ := blockSizeInBytes(raw.blockSizeMB); cooked.blobType == common.EBlobType.AppendBlob() && cookedSize > common.MaxAppendBlobBlockSize {
return cooked, fmt.Errorf("block size cannot be greater than %dMB for AppendBlob blob type", common.MaxAppendBlobBlockSize/common.MegaByte)
}
err = cooked.blockBlobTier.Parse(raw.blockBlobTier)
if err != nil {
return cooked, err
}
err = cooked.pageBlobTier.Parse(raw.pageBlobTier)
if err != nil {
return cooked, err
}
if raw.rehydratePriority == "" {
raw.rehydratePriority = "standard"
}
err = cooked.rehydratePriority.Parse(raw.rehydratePriority)
if err != nil {
return cooked, err
}
// Everything uses the new implementation of list-of-files now.
// This handles both list-of-files and include-path as a list enumerator.
// This saves us time because we know *exactly* what we're looking for right off the bat.
// Note that exclude-path is handled as a filter unlike include-path.
if raw.legacyInclude != "" || raw.legacyExclude != "" {
return cooked, fmt.Errorf("the include and exclude parameters have been replaced by include-pattern; include-path; exclude-pattern and exclude-path. For info, run: azcopy copy help")
}
if (len(raw.include) > 0 || len(raw.exclude) > 0) && cooked.FromTo == common.EFromTo.BlobFSTrash() {
return cooked, fmt.Errorf("include/exclude flags are not supported for this destination")
// note there's another, more rigorous check, in removeBfsResources()
}
// warn on exclude unsupported wildcards here. Include have to be later, to cover list-of-files
raw.warnIfHasWildcard(excludeWarningOncer, "exclude-path", raw.excludePath)
// unbuffered so this reads as we need it to rather than all at once in bulk
listChan := make(chan string)
var f *os.File
if raw.listOfFilesToCopy != "" {
f, err = os.Open(raw.listOfFilesToCopy)
if err != nil {
return cooked, fmt.Errorf("cannot open %s file passed with the list-of-file flag", raw.listOfFilesToCopy)
}
}
// Prepare UTF-8 byte order marker
utf8BOM := string([]byte{0xEF, 0xBB, 0xBF})
go func() {
defer close(listChan)
addToChannel := func(v string, paramName string) {
// empty strings should be ignored, otherwise the source root itself is selected
if len(v) > 0 {
raw.warnIfHasWildcard(includeWarningOncer, paramName, v)
listChan <- v
}
}
if f != nil {
scanner := bufio.NewScanner(f)
checkBOM := false
headerLineNum := 0
firstLineIsCurlyBrace := false
for scanner.Scan() {
v := scanner.Text()
// Check if the UTF-8 BOM is on the first line and remove it if necessary.
// Note that the UTF-8 BOM can be present on the same line feed as the first line of actual data, so just use TrimPrefix.
// If the line feed were separate, the empty string would be skipped later.
if !checkBOM {
v = strings.TrimPrefix(v, utf8BOM)
checkBOM = true
}
// provide clear warning if user uses old (obsolete) format by mistake
if headerLineNum <= 1 {
cleanedLine := strings.Replace(strings.Replace(v, " ", "", -1), "\t", "", -1)
cleanedLine = strings.TrimSuffix(cleanedLine, "[") // don't care which line this is on, could be third line
if cleanedLine == "{" && headerLineNum == 0 {
firstLineIsCurlyBrace = true
} else {
const jsonStart = "{\"Files\":"
jsonStartNoBrace := strings.TrimPrefix(jsonStart, "{")
isJson := cleanedLine == jsonStart || firstLineIsCurlyBrace && cleanedLine == jsonStartNoBrace
if isJson {
glcm.Error("The format for list-of-files has changed. The old JSON format is no longer supported")
}
}
headerLineNum++
}
addToChannel(v, "list-of-files")
}
}
// This occurs much earlier than the other include or exclude filters. It would be preferable to move them closer later on in the refactor.
includePathList := raw.parsePatterns(raw.includePath)
for _, v := range includePathList {
addToChannel(v, "include-path")
}
}()
// A combined implementation reduces the amount of code duplication present.
// However, it _does_ increase the amount of code-intertwining present.
if raw.listOfFilesToCopy != "" && raw.includePath != "" {
return cooked, errors.New("cannot combine list of files and include path")
}
if raw.listOfFilesToCopy != "" || raw.includePath != "" {
cooked.ListOfFilesChannel = listChan
}
if raw.includeBefore != "" {
// must set chooseEarliest = false, so that if there's an ambiguous local date, the latest will be returned
// (since that's safest for includeBefore. Better to choose the later time and do more work, than the earlier one and fail to pick up a changed file
parsedIncludeBefore, err := IncludeBeforeDateFilter{}.ParseISO8601(raw.includeBefore, false)
if err != nil {
return cooked, err
}
cooked.IncludeBefore = &parsedIncludeBefore
}
if raw.includeAfter != "" {
// must set chooseEarliest = true, so that if there's an ambiguous local date, the earliest will be returned
// (since that's safest for includeAfter. Better to choose the earlier time and do more work, than the later one and fail to pick up a changed file
parsedIncludeAfter, err := IncludeAfterDateFilter{}.ParseISO8601(raw.includeAfter, true)
if err != nil {
return cooked, err
}
cooked.IncludeAfter = &parsedIncludeAfter
}
versionsChan := make(chan string)
var filePtr *os.File
// Get file path from user which would contain list of all versionIDs
// Process the file line by line and then prepare a list of all version ids of the blob.
if raw.listOfVersionIDs != "" {
filePtr, err = os.Open(raw.listOfVersionIDs)
if err != nil {
return cooked, fmt.Errorf("cannot open %s file passed with the list-of-versions flag", raw.listOfVersionIDs)
}
}
go func() {
defer close(versionsChan)
addToChannel := func(v string) {
if len(v) > 0 {
versionsChan <- v
}
}
if filePtr != nil {
scanner := bufio.NewScanner(filePtr)
checkBOM := false
for scanner.Scan() {
v := scanner.Text()
if !checkBOM {
v = strings.TrimPrefix(v, utf8BOM)
checkBOM = true
}
addToChannel(v)
}
}
}()
if raw.listOfVersionIDs != "" {
cooked.ListOfVersionIDs = versionsChan
}
if cooked.FromTo.To() == common.ELocation.None() && strings.EqualFold(raw.metadata, common.MetadataAndBlobTagsClearFlag) { // in case of Blob, BlobFS and Files
glcm.Info("*** WARNING *** Metadata will be cleared because of input --metadata=clear ")
}
cooked.metadata = raw.metadata
if err = validateMetadataString(cooked.metadata); err != nil {
return cooked, err
}
cooked.contentType = raw.contentType
cooked.contentEncoding = raw.contentEncoding
cooked.contentLanguage = raw.contentLanguage
cooked.contentDisposition = raw.contentDisposition
cooked.cacheControl = raw.cacheControl
cooked.noGuessMimeType = raw.noGuessMimeType
cooked.preserveLastModifiedTime = raw.preserveLastModifiedTime
cooked.disableAutoDecoding = raw.disableAutoDecoding
err = cooked.trailingDot.Parse(raw.trailingDot)
if err != nil {
return cooked, err
}
if !(cooked.FromTo.To() == common.ELocation.Blob() || cooked.FromTo == common.EFromTo.BlobNone() || cooked.FromTo != common.EFromTo.BlobFSNone()) && raw.blobTags != "" {
return cooked, errors.New("blob tags can only be set when transferring to blob storage")
}
if cooked.FromTo.To() == common.ELocation.None() && strings.EqualFold(raw.blobTags, common.MetadataAndBlobTagsClearFlag) { // in case of Blob and BlobFS
glcm.Info("*** WARNING *** BlobTags will be cleared because of input --blob-tags=clear ")
}
blobTags := common.ToCommonBlobTagsMap(raw.blobTags)
err = validateBlobTagsKeyValue(blobTags)
if err != nil {
return cooked, err
}
cooked.blobTags = blobTags
// Check if user has provided `s2s-preserve-blob-tags` flag. If yes, we have to ensure that
// 1. Both source and destination must be blob storages.
// 2. `blob-tags` is not present as they create conflicting scenario of whether to preserve blob tags from the source or set user defined tags on the destination
if raw.s2sPreserveBlobTags {
if cooked.FromTo.From() != common.ELocation.Blob() || cooked.FromTo.To() != common.ELocation.Blob() {
return cooked, errors.New("either source or destination is not a blob storage. blob index tags is a property of blobs only therefore both source and destination must be blob storage")
} else if raw.blobTags != "" {
return cooked, errors.New("both s2s-preserve-blob-tags and blob-tags flags cannot be used in conjunction")
} else {
cooked.S2sPreserveBlobTags = raw.s2sPreserveBlobTags
}
}
// Setting CPK-N
cpkOptions := common.CpkOptions{}
// Setting CPK-N
if raw.cpkScopeInfo != "" {
if raw.cpkInfo {
return cooked, errors.New("cannot use both cpk-by-name and cpk-by-value at the same time")
}
cpkOptions.CpkScopeInfo = raw.cpkScopeInfo
}
// Setting CPK-V
// Get the key (EncryptionKey and EncryptionKeySHA256) value from environment variables when required.
cpkOptions.CpkInfo = raw.cpkInfo
if cpkOptions.CpkScopeInfo != "" || cpkOptions.CpkInfo {
// We only support transfer from source encrypted by user key when user wishes to download.
// Due to service limitation, S2S transfer is not supported for source encrypted by user key.
if cooked.FromTo.IsDownload() || cooked.FromTo.IsDelete() {
glcm.Info("Client Provided Key (CPK) for encryption/decryption is provided for download or delete scenario. " +
"Assuming source is encrypted.")
cpkOptions.IsSourceEncrypted = true
}
// TODO: Remove these warnings once service starts supporting it
if cooked.blockBlobTier != common.EBlockBlobTier.None() || cooked.pageBlobTier != common.EPageBlobTier.None() {
glcm.Info("Tier is provided by user explicitly. Ignoring it because Azure Service currently does" +
" not support setting tier when client provided keys are involved.")
}
destUrl, _ := url.Parse(cooked.Destination.Value)
if strings.Contains(destUrl.Host, "dfs.core.windows.net") {
return cooked, errors.New("client provided keys (CPK) based encryption is only supported with blob endpoints (blob.core.windows.net)")
}
}
cooked.CpkOptions = cpkOptions
// Make sure the given input is the one of the enums given by the blob SDK
err = cooked.deleteSnapshotsOption.Parse(raw.deleteSnapshotsOption)
if err != nil {
return cooked, err
}
if cooked.contentType != "" {
cooked.noGuessMimeType = true // As specified in the help text, noGuessMimeType is inferred here.
}
cooked.putMd5 = raw.putMd5
err = cooked.md5ValidationOption.Parse(raw.md5ValidationOption)
if err != nil {
return cooked, err
}
cooked.CheckLength = raw.CheckLength
// length of devnull will be 0, thus this will always fail unless downloading an empty file
if cooked.Destination.Value == common.Dev_Null {
cooked.CheckLength = false
}
// if redirection is triggered, avoid printing any output
if cooked.isRedirection() {
glcm.SetOutputFormat(common.EOutputFormat.None())
}
cooked.preserveSMBInfo = raw.preserveSMBInfo && areBothLocationsSMBAware(cooked.FromTo)
cooked.preservePOSIXProperties = raw.preservePOSIXProperties
if cooked.preservePOSIXProperties && !areBothLocationsPOSIXAware(cooked.FromTo) {
return cooked, fmt.Errorf("in order to use --preserve-posix-properties, both the source and destination must be POSIX-aware (Linux->Blob, Blob->Linux, Blob->Blob)")
}
if err = validatePreserveSMBPropertyOption(cooked.preserveSMBInfo, cooked.FromTo, &cooked.ForceWrite, "preserve-smb-info"); err != nil {
return cooked, err
}
isUserPersistingPermissions := raw.preservePermissions || raw.preserveSMBPermissions
if cooked.preserveSMBInfo && !isUserPersistingPermissions {
glcm.Info("Please note: the preserve-permissions flag is set to false, thus AzCopy will not copy SMB ACLs between the source and destination. To learn more: https://aka.ms/AzCopyandAzureFiles.")
}
if err = validatePreserveSMBPropertyOption(isUserPersistingPermissions, cooked.FromTo, &cooked.ForceWrite, PreservePermissionsFlag); err != nil {
return cooked, err
}
if err = validatePreserveOwner(raw.preserveOwner, cooked.FromTo); err != nil {
return cooked, err
}
cooked.preservePermissions = common.NewPreservePermissionsOption(isUserPersistingPermissions, raw.preserveOwner, cooked.FromTo)
// --as-subdir is OK on all sources and destinations, but additional verification has to be done down the line. (e.g. https://account.blob.core.windows.net is not a valid root)
cooked.asSubdir = raw.asSubdir
cooked.IncludeDirectoryStubs = raw.includeDirectoryStubs
if cooked.preservePermissions.IsTruthy() && cooked.FromTo.From() == common.ELocation.Blob() {
// If a user is trying to persist from Blob storage with ACLs, they probably want directories too, because ACLs only exist in HNS.
cooked.IncludeDirectoryStubs = true
}
cooked.backupMode = raw.backupMode
if err = validateBackupMode(cooked.backupMode, cooked.FromTo); err != nil {
return cooked, err
}
// Make sure the given input is the one of the enums given by the blob SDK
err = cooked.permanentDeleteOption.Parse(raw.permanentDeleteOption)
if err != nil {
return cooked, err
}
// check for the flag value relative to fromTo location type
// Example1: for Local to Blob, preserve-last-modified-time flag should not be set to true
// Example2: for Blob to Local, follow-symlinks, blob-tier flags should not be provided with values.
switch cooked.FromTo {
case common.EFromTo.LocalBlobFS():
if cooked.blobType != common.EBlobType.Detect() {
return cooked, fmt.Errorf("blob-type is not supported on ADLS Gen 2")
}
if cooked.preserveLastModifiedTime {
return cooked, fmt.Errorf("preserve-last-modified-time is not supported while uploading")
}
if cooked.blockBlobTier != common.EBlockBlobTier.None() ||
cooked.pageBlobTier != common.EPageBlobTier.None() {
return cooked, fmt.Errorf("blob-tier is not supported while uploading to ADLS Gen 2")
}
if cooked.preservePermissions.IsTruthy() {
return cooked, fmt.Errorf("preserve-smb-permissions is not supported while uploading to ADLS Gen 2")
}
if cooked.s2sPreserveProperties {
return cooked, fmt.Errorf("s2s-preserve-properties is not supported while uploading")
}
if cooked.s2sPreserveAccessTier {
return cooked, fmt.Errorf("s2s-preserve-access-tier is not supported while uploading")
}
if cooked.s2sInvalidMetadataHandleOption != common.DefaultInvalidMetadataHandleOption {
return cooked, fmt.Errorf("s2s-handle-invalid-metadata is not supported while uploading")
}
if cooked.s2sSourceChangeValidation {
return cooked, fmt.Errorf("s2s-detect-source-changed is not supported while uploading")
}
case common.EFromTo.LocalBlob():
if cooked.preserveLastModifiedTime {
return cooked, fmt.Errorf("preserve-last-modified-time is not supported while uploading to Blob Storage")
}
if cooked.s2sPreserveProperties {
return cooked, fmt.Errorf("s2s-preserve-properties is not supported while uploading to Blob Storage")
}
if cooked.s2sPreserveAccessTier {
return cooked, fmt.Errorf("s2s-preserve-access-tier is not supported while uploading to Blob Storage")
}
if cooked.s2sInvalidMetadataHandleOption != common.DefaultInvalidMetadataHandleOption {
return cooked, fmt.Errorf("s2s-handle-invalid-metadata is not supported while uploading to Blob Storage")
}
if cooked.s2sSourceChangeValidation {
return cooked, fmt.Errorf("s2s-detect-source-changed is not supported while uploading to Blob Storage")
}
case common.EFromTo.LocalFile():
if cooked.preserveLastModifiedTime {
return cooked, fmt.Errorf("preserve-last-modified-time is not supported while uploading")
}
if cooked.blockBlobTier != common.EBlockBlobTier.None() ||
cooked.pageBlobTier != common.EPageBlobTier.None() {
return cooked, fmt.Errorf("blob-tier is not supported while uploading to Azure File")
}
if cooked.s2sPreserveProperties {
return cooked, fmt.Errorf("s2s-preserve-properties is not supported while uploading")
}
if cooked.s2sPreserveAccessTier {
return cooked, fmt.Errorf("s2s-preserve-access-tier is not supported while uploading")
}
if cooked.s2sInvalidMetadataHandleOption != common.DefaultInvalidMetadataHandleOption {
return cooked, fmt.Errorf("s2s-handle-invalid-metadata is not supported while uploading")
}
if cooked.s2sSourceChangeValidation {
return cooked, fmt.Errorf("s2s-detect-source-changed is not supported while uploading")
}
if cooked.blobType != common.EBlobType.Detect() {
return cooked, fmt.Errorf("blob-type is not supported on Azure File")
}
case common.EFromTo.BlobLocal(),
common.EFromTo.FileLocal(),
common.EFromTo.BlobFSLocal():
if cooked.SymlinkHandling.Follow() {
return cooked, fmt.Errorf("follow-symlinks flag is not supported while downloading")
}
if cooked.blockBlobTier != common.EBlockBlobTier.None() ||
cooked.pageBlobTier != common.EPageBlobTier.None() {
return cooked, fmt.Errorf("blob-tier is not supported while downloading")
}
if cooked.noGuessMimeType {
return cooked, fmt.Errorf("no-guess-mime-type is not supported while downloading")
}
if len(cooked.contentType) > 0 || len(cooked.contentEncoding) > 0 || len(cooked.contentLanguage) > 0 || len(cooked.contentDisposition) > 0 || len(cooked.cacheControl) > 0 || len(cooked.metadata) > 0 {
return cooked, fmt.Errorf("content-type, content-encoding, content-language, content-disposition, cache-control, or metadata is not supported while downloading")
}
if cooked.s2sPreserveProperties {
return cooked, fmt.Errorf("s2s-preserve-properties is not supported while downloading")
}
if cooked.s2sPreserveAccessTier {
return cooked, fmt.Errorf("s2s-preserve-access-tier is not supported while downloading")
}
if cooked.s2sInvalidMetadataHandleOption != common.DefaultInvalidMetadataHandleOption {
return cooked, fmt.Errorf("s2s-handle-invalid-metadata is not supported while downloading")
}
if cooked.s2sSourceChangeValidation {
return cooked, fmt.Errorf("s2s-detect-source-changed is not supported while downloading")
}
case common.EFromTo.BlobFile(),
common.EFromTo.S3Blob(),
common.EFromTo.BlobBlob(),
common.EFromTo.FileBlob(),
common.EFromTo.FileFile(),
common.EFromTo.GCPBlob():
if cooked.preserveLastModifiedTime {
return cooked, fmt.Errorf("preserve-last-modified-time is not supported while copying from service to service")
}
if cooked.SymlinkHandling.Follow() {
return cooked, fmt.Errorf("follow-symlinks flag is not supported while copying from service to service")
}
// blob type is not supported if destination is not blob
if cooked.blobType != common.EBlobType.Detect() && cooked.FromTo.To() != common.ELocation.Blob() {
return cooked, fmt.Errorf("blob-type is not supported for the scenario (%s)", cooked.FromTo.String())
}
// Setting blob tier is supported only when destination is a blob storage. Disabling it for all the other transfer scenarios.
if (cooked.blockBlobTier != common.EBlockBlobTier.None() || cooked.pageBlobTier != common.EPageBlobTier.None()) &&
cooked.FromTo.To() != common.ELocation.Blob() {
return cooked, fmt.Errorf("blob-tier is not supported for the scenario (%s)", cooked.FromTo.String())
}
if cooked.noGuessMimeType {
return cooked, fmt.Errorf("no-guess-mime-type is not supported while copying from service to service")
}
if len(cooked.contentType) > 0 || len(cooked.contentEncoding) > 0 || len(cooked.contentLanguage) > 0 || len(cooked.contentDisposition) > 0 || len(cooked.cacheControl) > 0 || len(cooked.metadata) > 0 {
return cooked, fmt.Errorf("content-type, content-encoding, content-language, content-disposition, cache-control, or metadata is not supported while copying from service to service")
}
}
if err = validatePutMd5(cooked.putMd5, cooked.FromTo); err != nil {
return cooked, err
}
if err = validateMd5Option(cooked.md5ValidationOption, cooked.FromTo); err != nil {
return cooked, err
}
// Because of some of our defaults, these must live down here and can't be properly checked.
// TODO: Remove the above checks where they can't be done.
cooked.s2sPreserveProperties = raw.s2sPreserveProperties
cooked.s2sGetPropertiesInBackend = raw.s2sGetPropertiesInBackend
cooked.s2sPreserveAccessTier = raw.s2sPreserveAccessTier
cooked.s2sSourceChangeValidation = raw.s2sSourceChangeValidation
// If the user has provided some input with excludeBlobType flag, parse the input.
if len(raw.excludeBlobType) > 0 {
// Split the string using delimiter ';' and parse the individual blobType
blobTypes := strings.Split(raw.excludeBlobType, ";")
for _, blobType := range blobTypes {
var eBlobType common.BlobType
err := eBlobType.Parse(blobType)
if err != nil {
return cooked, fmt.Errorf("error parsing the exclude-blob-type %s provided with exclude-blob-type flag ", blobType)
}
cooked.excludeBlobType = append(cooked.excludeBlobType, eBlobType.ToBlobType())
}
}
err = cooked.s2sInvalidMetadataHandleOption.Parse(raw.s2sInvalidMetadataHandleOption)
if err != nil {
return cooked, err
}
// parse the filter patterns
cooked.IncludePatterns = raw.parsePatterns(raw.include)
cooked.ExcludePatterns = raw.parsePatterns(raw.exclude)
cooked.ExcludePathPatterns = raw.parsePatterns(raw.excludePath)
cooked.excludeContainer = raw.parsePatterns(raw.excludeContainer)
if (raw.includeFileAttributes != "" || raw.excludeFileAttributes != "") && fromTo.From() != common.ELocation.Local() {
return cooked, errors.New("cannot check file attributes on remote objects")
}
cooked.IncludeFileAttributes = raw.parsePatterns(raw.includeFileAttributes)
cooked.ExcludeFileAttributes = raw.parsePatterns(raw.excludeFileAttributes)
cooked.includeRegex = raw.parsePatterns(raw.includeRegex)
cooked.excludeRegex = raw.parsePatterns(raw.excludeRegex)
cooked.dryrunMode = raw.dryrun
if azcopyOutputVerbosity == common.EOutputVerbosity.Quiet() || azcopyOutputVerbosity == common.EOutputVerbosity.Essential() {
if cooked.ForceWrite == common.EOverwriteOption.Prompt() {
err = fmt.Errorf("cannot set output level '%s' with overwrite option '%s'", azcopyOutputVerbosity.String(), cooked.ForceWrite.String())
} else if cooked.dryrunMode {
err = fmt.Errorf("cannot set output level '%s' with dry-run mode", azcopyOutputVerbosity.String())
}
}
if err != nil {
return cooked, err
}
cooked.deleteDestinationFileIfNecessary = raw.deleteDestinationFileIfNecessary
return cooked, nil
}
var excludeWarningOncer = &sync.Once{}
var includeWarningOncer = &sync.Once{}
func (raw *rawCopyCmdArgs) warnIfHasWildcard(oncer *sync.Once, paramName string, value string) {
if strings.Contains(value, "*") || strings.Contains(value, "?") {
oncer.Do(func() {
glcm.Info(fmt.Sprintf("*** Warning *** The %s parameter does not support wildcards. The wildcard "+
"character provided will be interpreted literally and will not have any wildcard effect. To use wildcards "+
"(in filenames only, not paths) use include-pattern or exclude-pattern", paramName))
})
}
}
// When other commands use the copy command arguments to cook cook, set the blobType to None and validation option
// else parsing the arguments will fail.
func (raw *rawCopyCmdArgs) setMandatoryDefaults() {
raw.blobType = common.EBlobType.Detect().String()
raw.blockBlobTier = common.EBlockBlobTier.None().String()
raw.pageBlobTier = common.EPageBlobTier.None().String()
raw.md5ValidationOption = common.DefaultHashValidationOption.String()
raw.s2sInvalidMetadataHandleOption = common.DefaultInvalidMetadataHandleOption.String()
raw.forceWrite = common.EOverwriteOption.True().String()
raw.preserveOwner = common.PreserveOwnerDefault
}
func validateForceIfReadOnly(toForce bool, fromTo common.FromTo) error {
targetIsFiles := fromTo.To() == common.ELocation.File() ||
fromTo == common.EFromTo.FileTrash()
targetIsWindowsFS := fromTo.To() == common.ELocation.Local() &&
runtime.GOOS == "windows"
targetIsOK := targetIsFiles || targetIsWindowsFS
if toForce && !targetIsOK {
return errors.New("force-if-read-only is only supported when the target is Azure Files or a Windows file system")
}
return nil
}
func areBothLocationsSMBAware(fromTo common.FromTo) bool {
// preserverSMBInfo will be true by default for SMB-aware locations unless specified false.
// 1. Upload (Windows/Linux -> Azure File)
// 2. Download (Azure File -> Windows/Linux)
// 3. S2S (Azure File -> Azure File)
if (runtime.GOOS == "windows" || runtime.GOOS == "linux") &&
(fromTo == common.EFromTo.LocalFile() || fromTo == common.EFromTo.FileLocal()) {
return true
} else if fromTo == common.EFromTo.FileFile() {
return true
} else {
return false
}
}
func areBothLocationsPOSIXAware(fromTo common.FromTo) bool {
// POSIX properties are stored in blob metadata-- They don't need a special persistence strategy for S2S methods.
switch fromTo {
case common.EFromTo.BlobLocal(), common.EFromTo.LocalBlob(), common.EFromTo.BlobFSLocal(), common.EFromTo.LocalBlobFS():
return runtime.GOOS == "linux"
case common.EFromTo.BlobBlob(), common.EFromTo.BlobFSBlobFS(), common.EFromTo.BlobFSBlob(), common.EFromTo.BlobBlobFS():
return true
default:
return false
}
}
func validatePreserveSMBPropertyOption(toPreserve bool, fromTo common.FromTo, overwrite *common.OverwriteOption, flagName string) error {
if toPreserve && flagName == PreservePermissionsFlag && (fromTo == common.EFromTo.BlobBlob() || fromTo == common.EFromTo.BlobFSBlob() || fromTo == common.EFromTo.BlobBlobFS() || fromTo == common.EFromTo.BlobFSBlobFS()) {
// the user probably knows what they're doing if they're trying to persist permissions between blob-type endpoints.
return nil
} else if toPreserve && !(fromTo == common.EFromTo.LocalFile() ||
fromTo == common.EFromTo.FileLocal() ||
fromTo == common.EFromTo.FileFile()) {
return fmt.Errorf("%s is set but the job is not between %s-aware resources", flagName, common.Iff(flagName == PreservePermissionsFlag, "permission", "SMB"))
}
if toPreserve && (fromTo.IsUpload() || fromTo.IsDownload()) &&
runtime.GOOS != "windows" && runtime.GOOS != "linux" {
return fmt.Errorf("%s is set but persistence for up/downloads is supported only in Windows and Linux", flagName)
}
return nil
}
func validatePreserveOwner(preserve bool, fromTo common.FromTo) error {
if fromTo.IsDownload() {
return nil // it can be used in downloads
}
if preserve != common.PreserveOwnerDefault {
return fmt.Errorf("flag --%s can only be used on downloads", common.PreserveOwnerFlagName)
}
return nil
}
func validateSymlinkHandlingMode(symlinkHandling common.SymlinkHandlingType, fromTo common.FromTo) error {
if symlinkHandling.Preserve() {
switch fromTo {
case common.EFromTo.LocalBlob(), common.EFromTo.BlobLocal(), common.EFromTo.BlobFSLocal(), common.EFromTo.LocalBlobFS():
return nil // Fine on all OSes that support symlink via the OS package. (Win, MacOS, and Linux do, and that's what we officially support.)
case common.EFromTo.BlobBlob(), common.EFromTo.BlobFSBlobFS(), common.EFromTo.BlobBlobFS(), common.EFromTo.BlobFSBlob():
return nil // Blob->Blob doesn't involve any local requirements
default:
return fmt.Errorf("flag --%s can only be used on Blob<->Blob or Local<->Blob", common.PreserveSymlinkFlagName)
}
}