-
Notifications
You must be signed in to change notification settings - Fork 999
/
Copy pathsync.go
1472 lines (1385 loc) · 37.7 KB
/
sync.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
/*
* JuiceFS, Copyright 2018 Juicedata, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sync
import (
"bytes"
"errors"
"fmt"
"io"
"os"
"path"
"runtime"
"strings"
"sync"
"time"
"github.com/juicedata/juicefs/pkg/chunk"
"github.com/juicedata/juicefs/pkg/object"
"github.com/juicedata/juicefs/pkg/utils"
"github.com/juju/ratelimit"
"github.com/prometheus/client_golang/prometheus"
)
// The max number of key per listing request
const (
maxResults = 1000
defaultPartSize = 5 << 20
bufferSize = 32 << 10
maxBlock = defaultPartSize * 2
markDeleteSrc = -1
markDeleteDst = -2
markCopyPerms = -3
markChecksum = -4
)
var (
handled *utils.Bar
pending *utils.Bar
copied, copiedBytes *utils.Bar
checked, checkedBytes *utils.Bar
skipped, skippedBytes *utils.Bar
deleted, failed *utils.Bar
concurrent chan int
limiter *ratelimit.Bucket
)
var logger = utils.GetLogger("juicefs")
// human readable bytes size
func formatSize(bytes int64) string {
units := [7]string{" ", "K", "M", "G", "T", "P", "E"}
if bytes < 1024 {
return fmt.Sprintf("%v B", bytes)
}
z := 0
v := float64(bytes)
for v > 1024.0 {
z++
v /= 1024.0
}
return fmt.Sprintf("%.2f %siB", v, units[z])
}
// ListAll on all the keys that starts at marker from object storage.
func ListAll(store object.ObjectStorage, prefix, start, end string, followLink bool) (<-chan object.Object, error) {
startTime := time.Now()
logger.Debugf("Iterating objects from %s with prefix %s start %q", store, prefix, start)
out := make(chan object.Object, maxResults*10)
// As the result of object storage's List method doesn't include the marker key,
// we try List the marker key separately.
if start != "" && strings.HasPrefix(start, prefix) {
if obj, err := store.Head(start); err == nil {
logger.Debugf("Found start key: %s from %s in %s", start, store, time.Since(startTime))
out <- obj
}
}
if ch, err := store.ListAll(prefix, start, followLink); err == nil {
go func() {
for obj := range ch {
if obj != nil && end != "" && obj.Key() > end {
break
}
out <- obj
}
close(out)
}()
return out, nil
} else if !errors.Is(err, utils.ENOTSUP) {
return nil, err
}
marker := start
logger.Debugf("Listing objects from %s marker %q", store, marker)
objs, hasMore, nextToken, err := store.List(prefix, marker, "", "", maxResults, followLink)
if errors.Is(err, utils.ENOTSUP) {
return object.ListAllWithDelimiter(store, prefix, start, end, followLink)
}
if err != nil {
logger.Errorf("Can't list %s: %s", store, err.Error())
return nil, err
}
logger.Debugf("Found %d object from %s in %s", len(objs), store, time.Since(startTime))
go func() {
lastkey := ""
first := true
END:
for {
for _, obj := range objs {
key := obj.Key()
if !first && key <= lastkey {
logger.Errorf("The keys are out of order: marker %q, last %q current %q", marker, lastkey, key)
out <- nil
break END
}
if end != "" && key > end {
break END
}
lastkey = key
// logger.Debugf("key: %s", key)
out <- obj
first = false
}
if !hasMore {
break
}
marker = lastkey
startTime = time.Now()
logger.Debugf("Continue listing objects from %s marker %q", store, marker)
var nextToken2 string
objs, hasMore, nextToken2, err = store.List(prefix, marker, nextToken, "", maxResults, followLink)
count := 0
for err != nil && count < 3 {
logger.Warnf("Fail to list: %s, retry again", err.Error())
// slow down
time.Sleep(time.Millisecond * 100)
objs, hasMore, nextToken2, err = store.List(prefix, marker, nextToken, "", maxResults, followLink)
count++
}
logger.Debugf("Found %d object from %s in %s", len(objs), store, time.Since(startTime))
if err != nil {
// Telling that the listing has failed
out <- nil
logger.Errorf("Fail to list after %s: %s", marker, err.Error())
break
}
nextToken = nextToken2
if len(objs) > 0 && objs[0].Key() == marker {
// workaround from a object store that is not compatible to S3.
objs = objs[1:]
}
}
close(out)
}()
return out, nil
}
var bufPool = sync.Pool{
New: func() interface{} {
buf := make([]byte, bufferSize)
return &buf
},
}
func try(n int, f func() error) (err error) {
for i := 0; i < n; i++ {
err = f()
if err == nil {
return
}
logger.Debugf("Try %d failed: %s", i+1, err)
time.Sleep(time.Second * time.Duration(i*i))
}
return
}
func deleteObj(storage object.ObjectStorage, key string, dry bool) {
if dry {
logger.Debugf("Will delete %s from %s", key, storage)
deleted.Increment()
return
}
start := time.Now()
if err := try(3, func() error { return storage.Delete(key) }); err == nil {
deleted.Increment()
logger.Debugf("Deleted %s from %s in %s", key, storage, time.Since(start))
} else {
failed.Increment()
logger.Errorf("Failed to delete %s from %s in %s: %s", key, storage, time.Since(start), err)
}
}
func needCopyPerms(o1, o2 object.Object) bool {
f1 := o1.(object.File)
f2 := o2.(object.File)
return f2.Mode() != f1.Mode() || f2.Owner() != f1.Owner() || f2.Group() != f1.Group()
}
func copyPerms(dst object.ObjectStorage, obj object.Object, config *Config) {
start := time.Now()
key := obj.Key()
fi := obj.(object.File)
// chmod needs to be executed after chown, because chown will change setuid setgid to be invalid.
if err := dst.(object.FileSystem).Chown(key, fi.Owner(), fi.Group()); err != nil {
logger.Warnf("Chown %s to (%s,%s): %s", key, fi.Owner(), fi.Group(), err)
}
if !fi.IsSymlink() || !config.Links {
if err := dst.(object.FileSystem).Chmod(key, fi.Mode()); err != nil {
logger.Warnf("Chmod %s to %o: %s", key, fi.Mode(), err)
}
}
logger.Debugf("Copied permissions (%s:%s:%s) for %s in %s", fi.Owner(), fi.Group(), fi.Mode(), key, time.Since(start))
}
func doCheckSum(src, dst object.ObjectStorage, key string, obj object.Object, config *Config, equal *bool) error {
if obj.IsSymlink() && config.Links && (config.CheckAll || config.CheckNew) {
var srcLink, dstLink string
var err error
if s, ok := src.(object.SupportSymlink); ok {
if srcLink, err = s.Readlink(key); err != nil {
return err
}
}
if s, ok := dst.(object.SupportSymlink); ok {
if dstLink, err = s.Readlink(key); err != nil {
return err
}
}
*equal = srcLink == dstLink && srcLink != "" && dstLink != ""
return nil
}
abort := make(chan struct{})
checkPart := func(offset, length int64) error {
if limiter != nil {
limiter.Wait(length)
}
select {
case <-abort:
return fmt.Errorf("aborted")
case concurrent <- 1:
defer func() {
<-concurrent
}()
}
in, err := src.Get(key, offset, length)
if err != nil {
return fmt.Errorf("src get: %s", err)
}
defer in.Close()
in2, err := dst.Get(key, offset, length)
if err != nil {
return fmt.Errorf("dest get: %s", err)
}
defer in2.Close()
buf := bufPool.Get().(*[]byte)
defer bufPool.Put(buf)
buf2 := bufPool.Get().(*[]byte)
defer bufPool.Put(buf2)
for left := int(length); left > 0; left -= bufferSize {
bs := bufferSize
if left < bufferSize {
bs = left
}
*buf = (*buf)[:bs]
*buf2 = (*buf2)[:bs]
if _, err = io.ReadFull(in, *buf); err != nil {
return fmt.Errorf("src read: %s", err)
}
if _, err = io.ReadFull(in2, *buf2); err != nil {
return fmt.Errorf("dest read: %s", err)
}
if !bytes.Equal(*buf, *buf2) {
return fmt.Errorf("bytes not equal")
}
}
return nil
}
var err error
if obj.Size() < maxBlock {
err = checkPart(0, obj.Size())
} else {
n := int((obj.Size()-1)/defaultPartSize) + 1
errs := make(chan error, n)
for i := 0; i < n; i++ {
go func(num int) {
sz := int64(defaultPartSize)
if num == n-1 {
sz = obj.Size() - int64(num)*defaultPartSize
}
errs <- checkPart(int64(num)*defaultPartSize, sz)
}(i)
}
for i := 0; i < n; i++ {
if err = <-errs; err != nil {
close(abort)
break
}
}
}
if err != nil && err.Error() == "bytes not equal" {
*equal = false
err = nil
} else {
*equal = err == nil
}
return err
}
func checkSum(src, dst object.ObjectStorage, key string, obj object.Object, config *Config) (bool, error) {
start := time.Now()
var equal bool
err := try(3, func() error { return doCheckSum(src, dst, key, obj, config, &equal) })
if err == nil {
checked.Increment()
checkedBytes.IncrInt64(obj.Size())
if equal {
logger.Debugf("Checked %s OK (and equal) in %s,", key, time.Since(start))
} else {
logger.Warnf("Checked %s OK (but NOT equal) in %s,", key, time.Since(start))
}
} else {
logger.Errorf("Failed to check %s in %s: %s", key, time.Since(start), err)
}
return equal, err
}
var fastStreamRead = map[string]struct{}{"file": {}, "hdfs": {}, "jfs": {}, "gluster": {}}
var streamWrite = map[string]struct{}{"file": {}, "hdfs": {}, "sftp": {}, "gs": {}, "wasb": {}, "ceph": {}, "swift": {}, "webdav": {}, "upyun": {}, "jfs": {}, "gluster": {}}
var readInMem = map[string]struct{}{"mem": {}, "etcd": {}, "redis": {}, "tikv": {}, "mysql": {}, "postgres": {}, "sqlite3": {}}
func inMap(obj object.ObjectStorage, m map[string]struct{}) bool {
_, ok := m[strings.Split(obj.String(), "://")[0]]
return ok
}
func doCopySingle(src, dst object.ObjectStorage, key string, size int64) error {
if size > maxBlock && !inMap(dst, readInMem) && !inMap(src, fastStreamRead) {
var err error
var in io.Reader
downer := newParallelDownloader(src, key, size, 10<<20, concurrent)
defer downer.Close()
if inMap(dst, streamWrite) {
in = downer
} else {
var f *os.File
// download the object into disk
if f, err = os.CreateTemp("", "rep"); err != nil {
logger.Warnf("create temp file: %s", err)
return doCopySingle0(src, dst, key, size)
}
_ = os.Remove(f.Name()) // will be deleted after Close()
defer f.Close()
buf := bufPool.Get().(*[]byte)
defer bufPool.Put(buf)
if _, err = io.CopyBuffer(struct{ io.Writer }{f}, downer, *buf); err == nil {
_, err = f.Seek(0, 0)
in = f
}
}
if err == nil {
err = dst.Put(key, in)
}
if err != nil {
if _, e := src.Head(key); os.IsNotExist(e) {
logger.Debugf("Head src %s: %s", key, err)
copied.IncrInt64(-1)
err = nil
}
}
return err
}
return doCopySingle0(src, dst, key, size)
}
func doCopySingle0(src, dst object.ObjectStorage, key string, size int64) error {
concurrent <- 1
defer func() {
<-concurrent
}()
var in io.ReadCloser
var err error
if size == 0 {
if object.IsFileSystem(src) {
// for check permissions
r, err := src.Get(key, 0, -1)
if err != nil {
return err
}
_ = r.Close()
}
in = io.NopCloser(bytes.NewReader(nil))
} else {
in, err = src.Get(key, 0, size)
if err != nil {
if _, e := src.Head(key); os.IsNotExist(e) {
logger.Debugf("Head src %s: %s", key, err)
copied.IncrInt64(-1)
err = nil
}
return err
}
}
defer in.Close()
return dst.Put(key, &withProgress{in})
}
type withProgress struct {
r io.Reader
}
func (w *withProgress) Read(b []byte) (int, error) {
if limiter != nil {
limiter.Wait(int64(len(b)))
}
n, err := w.r.Read(b)
copiedBytes.IncrInt64(int64(n))
return n, err
}
func doUploadPart(src, dst object.ObjectStorage, srckey string, off, size int64, key, uploadID string, num int) (*object.Part, error) {
if limiter != nil {
limiter.Wait(size)
}
start := time.Now()
sz := size
p := chunk.NewOffPage(int(size))
defer p.Release()
data := p.Data
var part *object.Part
err := try(3, func() error {
in, err := src.Get(srckey, off, sz)
if err != nil {
return err
}
defer in.Close()
if _, err = io.ReadFull(in, data); err != nil {
return err
}
// PartNumber starts from 1
part, err = dst.UploadPart(key, uploadID, num+1, data)
return err
})
if err != nil {
logger.Warnf("Failed to copy data of %s part %d: %s", key, num, err)
return nil, fmt.Errorf("part %d: %s", num, err)
}
logger.Debugf("Copied data of %s part %d in %s", key, num, time.Since(start))
copiedBytes.IncrInt64(sz)
return part, nil
}
func choosePartSize(upload *object.MultipartUpload, size int64) int64 {
partSize := int64(upload.MinPartSize)
if partSize == 0 {
partSize = defaultPartSize
}
if size > partSize*int64(upload.MaxCount) {
partSize = size / int64(upload.MaxCount)
partSize = ((partSize-1)>>20 + 1) << 20 // align to MB
}
return partSize
}
func doCopyRange(src, dst object.ObjectStorage, key string, off, size int64, upload *object.MultipartUpload, num int, abort chan struct{}) (*object.Part, error) {
select {
case <-abort:
return nil, fmt.Errorf("aborted")
case concurrent <- 1:
defer func() {
<-concurrent
}()
}
limits := dst.Limits()
if size <= 32<<20 || !limits.IsSupportUploadPartCopy {
return doUploadPart(src, dst, key, off, size, key, upload.UploadID, num)
}
tmpkey := fmt.Sprintf("%s.part%d", key, num)
var up *object.MultipartUpload
var err error
err = try(3, func() error {
up, err = dst.CreateMultipartUpload(tmpkey)
return err
})
if err != nil {
return nil, fmt.Errorf("range(%d,%d): %s", off, size, err)
}
partSize := choosePartSize(up, size)
n := int((size-1)/partSize) + 1
logger.Debugf("Copying data of %s (range: %d,%d) as %d parts (size: %d): %s", key, off, size, n, partSize, up.UploadID)
parts := make([]*object.Part, n)
for i := 0; i < n; i++ {
sz := partSize
if i == n-1 {
sz = size - int64(i)*partSize
}
select {
case <-abort:
dst.AbortUpload(tmpkey, up.UploadID)
return nil, fmt.Errorf("aborted")
default:
}
parts[i], err = doUploadPart(src, dst, key, off+int64(i)*partSize, sz, tmpkey, up.UploadID, i)
if err != nil {
dst.AbortUpload(tmpkey, up.UploadID)
return nil, fmt.Errorf("range(%d,%d): %s", off, size, err)
}
}
err = try(3, func() error { return dst.CompleteUpload(tmpkey, up.UploadID, parts) })
if err != nil {
dst.AbortUpload(tmpkey, up.UploadID)
return nil, fmt.Errorf("multipart: %s", err)
}
var part *object.Part
err = try(3, func() error {
part, err = dst.UploadPartCopy(key, upload.UploadID, num+1, tmpkey, 0, size)
return err
})
_ = dst.Delete(tmpkey)
return part, err
}
func doCopyMultiple(src, dst object.ObjectStorage, key string, size int64, upload *object.MultipartUpload) error {
limits := dst.Limits()
if size > limits.MaxPartSize*int64(upload.MaxCount) {
return fmt.Errorf("object size %d is too large to copy", size)
}
partSize := choosePartSize(upload, size)
n := int((size-1)/partSize) + 1
logger.Debugf("Copying data of %s as %d parts (size: %d): %s", key, n, partSize, upload.UploadID)
abort := make(chan struct{})
parts := make([]*object.Part, n)
errs := make(chan error, n)
var err error
for i := 0; i < n; i++ {
go func(num int) {
sz := partSize
if num == n-1 {
sz = size - int64(num)*partSize
}
var copyErr error
parts[num], copyErr = doCopyRange(src, dst, key, int64(num)*partSize, sz, upload, num, abort)
errs <- copyErr
}(i)
}
for i := 0; i < n; i++ {
if err = <-errs; err != nil {
close(abort)
break
}
}
if err == nil {
err = try(3, func() error { return dst.CompleteUpload(key, upload.UploadID, parts) })
}
if err != nil {
dst.AbortUpload(key, upload.UploadID)
return fmt.Errorf("multipart: %s", err)
}
return nil
}
func copyData(src, dst object.ObjectStorage, key string, size int64) error {
start := time.Now()
var err error
if size < maxBlock {
err = try(3, func() error { return doCopySingle(src, dst, key, size) })
} else {
var upload *object.MultipartUpload
if upload, err = dst.CreateMultipartUpload(key); err == nil {
err = doCopyMultiple(src, dst, key, size, upload)
} else if err == utils.ENOTSUP {
err = try(3, func() error { return doCopySingle(src, dst, key, size) })
} else { // other error retry
if err = try(2, func() error {
upload, err = dst.CreateMultipartUpload(key)
return err
}); err == nil {
err = doCopyMultiple(src, dst, key, size, upload)
}
}
}
if err == nil {
logger.Debugf("Copied data of %s (%d bytes) in %s", key, size, time.Since(start))
} else {
logger.Errorf("Failed to copy data of %s in %s: %s", key, time.Since(start), err)
}
return err
}
func worker(tasks <-chan object.Object, src, dst object.ObjectStorage, config *Config) {
for obj := range tasks {
key := obj.Key()
switch obj.Size() {
case markDeleteSrc:
deleteObj(src, key, config.Dry)
case markDeleteDst:
deleteObj(dst, key, config.Dry)
case markCopyPerms:
if config.Dry {
logger.Debugf("Will copy permissions for %s", key)
} else {
copyPerms(dst, obj, config)
}
copied.Increment()
case markChecksum:
if config.Dry {
logger.Debugf("Will compare checksum for %s", key)
checked.Increment()
break
}
obj = obj.(*withSize).Object
if equal, err := checkSum(src, dst, key, obj, config); err != nil {
failed.Increment()
break
} else if equal {
if config.DeleteSrc {
deleteObj(src, key, false)
} else if config.Perms && (!obj.IsSymlink() || !config.Links) {
if o, e := dst.Head(key); e == nil {
if needCopyPerms(obj, o) {
copyPerms(dst, obj, config)
copied.Increment()
} else {
skipped.Increment()
skippedBytes.IncrInt64(obj.Size())
}
} else {
logger.Warnf("Failed to head object %s: %s", key, e)
failed.Increment()
}
} else {
skipped.Increment()
skippedBytes.IncrInt64(obj.Size())
}
break
}
// checkSum not equal, copy the object
fallthrough
default:
if config.Dry {
logger.Debugf("Will copy %s (%d bytes)", obj.Key(), obj.Size())
copied.Increment()
copiedBytes.IncrInt64(obj.Size())
break
}
var err error
if config.Links && obj.IsSymlink() {
if err = copyLink(src, dst, key); err != nil {
logger.Errorf("copy link failed: %s", err)
}
} else {
err = copyData(src, dst, key, obj.Size())
}
if err == nil && (config.CheckAll || config.CheckNew) {
var equal bool
if equal, err = checkSum(src, dst, key, obj, config); err == nil && !equal {
err = fmt.Errorf("checksums of copied object %s don't match", key)
}
}
if err == nil {
if mc, ok := dst.(object.MtimeChanger); ok {
if err = mc.Chtimes(obj.Key(), obj.Mtime()); err != nil && !errors.Is(err, utils.ENOTSUP) {
logger.Warnf("Update mtime of %s: %s", key, err)
}
}
if config.Perms {
copyPerms(dst, obj, config)
}
copied.Increment()
} else {
failed.Increment()
logger.Errorf("Failed to copy object %s: %s", key, err)
}
}
handled.Increment()
}
}
func copyLink(src object.ObjectStorage, dst object.ObjectStorage, key string) error {
if p, err := src.(object.SupportSymlink).Readlink(key); err != nil {
return err
} else {
if err := dst.Delete(key); err != nil {
logger.Debugf("Deleted %s from %s ", key, dst)
return err
}
// TODO: use relative path based on option
return dst.(object.SupportSymlink).Symlink(p, key)
}
}
type withSize struct {
object.Object
nsize int64
}
func (o *withSize) Size() int64 {
return o.nsize
}
type withFSize struct {
object.File
nsize int64
}
func (o *withFSize) Size() int64 {
return o.nsize
}
func deleteFromDst(tasks chan<- object.Object, dstobj object.Object, config *Config) bool {
if !config.Dirs && dstobj.IsDir() {
logger.Debug("Ignore deleting dst directory ", dstobj.Key())
return false
}
if config.Limit >= 0 {
if config.Limit == 0 {
return true
}
config.Limit--
}
tasks <- &withSize{dstobj, markDeleteDst}
handled.IncrTotal(1)
return false
}
func startSingleProducer(tasks chan<- object.Object, src, dst object.ObjectStorage, prefix string, config *Config) error {
start, end := config.Start, config.End
logger.Debugf("maxResults: %d, defaultPartSize: %d, maxBlock: %d", maxResults, defaultPartSize, maxBlock)
srckeys, err := ListAll(src, prefix, start, end, !config.Links)
if err != nil {
return fmt.Errorf("list %s: %s", src, err)
}
var dstkeys <-chan object.Object
if config.ForceUpdate {
t := make(chan object.Object)
close(t)
dstkeys = t
} else {
dstkeys, err = ListAll(dst, prefix, start, end, !config.Links)
if err != nil {
return fmt.Errorf("list %s: %s", dst, err)
}
}
return produce(tasks, srckeys, dstkeys, config)
}
func produce(tasks chan<- object.Object, srckeys, dstkeys <-chan object.Object, config *Config) error {
srckeys = filter(srckeys, config.rules, config)
dstkeys = filter(dstkeys, config.rules, config)
var dstobj object.Object
for obj := range srckeys {
if obj == nil {
return fmt.Errorf("listing failed, stop syncing, waiting for pending ones")
}
if !config.Dirs && obj.IsDir() {
logger.Debug("Ignore directory ", obj.Key())
continue
}
if config.Limit >= 0 {
if config.Limit == 0 {
return nil
}
config.Limit--
}
handled.IncrTotal(1)
if dstobj != nil && obj.Key() > dstobj.Key() {
if config.DeleteDst {
if deleteFromDst(tasks, dstobj, config) {
return nil
}
}
dstobj = nil
}
if dstobj == nil {
for dstobj = range dstkeys {
if dstobj == nil {
return fmt.Errorf("listing failed, stop syncing, waiting for pending ones")
}
if obj.Key() <= dstobj.Key() {
break
}
if config.DeleteDst {
if deleteFromDst(tasks, dstobj, config) {
return nil
}
}
dstobj = nil
}
}
// FIXME: there is a race when source is modified during coping
if dstobj == nil || obj.Key() < dstobj.Key() {
if config.Existing {
skipped.Increment()
skippedBytes.IncrInt64(obj.Size())
handled.Increment()
continue
}
tasks <- obj
} else { // obj.key == dstobj.key
if config.IgnoreExisting {
skipped.Increment()
skippedBytes.IncrInt64(obj.Size())
handled.Increment()
dstobj = nil
continue
}
if config.ForceUpdate ||
(config.Update && obj.Mtime().Unix() > dstobj.Mtime().Unix()) ||
(!config.Update && obj.Size() != dstobj.Size()) {
tasks <- obj
} else if config.Update && obj.Mtime().Unix() < dstobj.Mtime().Unix() {
skipped.Increment()
skippedBytes.IncrInt64(obj.Size())
handled.Increment()
} else if config.CheckAll { // two objects are likely the same
tasks <- &withSize{obj, markChecksum}
} else if config.DeleteSrc {
tasks <- &withSize{obj, markDeleteSrc}
} else if config.Perms && needCopyPerms(obj, dstobj) {
tasks <- &withFSize{obj.(object.File), markCopyPerms}
} else {
skipped.Increment()
skippedBytes.IncrInt64(obj.Size())
handled.Increment()
}
dstobj = nil
}
}
if config.DeleteDst {
if dstobj != nil {
if deleteFromDst(tasks, dstobj, config) {
return nil
}
}
for dstobj = range dstkeys {
if dstobj != nil {
if deleteFromDst(tasks, dstobj, config) {
return nil
}
}
}
}
return nil
}
type rule struct {
pattern string
include bool
}
func parseRule(name, p string) rule {
if runtime.GOOS == "windows" {
p = strings.Replace(p, "\\", "/", -1)
}
return rule{pattern: p, include: name == "-include"}
}
func parseIncludeRules(args []string) (rules []rule) {
l := len(args)
for i, a := range args {
if strings.HasPrefix(a, "--") {
a = a[1:]
}
if l-1 > i && (a == "-include" || a == "-exclude") {
if _, err := path.Match(args[i+1], "xxxx"); err != nil {
logger.Warnf("ignore invalid pattern: %s %s", a, args[i+1])
continue
}
rules = append(rules, parseRule(a, args[i+1]))
} else if strings.HasPrefix(a, "-include=") || strings.HasPrefix(a, "-exclude=") {
if s := strings.Split(a, "="); len(s) == 2 && s[1] != "" {
if _, err := path.Match(s[1], "xxxx"); err != nil {
logger.Warnf("ignore invalid pattern: %s", a)
continue
}
rules = append(rules, parseRule(s[0], s[1]))
}
}
}
return
}
func filterKey(o object.Object, now time.Time, rules []rule, config *Config) bool {
var ok bool = true
if !o.IsDir() && !o.IsSymlink() {
ok = o.Size() >= int64(config.MinSize) && o.Size() <= int64(config.MaxSize)
if ok && config.MaxAge > 0 {
ok = o.Mtime().After(now.Add(-config.MaxAge))
}
if ok && config.MinAge > 0 {
ok = o.Mtime().Before(now.Add(-config.MinAge))
}
}
if ok {
if config.MatchFullPath {
ok = matchFullPath(rules, o.Key())
} else {
ok = matchLeveledPath(rules, o.Key())
}
}
return ok
}
func filter(keys <-chan object.Object, rules []rule, config *Config) <-chan object.Object {
r := make(chan object.Object)
now := time.Now()
go func() {
for o := range keys {
if o == nil {
// Telling that the listing has failed
r <- nil
break
}
if filterKey(o, now, rules, config) {
r <- o
} else {
logger.Debugf("exclude %s size: %d, mtime: %s", o.Key(), o.Size(), o.Mtime())
}
}
close(r)
}()
return r
}
func matchTwoStar(p string, s []string) bool {
if len(s) == 0 {
return p == "*"
}
idx := strings.Index(p, "**")
if idx == -1 {
ok, _ := path.Match(p, strings.Join(s, "/"))
return ok
}
ok, _ := path.Match(p[:idx+1], s[0])
if !ok {
return false
}
for i := 0; i <= len(s); i++ {
tp := p[idx+1:]
if i == 0 {
tp = p[:idx] + p[idx+1:]
}
if matchTwoStar(tp, s[i:]) {
return true
}
}
return false
}
func matchPrefix(p, s []string) bool {
if len(p) == 0 || len(s) == 0 {
return len(p) == len(s)
}
first := p[0]
n := len(s)
switch {
case first == "***":
return true
case strings.Contains(first, "**"):
for i := 1; i <= n; i++ {
if matchTwoStar(first, s[:i]) && matchPrefix(p[1:], s[i:]) {
return true
}
}
return false
default: