-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathcampaign_test.go
1283 lines (1120 loc) · 38.9 KB
/
campaign_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 leaderelection
import (
"context"
"fmt"
"math/rand"
"os"
"strconv"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/vimeo/go-clocks/fake"
"github.com/vimeo/go-clocks/offset"
"github.com/vimeo/leaderelection/entry"
"github.com/vimeo/leaderelection/memory"
)
func init() {
// Seed the PRNG with something mostly run-specific (used for jitter)
rand.Seed(int64(os.Getpid()) * time.Now().UnixNano())
}
func TestAcquireTrivialUncontendedFakeClock(t *testing.T) {
t.Parallel()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
d := memory.NewDecider()
elected := atomicBool{}
onElectedCalls := 0
fc := fake.NewClock(time.Now())
c := Config{
Decider: d,
HostPort: []string{"127.0.0.1:8080"},
LeaderID: "yabadabadoo",
OnElected: func(ctx context.Context, tv *TimeView) {
if elected.get() {
t.Error("OnElected called while still elected")
}
elected.set(true)
onElectedCalls++
},
OnOusting: func(ctx context.Context) {
elected.set(false)
},
LeaderChanged: func(ctx context.Context, entry entry.RaceEntry) {
},
TermLength: time.Minute * 30,
MaxClockSkew: time.Second * 10,
Clock: fc,
}
if sleepers := fc.NumSleepers(); sleepers != 0 {
t.Errorf("unexpected number of goroutines sleeping; want %d; got %d", 0, sleepers)
}
acquireCh := make(chan error, 1)
go func() {
acquireCh <- c.Acquire(ctx)
}()
// wait until manageWin goes to sleep waiting for the next time it needs to awaken.
fc.AwaitSleepers(1)
if sleepers := fc.NumSleepers(); sleepers != 1 {
t.Errorf("unexpected number of goroutines sleeping; want %d; got %d", 1, sleepers)
}
// Advance from our initial timestamp up to half-way into the term.
// (MaxClockSkew past the point we're expecting to wake-up)
// This should wake up our sleeping goroutine
fc.Advance(c.TermLength / 2)
// wait for manageWin to go back to sleep again, and then cancel the context
fc.AwaitSleepers(1)
if sleepers := fc.NumSleepers(); sleepers != 1 {
t.Errorf("unexpected number of goroutines sleeping; want %d; got %d", 1, sleepers)
}
cancel()
if err := <-acquireCh; err != context.Canceled {
t.Errorf("failed to acquire: %s", err)
}
if onElectedCalls != 1 {
t.Errorf("unexpected number of OnElected calls: %d", onElectedCalls)
}
}
func TestAcquireTrivialWithMinorContentionFakeClock(t *testing.T) {
t.Parallel()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
d := memory.NewDecider()
elected := atomicBool{}
onElectedCalls := 0
wg := sync.WaitGroup{}
defer wg.Wait()
fc := fake.NewClock(time.Now())
loserConfig := Config{
OnElected: func(context.Context, *TimeView) { t.Error("unexpected election win of loser") },
LeaderChanged: func(_ context.Context, e entry.RaceEntry) { t.Logf("lost election: %+v", e) },
LeaderID: "nottheleader",
HostPort: []string{"127.0.0.2:7123"},
Decider: d,
TermLength: time.Minute * 30,
ConnectionParams: []byte("bimbat"),
MaxClockSkew: time.Second,
Clock: fc,
}
const realleaderID = "yabadabadoo"
const realLeaderConnectionParams = "boodle_doodle"
c := Config{
Decider: d,
HostPort: []string{"127.0.0.1:8080"},
LeaderID: realleaderID,
OnElected: func(ctx context.Context, tv *TimeView) {
if elected.get() {
t.Error("OnElected called while still elected")
}
elected.set(true)
onElectedCalls++
},
OnOusting: func(ctx context.Context) {
elected.set(false)
},
LeaderChanged: func(ctx context.Context, rentry entry.RaceEntry) {
if rentry.LeaderID != realleaderID && rentry.ElectionNumber != entry.NoElections {
t.Errorf("wrong leader grabbed lock: %q", rentry.LeaderID)
}
if string(rentry.ConnectionParams) != realLeaderConnectionParams && rentry.ElectionNumber != entry.NoElections {
t.Errorf("wrong ConnectionParams: %q; expected %q",
string(rentry.ConnectionParams), realLeaderConnectionParams)
}
},
TermLength: time.Minute * 30,
MaxClockSkew: time.Second,
ConnectionParams: []byte(realLeaderConnectionParams),
Clock: fc,
}
if sleepers := fc.NumSleepers(); sleepers != 0 {
t.Errorf("unexpected number of goroutines sleeping; want %d; got %d", 0, sleepers)
}
acquireCh := make(chan error, 1)
go func() {
acquireCh <- c.Acquire(ctx)
}()
// wait until manageWin goes to sleep waiting for the next time it needs to awaken.
fc.AwaitSleepers(1)
if sleepers := fc.NumSleepers(); sleepers != 1 {
t.Errorf("unexpected number of goroutines sleeping; want %d; got %d", 1, sleepers)
}
// now that the winning candidate is sleeping after having won, spin
// off another goroutine with a loser to contend on the lock.
wg.Add(1)
go func() {
defer wg.Done()
if err := loserConfig.Acquire(ctx); err != context.Canceled {
t.Errorf("non-cancel error: %s", err)
}
}()
// Advance from our initial timestamp up to half-way into the term.
// (MaxClockSkew past the point we're expecting to wake-up)
// This should wake up our sleeping goroutine
fc.Advance(c.TermLength / 2)
// wait for manageWin to go back to sleep again, and then cancel the context
fc.AwaitSleepers(2)
if sleepers := fc.NumSleepers(); sleepers != 2 {
t.Errorf("unexpected number of goroutines sleeping; want %d; got %d", 2, sleepers)
}
cancel()
if err := <-acquireCh; err != context.Canceled {
t.Errorf("failed to acquire: %s", err)
}
if onElectedCalls != 1 {
t.Errorf("unexpected number of OnElected calls: %d", onElectedCalls)
}
}
func TestAcquireSkewedWithMinorContentionFakeClock(t *testing.T) {
t.Parallel()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
d := memory.NewDecider()
elected := atomicBool{}
onElectedCalls := 0
wg := sync.WaitGroup{}
defer wg.Wait()
fc := fake.NewClock(time.Now())
const termLen = time.Second * 10
loserConfig := Config{
OnElected: func(context.Context, *TimeView) { t.Error("unexpected election win of loser") },
LeaderChanged: func(_ context.Context, e entry.RaceEntry) { t.Logf("lost election: %+v", e) },
LeaderID: "nottheleader",
HostPort: []string{"127.0.0.2:7123"},
Decider: d,
TermLength: termLen,
ConnectionParams: []byte("bimbat"),
MaxClockSkew: time.Second,
// Use a clock-skew that's barely within the MaxClockSkew range
Clock: offset.NewOffsetClock(fc, -750*time.Millisecond),
}
const realleaderID = "yabadabadoo"
const realLeaderConnectionParams = "boodle_doodle"
c := Config{
Decider: d,
HostPort: []string{"127.0.0.1:8080"},
LeaderID: realleaderID,
OnElected: func(ctx context.Context, tv *TimeView) {
if elected.get() {
t.Error("OnElected called while still elected")
}
elected.set(true)
onElectedCalls++
},
OnOusting: func(ctx context.Context) {
elected.set(false)
},
LeaderChanged: func(ctx context.Context, rentry entry.RaceEntry) {
if rentry.LeaderID != realleaderID && rentry.ElectionNumber != entry.NoElections {
t.Errorf("wrong leader grabbed lock: %q", rentry.LeaderID)
}
if string(rentry.ConnectionParams) != realLeaderConnectionParams && rentry.ElectionNumber != entry.NoElections {
t.Errorf("wrong ConnectionParams: %q; expected %q",
string(rentry.ConnectionParams), realLeaderConnectionParams)
}
},
TermLength: termLen,
MaxClockSkew: time.Second,
ConnectionParams: []byte(realLeaderConnectionParams),
Clock: fc,
}
if sleepers := fc.NumSleepers(); sleepers != 0 {
t.Errorf("unexpected number of goroutines sleeping; want %d; got %d", 0, sleepers)
}
acquireCh := make(chan error, 1)
go func() {
acquireCh <- c.Acquire(ctx)
}()
// wait until manageWin goes to sleep waiting for the next time it needs to awaken.
fc.AwaitSleepers(1)
if sleepers := fc.NumSleepers(); sleepers != 1 {
t.Errorf("unexpected number of goroutines sleeping; want %d; got %d", 1, sleepers)
}
// now that the winning candidate is sleeping after having won, spin
// off another goroutine with a loser to contend on the lock.
wg.Add(1)
go func() {
defer wg.Done()
if err := loserConfig.Acquire(ctx); err != context.Canceled {
t.Errorf("non-cancel error: %s", err)
}
}()
// step forward 1000 times, making sure the loser never wins
for l := 0; l < 1000; l++ {
fc.Advance(time.Millisecond * 750)
fc.AwaitSleepers(2)
if sleepers := fc.NumSleepers(); sleepers != 2 {
t.Errorf("unexpected number of goroutines sleeping; want %d; got %d", 2, sleepers)
}
}
cancel()
if err := <-acquireCh; err != context.Canceled {
t.Errorf("failed to acquire: %s", err)
}
if onElectedCalls != 1 {
t.Errorf("unexpected number of OnElected calls: %d", onElectedCalls)
}
}
func TestAcquireAndReplaceWithFakeClockAndSkew(t *testing.T) {
t.Parallel()
wg := sync.WaitGroup{}
defer wg.Wait()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
d := memory.NewDecider()
firstElected := atomicBool{}
firstElectedCh := make(chan struct{})
secondElected := atomicBool{}
secondElectedCh := make(chan struct{})
onElectedCalls := 0
baseTime := time.Now()
fc := fake.NewClock(baseTime)
const secondClockOffset = -time.Second
secondWinnerClock := offset.NewOffsetClock(fc, secondClockOffset)
firstTV := (*TimeView)(nil)
firstCtx := context.Context(nil)
secondTV := (*TimeView)(nil)
secondCtx := context.Context(nil)
secondWinnerConfig := Config{
OnElected: func(ctx context.Context, tv *TimeView) {
t.Logf("election win by second winner")
secondTV = tv
secondCtx = ctx
secondElected.set(true)
close(secondElectedCh)
},
LeaderChanged: func(_ context.Context, e entry.RaceEntry) { t.Logf("lost election: %+v", e) },
OnOusting: func(ctx context.Context) {
t.Logf("second candidate ousted (or shutdown)")
select {
case <-ctx.Done():
return
default:
// this one shouldn't happen
t.Errorf("second candidate ousted, not cancelled")
}
},
LeaderID: "nottheleaderYet",
HostPort: []string{"127.0.0.2:7123"},
Decider: d,
TermLength: time.Minute * 30,
ConnectionParams: []byte("bimbat"),
MaxClockSkew: time.Second,
Clock: secondWinnerClock,
}
const realleaderID = "yabadabadoo"
const realLeaderConnectionParams = "boodle_doodle"
firstWinnerCtx, firstWinnerCancel := context.WithCancel(ctx)
c := Config{
Decider: d,
HostPort: []string{"127.0.0.1:8080"},
LeaderID: realleaderID,
OnElected: func(ctx context.Context, tv *TimeView) {
if firstElected.get() {
t.Error("OnElected called while still elected")
}
firstElected.set(true)
onElectedCalls++
firstTV = tv
firstCtx = ctx
close(firstElectedCh)
},
OnOusting: func(ctx context.Context) {
firstElected.set(false)
},
LeaderChanged: func(ctx context.Context, rentry entry.RaceEntry) {
if rentry.LeaderID != realleaderID && rentry.ElectionNumber != entry.NoElections {
t.Errorf("wrong leader grabbed lock: %q", rentry.LeaderID)
}
if string(rentry.ConnectionParams) != realLeaderConnectionParams && rentry.ElectionNumber != entry.NoElections {
t.Errorf("wrong ConnectionParams: %q; expected %q",
string(rentry.ConnectionParams), realLeaderConnectionParams)
}
},
TermLength: time.Minute * 30,
MaxClockSkew: time.Second,
ConnectionParams: []byte(realLeaderConnectionParams),
Clock: fc,
}
if sleepers := fc.NumSleepers(); sleepers != 0 {
t.Errorf("unexpected number of goroutines sleeping; want %d; got %d", 0, sleepers)
}
acquireCh := make(chan error, 1)
go func() {
acquireCh <- c.Acquire(firstWinnerCtx)
}()
// wait until manageWin goes to sleep waiting for the next time it needs to awaken.
fc.AwaitSleepers(1)
if sleepers := fc.NumSleepers(); sleepers != 1 {
t.Errorf("unexpected number of goroutines sleeping; want %d; got %d", 1, sleepers)
}
// wait for the first candidate's OnElected callback to complete
<-firstElectedCh
if firstTV == nil {
t.Fatalf("first candidate's timeview is nil")
}
// Before we advance time, verify that we have the right timestamp returned by our TimeView
if termEnd := firstTV.Get(); !termEnd.Equal(baseTime.Add(c.TermLength)) {
t.Errorf("unexpected term end in TimeView: %s; expected %s",
termEnd, baseTime.Add(c.TermLength))
}
// now that the winning candidate is sleeping after having won, spin
// off another goroutine with a loser to contend on the lock.
wg.Add(1)
go func() {
defer wg.Done()
if err := secondWinnerConfig.Acquire(ctx); err != context.Canceled {
t.Errorf("non-cancel error: %s", err)
}
}()
// make sure the secondWinner has actually gone to sleep
fc.AwaitSleepers(2)
// Advance from our initial timestamp up to half-way into the term.
// (MaxClockSkew past the point we're expecting to wake-up)
// This should wake up our sleeping goroutine
fc.Advance(c.TermLength / 2)
// wait for manageWin to go back to sleep again, and then cancel the context
fc.AwaitSleepers(2)
if sleepers := fc.NumSleepers(); sleepers != 2 {
t.Errorf("unexpected number of goroutines sleeping; want %d; got %d", 2, sleepers)
}
if firstTV == nil {
t.Fatalf("first candidate's timeview is nil")
}
select {
case <-firstCtx.Done():
t.Errorf("first candidate's callback context cancelled mid-term")
default:
}
if termEnd := firstTV.Get(); !termEnd.Equal(baseTime.Add(c.TermLength + c.TermLength/2)) {
t.Errorf("unexpected term end in TimeView: %s; expected %s",
termEnd, baseTime.Add(c.TermLength+c.TermLength/2))
}
// Cancel the first leader, so the next one can take over once we get
// to the end of the leader-election term.
firstWinnerCancel()
// wait for the first winner to exit.
if err := <-acquireCh; err != context.Canceled {
t.Errorf("failed to acquire: %s", err)
}
select {
case <-firstCtx.Done():
default:
t.Errorf("first candidate's callback context not cancelled")
}
// Now, advance to just before the end of the term (according to the
// remaining candidate)
if awoken := fc.Advance(c.TermLength/2 + secondClockOffset - time.Microsecond); awoken != 0 {
t.Errorf("too many sleepers awoken %d; wanted 0", awoken)
}
t.Logf("times: %v; now %v; first termExpiry %s", fc.Sleepers(), fc.Now(),
baseTime.Add(c.TermLength+secondClockOffset))
// now, advance all the way to the end of the term according to the
// second candidate (the second candidate should still be sleeping
// anyway)
// no one should awaken since the original lock holder had its context cancelled.
if awoken := fc.Advance(time.Microsecond); awoken != 0 {
t.Errorf("too many sleepers awoken %d; wanted 0", awoken)
}
// In this test, the max clock-skew exactly matches the skew for our
// second candidate, so we should still need another second in
// fake-time before it thinks the term is up. However, we jitter the
// return by 10%.
if awoken := fc.Advance(secondWinnerConfig.MaxClockSkew); awoken != 0 {
t.Errorf("too many sleepers awoken %d; wanted 0", awoken)
}
// now, advance 10% of the term-length so we're guaranteed that the
// client has awoken.
if awoken := fc.Advance(secondWinnerConfig.TermLength / 10); awoken != 1 {
t.Errorf("unexpected number of sleepers awoken %d; wanted 1; now: %s", awoken, fc.Now())
}
// wait for manageWin to go back to sleep, and then cancel the context
// once we've checked a few things
fc.AwaitSleepers(1)
if sleepers := fc.NumSleepers(); sleepers != 1 {
t.Errorf("unexpected number of goroutines sleeping; want %d; got %d", 1, sleepers)
}
// now, advance 50% of the term-length so we get past the extension
// done by the first candidate
if awoken := fc.Advance(secondWinnerConfig.TermLength / 2); awoken != 1 {
t.Errorf("unexpected number of sleepers awoken %d; wanted 1", awoken)
}
<-secondElectedCh
if secondTV == nil {
t.Fatalf("second candidate TimeView is nil")
}
{
e, readErr := d.ReadCurrent(ctx)
if readErr != nil {
t.Fatalf("unexpected read error: %s", readErr)
}
if !e.TermExpiry.Equal(secondTV.Get()) {
t.Errorf("unexpected timestamp in second TimeView %s; expected %s",
e.TermExpiry, secondTV.Get())
}
if e.TermExpiry.Add(-secondWinnerConfig.TermLength).Before(firstTV.Get().Add(secondClockOffset)) {
t.Errorf("second winner acquired leadership before first term ended: new begin: %s; old end: %s ",
e.TermExpiry.Add(-secondWinnerConfig.TermLength), firstTV.Get().Add(secondClockOffset))
}
}
select {
case <-secondCtx.Done():
t.Errorf("second candidate callback context cancelled prematurely")
default:
}
cancel()
if onElectedCalls != 1 {
t.Errorf("unexpected number of OnElected calls: %d", onElectedCalls)
}
}
func TestMultipleContendersWithFakeClockAndSkew(t *testing.T) {
t.Parallel()
wg := sync.WaitGroup{}
defer wg.Wait()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
d := memory.NewDecider()
type cState struct {
tv atomic.Value
ctx context.Context
elected atomicBool
c Config
oustingCh chan struct{}
}
const numContenders = 16
const termLength = time.Minute * 20
contenders := make([]cState, numContenders)
baseTime := time.Now()
fc := fake.NewClock(baseTime)
electedCh := make(chan int, 1)
for z := 0; z < numContenders; z++ {
lz := z
contenders[lz] = cState{
oustingCh: make(chan struct{}, 1),
c: Config{
OnElected: func(ctx context.Context, tv *TimeView) {
t.Logf("election win by %d", lz)
contenders[lz].tv.Store(tv)
contenders[lz].ctx = ctx
contenders[lz].elected.set(true)
electedCh <- lz
},
LeaderChanged: func(_ context.Context, e entry.RaceEntry) { t.Logf("%d lost election: %+v", lz, e) },
OnOusting: func(ctx context.Context) {
t.Logf("%d ousted", lz)
contenders[lz].elected.set(false)
select {
case contenders[lz].oustingCh <- struct{}{}:
default:
t.Logf("ousting channel would block (contender %d)", lz)
}
},
LeaderID: "maybeLeader" + strconv.Itoa(lz),
HostPort: nil,
Decider: d,
TermLength: termLength,
ConnectionParams: []byte("bimbat" + strconv.Itoa(lz)),
MaxClockSkew: time.Second,
// Give different candidates progressively earlier offsets
Clock: offset.NewOffsetClock(fc,
-time.Duration(lz)*time.Millisecond*8),
},
}
}
if sleepers := fc.NumSleepers(); sleepers != 0 {
t.Errorf("fail: unexpected number of goroutines sleeping; want %d; got %d", 0, sleepers)
}
for z := range contenders {
lz := z
wg.Add(1)
go func() {
defer wg.Done()
if err := contenders[lz].c.Acquire(ctx); err != context.Canceled {
t.Errorf("non-cancel error: %s", err)
}
}()
}
// wait until manageWin goes to sleep waiting for the next time it needs to awaken.
fc.AwaitSleepers(numContenders)
if sleepers := fc.NumSleepers(); sleepers != numContenders {
t.Errorf("fail: unexpected number of goroutines sleeping; want %d; got %d", numContenders, sleepers)
}
// wait for the first leader's OnElected callback to complete
leaderID := <-electedCh
{
leaderTV := contenders[leaderID].tv.Load()
if leaderTV == nil || leaderTV.(*TimeView) == nil {
t.Fatalf("fail: first candidate's timeview is nil")
}
// verify that no one else thinks they won this election
OTHERLEADERSLOOP:
for {
select {
case otherLeaderID := <-electedCh:
t.Errorf("fail: second winner of election %d; already have %d",
otherLeaderID, leaderID)
default:
break OTHERLEADERSLOOP
}
}
leaders := make([]int, 0, 1)
for z := range contenders {
if contenders[z].elected.get() {
leaders = append(leaders, z)
}
}
if len(leaders) > 1 {
t.Errorf("fail: multiple leaders: %v", leaders)
}
expectedTermEnd := baseTime.Add(termLength - time.Duration(leaderID)*time.Millisecond*8)
if termEnd := leaderTV.(*TimeView).Get(); !termEnd.Equal(expectedTermEnd) {
t.Errorf("fail: unexpected term end in TimeView: %s; expected %s",
termEnd, expectedTermEnd)
}
}
const maxjitterTime = time.Duration(float64(termLength) * jitterTermMaxFraction)
// Advance from our initial timestamp up to the end of the term, plus
// 10% to get past the max jitter we add
fc.Advance(termLength + maxjitterTime)
// wait for manageWin to go to sleep on the leader and all the others
// to go to sleep awaiting the next term.
fc.AwaitSleepers(numContenders)
if sleepers := fc.NumSleepers(); sleepers != numContenders {
t.Errorf("fail: unexpected number of goroutines sleeping; want %d; got %d",
numContenders, sleepers)
}
{
oldTermEnd := baseTime.Add(termLength - time.Duration(leaderID)*time.Millisecond*8)
oldLeader := leaderID
// we know that the looping/acquisition/manageWin goroutines
// are all sleeping. Find out whether the old leader extended
// its lease.
oldleaderTV := contenders[leaderID].tv.Load()
if oldleaderTV.(*TimeView).Get().Equal(oldTermEnd) {
// new leader; wait for its elected cb to complete and
// the old one's ousting channel to get a message
<-contenders[oldLeader].oustingCh
leaderID = <-electedCh
}
leaderTV := contenders[leaderID].tv.Load().(*TimeView)
if leaderTV == nil {
t.Fatalf("fail: leader's timeview is nil")
}
expectedTermEnd := baseTime.Add(2*termLength + maxjitterTime - time.Duration(leaderID)*time.Millisecond*8)
// Before we advance time, verify that we have the right
// timestamp returned by our TimeView
if termEnd := leaderTV.Get(); !termEnd.Equal(
expectedTermEnd) {
t.Errorf("fail: unexpected term end in TimeView: %s; expected %s",
termEnd, expectedTermEnd)
}
// verify that no one else thinks they won this election
OTHERLEADERSLOOP2:
for {
select {
case otherLeaderID := <-electedCh:
if otherLeaderID != leaderID {
t.Errorf("fail: second winner of election %d; already have %d",
otherLeaderID, leaderID)
}
default:
break OTHERLEADERSLOOP2
}
}
cbleaders := make([]int, 0, 1)
tvleaders := make([]int, 0, 1)
for z := range contenders {
if contenders[z].elected.get() {
cbleaders = append(cbleaders, z)
}
if contenders[z].tv.Load() != nil && contenders[z].tv.Load().(*TimeView).Get().After(contenders[z].c.Clock.Now()) {
tvleaders = append(tvleaders, z)
}
}
if len(cbleaders) > 1 {
t.Errorf("fail: multiple leaders by callback: %v", cbleaders)
}
if len(tvleaders) > 1 {
t.Errorf("fail: multiple leaders by TimeView: %v", tvleaders)
}
}
cancel()
}
type deadliningRaceDecider struct {
inner RaceDecider
// Toggle errors for reads and writes separately
deadlineWrite bool
cancelWrite bool
deadlineRead bool
cancelRead bool
}
// WriteEntry implementations should write the entry argument to
// stable-storage in a transactional-way such that only one contender
// wins per-election/term
// The interface{} return value is a new token if the write succeeded.
func (d *deadliningRaceDecider) WriteEntry(ctx context.Context, entry *entry.RaceEntry) (entry.LeaderToken, error) {
switch {
case d.cancelWrite:
return nil, fmt.Errorf("won the lottery: %w", context.Canceled)
case d.deadlineWrite:
return nil, fmt.Errorf("lost the lottery: %w", context.DeadlineExceeded)
default:
}
return d.inner.WriteEntry(ctx, entry)
}
// ReadCurrent should provide the latest version of RaceEntry available
// and put any additional information needed to ensure transactional
// behavior in the Token-field.
func (d *deadliningRaceDecider) ReadCurrent(ctx context.Context) (*entry.RaceEntry, error) {
switch {
case d.cancelRead:
return nil, fmt.Errorf("won the lottery: %w", context.Canceled)
case d.deadlineRead:
return nil, fmt.Errorf("lost the lottery: %w", context.DeadlineExceeded)
default:
}
return d.inner.ReadCurrent(ctx)
}
func TestAcquireTrivialWithMinorContentionFakeClockAndDeadliningRaceDecider(t *testing.T) {
t.Parallel()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
d := deadliningRaceDecider{
inner: memory.NewDecider(),
}
elected := atomicBool{}
onElectedCalls := 0
wg := sync.WaitGroup{}
defer wg.Wait()
fc := fake.NewClock(time.Now())
loserConfig := Config{
OnElected: func(context.Context, *TimeView) { t.Error("unexpected election win of loser") },
LeaderChanged: nil,
OnOusting: nil,
LeaderID: "nottheleader",
HostPort: []string{"127.0.0.2:7123"},
Decider: d.inner,
TermLength: time.Minute * 30,
ConnectionParams: []byte("bimbat"),
MaxClockSkew: time.Second,
Clock: fc,
}
const realleaderID = "yabadabadoo"
const realLeaderConnectionParams = "boodle_doodle"
c := Config{
Decider: &d,
HostPort: []string{"127.0.0.1:8080"},
LeaderID: realleaderID,
OnElected: func(ctx context.Context, tv *TimeView) {
if elected.get() {
t.Error("OnElected called while still elected")
}
elected.set(true)
onElectedCalls++
},
OnOusting: func(ctx context.Context) {
elected.set(false)
},
// use a nil LeaderChanged
LeaderChanged: nil,
TermLength: time.Minute * 30,
MaxClockSkew: time.Second,
ConnectionParams: []byte(realLeaderConnectionParams),
Clock: fc,
}
if sleepers := fc.NumSleepers(); sleepers != 0 {
t.Errorf("unexpected number of goroutines sleeping; want %d; got %d", 0, sleepers)
}
// make the racedecider return DeadlineExceeded
d.deadlineWrite = true
acquireCh := make(chan error, 1)
go func() {
acquireCh <- c.Acquire(ctx)
}()
// we can guarantee that both the attempt to write and the attempt to read should have failed with DeadlineExceeded here.
// wait for the backoff sleep at the end of the loop.
fc.AwaitSleepers(1)
if sleepers := fc.NumSleepers(); sleepers != 1 {
t.Errorf("unexpected number of goroutines sleeping; want %d; got %d", 1, sleepers)
}
// switch to canceled errors (now that everyone's asleep, this is safe)
d.deadlineWrite = false
d.cancelWrite = true
d.deadlineRead = true
// advance by 2ms to rouse the Acquire loop (the base backoff is 1ms)
if woken := fc.Advance(2 * time.Millisecond); woken != 1 {
t.Errorf("unexpected number of goroutines awoken by 2ms advance: %d; expected 1", woken)
}
// wait for Acquire to go back to sleep
fc.AwaitSleepers(1)
if sleepers := fc.NumSleepers(); sleepers != 1 {
t.Errorf("unexpected number of goroutines sleeping; want %d; got %d", 1, sleepers)
}
// now that everyone's asleep again, let the RaceDecider do its job
d.cancelWrite = false
d.deadlineRead = false
// advance by 2ms to rouse the Acquire loop (the base backoff is 1ms,
// and this is backoff 2 with an exponent of 1.2, so 2ms is still enough)
if woken := fc.Advance(2 * time.Millisecond); woken != 1 {
t.Errorf("unexpected number of goroutines awoken by 2ms advance: %d; expected 1", woken)
}
// now we should be able to actually win.
// wait until manageWin goes to sleep waiting for the next time it needs to awaken.
fc.AwaitSleepers(1)
if sleepers := fc.NumSleepers(); sleepers != 1 {
t.Errorf("unexpected number of goroutines sleeping; want %d; got %d", 1, sleepers)
}
// now that the winning candidate is sleeping after having won, spin
// off another goroutine with a loser to contend on the lock.
wg.Add(1)
go func() {
defer wg.Done()
if err := loserConfig.Acquire(ctx); err != context.Canceled {
t.Errorf("non-cancel error: %s", err)
}
}()
// Advance from our initial timestamp up to half-way into the term.
// (MaxClockSkew past the point we're expecting to wake-up)
// This should wake up our sleeping goroutine
fc.Advance(c.TermLength / 2)
// wait for manageWin to go back to sleep again, and then cancel the context
fc.AwaitSleepers(2)
if sleepers := fc.NumSleepers(); sleepers != 2 {
t.Errorf("unexpected number of goroutines sleeping; want %d; got %d", 2, sleepers)
}
cancel()
if err := <-acquireCh; err != context.Canceled {
t.Errorf("failed to acquire: %s", err)
}
if onElectedCalls != 1 {
t.Errorf("unexpected number of OnElected calls: %d", onElectedCalls)
}
}
func TestAcquireFakeClockAndDeadliningRaceDecider(t *testing.T) {
t.Parallel()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
d := deadliningRaceDecider{
inner: memory.NewDecider(),
}
elected := atomicBool{}
onElectedCalls := uint64(0)
wg := sync.WaitGroup{}
defer wg.Wait()
fc := fake.NewClock(time.Now())
loserOK := atomicBool{}
loserConfig := Config{
OnElected: func(context.Context, *TimeView) {
if loserOK.get() {
return
}
t.Error("unexpected election win of loser")
},
LeaderChanged: nil,
OnOusting: nil,
LeaderID: "nottheleader",
HostPort: []string{"127.0.0.2:7123"},
Decider: d.inner,
TermLength: time.Minute * 30,
ConnectionParams: []byte("bimbat"),
MaxClockSkew: time.Second,
Clock: fc,
}
const realleaderID = "yabadabadoo"
const realLeaderConnectionParams = "boodle_doodle"
oustCh := make(chan struct{}, 3)
c := Config{
Decider: &d,
HostPort: []string{"127.0.0.1:8080"},
LeaderID: realleaderID,
OnElected: func(ctx context.Context, tv *TimeView) {
if elected.get() {
t.Error("OnElected called while still elected")
}
elected.set(true)
atomic.AddUint64(&onElectedCalls, 1)
},
OnOusting: func(ctx context.Context) {
elected.set(false)
select {
case oustCh <- struct{}{}:
default:
t.Errorf("filled up ousting channel (capacity %d)", cap(oustCh))
}
},
// use a nil LeaderChanged
LeaderChanged: nil,
TermLength: time.Minute * 30,
MaxClockSkew: time.Second,
ConnectionParams: []byte(realLeaderConnectionParams),
Clock: fc,
}
if sleepers := fc.NumSleepers(); sleepers != 0 {
t.Errorf("unexpected number of goroutines sleeping; want %d; got %d", 0, sleepers)
}
// make the racedecider return DeadlineExceeded
d.deadlineWrite = true
acquireCh := make(chan error, 1)
go func() {
acquireCh <- c.Acquire(ctx)
}()
// we can guarantee that both the attempt to write and the attempt to read should have failed with DeadlineExceeded here.
// wait for the backoff sleep at the end of the loop.
fc.AwaitSleepers(1)
if sleepers := fc.NumSleepers(); sleepers != 1 {
t.Errorf("unexpected number of goroutines sleeping; want %d; got %d", 1, sleepers)
}
// switch to canceled errors (now that everyone's asleep, this is safe)
d.deadlineWrite = false
d.cancelWrite = true
d.deadlineRead = true
// advance by 2ms to rouse the Acquire loop (the base backoff is 1ms)
if woken := fc.Advance(2 * time.Millisecond); woken != 1 {
t.Errorf("unexpected number of goroutines awoken by 2ms advance: %d; expected 1", woken)
}
// wait for Acquire to go back to sleep
fc.AwaitSleepers(1)