forked from viamrobotics/rdk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsync_test.go
885 lines (796 loc) · 26.5 KB
/
sync_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
package builtin
import (
"context"
"io"
"os"
"path/filepath"
"sort"
"sync/atomic"
"testing"
"time"
clk "github.com/benbjohnson/clock"
"github.com/edaniels/golog"
"github.com/pkg/errors"
v1 "go.viam.com/api/app/datasync/v1"
"go.viam.com/test"
"google.golang.org/grpc"
"go.viam.com/rdk/resource"
"go.viam.com/rdk/services/datamanager/datacapture"
"go.viam.com/rdk/services/datamanager/datasync"
)
const (
syncIntervalMins = 0.0008
syncInterval = time.Millisecond * 50
)
// TODO DATA-849: Add a test that validates that sync interval is accurately respected.
func TestSyncEnabled(t *testing.T) {
captureInterval := time.Millisecond * 10
tests := []struct {
name string
initialServiceDisableStatus bool
newServiceDisableStatus bool
}{
{
name: "config with sync disabled should sync nothing",
initialServiceDisableStatus: true,
newServiceDisableStatus: true,
},
{
name: "config with sync enabled should sync",
initialServiceDisableStatus: false,
newServiceDisableStatus: false,
},
{
name: "disabling sync should stop syncing",
initialServiceDisableStatus: false,
newServiceDisableStatus: true,
},
{
name: "enabling sync should trigger syncing to start",
initialServiceDisableStatus: true,
newServiceDisableStatus: false,
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
// Set up server.
mockClock := clk.NewMock()
// Make mockClock the package level clock used by the dmsvc so that we can simulate time's passage
clock = mockClock
tmpDir := t.TempDir()
// Set up data manager.
dmsvc, r := newTestDataManager(t)
defer dmsvc.Close(context.Background())
mockClient := mockDataSyncServiceClient{
succesfulDCRequests: make(chan *v1.DataCaptureUploadRequest, 100),
failedDCRequests: make(chan *v1.DataCaptureUploadRequest, 100),
fail: &atomic.Bool{},
}
dmsvc.SetSyncerConstructor(getTestSyncerConstructorMock(mockClient))
cfg, deps := setupConfig(t, enabledBinaryCollectorConfigPath)
// Set up service config.
cfg.CaptureDisabled = false
cfg.ScheduledSyncDisabled = tc.initialServiceDisableStatus
cfg.CaptureDir = tmpDir
cfg.SyncIntervalMins = syncIntervalMins
resources := resourcesFromDeps(t, r, deps)
err := dmsvc.Reconfigure(context.Background(), resources, resource.Config{
ConvertedAttributes: cfg,
})
test.That(t, err, test.ShouldBeNil)
mockClock.Add(captureInterval)
waitForCaptureFilesToExceedNFiles(tmpDir, 0)
mockClock.Add(syncInterval)
var sentReq bool
wait := time.After(time.Second)
select {
case <-wait:
case <-mockClient.succesfulDCRequests:
sentReq = true
}
if !tc.initialServiceDisableStatus {
test.That(t, sentReq, test.ShouldBeTrue)
} else {
test.That(t, sentReq, test.ShouldBeFalse)
}
// Set up service config.
cfg.CaptureDisabled = false
cfg.ScheduledSyncDisabled = tc.newServiceDisableStatus
cfg.CaptureDir = tmpDir
cfg.SyncIntervalMins = syncIntervalMins
resources = resourcesFromDeps(t, r, deps)
err = dmsvc.Reconfigure(context.Background(), resources, resource.Config{
ConvertedAttributes: cfg,
})
test.That(t, err, test.ShouldBeNil)
// Drain any requests that were already sent before Update returned.
for len(mockClient.succesfulDCRequests) > 0 {
<-mockClient.succesfulDCRequests
}
var sentReqAfterUpdate bool
mockClock.Add(captureInterval)
waitForCaptureFilesToExceedNFiles(tmpDir, 0)
mockClock.Add(syncInterval)
wait = time.After(time.Second)
select {
case <-wait:
case <-mockClient.succesfulDCRequests:
sentReqAfterUpdate = true
}
err = dmsvc.Close(context.Background())
test.That(t, err, test.ShouldBeNil)
if !tc.newServiceDisableStatus {
test.That(t, sentReqAfterUpdate, test.ShouldBeTrue)
} else {
test.That(t, sentReqAfterUpdate, test.ShouldBeFalse)
}
})
}
}
// TODO DATA-849: Test concurrent capture and sync more thoroughly.
func TestDataCaptureUploadIntegration(t *testing.T) {
// Set exponential factor to 1 and retry wait time to 20ms so retries happen very quickly.
datasync.RetryExponentialFactor.Store(int32(1))
datasync.InitialWaitTimeMillis.Store(int32(20))
tests := []struct {
name string
dataType v1.DataType
manualSync bool
scheduledSyncDisabled bool
failTransiently bool
emptyFile bool
}{
{
name: "previously captured tabular data should be synced at start up",
dataType: v1.DataType_DATA_TYPE_TABULAR_SENSOR,
},
{
name: "previously captured binary data should be synced at start up",
dataType: v1.DataType_DATA_TYPE_BINARY_SENSOR,
},
{
name: "manual sync should successfully sync captured tabular data",
dataType: v1.DataType_DATA_TYPE_TABULAR_SENSOR,
manualSync: true,
scheduledSyncDisabled: true,
},
{
name: "manual sync should successfully sync captured binary data",
dataType: v1.DataType_DATA_TYPE_BINARY_SENSOR,
manualSync: true,
scheduledSyncDisabled: true,
},
{
name: "running manual and scheduled sync concurrently should not cause data races or duplicate uploads",
dataType: v1.DataType_DATA_TYPE_TABULAR_SENSOR,
manualSync: true,
},
{
name: "if tabular uploads fail transiently, they should be retried until they succeed",
dataType: v1.DataType_DATA_TYPE_TABULAR_SENSOR,
failTransiently: true,
},
{
name: "if binary uploads fail transiently, they should be retried until they succeed",
dataType: v1.DataType_DATA_TYPE_BINARY_SENSOR,
failTransiently: true,
},
{
name: "files with no sensor data should not be synced",
emptyFile: true,
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
// Set up server.
mockClock := clk.NewMock()
clock = mockClock
tmpDir := t.TempDir()
// Set up data manager.
dmsvc, r := newTestDataManager(t)
defer dmsvc.Close(context.Background())
var cfg *Config
var deps []string
captureInterval := time.Millisecond * 10
if tc.emptyFile {
cfg, deps = setupConfig(t, infrequentCaptureTabularCollectorConfigPath)
} else {
if tc.dataType == v1.DataType_DATA_TYPE_TABULAR_SENSOR {
cfg, deps = setupConfig(t, enabledTabularCollectorConfigPath)
} else {
cfg, deps = setupConfig(t, enabledBinaryCollectorConfigPath)
}
}
// Set up service config with only capture enabled.
cfg.CaptureDisabled = false
cfg.ScheduledSyncDisabled = true
cfg.SyncIntervalMins = syncIntervalMins
cfg.CaptureDir = tmpDir
resources := resourcesFromDeps(t, r, deps)
err := dmsvc.Reconfigure(context.Background(), resources, resource.Config{
ConvertedAttributes: cfg,
})
test.That(t, err, test.ShouldBeNil)
// Let it capture a bit, then close.
for i := 0; i < 20; i++ {
mockClock.Add(captureInterval)
}
err = dmsvc.Close(context.Background())
test.That(t, err, test.ShouldBeNil)
// Get all captured data.
numFiles, capturedData, err := getCapturedData(tmpDir)
test.That(t, err, test.ShouldBeNil)
if tc.emptyFile {
test.That(t, len(capturedData), test.ShouldEqual, 0)
} else {
test.That(t, len(capturedData), test.ShouldBeGreaterThan, 0)
}
// Turn dmsvc back on with capture disabled.
newDMSvc, r := newTestDataManager(t)
defer newDMSvc.Close(context.Background())
mockClient := mockDataSyncServiceClient{
succesfulDCRequests: make(chan *v1.DataCaptureUploadRequest, 100),
failedDCRequests: make(chan *v1.DataCaptureUploadRequest, 100),
fail: &atomic.Bool{},
}
newDMSvc.SetSyncerConstructor(getTestSyncerConstructorMock(mockClient))
cfg.CaptureDisabled = true
cfg.ScheduledSyncDisabled = tc.scheduledSyncDisabled
cfg.SyncIntervalMins = syncIntervalMins
resources = resourcesFromDeps(t, r, deps)
err = newDMSvc.Reconfigure(context.Background(), resources, resource.Config{
ConvertedAttributes: cfg,
})
test.That(t, err, test.ShouldBeNil)
if tc.failTransiently {
// Simulate the backend returning errors some number of times, and validate that the dmsvc is continuing
// to retry.
numFails := 3
mockClient.fail.Store(true)
for i := 0; i < numFails; i++ {
mockClock.Add(syncInterval)
// Each time we sync, we should get a sync request for each file.
for j := 0; j < numFiles; j++ {
wait := time.After(time.Second * 5)
select {
case <-wait:
t.Fatalf("timed out waiting for sync request")
case <-mockClient.failedDCRequests:
}
}
}
}
mockClient.fail.Store(false)
// If testing manual sync, call sync. Call it multiple times to ensure concurrent calls are safe.
if tc.manualSync {
err = newDMSvc.Sync(context.Background(), nil)
test.That(t, err, test.ShouldBeNil)
err = newDMSvc.Sync(context.Background(), nil)
test.That(t, err, test.ShouldBeNil)
}
var successfulReqs []*v1.DataCaptureUploadRequest
// Get the successful requests
mockClock.Add(syncInterval)
for i := 0; i < numFiles; i++ {
wait := time.After(time.Second * 5)
select {
case <-wait:
t.Fatalf("timed out waiting for sync request")
case r := <-mockClient.succesfulDCRequests:
successfulReqs = append(successfulReqs, r)
}
}
// Give it time to delete files after upload.
waitUntilNoFiles(tmpDir)
err = newDMSvc.Close(context.Background())
test.That(t, err, test.ShouldBeNil)
// Validate that all captured data was synced.
syncedData := getUploadedData(successfulReqs)
compareSensorData(t, tc.dataType, syncedData, capturedData)
// After all uploads succeed, all files should be deleted.
test.That(t, len(getAllFileInfos(tmpDir)), test.ShouldEqual, 0)
})
}
}
func TestArbitraryFileUpload(t *testing.T) {
// Set exponential factor to 1 and retry wait time to 20ms so retries happen very quickly.
datasync.RetryExponentialFactor.Store(int32(1))
fileName := "some_file_name.txt"
fileExt := ".txt"
tests := []struct {
name string
manualSync bool
scheduleSyncDisabled bool
}{
{
name: "scheduled sync of arbitrary files should work",
manualSync: false,
scheduleSyncDisabled: false,
},
{
name: "manual sync of arbitrary files should work",
manualSync: true,
scheduleSyncDisabled: true,
},
{
name: "running manual and scheduled sync concurrently should work and not lead to duplicate uploads",
manualSync: true,
scheduleSyncDisabled: false,
},
{
name: "if an error response is received from the backend, local files should not be deleted",
manualSync: false,
scheduleSyncDisabled: false,
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
// Set up server.
mockClock := clk.NewMock()
clock = mockClock
additionalPathsDir := t.TempDir()
captureDir := t.TempDir()
// Set up dmsvc config.
dmsvc, r := newTestDataManager(t)
dmsvc.SetWaitAfterLastModifiedMillis(0)
defer dmsvc.Close(context.Background())
mockClient := mockDataSyncServiceClient{
succesfulDCRequests: make(chan *v1.DataCaptureUploadRequest, 100),
failedDCRequests: make(chan *v1.DataCaptureUploadRequest, 100),
fileUploads: make(chan *mockFileUploadClient, 100),
fail: &atomic.Bool{},
}
dmsvc.SetSyncerConstructor(getTestSyncerConstructorMock(mockClient))
cfg, deps := setupConfig(t, disabledTabularCollectorConfigPath)
cfg.ScheduledSyncDisabled = tc.scheduleSyncDisabled
cfg.SyncIntervalMins = syncIntervalMins
cfg.AdditionalSyncPaths = []string{additionalPathsDir}
cfg.CaptureDir = captureDir
// Start dmsvc.
resources := resourcesFromDeps(t, r, deps)
err := dmsvc.Reconfigure(context.Background(), resources, resource.Config{
ConvertedAttributes: cfg,
})
test.That(t, err, test.ShouldBeNil)
// Write file to the path.
var fileContents []byte
for i := 0; i < 1000; i++ {
fileContents = append(fileContents, []byte("happy cows come from california\n")...)
}
tmpFile, err := os.Create(filepath.Join(additionalPathsDir, fileName))
test.That(t, err, test.ShouldBeNil)
_, err = tmpFile.Write(fileContents)
test.That(t, err, test.ShouldBeNil)
test.That(t, tmpFile.Close(), test.ShouldBeNil)
// Advance the clock syncInterval so it tries to sync the files.
mockClock.Add(syncInterval)
// Call manual sync.
if tc.manualSync {
err = dmsvc.Sync(context.Background(), nil)
test.That(t, err, test.ShouldBeNil)
}
// Wait for upload requests.
var fileUploads []*mockFileUploadClient
var urs []*v1.FileUploadRequest
// Get the successful requests
wait := time.After(time.Second * 5)
select {
case <-wait:
t.Fatalf("timed out waiting for sync request")
case r := <-mockClient.fileUploads:
fileUploads = append(fileUploads, r)
select {
case <-wait:
t.Fatalf("timed out waiting for sync request")
case <-r.closed:
urs = append(urs, r.urs...)
}
}
// Validate error and URs.
// Validate first metadata message.
test.That(t, len(fileUploads), test.ShouldEqual, 1)
test.That(t, len(urs), test.ShouldBeGreaterThan, 0)
actMD := urs[0].GetMetadata()
test.That(t, actMD, test.ShouldNotBeNil)
test.That(t, actMD.Type, test.ShouldEqual, v1.DataType_DATA_TYPE_FILE)
test.That(t, actMD.FileName, test.ShouldEqual, fileName)
test.That(t, actMD.FileExtension, test.ShouldEqual, fileExt)
test.That(t, actMD.PartId, test.ShouldNotBeBlank)
// Validate ensuing data messages.
dataRequests := urs[1:]
var actData []byte
for _, d := range dataRequests {
actData = append(actData, d.GetFileContents().GetData()...)
}
test.That(t, actData, test.ShouldResemble, fileContents)
// Validate file no longer exists.
waitUntilNoFiles(additionalPathsDir)
test.That(t, len(getAllFileInfos(additionalPathsDir)), test.ShouldEqual, 0)
test.That(t, dmsvc.Close(context.Background()), test.ShouldBeNil)
})
}
}
func TestStreamingDCUpload(t *testing.T) {
tests := []struct {
name string
serviceFail bool
}{
{
name: "A data capture file greater than MaxUnaryFileSize should be successfully uploaded" +
"via the streaming rpc.",
serviceFail: false,
},
{
name: "if an error response is received from the backend, local files should not be deleted",
serviceFail: true,
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
// Set up server.
mockClock := clk.NewMock()
clock = mockClock
tmpDir := t.TempDir()
// Set up data manager.
dmsvc, r := newTestDataManager(t)
defer dmsvc.Close(context.Background())
var cfg *Config
var deps []string
captureInterval := time.Millisecond * 10
cfg, deps = setupConfig(t, enabledBinaryCollectorConfigPath)
// Set up service config with just capture enabled.
cfg.CaptureDisabled = false
cfg.ScheduledSyncDisabled = true
cfg.SyncIntervalMins = syncIntervalMins
cfg.CaptureDir = tmpDir
resources := resourcesFromDeps(t, r, deps)
err := dmsvc.Reconfigure(context.Background(), resources, resource.Config{
ConvertedAttributes: cfg,
})
test.That(t, err, test.ShouldBeNil)
// Capture an image, then close.
mockClock.Add(captureInterval)
err = dmsvc.Close(context.Background())
test.That(t, err, test.ShouldBeNil)
// Get all captured data.
_, capturedData, err := getCapturedData(tmpDir)
test.That(t, err, test.ShouldBeNil)
// Turn dmsvc back on with capture disabled.
newDMSvc, r := newTestDataManager(t)
defer newDMSvc.Close(context.Background())
f := atomic.Bool{}
f.Store(tc.serviceFail)
mockClient := mockDataSyncServiceClient{
streamingDCUploads: make(chan *mockStreamingDCClient, 10),
fail: &f,
}
// Set max unary file size to 1 byte, so it uses the streaming rpc.
datasync.MaxUnaryFileSize = 1
newDMSvc.SetSyncerConstructor(getTestSyncerConstructorMock(mockClient))
cfg.CaptureDisabled = true
cfg.ScheduledSyncDisabled = true
resources = resourcesFromDeps(t, r, deps)
err = newDMSvc.Reconfigure(context.Background(), resources, resource.Config{
ConvertedAttributes: cfg,
})
test.That(t, err, test.ShouldBeNil)
// Call sync.
err = newDMSvc.Sync(context.Background(), nil)
test.That(t, err, test.ShouldBeNil)
// Wait for upload requests.
var uploads []*mockStreamingDCClient
var urs []*v1.StreamingDataCaptureUploadRequest
// Get the successful requests
wait := time.After(time.Second * 3)
select {
case <-wait:
if !tc.serviceFail {
t.Fatalf("timed out waiting for sync request")
}
case r := <-mockClient.streamingDCUploads:
uploads = append(uploads, r)
select {
case <-wait:
t.Fatalf("timed out waiting for sync request")
case <-r.closed:
urs = append(urs, r.reqs...)
}
}
// Validate error and URs.
remainingFiles := getAllFilePaths(tmpDir)
if tc.serviceFail {
// Error case, file should not be deleted.
test.That(t, len(remainingFiles), test.ShouldEqual, 1)
} else {
// Validate first metadata message.
test.That(t, len(uploads), test.ShouldEqual, 1)
test.That(t, len(urs), test.ShouldBeGreaterThan, 0)
actMD := urs[0].GetMetadata()
test.That(t, actMD, test.ShouldNotBeNil)
test.That(t, actMD.GetUploadMetadata(), test.ShouldNotBeNil)
test.That(t, actMD.GetSensorMetadata(), test.ShouldNotBeNil)
test.That(t, actMD.GetUploadMetadata().Type, test.ShouldEqual, v1.DataType_DATA_TYPE_BINARY_SENSOR)
test.That(t, actMD.GetUploadMetadata().PartId, test.ShouldNotBeBlank)
// Validate ensuing data messages.
dataRequests := urs[1:]
var actData []byte
for _, d := range dataRequests {
actData = append(actData, d.GetData()...)
}
test.That(t, actData, test.ShouldResemble, capturedData[0].GetBinary())
// Validate file no longer exists.
waitUntilNoFiles(tmpDir)
test.That(t, len(getAllFileInfos(tmpDir)), test.ShouldEqual, 0)
}
test.That(t, dmsvc.Close(context.Background()), test.ShouldBeNil)
})
}
}
func TestSyncConfigUpdateBehavior(t *testing.T) {
newSyncIntervalMins := 0.009
tests := []struct {
name string
initSyncDisabled bool
initSyncIntervalMins float64
newSyncDisabled bool
newSyncIntervalMins float64
}{
{
name: "all sync config stays the same, syncer should not cancel, ticker stays the same",
initSyncDisabled: false,
initSyncIntervalMins: syncIntervalMins,
newSyncDisabled: false,
newSyncIntervalMins: syncIntervalMins,
},
{
name: "sync config changes, new ticker should be created for sync",
initSyncDisabled: false,
initSyncIntervalMins: syncIntervalMins,
newSyncDisabled: false,
newSyncIntervalMins: newSyncIntervalMins,
},
{
name: "sync gets disabled, syncer should be nil",
initSyncDisabled: false,
initSyncIntervalMins: syncIntervalMins,
newSyncDisabled: true,
newSyncIntervalMins: syncIntervalMins,
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
// Set up server.
mockClock := clk.NewMock()
// Make mockClock the package level clock used by the dmsvc so that we can simulate time's passage
clock = mockClock
tmpDir := t.TempDir()
// Set up data manager.
dmsvc, r := newTestDataManager(t)
defer dmsvc.Close(context.Background())
mockClient := mockDataSyncServiceClient{
succesfulDCRequests: make(chan *v1.DataCaptureUploadRequest, 100),
failedDCRequests: make(chan *v1.DataCaptureUploadRequest, 100),
fail: &atomic.Bool{},
}
dmsvc.SetSyncerConstructor(getTestSyncerConstructorMock(mockClient))
cfg, deps := setupConfig(t, enabledBinaryCollectorConfigPath)
// Set up service config.
cfg.CaptureDisabled = false
cfg.ScheduledSyncDisabled = tc.initSyncDisabled
cfg.CaptureDir = tmpDir
cfg.SyncIntervalMins = tc.initSyncIntervalMins
resources := resourcesFromDeps(t, r, deps)
err := dmsvc.Reconfigure(context.Background(), resources, resource.Config{
ConvertedAttributes: cfg,
})
test.That(t, err, test.ShouldBeNil)
builtInSvc := dmsvc.(*builtIn)
initTicker := builtInSvc.syncTicker
// Reconfigure the dmsvc with new sync configs
cfg.ScheduledSyncDisabled = tc.newSyncDisabled
cfg.SyncIntervalMins = tc.newSyncIntervalMins
err = dmsvc.Reconfigure(context.Background(), resources, resource.Config{
ConvertedAttributes: cfg,
})
test.That(t, err, test.ShouldBeNil)
newBuildInSvc := dmsvc.(*builtIn)
newTicker := newBuildInSvc.syncTicker
newSyncer := newBuildInSvc.syncer
if tc.newSyncDisabled {
test.That(t, newSyncer, test.ShouldBeNil)
}
if tc.initSyncDisabled != tc.newSyncDisabled ||
tc.initSyncIntervalMins != tc.newSyncIntervalMins {
test.That(t, initTicker, test.ShouldNotEqual, newTicker)
}
})
}
}
func getAllFilePaths(dir string) []string {
var filePaths []string
_ = filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
if err != nil || info.IsDir() {
// ignore errors/unreadable files and directories
//nolint:nilerr
return nil
}
filePaths = append(filePaths, path)
return nil
})
return filePaths
}
func getCapturedData(dir string) (int, []*v1.SensorData, error) {
var allFiles []*datacapture.File
filePaths := getAllFilePaths(dir)
var numFiles int
for _, f := range filePaths {
osFile, err := os.Open(f)
if err != nil {
return 0, nil, err
}
dcFile, err := datacapture.ReadFile(osFile)
if err != nil {
return 0, nil, err
}
allFiles = append(allFiles, dcFile)
}
var ret []*v1.SensorData
for _, dcFile := range allFiles {
containsData := false
for {
next, err := dcFile.ReadNext()
if errors.Is(err, io.EOF) {
break
}
containsData = true
if err != nil {
return 0, nil, err
}
ret = append(ret, next)
}
if containsData {
numFiles++
}
}
return numFiles, ret, nil
}
func getUploadedData(urs []*v1.DataCaptureUploadRequest) []*v1.SensorData {
var syncedData []*v1.SensorData
for _, ur := range urs {
sd := ur.GetSensorContents()
syncedData = append(syncedData, sd...)
}
return syncedData
}
func compareSensorData(t *testing.T, dataType v1.DataType, act, exp []*v1.SensorData) {
if len(act) == 0 && len(exp) == 0 {
return
}
// Sort both by time requested.
sort.SliceStable(act, func(i, j int) bool {
diffRequested := act[j].GetMetadata().GetTimeRequested().AsTime().Sub(act[i].GetMetadata().GetTimeRequested().AsTime())
switch {
case diffRequested > 0:
return true
case diffRequested == 0:
return act[j].GetMetadata().GetTimeReceived().AsTime().Sub(act[i].GetMetadata().GetTimeReceived().AsTime()) > 0
default:
return false
}
})
sort.SliceStable(exp, func(i, j int) bool {
diffRequested := exp[j].GetMetadata().GetTimeRequested().AsTime().Sub(exp[i].GetMetadata().GetTimeRequested().AsTime())
switch {
case diffRequested > 0:
return true
case diffRequested == 0:
return exp[j].GetMetadata().GetTimeReceived().AsTime().Sub(exp[i].GetMetadata().GetTimeReceived().AsTime()) > 0
default:
return false
}
})
test.That(t, len(act), test.ShouldEqual, len(exp))
for i := range act {
test.That(t, act[i].GetMetadata(), test.ShouldResemble, exp[i].GetMetadata())
if dataType == v1.DataType_DATA_TYPE_TABULAR_SENSOR {
test.That(t, act[i].GetStruct(), test.ShouldResemble, exp[i].GetStruct())
} else {
test.That(t, act[i].GetBinary(), test.ShouldResemble, exp[i].GetBinary())
}
}
}
type mockDataSyncServiceClient struct {
succesfulDCRequests chan *v1.DataCaptureUploadRequest
failedDCRequests chan *v1.DataCaptureUploadRequest
fileUploads chan *mockFileUploadClient
streamingDCUploads chan *mockStreamingDCClient
fail *atomic.Bool
}
func (c mockDataSyncServiceClient) DataCaptureUpload(
ctx context.Context,
ur *v1.DataCaptureUploadRequest,
opts ...grpc.CallOption,
) (*v1.DataCaptureUploadResponse, error) {
if c.fail.Load() {
select {
case <-ctx.Done():
return nil, ctx.Err()
case c.failedDCRequests <- ur:
return nil, errors.New("oh no error")
}
}
select {
case <-ctx.Done():
return nil, ctx.Err()
case c.succesfulDCRequests <- ur:
return &v1.DataCaptureUploadResponse{}, nil
}
}
func (c mockDataSyncServiceClient) FileUpload(ctx context.Context, opts ...grpc.CallOption) (v1.DataSyncService_FileUploadClient, error) {
if c.fail.Load() {
return nil, errors.New("oh no error")
}
ret := &mockFileUploadClient{closed: make(chan struct{})}
c.fileUploads <- ret
return ret, nil
}
func (c mockDataSyncServiceClient) StreamingDataCaptureUpload(ctx context.Context,
opts ...grpc.CallOption,
) (v1.DataSyncService_StreamingDataCaptureUploadClient, error) {
if c.fail.Load() {
return nil, errors.New("oh no error")
}
ret := &mockStreamingDCClient{closed: make(chan struct{})}
c.streamingDCUploads <- ret
return ret, nil
}
type mockFileUploadClient struct {
urs []*v1.FileUploadRequest
closed chan struct{}
grpc.ClientStream
}
func (m *mockFileUploadClient) Send(req *v1.FileUploadRequest) error {
m.urs = append(m.urs, req)
return nil
}
func (m *mockFileUploadClient) CloseAndRecv() (*v1.FileUploadResponse, error) {
m.closed <- struct{}{}
return &v1.FileUploadResponse{}, nil
}
func (m *mockFileUploadClient) CloseSend() error {
return nil
}
type mockStreamingDCClient struct {
reqs []*v1.StreamingDataCaptureUploadRequest
closed chan struct{}
grpc.ClientStream
}
func (m *mockStreamingDCClient) Send(req *v1.StreamingDataCaptureUploadRequest) error {
m.reqs = append(m.reqs, req)
return nil
}
func (m *mockStreamingDCClient) CloseAndRecv() (*v1.StreamingDataCaptureUploadResponse, error) {
m.closed <- struct{}{}
return &v1.StreamingDataCaptureUploadResponse{}, nil
}
func (m *mockStreamingDCClient) CloseSend() error {
return nil
}
func getTestSyncerConstructorMock(client mockDataSyncServiceClient) datasync.ManagerConstructor {
return func(identity string, _ v1.DataSyncServiceClient, logger golog.Logger) (datasync.Manager, error) {
return datasync.NewManager(identity, client, logger)
}
}
func waitUntilNoFiles(dir string) {
totalWait := time.Second * 3
waitPerCheck := time.Millisecond * 10
iterations := int(totalWait / waitPerCheck)
files := getAllFileInfos(dir)
for i := 0; i < iterations; i++ {
if len(files) == 0 {
return
}
time.Sleep(waitPerCheck)
files = getAllFileInfos(dir)
}
}