-
Notifications
You must be signed in to change notification settings - Fork 25
/
hostdb_test.go
1314 lines (1178 loc) · 35.5 KB
/
hostdb_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 stores
import (
"context"
"errors"
"fmt"
"reflect"
"testing"
"time"
"github.com/google/go-cmp/cmp"
rhpv2 "go.sia.tech/core/rhp/v2"
rhpv3 "go.sia.tech/core/rhp/v3"
"go.sia.tech/core/types"
"go.sia.tech/renterd/api"
"go.sia.tech/renterd/internal/gouging"
"go.sia.tech/renterd/internal/test"
sql "go.sia.tech/renterd/stores/sql"
)
// TestSQLHostDB tests the basic functionality of SQLHostDB using an in-memory
// SQLite DB.
func TestSQLHostDB(t *testing.T) {
ss := newTestSQLStore(t, defaultTestSQLStoreConfig)
defer ss.Close()
// Try to fetch a random host. Should fail.
ctx := context.Background()
hk := types.GeneratePrivateKey().PublicKey()
_, err := ss.Host(ctx, hk)
if !errors.Is(err, api.ErrHostNotFound) {
t.Fatal(err)
}
// Add the host
err = ss.addTestHost(hk)
if err != nil {
t.Fatal(err)
}
// Assert it's returned
allHosts, err := ss.Hosts(ctx, api.HostOptions{
FilterMode: api.HostFilterModeAll,
UsabilityMode: api.UsabilityFilterModeAll,
AddressContains: "",
KeyIn: nil,
Offset: 0,
Limit: -1,
})
if err != nil {
t.Fatal(err)
}
if len(allHosts) != 1 || allHosts[0].PublicKey != hk {
t.Fatal("unexpected result", len(allHosts))
}
// Insert an announcement for the host and another one for an unknown
// host.
if err := ss.announceHost(hk, "address"); err != nil {
t.Fatal(err)
}
// Fetch the host
h, err := ss.Host(ctx, hk)
if err != nil {
t.Fatal(err)
} else if h.NetAddress != "address" {
t.Fatalf("unexpected address: %v", h.NetAddress)
} else if h.LastAnnouncement.IsZero() {
t.Fatal("last announcement not set")
}
// Same thing again but with hosts.
hosts, err := ss.Hosts(ctx, api.HostOptions{
FilterMode: api.HostFilterModeAll,
UsabilityMode: api.UsabilityFilterModeAll,
AddressContains: "",
KeyIn: nil,
Offset: 0,
Limit: -1,
})
if err != nil {
t.Fatal(err)
}
if len(hosts) != 1 {
t.Fatal("wrong number of hosts", len(hosts))
}
h1 := hosts[0]
if !reflect.DeepEqual(h1, h) {
fmt.Println(h1)
fmt.Println(h)
t.Fatal("mismatch")
}
// Same thing again but with Host.
h2, err := ss.Host(ctx, hk)
if err != nil {
t.Fatal(err)
}
if h2.NetAddress != h.NetAddress {
t.Fatal("wrong net address")
}
if h2.KnownSince.IsZero() {
t.Fatal("known since not set")
}
// Insert another announcement for an unknown host.
randomHK := types.PublicKey{1, 4, 7}
if err := ss.announceHost(types.PublicKey{1, 4, 7}, "na"); err != nil {
t.Fatal(err)
}
h3, err := ss.Host(ctx, randomHK)
if err != nil {
t.Fatal(err)
}
if h3.NetAddress != "na" {
t.Fatal("wrong net address")
}
if h3.KnownSince.IsZero() {
t.Fatal("known since not set")
}
}
// TestHosts is a unit test for the Hosts method of the SQLHostDB type.
func TestHosts(t *testing.T) {
ss := newTestSQLStore(t, defaultTestSQLStoreConfig)
defer ss.Close()
ctx := context.Background()
// add 3 hosts
var hks []types.PublicKey
for i := 1; i <= 3; i++ {
if err := ss.addCustomTestHost(types.PublicKey{byte(i)}, fmt.Sprintf("foo.com:100%d", i)); err != nil {
t.Fatal(err)
}
hks = append(hks, types.PublicKey{byte(i)})
}
hk1, hk2, hk3 := hks[0], hks[1], hks[2]
// search all hosts
his, err := ss.Hosts(context.Background(), api.HostOptions{
FilterMode: api.HostFilterModeAll,
UsabilityMode: api.UsabilityFilterModeAll,
AddressContains: "",
KeyIn: nil,
Offset: 0,
Limit: -1,
})
if err != nil {
t.Fatal(err)
} else if len(his) != 3 {
t.Fatal("unexpected")
}
// assert offset & limit are taken into account
his, err = ss.Hosts(context.Background(), api.HostOptions{
FilterMode: api.HostFilterModeAll,
UsabilityMode: api.UsabilityFilterModeAll,
AddressContains: "",
KeyIn: nil,
Offset: 0,
Limit: 1,
})
if err != nil {
t.Fatal(err)
} else if len(his) != 1 {
t.Fatal("unexpected")
}
his, err = ss.Hosts(context.Background(), api.HostOptions{
FilterMode: api.HostFilterModeAll,
UsabilityMode: api.UsabilityFilterModeAll,
AddressContains: "",
KeyIn: nil,
Offset: 1,
Limit: 2,
})
if err != nil {
t.Fatal(err)
} else if len(his) != 2 {
t.Fatal("unexpected")
}
his, err = ss.Hosts(context.Background(), api.HostOptions{
FilterMode: api.HostFilterModeAll,
UsabilityMode: api.UsabilityFilterModeAll,
AddressContains: "",
KeyIn: nil,
Offset: 3,
Limit: 1,
})
if err != nil {
t.Fatal(err)
} else if len(his) != 0 {
t.Fatal("unexpected")
}
// assert address and key filters are taken into account
if hosts, err := ss.Hosts(ctx, api.HostOptions{
FilterMode: api.HostFilterModeAll,
UsabilityMode: api.UsabilityFilterModeAll,
AddressContains: "com:1001",
KeyIn: nil,
Offset: 0,
Limit: -1,
}); err != nil || len(hosts) != 1 {
t.Fatal("unexpected", len(hosts), err)
}
if hosts, err := ss.Hosts(ctx, api.HostOptions{
FilterMode: api.HostFilterModeAll,
UsabilityMode: api.UsabilityFilterModeAll,
AddressContains: "",
KeyIn: []types.PublicKey{hk2, hk3},
Offset: 0,
Limit: -1,
}); err != nil || len(hosts) != 2 {
t.Fatal("unexpected", len(hosts), err)
}
if hosts, err := ss.Hosts(ctx, api.HostOptions{
FilterMode: api.HostFilterModeAll,
UsabilityMode: api.UsabilityFilterModeAll,
AddressContains: "com:1002",
KeyIn: []types.PublicKey{hk2, hk3},
Offset: 0,
Limit: -1,
}); err != nil || len(hosts) != 1 {
t.Fatal("unexpected", len(hosts), err)
}
if hosts, err := ss.Hosts(ctx, api.HostOptions{
FilterMode: api.HostFilterModeAll,
UsabilityMode: api.UsabilityFilterModeAll,
AddressContains: "com:1002",
KeyIn: []types.PublicKey{hk1},
Offset: 0,
Limit: -1,
}); err != nil || len(hosts) != 0 {
t.Fatal("unexpected", len(hosts), err)
}
// assert host filter mode is taken into account
err = ss.UpdateHostBlocklistEntries(context.Background(), []string{"foo.com:1001"}, nil, false)
if err != nil {
t.Fatal(err)
}
his, err = ss.Hosts(context.Background(), api.HostOptions{
FilterMode: api.HostFilterModeAllowed,
UsabilityMode: api.UsabilityFilterModeAll,
AddressContains: "",
KeyIn: nil,
Offset: 0,
Limit: -1,
})
if err != nil {
t.Fatal(err)
} else if len(his) != 2 {
t.Fatal("unexpected")
} else if his[0].PublicKey != (types.PublicKey{2}) || his[1].PublicKey != (types.PublicKey{3}) {
t.Fatal("unexpected", his[0].PublicKey, his[1].PublicKey)
}
his, err = ss.Hosts(context.Background(), api.HostOptions{
FilterMode: api.HostFilterModeBlocked,
UsabilityMode: api.UsabilityFilterModeAll,
AddressContains: "",
KeyIn: nil,
Offset: 0,
Limit: -1,
})
if err != nil {
t.Fatal(err)
} else if len(his) != 1 {
t.Fatal("unexpected")
} else if his[0].PublicKey != (types.PublicKey{1}) {
t.Fatal("unexpected", his)
}
err = ss.UpdateHostBlocklistEntries(context.Background(), nil, nil, true)
if err != nil {
t.Fatal(err)
}
// add host checks
h1c := newTestHostCheck()
h1c.ScoreBreakdown.Age = .1
err = ss.UpdateHostCheck(context.Background(), hk1, h1c)
if err != nil {
t.Fatal(err)
}
h2c := newTestHostCheck()
h2c.ScoreBreakdown.Age = .21
err = ss.UpdateHostCheck(context.Background(), hk2, h2c)
if err != nil {
t.Fatal(err)
}
// assert number of host checks
checkCount := func() int64 {
t.Helper()
return ss.Count("host_checks")
}
if cnt := checkCount(); cnt != 2 {
t.Fatal("unexpected", cnt)
}
// fetch all hosts
his, err = ss.Hosts(context.Background(), api.HostOptions{
FilterMode: api.HostFilterModeAll,
UsabilityMode: api.UsabilityFilterModeAll,
AddressContains: "",
KeyIn: nil,
Offset: 0,
Limit: -1,
})
if err != nil {
t.Fatal(err)
} else if len(his) != 3 {
t.Fatal("unexpected", len(his))
}
// assert h1 and h2 have the expected checks
if his[0].Checks != h1c {
t.Fatal("unexpected", his[0].Checks)
} else if his[1].Checks != h2c {
t.Fatal("unexpected", his[1].Checks)
}
// use reflection to check whether usability is correctly taken into account
// for every field of the usability breakdown
opts := api.HostOptions{
FilterMode: api.HostFilterModeAll,
AddressContains: "",
KeyIn: nil,
Offset: 0,
Limit: -1,
}
assertHostUsability := func() error {
t.Helper()
opts.UsabilityMode = api.UsabilityFilterModeUsable
if his, err := ss.Hosts(ctx, opts); err != nil {
return err
} else if len(his) != 1 {
return fmt.Errorf("expected one usable host, but got %d", len(his))
} else if his[0].PublicKey != hk1 {
return fmt.Errorf("unexpected host is usable, hk %v", his[0].PublicKey)
}
opts.UsabilityMode = api.UsabilityFilterModeUnusable
if his, err := ss.Hosts(context.Background(), opts); err != nil {
return err
} else if len(his) != 1 {
return fmt.Errorf("expected one unusable host, but got %d", len(his))
} else if his[0].PublicKey != hk2 {
return fmt.Errorf("unexpected host is unusable, hk %v", his[0].PublicKey)
}
return nil
}
v := reflect.ValueOf(&h2c.UsabilityBreakdown).Elem()
for i := 0; i < v.NumField(); i++ {
field := v.Field(i)
if !field.CanSet() || field.Kind() != reflect.Bool {
continue
}
field.SetBool(true)
if err := ss.UpdateHostCheck(ctx, hk2, h2c); err != nil {
t.Fatalf("failed to update host check after setting %s: %v", v.Type().Field(i).Name, err)
} else if err := assertHostUsability(); err != nil {
t.Fatalf("usability filter is not taken into account after setting %s: %v", v.Type().Field(i).Name, err)
}
field.SetBool(false)
}
// assert cascade delete on host
_, err = ss.DB().Exec(context.Background(), "DELETE FROM hosts WHERE public_key = ?", sql.PublicKey(types.PublicKey{1}))
if err != nil {
t.Fatal(err)
}
if cnt := checkCount(); cnt != 1 {
t.Fatal("unexpected", cnt)
}
}
func TestUsableHosts(t *testing.T) {
ss := newTestSQLStore(t, defaultTestSQLStoreConfig)
defer ss.Close()
ctx := context.Background()
// prepare hosts & contracts
//
// h1: usable
// h2: not usable - blocked
// h3: not usable - no host check
// h4: not usable - no contract
var hks []types.PublicKey
for i := 1; i <= 4; i++ {
// add host
hk := types.PublicKey{byte(i)}
addr := fmt.Sprintf("foo.com:100%d", i)
err := ss.addCustomTestHost(hk, addr)
if err != nil {
t.Fatal(err)
}
hks = append(hks, hk)
// add host scan
hs := test.NewHostSettings()
pt := test.NewHostPriceTable()
s1 := newTestScan(hk, time.Now(), hs, pt, true)
if err := ss.RecordHostScans(context.Background(), []api.HostScan{s1}); err != nil {
t.Fatal(err)
}
// add host check
if i != 3 {
hc := newTestHostCheck()
err = ss.UpdateHostCheck(context.Background(), hk, hc)
if err != nil {
t.Fatal(err)
}
}
// add contract
if i != 4 {
_, err = ss.addTestContract(types.FileContractID{byte(i)}, hk)
if err != nil {
t.Fatal(err)
}
}
// block host
if i == 2 {
err = ss.UpdateHostBlocklistEntries(context.Background(), []string{addr}, nil, false)
if err != nil {
t.Fatal(err)
}
}
}
// assert h1 is usable
hosts, err := ss.UsableHosts(ctx)
if err != nil {
t.Fatal(err)
} else if len(hosts) != 1 {
t.Fatal("unexpected", len(hosts))
} else if hosts[0].PublicKey != hks[0] {
t.Fatal("unexpected", hosts)
} else if hosts[0].SiamuxAddr != "foo.com:9983" {
t.Fatal("unexpected", hosts)
}
// create gouging checker
gs := test.GougingSettings
cs := api.ConsensusState{Synced: true}
gc := gouging.NewChecker(gs, cs)
// assert h1 is not gouging
h1 := hosts[0]
if gc.CheckV1(&h1.HS, &h1.PT).Gouging() {
t.Fatal("unexpected")
}
// record a scan for h1 to make it gouging
hs := test.NewHostSettings()
pt := test.NewHostPriceTable()
pt.UploadBandwidthCost = gs.MaxUploadPrice
s1 := newTestScan(h1.PublicKey, time.Now(), hs, pt, true)
if err := ss.RecordHostScans(context.Background(), []api.HostScan{s1}); err != nil {
t.Fatal(err)
}
// fetch it again
hosts, err = ss.UsableHosts(ctx)
if err != nil {
t.Fatal(err)
} else if len(hosts) != 1 {
t.Fatal("unexpected", len(hosts))
}
// assert h1 is now gouging
h1 = hosts[0]
if !gc.CheckV1(&h1.HS, &h1.PT).Gouging() {
t.Fatal("unexpected", h1.PT.UploadBandwidthCost, gs.MaxUploadPrice)
}
// create helper to assert number of usable hosts
assertNumUsableHosts := func(n int) {
t.Helper()
hosts, err = ss.UsableHosts(ctx)
if err != nil {
t.Fatal(err)
} else if len(hosts) != n {
t.Fatal("unexpected", len(hosts))
}
}
// unblock h2
if err := ss.UpdateHostBlocklistEntries(context.Background(), nil, nil, true); err != nil {
t.Fatal(err)
}
assertNumUsableHosts(2)
// add host check for h3
hc := newTestHostCheck()
err = ss.UpdateHostCheck(context.Background(), types.PublicKey{3}, hc)
if err != nil {
t.Fatal(err)
}
assertNumUsableHosts(3)
// add contract for h4
_, err = ss.addTestContract(types.FileContractID{byte(4)}, types.PublicKey{4})
if err != nil {
t.Fatal(err)
}
assertNumUsableHosts(4)
// add an allowlist
ss.UpdateHostAllowlistEntries(context.Background(), []types.PublicKey{{9}}, nil, false)
assertNumUsableHosts(0)
}
// TestRecordScan is a test for recording scans.
func TestRecordScan(t *testing.T) {
ss := newTestSQLStore(t, defaultTestSQLStoreConfig)
defer ss.Close()
// Add a host.
hk := types.GeneratePrivateKey().PublicKey()
err := ss.addCustomTestHost(hk, "host.com")
if err != nil {
t.Fatal(err)
}
// The host shouldn't have any interaction related fields set.
ctx := context.Background()
host, err := ss.Host(ctx, hk)
if err != nil {
t.Fatal(err)
}
if host.Interactions != (api.HostInteractions{}) {
t.Fatal("mismatch", cmp.Diff(host.Interactions, api.HostInteractions{}))
}
if host.Settings != (rhpv2.HostSettings{}) {
t.Fatal("mismatch")
}
// Fetch the host directly to get the creation time.
h, err := ss.Host(ctx, hk)
if err != nil {
t.Fatal(err)
} else if h.KnownSince.IsZero() {
t.Fatal("known since not set")
}
// Record a scan.
firstScanTime := time.Now().UTC()
settings := rhpv2.HostSettings{NetAddress: "host.com"}
pt := rhpv3.HostPriceTable{
HostBlockHeight: 123,
}
if err := ss.RecordHostScans(ctx, []api.HostScan{newTestScan(hk, firstScanTime, settings, pt, true)}); err != nil {
t.Fatal(err)
}
host, err = ss.Host(ctx, hk)
if err != nil {
t.Fatal(err)
} else if time.Now().Before(host.PriceTable.Expiry) {
t.Fatal("invalid expiry")
} else if host.PriceTable.HostBlockHeight != pt.HostBlockHeight {
t.Fatalf("mismatch %v %v", host.PriceTable.HostBlockHeight, pt.HostBlockHeight)
}
// We expect no uptime or downtime from only a single scan.
uptime := time.Duration(0)
downtime := time.Duration(0)
if host.Interactions.LastScan.UnixMilli() != firstScanTime.UnixMilli() {
t.Fatal("wrong time")
}
host.Interactions.LastScan = time.Time{}
if expected := (api.HostInteractions{
TotalScans: 1,
LastScan: time.Time{},
LastScanSuccess: true,
SecondToLastScanSuccess: false,
Uptime: uptime,
Downtime: downtime,
SuccessfulInteractions: 1,
FailedInteractions: 0,
}); host.Interactions != expected {
t.Fatal("mismatch", cmp.Diff(host.Interactions, expected))
}
if !reflect.DeepEqual(host.Settings, settings) {
t.Fatal("mismatch")
}
// Record another scan 1 hour after the previous one. We don't pass any
// subnets this time.
secondScanTime := firstScanTime.Add(time.Hour)
pt.HostBlockHeight = 456
if err := ss.RecordHostScans(ctx, []api.HostScan{newTestScan(hk, secondScanTime, settings, pt, true)}); err != nil {
t.Fatal(err)
}
host, err = ss.Host(ctx, hk)
if err != nil {
t.Fatal(err)
} else if host.Interactions.LastScan.UnixMilli() != secondScanTime.UnixMilli() {
t.Fatal("wrong time")
}
host.Interactions.LastScan = time.Time{}
uptime += secondScanTime.Sub(firstScanTime)
if host.Interactions != (api.HostInteractions{
TotalScans: 2,
LastScan: time.Time{},
LastScanSuccess: true,
SecondToLastScanSuccess: true,
Uptime: uptime,
Downtime: downtime,
SuccessfulInteractions: 2,
FailedInteractions: 0,
}) {
t.Fatal("mismatch")
}
// Record another scan 2 hours after the second one. This time it fails.
thirdScanTime := secondScanTime.Add(2 * time.Hour)
if err := ss.RecordHostScans(ctx, []api.HostScan{newTestScan(hk, thirdScanTime, settings, pt, false)}); err != nil {
t.Fatal(err)
}
host, err = ss.Host(ctx, hk)
if err != nil {
t.Fatal(err)
}
if host.Interactions.LastScan.UnixMilli() != thirdScanTime.UnixMilli() {
t.Fatal("wrong time")
}
host.Interactions.LastScan = time.Time{}
downtime += thirdScanTime.Sub(secondScanTime)
if host.Interactions != (api.HostInteractions{
TotalScans: 3,
LastScan: time.Time{},
LastScanSuccess: false,
SecondToLastScanSuccess: true,
Uptime: uptime,
Downtime: downtime,
SuccessfulInteractions: 2,
FailedInteractions: 1,
}) {
t.Fatal("mismatch")
}
}
func TestRemoveHosts(t *testing.T) {
ss := newTestSQLStore(t, defaultTestSQLStoreConfig)
defer ss.Close()
// add a host
hk := types.GeneratePrivateKey().PublicKey()
err := ss.addTestHost(hk)
if err != nil {
t.Fatal(err)
}
// fetch the host and assert the downtime is zero
h, err := ss.Host(context.Background(), hk)
if err != nil {
t.Fatal(err)
} else if h.Interactions.Downtime != 0 {
t.Fatal("downtime is not zero")
}
// assert no hosts are removed
removed, err := ss.RemoveOfflineHosts(context.Background(), 0, time.Hour)
if err != nil {
t.Fatal(err)
}
if removed != 0 {
t.Fatal("expected no hosts to be removed")
}
now := time.Now().UTC()
pt := rhpv3.HostPriceTable{}
t1 := now.Add(-time.Minute * 120) // 2 hours ago
t2 := now.Add(-time.Minute * 90) // 1.5 hours ago (30min downtime)
hi1 := newTestScan(hk, t1, rhpv2.HostSettings{NetAddress: "host.com"}, pt, false)
hi2 := newTestScan(hk, t2, rhpv2.HostSettings{NetAddress: "host.com"}, pt, false)
// record interactions
if err := ss.RecordHostScans(context.Background(), []api.HostScan{hi1, hi2}); err != nil {
t.Fatal(err)
}
// fetch the host and assert the downtime is 30 minutes and he has 2 recent scan failures
h, err = ss.Host(context.Background(), hk)
if err != nil {
t.Fatal(err)
}
if h.Interactions.Downtime.Minutes() != 30 {
t.Fatal("downtime is not 30 minutes", h.Interactions.Downtime.Minutes())
}
if h.Interactions.FailedInteractions != 2 {
t.Fatal("recent scan failures is not 2", h.Interactions.FailedInteractions)
}
// assert no hosts are removed
removed, err = ss.RemoveOfflineHosts(context.Background(), 0, time.Hour)
if err != nil {
t.Fatal(err)
}
if removed != 0 {
t.Fatal("expected no hosts to be removed")
}
// record interactions
t3 := now.Add(-time.Minute * 60) // 1 hour ago (60min downtime)
hi3 := newTestScan(hk, t3, rhpv2.HostSettings{NetAddress: "host.com"}, pt, false)
if err := ss.RecordHostScans(context.Background(), []api.HostScan{hi3}); err != nil {
t.Fatal(err)
}
// assert no hosts are removed at 61 minutes
removed, err = ss.RemoveOfflineHosts(context.Background(), 0, time.Minute*61)
if err != nil {
t.Fatal(err)
}
if removed != 0 {
t.Fatal("expected no hosts to be removed")
}
// assert no hosts are removed at 60 minutes if we require at least 4 failed scans
removed, err = ss.RemoveOfflineHosts(context.Background(), 4, time.Minute*60)
if err != nil {
t.Fatal(err)
}
if removed != 0 {
t.Fatal("expected no hosts to be removed")
}
// assert hosts gets removed at 60 minutes if we require at least 3 failed scans
removed, err = ss.RemoveOfflineHosts(context.Background(), 3, time.Minute*60)
if err != nil {
t.Fatal(err)
}
if removed != 1 {
t.Fatal("expected 1 host to be removed")
}
// assert host is removed from the database
if _, err = ss.Host(context.Background(), hk); !errors.Is(err, api.ErrHostNotFound) {
t.Fatal("expected record not found error")
}
}
func TestSQLHostAllowlist(t *testing.T) {
ss := newTestSQLStore(t, defaultTestSQLStoreConfig)
defer ss.Close()
ctx := context.Background()
numEntries := func() int {
t.Helper()
bl, err := ss.HostAllowlist(ctx)
if err != nil {
t.Fatal(err)
}
return len(bl)
}
numHosts := func() int {
t.Helper()
hosts, err := ss.Hosts(ctx, api.HostOptions{
FilterMode: api.HostFilterModeAllowed,
UsabilityMode: api.UsabilityFilterModeAll,
AddressContains: "",
KeyIn: nil,
Offset: 0,
Limit: -1,
})
if err != nil {
t.Fatal(err)
}
return len(hosts)
}
numRelations := func() (cnt int64) {
t.Helper()
return ss.Count("host_allowlist_entry_hosts")
}
isAllowed := func(hk types.PublicKey) bool {
t.Helper()
host, err := ss.Host(ctx, hk)
if err != nil {
t.Fatal(err)
}
return !host.Blocked
}
// add three hosts
hks, err := ss.addTestHosts(3)
if err != nil {
t.Fatal(err)
}
hk1, hk2, hk3 := hks[0], hks[1], hks[2]
// assert we can find them
if numHosts() != 3 {
t.Fatalf("unexpected number of hosts, %v != 3", numHosts())
}
// assert allowlist is empty
if numEntries() != 0 {
t.Fatalf("unexpected number of entries in allowlist, %v != 0", numEntries())
}
// assert we can add entries to the allowlist
err = ss.UpdateHostAllowlistEntries(ctx, []types.PublicKey{hk1, hk2}, nil, false)
if err != nil {
t.Fatal(err)
}
if numEntries() != 2 {
t.Fatalf("unexpected number of entries in allowlist, %v != 2", numEntries())
}
if numRelations() != 2 {
t.Fatalf("unexpected number of entries in join table, %v != 2", numRelations())
}
// assert both h1 and h2 are allowed now
if !isAllowed(hk1) || !isAllowed(hk2) || isAllowed(hk3) {
t.Fatal("unexpected hosts are allowed", isAllowed(hk1), isAllowed(hk2), isAllowed(hk3))
}
// assert adding the same entry is a no-op and we can remove an entry at the same time
err = ss.UpdateHostAllowlistEntries(ctx, []types.PublicKey{hk1}, []types.PublicKey{hk2}, false)
if err != nil {
t.Fatal(err)
}
if numEntries() != 1 {
t.Fatalf("unexpected number of entries in allowlist, %v != 1", numEntries())
}
if numRelations() != 1 {
t.Fatalf("unexpected number of entries in join table, %v != 1", numRelations())
}
// assert only h1 is allowed now
if !isAllowed(hk1) || isAllowed(hk2) || isAllowed(hk3) {
t.Fatal("unexpected hosts are allowed", isAllowed(hk1), isAllowed(hk2), isAllowed(hk3))
}
// assert removing a non-existing entry is a no-op
err = ss.UpdateHostAllowlistEntries(ctx, nil, []types.PublicKey{hk2}, false)
if err != nil {
t.Fatal(err)
}
assertHosts := func(total, allowed, blocked int) error {
t.Helper()
hosts, err := ss.Hosts(context.Background(), api.HostOptions{
FilterMode: api.HostFilterModeAll,
UsabilityMode: api.UsabilityFilterModeAll,
AddressContains: "",
KeyIn: nil,
Offset: 0,
Limit: -1,
})
if err != nil {
return err
}
if len(hosts) != total {
return fmt.Errorf("invalid number of hosts: %v", len(hosts))
}
hosts, err = ss.Hosts(context.Background(), api.HostOptions{
FilterMode: api.HostFilterModeAllowed,
UsabilityMode: api.UsabilityFilterModeAll,
AddressContains: "",
KeyIn: nil,
Offset: 0,
Limit: -1,
})
if err != nil {
return err
}
if len(hosts) != allowed {
return fmt.Errorf("invalid number of hosts: %v", len(hosts))
}
hosts, err = ss.Hosts(context.Background(), api.HostOptions{
FilterMode: api.HostFilterModeBlocked,
UsabilityMode: api.UsabilityFilterModeAll,
AddressContains: "",
KeyIn: nil,
Offset: 0,
Limit: -1,
})
if err != nil {
return err
}
if len(hosts) != blocked {
return fmt.Errorf("invalid number of hosts: %v", len(hosts))
}
return nil
}
// Search for hosts using different modes. Should have 3 hosts in total, 2
// allowed ones and 2 blocked ones.
if err := assertHosts(3, 1, 2); err != nil {
t.Fatal(err)
}
// remove host 1
if err := ss.DeleteHost(hk1); err != nil {
t.Fatal(err)
}
if numHosts() != 0 {
t.Fatalf("unexpected number of hosts, %v != 0", numHosts())
}
if numRelations() != 0 {
t.Fatalf("unexpected number of entries in join table, %v != 0", numRelations())
}
if numEntries() != 1 {
t.Fatalf("unexpected number of entries in blocklist, %v != 1", numEntries())
}
// Search for hosts using different modes. Should have 2 hosts in total, 0
// allowed ones and 2 blocked ones.
if err := assertHosts(2, 0, 2); err != nil {
t.Fatal(err)
}
// remove the allowlist entry for h1
err = ss.UpdateHostAllowlistEntries(ctx, nil, []types.PublicKey{hk1}, false)
if err != nil {
t.Fatal(err)
}
// Search for hosts using different modes. Should have 2 hosts in total, 2
// allowed ones and 0 blocked ones.
if err := assertHosts(2, 2, 0); err != nil {
t.Fatal(err)
}
// assert hosts reappear
if numHosts() != 2 {
t.Fatalf("unexpected number of hosts, %v != 2", numHosts())
}
if numEntries() != 0 {
t.Fatalf("unexpected number of entries in blocklist, %v != 0", numEntries())
}
}
func TestSQLHostBlocklist(t *testing.T) {
ss := newTestSQLStore(t, defaultTestSQLStoreConfig)
defer ss.Close()
ctx := context.Background()
numEntries := func() int {
t.Helper()
bl, err := ss.HostBlocklist(ctx)
if err != nil {
t.Fatal(err)
}
return len(bl)
}
numHosts := func() int {
t.Helper()
hosts, err := ss.Hosts(ctx, api.HostOptions{
FilterMode: api.HostFilterModeAllowed,
UsabilityMode: api.UsabilityFilterModeAll,
AddressContains: "",
KeyIn: nil,
Offset: 0,
Limit: -1,
})
if err != nil {
t.Fatal(err)
}
return len(hosts)
}
numAllowlistRelations := func() (cnt int64) {
t.Helper()
return ss.Count("host_allowlist_entry_hosts")
}
numBlocklistRelations := func() (cnt int64) {
t.Helper()
return ss.Count("host_blocklist_entry_hosts")
}
isBlocked := func(hk types.PublicKey) bool {
t.Helper()
host, _ := ss.Host(ctx, hk)
return host.Blocked
}
// add three hosts