/
uploadheap_test.go
1262 lines (1158 loc) · 40.2 KB
/
uploadheap_test.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
package renter
import (
"bytes"
"fmt"
"io"
"os"
"reflect"
"strings"
"testing"
"time"
"gitlab.com/NebulousLabs/errors"
"go.sia.tech/siad/build"
"go.sia.tech/siad/crypto"
"go.sia.tech/siad/modules"
"go.sia.tech/siad/modules/renter/filesystem"
"go.sia.tech/siad/modules/renter/filesystem/siafile"
"go.sia.tech/siad/persist"
"go.sia.tech/siad/siatest/dependencies"
)
// TestUploadHeap tests the uploadheap subsystem
func TestUploadHeap(t *testing.T) {
if testing.Short() {
t.SkipNow()
}
t.Parallel()
// Basic function tests
t.Run("Basic", testUploadHeapBasic)
// Specific method unit tests
t.Run("managedAddChunkToHeap", testManagedAddChunksToHeap)
t.Run("managedBuildChunkHeap", testManagedBuildChunkHeap)
t.Run("managedBuildUnfinishedChunks", testManagedBuildUnfinishedChunks)
t.Run("managedPushChunkForRepair", testManagedPushChunkForRepair)
t.Run("managedTryUpdate", testManagedTryUpdate)
// Specific condition unit tests
t.Run("AddChunksToHeapPanic", testAddChunksToHeapPanic)
t.Run("AddDirectories", testAddDirectoryBackToHeap)
t.Run("HeapMaps", testUploadHeapMaps)
t.Run("PauseChan", testUploadHeapPauseChan)
t.Run("RemoteChunks", testAddRemoteChunksToHeap)
// Regression Tests
t.Run("Regression_SwitchStuckStatus", testChunkSwitchStuckStatus)
}
// testManagedBuildUnfinishedChunks probes managedBuildUnfinishedChunks to make
// sure that the correct chunks are being added to the heap
func testManagedBuildUnfinishedChunks(t *testing.T) {
// Create Renter
rt, err := newRenterTesterWithDependency(t.Name(), &dependencies.DependencyDisableRepairAndHealthLoops{})
if err != nil {
t.Fatal(err)
}
defer func() {
if err := rt.Close(); err != nil {
t.Fatal(err)
}
}()
// Create file on disk
path, err := rt.createZeroByteFileOnDisk()
if err != nil {
t.Fatal(err)
}
// Create file with more than 1 chunk and mark the first chunk at stuck
rsc, _ := modules.NewRSCode(1, 1)
siaPath, err := modules.NewSiaPath("stuckFile")
if err != nil {
t.Fatal(err)
}
up := modules.FileUploadParams{
Source: path,
SiaPath: siaPath,
ErasureCode: rsc,
}
err = rt.renter.staticFileSystem.NewSiaFile(up.SiaPath, up.Source, up.ErasureCode, crypto.GenerateSiaKey(crypto.RandomCipherType()), 10e3, persist.DefaultDiskPermissionsTest, false)
if err != nil {
t.Fatal(err)
}
f, err := rt.renter.staticFileSystem.OpenSiaFile(up.SiaPath)
if err != nil {
t.Fatal(err)
}
if f.NumChunks() <= 1 {
t.Fatalf("File created with not enough chunks for test, have %v need at least 2", f.NumChunks())
}
if err = f.SetStuck(uint64(0), true); err != nil {
t.Fatal(err)
}
// Create maps to pass into methods
hosts := make(map[string]struct{})
offline := make(map[string]bool)
goodForRenew := make(map[string]bool)
// Manually add workers to worker pool
rt.renter.staticWorkerPool.mu.Lock()
for i := 0; i < int(f.NumChunks()); i++ {
rt.renter.staticWorkerPool.workers[fmt.Sprint(i)] = &worker{}
}
rt.renter.staticWorkerPool.mu.Unlock()
// Call managedBuildUnfinishedChunks as not stuck loop, all un stuck chunks
// should be returned
uucs := rt.renter.managedBuildUnfinishedChunks(f, hosts, targetUnstuckChunks, offline, goodForRenew, rt.renter.repairMemoryManager)
if len(uucs) != int(f.NumChunks())-1 {
t.Fatalf("Incorrect number of chunks returned, expected %v got %v", int(f.NumChunks())-1, len(uucs))
}
for _, c := range uucs {
if c.stuck {
t.Fatal("Found stuck chunk when expecting only unstuck chunks")
}
}
// Call managedBuildUnfinishedChunks as stuck loop, all stuck chunks should
// be returned
uucs = rt.renter.managedBuildUnfinishedChunks(f, hosts, targetStuckChunks, offline, goodForRenew, rt.renter.repairMemoryManager)
if len(uucs) != 1 {
t.Fatalf("Incorrect number of chunks returned, expected 1 got %v", len(uucs))
}
for _, c := range uucs {
if !c.stuck {
t.Fatal("Found unstuck chunk when expecting only stuck chunks")
}
}
// Remove file on disk to make file not repairable
err = os.Remove(path)
if err != nil {
t.Fatal(err)
}
// Call managedBuildUnfinishedChunks as not stuck loop, since the file is
// now not repairable it should return no chunks
uucs = rt.renter.managedBuildUnfinishedChunks(f, hosts, targetUnstuckChunks, offline, goodForRenew, rt.renter.repairMemoryManager)
if len(uucs) != 0 {
t.Fatalf("Incorrect number of chunks returned, expected 0 got %v", len(uucs))
}
// Call managedBuildUnfinishedChunks as stuck loop, all chunks should be
// returned because they should have been marked as stuck by the previous
// call and stuck chunks should still be returned if the file is not
// repairable
uucs = rt.renter.managedBuildUnfinishedChunks(f, hosts, targetStuckChunks, offline, goodForRenew, rt.renter.repairMemoryManager)
if len(uucs) != int(f.NumChunks()) {
t.Fatalf("Incorrect number of chunks returned, expected %v got %v", f.NumChunks(), len(uucs))
}
for _, c := range uucs {
if !c.stuck {
t.Fatal("Found unstuck chunk when expecting only stuck chunks")
}
}
}
// testManagedBuildChunkHeap probes managedBuildChunkHeap to make sure that the
// correct chunks are being added to the heap
func testManagedBuildChunkHeap(t *testing.T) {
// Create Renter
rt, err := newRenterTesterWithDependency(t.Name(), &dependencies.DependencyDisableRepairAndHealthLoops{})
if err != nil {
t.Fatal(err)
}
defer func() {
if err := rt.Close(); err != nil {
t.Fatal(err)
}
}()
// Create 2 files
source, err := rt.createZeroByteFileOnDisk()
if err != nil {
t.Fatal(err)
}
rsc, _ := modules.NewRSCode(1, 1)
up := modules.FileUploadParams{
Source: source,
SiaPath: modules.RandomSiaPath(),
ErasureCode: rsc,
}
err = rt.renter.staticFileSystem.NewSiaFile(up.SiaPath, up.Source, up.ErasureCode, crypto.GenerateSiaKey(crypto.RandomCipherType()), 10e3, persist.DefaultDiskPermissionsTest, false)
if err != nil {
t.Fatal(err)
}
f1, err := rt.renter.staticFileSystem.OpenSiaFile(up.SiaPath)
if err != nil {
t.Fatal(err)
}
// Manually add workers to worker pool and create host map
hosts := make(map[string]struct{})
rt.renter.staticWorkerPool.mu.Lock()
for i := 0; i < int(f1.NumChunks()); i++ {
rt.renter.staticWorkerPool.workers[fmt.Sprint(i)] = &worker{}
}
rt.renter.staticWorkerPool.mu.Unlock()
// Call managedBuildChunkHeap as repair loop, we should see all the chunks
// from the file added
offline, goodForRenew, _ := rt.renter.managedContractUtilityMaps()
rt.renter.managedBuildChunkHeap(modules.RootSiaPath(), hosts, targetUnstuckChunks, offline, goodForRenew)
if rt.renter.uploadHeap.managedLen() != int(f1.NumChunks()) {
t.Fatalf("Expected heap length of %v but got %v", f1.NumChunks(), rt.renter.uploadHeap.managedLen())
}
}
// addChunksOfDifferentHealth is a helper function for TestUploadHeap to add
// numChunks number of chunks that each have different healths to the uploadHeap
func addChunksOfDifferentHealth(r *Renter, numChunks int, priority, fileRecentlySuccessful, stuck, remote bool) error {
var UID siafile.SiafileUID
if priority {
UID = "priority"
} else if fileRecentlySuccessful {
UID = "fileRecentlySuccessful"
} else if stuck {
UID = "stuck"
} else if remote {
UID = "remote"
} else {
UID = "unstuck"
}
// Add numChunks number of chunks to the upload heap. Set the id index and
// health to the value of health. Since health of 0 is full health, start i
// at 1
for i := 1; i <= numChunks; i++ {
chunk := &unfinishedUploadChunk{
id: uploadChunkID{
fileUID: UID,
index: uint64(i),
},
stuck: stuck,
fileRecentlySuccessful: fileRecentlySuccessful,
staticPriority: priority,
health: float64(i),
onDisk: !remote,
staticAvailableChan: make(chan struct{}),
staticUploadCompletedChan: make(chan struct{}),
staticMemoryManager: r.repairMemoryManager,
}
pushed, err := r.managedPushChunkForRepair(chunk, chunkTypeLocalChunk)
if err != nil {
return err
}
if !pushed {
return fmt.Errorf("unable to push chunk: %v", chunk)
}
}
return nil
}
// testUploadHeapBasic probes the basic functionality of the upload heap, such
// as making sure chunks are sorted correctly
func testUploadHeapBasic(t *testing.T) {
// Create renter
rt, err := newRenterTesterWithDependency(t.Name(), &dependencies.DependencyDisableRepairAndHealthLoops{})
if err != nil {
t.Fatal(err)
}
defer func() {
if err := rt.Close(); err != nil {
t.Fatal(err)
}
}()
// Add chunks to heap. Chunks are prioritize by stuck status first and then
// by piecesComplete/piecesNeeded
//
// Add 2 chunks of each type to confirm the type and the health is
// prioritized properly
err = addChunksOfDifferentHealth(rt.renter, 2, true, false, false, false)
if err != nil {
t.Fatal(err)
}
err = addChunksOfDifferentHealth(rt.renter, 2, false, true, false, false)
if err != nil {
t.Fatal(err)
}
err = addChunksOfDifferentHealth(rt.renter, 2, false, false, true, false)
if err != nil {
t.Fatal(err)
}
err = addChunksOfDifferentHealth(rt.renter, 2, false, false, false, true)
if err != nil {
t.Fatal(err)
}
err = addChunksOfDifferentHealth(rt.renter, 2, false, false, false, false)
if err != nil {
t.Fatal(err)
}
// There should be 10 chunks in the heap
if rt.renter.uploadHeap.managedLen() != 10 {
t.Fatalf("Expected %v chunks in heap found %v",
10, rt.renter.uploadHeap.managedLen())
}
// Save chunks
var chunks []*unfinishedUploadChunk
// Check order of chunks
// - First 2 chunks should be priority
// - Second 2 chunks should be fileRecentlyRepair
// - Third 2 chunks should be stuck
// - Fourth 2 chunks should be remote (ie !onDisk)
// - Last 2 chunks should be unstuck
chunk1 := rt.renter.uploadHeap.managedPop()
chunk2 := rt.renter.uploadHeap.managedPop()
if !chunk1.staticPriority || !chunk2.staticPriority {
t.Fatalf("Expected chunks to be priority, got priority %v and %v",
chunk1.staticPriority, chunk2.staticPriority)
}
if chunk1.health < chunk2.health {
t.Fatalf("expected top chunk to have worst health, chunk1: %v, chunk2: %v",
chunk1.health, chunk2.health)
}
topChunk := chunk1
chunks = append(chunks, chunk1, chunk2)
chunk1 = rt.renter.uploadHeap.managedPop()
chunk2 = rt.renter.uploadHeap.managedPop()
if !chunk1.fileRecentlySuccessful || !chunk2.fileRecentlySuccessful {
t.Fatalf("Expected chunks to be fileRecentlySuccessful, got fileRecentlySuccessful %v and %v",
chunk1.fileRecentlySuccessful, chunk2.fileRecentlySuccessful)
}
if chunk1.health < chunk2.health {
t.Fatalf("expected top chunk to have worst health, chunk1: %v, chunk2: %v",
chunk1.health, chunk2.health)
}
chunks = append(chunks, chunk1, chunk2)
chunk1 = rt.renter.uploadHeap.managedPop()
chunk2 = rt.renter.uploadHeap.managedPop()
if !chunk1.stuck || !chunk2.stuck {
t.Fatalf("Expected chunks to be stuck, got stuck %v and %v",
chunk1.stuck, chunk2.stuck)
}
if chunk1.health < chunk2.health {
t.Fatalf("expected top chunk to have worst health, chunk1: %v, chunk2: %v",
chunk1.health, chunk2.health)
}
chunks = append(chunks, chunk1, chunk2)
chunk1 = rt.renter.uploadHeap.managedPop()
chunk2 = rt.renter.uploadHeap.managedPop()
if chunk1.onDisk || chunk2.onDisk {
t.Fatalf("Expected chunks to be remote and not onDisk, got onDisk %v and %v",
chunk1.onDisk, chunk2.onDisk)
}
if chunk1.health < chunk2.health {
t.Fatalf("expected top chunk to have worst health, chunk1: %v, chunk2: %v",
chunk1.health, chunk2.health)
}
middleChunk := chunk1
chunks = append(chunks, chunk1, chunk2)
chunk1 = rt.renter.uploadHeap.managedPop()
chunk2 = rt.renter.uploadHeap.managedPop()
if chunk1.health < chunk2.health {
t.Fatalf("expected top chunk to have worst health, chunk1: %v, chunk2: %v",
chunk1.health, chunk2.health)
}
bottomChunk := chunk2
chunks = append(chunks, chunk1, chunk2)
// Clear and reset the heap
uh := &rt.renter.uploadHeap
err = uh.managedReset()
if err != nil {
t.Fatal(err)
}
uh.mu.Lock()
uh.repairingChunks = make(map[uploadChunkID]*unfinishedUploadChunk)
uh.mu.Unlock()
// Add the chunks back to the heap
for _, chunk := range chunks {
pushed, err := rt.renter.managedPushChunkForRepair(chunk, chunkTypeLocalChunk)
if err != nil {
t.Fatal(err)
}
if !pushed {
t.Fatal("chunk not pushed")
}
}
// Test removing the top chunk
uh.mu.Lock()
uh.heap.removeByID(topChunk)
if uh.heap.Len() != len(chunks)-1 {
t.Fatal("Chunk not removed from heap")
}
// Test removing the bottom chunk
uh.heap.removeByID(bottomChunk)
if uh.heap.Len() != len(chunks)-2 {
t.Fatal("Chunk not removed from heap")
}
// Test removing a chunk in the middle
uh.heap.removeByID(middleChunk)
if uh.heap.Len() != len(chunks)-3 {
t.Fatal("Chunk not removed from heap")
}
uh.mu.Unlock()
}
// testManagedAddChunksToHeap probes the managedAddChunksToHeap method to ensure
// it is functioning as intended
func testManagedAddChunksToHeap(t *testing.T) {
// Create Renter
rt, err := newRenterTesterWithDependency(t.Name(), &dependencies.DependencyDisableRepairAndHealthLoops{})
if err != nil {
t.Fatal(err)
}
defer func() {
if err := rt.Close(); err != nil {
t.Fatal(err)
}
}()
// Create File params
rsc, _ := modules.NewRSCode(1, 1) // Minimum erasure coding
source, err := rt.createZeroByteFileOnDisk()
if err != nil {
t.Fatal(err)
}
up := modules.FileUploadParams{
Source: source,
ErasureCode: rsc,
}
// Create files in multiple directories
var numChunks uint64
dirSiaPaths := rt.renter.newUniqueRefreshPaths()
names := []string{"rootFile", "subdir/File", "subdir2/file"}
for _, name := range names {
siaPath, err := modules.NewSiaPath(name)
if err != nil {
t.Fatal(err)
}
up.SiaPath = siaPath
// File size 100 to help ensure only 1 chunk per file
err = rt.renter.staticFileSystem.NewSiaFile(up.SiaPath, up.Source, up.ErasureCode, crypto.GenerateSiaKey(crypto.RandomCipherType()), 100, persist.DefaultDiskPermissionsTest, false)
if err != nil {
t.Fatal(err)
}
f, err := rt.renter.staticFileSystem.OpenSiaFile(up.SiaPath)
if err != nil {
t.Fatal(err)
}
// Track number of chunks
numChunks += f.NumChunks()
dirSiaPath, err := siaPath.Dir()
if err != nil {
t.Fatal(err)
}
// Close File
err = f.Close()
if err != nil {
t.Fatal(err)
}
// Make sure directories are created
err = rt.renter.CreateDir(dirSiaPath, modules.DefaultDirPerm)
if err != nil && !errors.Contains(err, filesystem.ErrExists) {
t.Fatal(err)
}
err = dirSiaPaths.callAdd(dirSiaPath)
if err != nil {
t.Fatal(err)
}
}
// Call bubbled to ensure directory metadata is updated
dirSiaPaths.callRefreshAllBlocking()
// Wait until the root health has been updated
err = build.Retry(100, 100*time.Millisecond, func() error {
rd, err := rt.renter.DirList(modules.RootSiaPath())
if err != nil {
return err
}
if rd[0].Health == 0 {
return errors.New("root health not updated")
}
return nil
})
if err != nil {
t.Fatal(err)
}
// Manually add workers to worker pool and create host map
hosts := make(map[string]struct{})
rt.renter.staticWorkerPool.mu.Lock()
for i := 0; i < rsc.MinPieces(); i++ {
rt.renter.staticWorkerPool.workers[fmt.Sprint(i)] = &worker{}
}
rt.renter.staticWorkerPool.mu.Unlock()
// Make sure directory Heap is ready
err = rt.renter.managedPushUnexploredDirectory(modules.RootSiaPath())
if err != nil {
t.Fatal(err)
}
// call managedAddChunksTo Heap
siaPaths, err := rt.renter.managedAddChunksToHeap(hosts)
if err != nil {
t.Fatal(err)
}
// Confirm that all chunks from all the directories were added since there
// are not enough chunks in only one directory to fill the heap
totalDirs := len(siaPaths.childDirs) + len(siaPaths.parentDirs)
if totalDirs != 3 {
t.Fatal("Expected 3 siaPaths to be returned, got", totalDirs)
}
if rt.renter.uploadHeap.managedLen() != int(numChunks) {
t.Fatalf("Expected uploadHeap to have %v chunks but it has %v chunks", numChunks, rt.renter.uploadHeap.managedLen())
}
}
// testAddRemoteChunksToHeap probes how the upload heap handles adding chunks
// when there are remote chunks present
func testAddRemoteChunksToHeap(t *testing.T) {
// Create Renter with dependencies that prevent the background repair
// loop from running as well as ensure that chunks viewed as not
// repairable are added to the heap.
rt, err := newRenterTesterWithDependency(t.Name(), &dependencies.DependencyAddUnrepairableChunks{})
if err != nil {
t.Fatal(err)
}
defer func() {
if err := rt.Close(); err != nil {
t.Fatal(err)
}
}()
// Create a local file for the local file uploads
source, err := rt.createZeroByteFileOnDisk()
if err != nil {
t.Fatal(err)
}
// Create common File params
_, rsc := testingFileParams()
up := modules.FileUploadParams{
ErasureCode: rsc,
}
// Create local and remote files in the root directory an a sub directory
var numChunks int
dirSiaPaths := rt.renter.newUniqueRefreshPaths()
names := []string{"remoteFile", "localFile", "sub/remoteFile", "sub/localFile"}
for _, name := range names {
// Create the SiaPath for the file
siaPath, err := modules.NewSiaPath(name)
if err != nil {
t.Fatal(err)
}
// Update the upload params
up.SiaPath = siaPath
if strings.Contains(name, "remoteFile") {
up.Source = ""
}
if strings.Contains(name, "localFile") {
up.Source = source
}
// Create the siafile and open it. Filesize is small as the files need
// to each only have one chunk. This is because there are 4 files and
// the uploadHeap size for testing is 5. If there are more than 5 chunks
// total the test will fail and not hit the intended test case.
err = rt.renter.staticFileSystem.NewSiaFile(up.SiaPath, up.Source, up.ErasureCode, crypto.GenerateSiaKey(crypto.RandomCipherType()), 100, persist.DefaultDiskPermissionsTest, false)
if err != nil {
t.Fatal(err)
}
f, err := rt.renter.staticFileSystem.OpenSiaFile(up.SiaPath)
if err != nil {
t.Fatal(err)
}
// Track number of chunks
numChunks += int(f.NumChunks())
// Make sure directories are created
dirSiaPath, err := siaPath.Dir()
if err != nil {
t.Fatal(err)
}
err = rt.renter.CreateDir(dirSiaPath, modules.DefaultDirPerm)
if err != nil && !errors.Contains(err, filesystem.ErrExists) {
t.Fatal(err)
}
dirSiaPaths.callAdd(dirSiaPath)
}
// Call bubbled to ensure directory metadata is updated
err = dirSiaPaths.callRefreshAll()
if err != nil {
t.Fatal(err)
}
// Block until all bubbles are done
rt.managedBlockUntilBubblesComplete()
// Manually add workers to worker pool and create host map
hosts := make(map[string]struct{})
rt.renter.staticWorkerPool.mu.Lock()
for i := 0; i < rsc.MinPieces(); i++ {
rt.renter.staticWorkerPool.workers[fmt.Sprint(i)] = &worker{}
}
rt.renter.staticWorkerPool.mu.Unlock()
// Make sure directory Heap is ready
err = rt.renter.managedPushUnexploredDirectory(modules.RootSiaPath())
if err != nil {
t.Fatal(err)
}
// call managedAddChunksToHeap
_, err = rt.renter.managedAddChunksToHeap(hosts)
if err != nil {
t.Fatal(err)
}
// Since there are fewer chunks than the max size of the heap, the repair
// code will add all the chunks to the heap.
//
// NOTE: through print statements it was validated that the test starts with
// trying to add the chunks from the root directory. The local file is
// skipped because the directory heap has a remote file in it. The remote
// file in the root directory is added and the root directory is added back
// to the directory heap, this time it is not seen as remote because the
// remote file has already been added.
//
// The sub directory is then popped, since no more remote files are seen in
// the directory heap, both the remote and local chunks are added.
//
// Then the root directory is popped again and now the local file is added.
if rt.renter.uploadHeap.managedLen() != numChunks {
t.Fatalf("Expected uploadHeap to have %v chunks but it has %v chunks", numChunks, rt.renter.uploadHeap.managedLen())
}
}
// testAddDirectoryBackToHeap ensures that when not all the chunks in a
// directory are added to the uploadHeap that the directory is added back to the
// directoryHeap with an updated Health
func testAddDirectoryBackToHeap(t *testing.T) {
// Create Renter with interrupt dependency
rt, err := newRenterTesterWithDependency(t.Name(), &dependencies.DependencyDisableRepairAndHealthLoops{})
if err != nil {
t.Fatal(err)
}
defer func() {
if err := rt.Close(); err != nil {
t.Fatal(err)
}
}()
// Create file
rsc, _ := modules.NewRSCode(1, 1)
siaPath, err := modules.NewSiaPath("test")
if err != nil {
t.Fatal(err)
}
source, err := rt.createZeroByteFileOnDisk()
if err != nil {
t.Fatal(err)
}
up := modules.FileUploadParams{
Source: source,
SiaPath: siaPath,
ErasureCode: rsc,
}
err = rt.renter.staticFileSystem.NewSiaFile(up.SiaPath, up.Source, up.ErasureCode, crypto.GenerateSiaKey(crypto.RandomCipherType()), modules.SectorSize, persist.DefaultDiskPermissionsTest, false)
if err != nil {
t.Fatal(err)
}
f, err := rt.renter.staticFileSystem.OpenSiaFile(up.SiaPath)
if err != nil {
t.Fatal(err)
}
// Create maps for method inputs
hosts := make(map[string]struct{})
offline := make(map[string]bool)
goodForRenew := make(map[string]bool)
// Manually add workers to worker pool
rt.renter.staticWorkerPool.mu.Lock()
for i := 0; i < int(f.NumChunks()); i++ {
rt.renter.staticWorkerPool.workers[fmt.Sprint(i)] = &worker{}
}
rt.renter.staticWorkerPool.mu.Unlock()
// Confirm we are starting with an empty upload and directory heap
if rt.renter.uploadHeap.managedLen() != 0 {
t.Fatal("Expected upload heap to be empty but has length of", rt.renter.uploadHeap.managedLen())
}
// Directory Heap is also empty when using renter with dependencies.
if rt.renter.directoryHeap.managedLen() != 0 {
t.Fatal("Expected directory heap to be empty but has length of", rt.renter.directoryHeap.managedLen())
}
// Add chunks from file to uploadHeap
rt.renter.callBuildAndPushChunks([]*filesystem.FileNode{f}, hosts, targetUnstuckChunks, offline, goodForRenew)
// Upload heap should now have NumChunks chunks and directory heap should still be empty
if rt.renter.uploadHeap.managedLen() != int(f.NumChunks()) {
t.Fatalf("Expected upload heap to be of size %v but was %v", f.NumChunks(), rt.renter.uploadHeap.managedLen())
}
if rt.renter.directoryHeap.managedLen() != 0 {
t.Fatal("Expected directory heap to be empty but has length of", rt.renter.directoryHeap.managedLen())
}
// Empty uploadHeap
rt.renter.uploadHeap.managedReset()
// Fill upload heap with chunks that are a worse health than the chunks in
// the file
var i uint64
for rt.renter.uploadHeap.managedLen() < maxUploadHeapChunks {
chunk := &unfinishedUploadChunk{
id: uploadChunkID{
fileUID: "chunk",
index: i,
},
stuck: false,
piecesCompleted: -1,
staticPiecesNeeded: 1,
staticAvailableChan: make(chan struct{}),
staticUploadCompletedChan: make(chan struct{}),
staticMemoryManager: rt.renter.repairMemoryManager,
}
pushed, err := rt.renter.managedPushChunkForRepair(chunk, chunkTypeLocalChunk)
if err != nil {
t.Fatal(err)
}
if !pushed {
t.Fatal("Chunk should have been added to heap")
}
i++
}
// Record length of upload heap
uploadHeapLen := rt.renter.uploadHeap.managedLen()
// Try and add chunks to upload heap again
rt.renter.callBuildAndPushChunks([]*filesystem.FileNode{f}, hosts, targetUnstuckChunks, offline, goodForRenew)
// No chunks should have been added to the upload heap
if rt.renter.uploadHeap.managedLen() != uploadHeapLen {
t.Fatalf("Expected upload heap to be of size %v but was %v", uploadHeapLen, rt.renter.uploadHeap.managedLen())
}
// There should be one directory in the directory heap now
if rt.renter.directoryHeap.managedLen() != 1 {
t.Fatal("Expected directory heap to have 1 element but has length of", rt.renter.directoryHeap.managedLen())
}
// The directory should be marked as explored
d := rt.renter.directoryHeap.managedPop()
if !d.explored {
t.Fatal("Directory should be explored")
}
// The directory should be the root directory as that is where we created
// the test file
if !d.staticSiaPath.Equals(modules.RootSiaPath()) {
t.Fatal("Expected Directory siapath to be the root siaPath but was", d.staticSiaPath.String())
}
// The directory health should be that of the file since none of the chunks
// were added
health, _, _, _, _, _, _ := f.Health(offline, goodForRenew)
if d.health != health {
t.Fatalf("Expected directory health to be %v but was %v", health, d.health)
}
}
// testUploadHeapMaps tests that the uploadHeap's maps are properly updated
// through pushing, popping, and resetting the heap
func testUploadHeapMaps(t *testing.T) {
// Create renter
rt, err := newRenterTesterWithDependency(t.Name(), &dependencies.DependencyDisableRepairAndHealthLoops{})
if err != nil {
t.Fatal(err)
}
defer func() {
if err := rt.Close(); err != nil {
t.Fatal(err)
}
}()
// Add stuck and unstuck chunks to heap to fill up the heap maps
numHeapChunks := uint64(10)
sf, err := rt.renter.newRenterTestFile()
if err != nil {
t.Fatal(err)
}
for i := uint64(0); i < numHeapChunks; i++ {
// Create minimum chunk
stuck := i%2 == 0
chunk := &unfinishedUploadChunk{
id: uploadChunkID{
fileUID: siafile.SiafileUID(fmt.Sprintf("chunk - %v", i)),
index: i,
},
fileEntry: sf.Copy(),
stuck: stuck,
piecesCompleted: 1,
staticPiecesNeeded: 1,
staticAvailableChan: make(chan struct{}),
staticUploadCompletedChan: make(chan struct{}),
staticMemoryManager: rt.renter.repairMemoryManager,
}
// push chunk to heap
pushed, err := rt.renter.managedPushChunkForRepair(chunk, chunkTypeLocalChunk)
if err != nil {
t.Fatal(err)
}
if !pushed {
t.Fatal("unable to push chunk", chunk)
}
// Confirm chunk is in the correct map
if stuck {
_, ok := rt.renter.uploadHeap.stuckHeapChunks[chunk.id]
if !ok {
t.Fatal("stuck chunk not in stuck chunk heap map")
}
} else {
_, ok := rt.renter.uploadHeap.unstuckHeapChunks[chunk.id]
if !ok {
t.Fatal("unstuck chunk not in unstuck chunk heap map")
}
}
}
// Close original siafile entry
sf.Close()
// Confirm length of maps
if len(rt.renter.uploadHeap.unstuckHeapChunks) != int(numHeapChunks/2) {
t.Fatalf("Expected %v unstuck chunks in map but found %v", numHeapChunks/2, len(rt.renter.uploadHeap.unstuckHeapChunks))
}
if len(rt.renter.uploadHeap.stuckHeapChunks) != int(numHeapChunks/2) {
t.Fatalf("Expected %v stuck chunks in map but found %v", numHeapChunks/2, len(rt.renter.uploadHeap.stuckHeapChunks))
}
if len(rt.renter.uploadHeap.repairingChunks) != 0 {
t.Fatalf("Expected %v repairing chunks in map but found %v", 0, len(rt.renter.uploadHeap.repairingChunks))
}
// Pop off some chunks
poppedChunks := 3
for i := 0; i < poppedChunks; i++ {
// Pop chunk
chunk := rt.renter.uploadHeap.managedPop()
// Confirm it is in the repairing map
_, ok := rt.renter.uploadHeap.repairingChunks[chunk.id]
if !ok {
t.Fatal("popped chunk not found in repairing map")
}
// Confirm the chunk cannot be pushed back onto the heap
pushed, err := rt.renter.managedPushChunkForRepair(chunk, chunkTypeLocalChunk)
if err != nil {
t.Fatal(err)
}
if pushed {
t.Fatal("should not have been able to push chunk back onto heap")
}
}
// Confirm length of maps
if len(rt.renter.uploadHeap.repairingChunks) != poppedChunks {
t.Fatalf("Expected %v repairing chunks in map but found %v", poppedChunks, len(rt.renter.uploadHeap.repairingChunks))
}
remainingChunks := len(rt.renter.uploadHeap.unstuckHeapChunks) + len(rt.renter.uploadHeap.stuckHeapChunks)
if remainingChunks != int(numHeapChunks)-poppedChunks {
t.Fatalf("Expected %v chunks to still be in the heap maps but found %v", int(numHeapChunks)-poppedChunks, remainingChunks)
}
// Reset the heap
if err := rt.renter.uploadHeap.managedReset(); err != nil {
t.Fatal(err)
}
// Confirm length of maps
if len(rt.renter.uploadHeap.repairingChunks) != poppedChunks {
t.Fatalf("Expected %v repairing chunks in map but found %v", poppedChunks, len(rt.renter.uploadHeap.repairingChunks))
}
remainingChunks = len(rt.renter.uploadHeap.unstuckHeapChunks) + len(rt.renter.uploadHeap.stuckHeapChunks)
if remainingChunks != 0 {
t.Fatalf("Expected %v chunks to still be in the heap maps but found %v", 0, remainingChunks)
}
}
// testUploadHeapPauseChan makes sure that sequential calls to pause and resume
// won't cause panics for closing a closed channel
func testUploadHeapPauseChan(t *testing.T) {
// Initial UploadHeap with the pauseChan initialized such that the uploads
// and repairs are not paused
uh := uploadHeap{
pauseChan: make(chan struct{}),
}
close(uh.pauseChan)
if uh.managedIsPaused() {
t.Error("Repairs and Uploads should not be paused")
}
// Call resume on an initialized heap
uh.managedResume()
// Call Pause twice in a row
uh.managedPause(DefaultPauseDuration)
uh.managedPause(DefaultPauseDuration)
// Call Resume twice in a row
uh.managedResume()
uh.managedResume()
}
// testChunkSwitchStuckStatus is a regression test that confirms the upload heap
// won't panic due to a chunk's stuck status changing while it is in the heap
// and being added twice
func testChunkSwitchStuckStatus(t *testing.T) {
// Create renter
rt, err := newRenterTesterWithDependency(t.Name(), &dependencies.DependencyDisableRepairAndHealthLoops{})
if err != nil {
t.Fatal(err)
}
defer func() {
if err := rt.Close(); err != nil {
t.Fatal(err)
}
}()
// Create minimum chunk
chunk := &unfinishedUploadChunk{
id: uploadChunkID{
fileUID: siafile.SiafileUID("chunk"),
index: 0,
},
staticMemoryManager: rt.renter.repairMemoryManager,
}
// push chunk to heap
pushed, err := rt.renter.managedPushChunkForRepair(chunk, chunkTypeLocalChunk)
if err != nil {
t.Fatal(err)
}
if !pushed {
t.Fatal("unable to push chunk", chunk)
}
if rt.renter.uploadHeap.managedLen() != 1 {
t.Error("Expected only 1 chunk in heap")
}
// Mark chunk as stuck and push again
//
// Regression check 1: previously this second push call would succeed and
// the length of the heap would be 2
chunk.stuck = true
pushed, err = rt.renter.managedPushChunkForRepair(chunk, chunkTypeLocalChunk)
if err != nil {
t.Fatal(err)
}
if pushed {
t.Error("should not be able to push chunk again")
}
if rt.renter.uploadHeap.managedLen() != 1 {
t.Error("Expected only 1 chunk in heap")
}
// Pop the chunk
chunk = rt.renter.uploadHeap.managedPop()
if chunk == nil {
t.Fatal("Nil chunk popped")
}
// A second pop call should not panic
//
// Regression check 2: previously this would trigger the build.Critical that
// the popped chunk was already in the repair map
chunk = rt.renter.uploadHeap.managedPop()
if chunk != nil {
t.Fatal("Expected nil chunk")
}
}
// testManagedPushChunkForRepair probes the Renter's managedPushChunkForRepair
// method with the streamChunk type
func testManagedPushChunkForRepair(t *testing.T) {
// Create renter
rt, err := newRenterTesterWithDependency(t.Name(), &dependencies.DependencySkipPrepareNextChunk{})
if err != nil {
t.Fatal(err)
}
defer func() {
if err := rt.Close(); err != nil {
t.Fatal(err)
}
}()
uh := &rt.renter.uploadHeap
// Create a stream chunk
file, err := rt.renter.newRenterTestFile()
if err != nil {
t.Fatal(err)
}
defer func() {