forked from cockroachdb/cockroach
-
Notifications
You must be signed in to change notification settings - Fork 0
/
context_test.go
1397 lines (1221 loc) · 44 KB
/
context_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
// Copyright 2014 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0, included in the file
// licenses/APL.txt.
package rpc
import (
"context"
"fmt"
"math"
"net"
"strconv"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/cockroachdb/cockroach/pkg/roachpb"
"github.com/cockroachdb/cockroach/pkg/settings/cluster"
"github.com/cockroachdb/cockroach/pkg/testutils"
"github.com/cockroachdb/cockroach/pkg/util"
"github.com/cockroachdb/cockroach/pkg/util/grpcutil"
"github.com/cockroachdb/cockroach/pkg/util/hlc"
"github.com/cockroachdb/cockroach/pkg/util/leaktest"
"github.com/cockroachdb/cockroach/pkg/util/log"
"github.com/cockroachdb/cockroach/pkg/util/netutil"
"github.com/cockroachdb/cockroach/pkg/util/retry"
"github.com/cockroachdb/cockroach/pkg/util/stop"
"github.com/cockroachdb/cockroach/pkg/util/syncutil"
"github.com/cockroachdb/cockroach/pkg/util/timeutil"
"github.com/cockroachdb/cockroach/pkg/util/tracing"
"github.com/cockroachdb/cockroach/pkg/util/uuid"
"github.com/cockroachdb/logtags"
"github.com/pkg/errors"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/keepalive"
"google.golang.org/grpc/status"
)
// AddTestingDialOpts adds extra dialing options to the rpc Context. This should
// be done before GRPCDial is called.
func (ctx *Context) AddTestingDialOpts(opts ...grpc.DialOption) {
ctx.testingDialOpts = append(ctx.testingDialOpts, opts...)
}
func newTestServer(t testing.TB, ctx *Context, extraOpts ...grpc.ServerOption) *grpc.Server {
tlsConfig, err := ctx.GetServerTLSConfig()
if err != nil {
t.Fatal(err)
}
opts := []grpc.ServerOption{
grpc.Creds(credentials.NewTLS(tlsConfig)),
grpc.StatsHandler(&ctx.stats),
}
opts = append(opts, extraOpts...)
return grpc.NewServer(opts...)
}
func newTestContext(clusterID uuid.UUID, clock *hlc.Clock, stopper *stop.Stopper) *Context {
rctx := NewContext(
log.AmbientContext{Tracer: tracing.NewTracer()},
testutils.NewNodeTestBaseContext(),
clock,
stopper,
&cluster.MakeTestingClusterSettings().Version,
)
// Ensure that tests using this test context and restart/shut down
// their servers do not inadvertently start talking to servers from
// unrelated concurrent tests.
rctx.ClusterID.Set(context.TODO(), clusterID)
return rctx
}
func TestHeartbeatCB(t *testing.T) {
defer leaktest.AfterTest(t)()
testutils.RunTrueAndFalse(t, "compression", func(t *testing.T, compression bool) {
stopper := stop.NewStopper()
defer stopper.Stop(context.TODO())
// Shared cluster ID by all RPC peers (this ensures that the peers
// don't talk to servers from unrelated tests by accident).
clusterID := uuid.MakeV4()
clock := hlc.NewClock(timeutil.Unix(0, 20).UnixNano, time.Nanosecond)
serverCtx := newTestContext(clusterID, clock, stopper)
serverCtx.rpcCompression = compression
const serverNodeID = 1
serverCtx.NodeID.Set(context.TODO(), serverNodeID)
s := newTestServer(t, serverCtx)
RegisterHeartbeatServer(s, &HeartbeatService{
clock: clock,
remoteClockMonitor: serverCtx.RemoteClocks,
clusterID: &serverCtx.ClusterID,
nodeID: &serverCtx.NodeID,
version: serverCtx.version,
})
ln, err := netutil.ListenAndServeGRPC(serverCtx.Stopper, s, util.TestAddr)
if err != nil {
t.Fatal(err)
}
remoteAddr := ln.Addr().String()
// Clocks don't matter in this test.
clientCtx := newTestContext(clusterID, clock, stopper)
clientCtx.rpcCompression = compression
var once sync.Once
ch := make(chan struct{})
clientCtx.HeartbeatCB = func() {
once.Do(func() {
close(ch)
})
}
if _, err := clientCtx.GRPCDialNode(remoteAddr, serverNodeID).Connect(context.Background()); err != nil {
t.Fatal(err)
}
<-ch
})
}
type internalServer struct{}
func (*internalServer) Batch(
context.Context, *roachpb.BatchRequest,
) (*roachpb.BatchResponse, error) {
return nil, nil
}
func (*internalServer) RangeFeed(
_ *roachpb.RangeFeedRequest, _ roachpb.Internal_RangeFeedServer,
) error {
panic("unimplemented")
}
// TestInternalServerAddress verifies that RPCContext uses AdvertiseAddr, not Addr, to
// determine whether to apply the local server optimization.
//
// Prevents regression of https://github.com/cockroachdb/cockroach/issues/19991.
func TestInternalServerAddress(t *testing.T) {
defer leaktest.AfterTest(t)()
stopper := stop.NewStopper()
defer stopper.Stop(context.TODO())
// Can't be zero because that'd be an empty offset.
clock := hlc.NewClock(timeutil.Unix(0, 1).UnixNano, time.Nanosecond)
serverCtx := newTestContext(uuid.MakeV4(), clock, stopper)
serverCtx.Config.Addr = "127.0.0.1:9999"
serverCtx.Config.AdvertiseAddr = "127.0.0.1:8888"
serverCtx.NodeID.Set(context.TODO(), 1)
internal := &internalServer{}
serverCtx.SetLocalInternalServer(internal)
exp := internalClientAdapter{internal}
if ic := serverCtx.GetLocalInternalClientForAddr(serverCtx.Config.AdvertiseAddr, 1); ic != exp {
t.Fatalf("expected %+v, got %+v", exp, ic)
}
}
// TestHeartbeatHealth verifies that the health status changes after
// heartbeats succeed or fail.
func TestHeartbeatHealth(t *testing.T) {
defer leaktest.AfterTest(t)()
stopper := stop.NewStopper()
defer stopper.Stop(context.TODO())
// Can't be zero because that'd be an empty offset.
clock := hlc.NewClock(timeutil.Unix(0, 1).UnixNano, time.Nanosecond)
// Shared cluster ID by all RPC peers (this ensures that the peers
// don't talk to servers from unrelated tests by accident).
clusterID := uuid.MakeV4()
const serverNodeID = 1
const clientNodeID = 2
serverCtx := newTestContext(clusterID, clock, stop.NewStopper())
serverCtx.NodeID.Set(context.TODO(), serverNodeID)
s := newTestServer(t, serverCtx)
heartbeat := &ManualHeartbeatService{
ready: make(chan error),
stopper: stopper,
clock: clock,
remoteClockMonitor: serverCtx.RemoteClocks,
version: serverCtx.version,
nodeID: &serverCtx.NodeID,
}
RegisterHeartbeatServer(s, heartbeat)
errFailedHeartbeat := errors.New("failed heartbeat")
var hbSuccess atomic.Value
hbSuccess.Store(true)
go func() {
for {
var err error
if !hbSuccess.Load().(bool) {
err = errFailedHeartbeat
}
select {
case <-stopper.ShouldStop():
return
case heartbeat.ready <- err:
}
}
}()
lisNotLocalServer, err := net.Listen("tcp", "127.0.0.1:0")
defer func() {
netutil.FatalIfUnexpected(lisNotLocalServer.Close())
}()
if err != nil {
t.Fatal(err)
}
lisLocalServer, err := net.Listen("tcp", "127.0.0.1:0")
defer func() {
netutil.FatalIfUnexpected(lisLocalServer.Close())
}()
if err != nil {
t.Fatal(err)
}
clientCtx := newTestContext(clusterID, clock, stopper)
clientCtx.NodeID.Set(context.TODO(), clientNodeID)
clientCtx.Addr = lisNotLocalServer.Addr().String()
clientCtx.AdvertiseAddr = lisLocalServer.Addr().String()
// Make the interval shorter to speed up the test.
clientCtx.heartbeatInterval = 1 * time.Millisecond
ln, err := netutil.ListenAndServeGRPC(serverCtx.Stopper, s, util.TestAddr)
if err != nil {
t.Fatal(err)
}
remoteAddr := ln.Addr().String()
if _, err := clientCtx.GRPCDialNode(
remoteAddr, serverNodeID).Connect(context.Background()); err != nil {
t.Fatal(err)
}
// Wait for the connection.
testutils.SucceedsSoon(t, func() error {
err := clientCtx.TestingConnHealth(remoteAddr, serverNodeID)
if err != nil && err != ErrNotHeartbeated {
t.Fatal(err)
}
return err
})
assertGauges(t, clientCtx.Metrics(),
0 /* initializing */, 1 /* nominal */, 0 /* failed */)
// Should be unhealthy in the presence of failing heartbeats.
hbSuccess.Store(false)
testutils.SucceedsSoon(t, func() error {
if err := clientCtx.TestingConnHealth(remoteAddr, serverNodeID); !testutils.IsError(err, errFailedHeartbeat.Error()) {
return errors.Errorf("unexpected error: %v", err)
}
return nil
})
assertGauges(t, clientCtx.Metrics(),
0 /* initializing */, 0 /* nominal */, 1 /* failed */)
// Should become healthy in the presence of successful heartbeats.
hbSuccess.Store(true)
testutils.SucceedsSoon(t, func() error {
return clientCtx.TestingConnHealth(remoteAddr, serverNodeID)
})
assertGauges(t, clientCtx.Metrics(),
0 /* initializing */, 1 /* nominal */, 0 /* failed */)
// Should become unhealthy again in the presence of failing heartbeats.
hbSuccess.Store(false)
testutils.SucceedsSoon(t, func() error {
if err := clientCtx.TestingConnHealth(remoteAddr, serverNodeID); !testutils.IsError(err, errFailedHeartbeat.Error()) {
return errors.Errorf("unexpected error: %v", err)
}
return nil
})
assertGauges(t, clientCtx.Metrics(),
0 /* initializing */, 0 /* nominal */, 1 /* failed */)
// Should become healthy in the presence of successful heartbeats.
hbSuccess.Store(true)
testutils.SucceedsSoon(t, func() error {
return clientCtx.TestingConnHealth(remoteAddr, serverNodeID)
})
assertGauges(t, clientCtx.Metrics(),
0 /* initializing */, 1 /* nominal */, 0 /* failed */)
// Ensure that non-existing connections return ErrNotHeartbeated.
lisNonExistentConnection, err := net.Listen("tcp", "127.0.0.1:0")
defer func() {
netutil.FatalIfUnexpected(lisNonExistentConnection.Close())
}()
if err != nil {
t.Fatal(err)
}
if err := clientCtx.TestingConnHealth(lisNonExistentConnection.Addr().String(), 3); err != ErrNotHeartbeated {
t.Errorf("wanted ErrNotHeartbeated, not %v", err)
}
// The connection to Node 3 on the lisNonExistentConnection should be
// initializing and the server connection should be nominal.
testutils.SucceedsSoon(t, func() error {
return checkGauges(clientCtx.Metrics(),
1 /* initializing */, 1 /* nominal */, 0 /* failed */)
})
if err := clientCtx.TestingConnHealth(clientCtx.Addr, clientNodeID); err != ErrNotHeartbeated {
t.Errorf("wanted ErrNotHeartbeated, not %v", err)
}
// Ensure that the local Addr returns ErrNotHeartbeated without having dialed
// a connection but the local AdvertiseAddr successfully returns no error when
// an internal server has been registered.
clientCtx.SetLocalInternalServer(&internalServer{})
if err := clientCtx.TestingConnHealth(clientCtx.Addr, clientNodeID); err != ErrNotHeartbeated {
t.Errorf("wanted ErrNotHeartbeated, not %v", err)
}
if err := clientCtx.TestingConnHealth(clientCtx.AdvertiseAddr, clientNodeID); err != nil {
t.Error(err)
}
// Ensure that when the server closes its connection the context attempts to
// reconnect. Both the server connection on Node 1 and the non-existent
// connection should be initializing.
serverCtx.Stopper.Stop(context.Background())
testutils.SucceedsSoon(t, func() error {
return checkGauges(clientCtx.Metrics(),
2 /* initializing */, 0 /* nominal */, 0 /* failed */)
})
const expNumStarted = 3 // 2 for the server and 1 for the non-existent conn
numStarted := clientCtx.Metrics().HeartbeatLoopsStarted.Count()
if numStarted != expNumStarted {
t.Fatalf("expected %d heartbeat loops to have been started, got %d",
expNumStarted, numStarted)
}
const expNumExited = 1 // 1 for the server upon shutdown
numExited := clientCtx.Metrics().HeartbeatLoopsExited.Count()
if numExited != expNumExited {
t.Fatalf("expected %d heartbeat loops to have exited, got %d",
expNumExited, numExited)
}
}
func checkGauges(m *Metrics, initializing, nominal, failed int64) error {
if got := m.HeartbeatsInitializing.Value(); got != initializing {
return errors.Errorf("expected %d initializing heartbeats, got %d", initializing, got)
}
if got := m.HeartbeatsNominal.Value(); got != nominal {
return errors.Errorf("expected %d nominal heartbeats, got %d", nominal, got)
}
if got := m.HeartbeatsFailed.Value(); got != failed {
return errors.Errorf("expected %d failed heartbeats, got %d", failed, got)
}
return nil
}
func assertGauges(t *testing.T, m *Metrics, initializing, nominal, failed int64) {
t.Helper()
if err := checkGauges(m, initializing, nominal, failed); err != nil {
t.Error(err)
}
}
// TestConnectionRemoveNodeIDZero verifies that when a connection initiated via
// GRPCDialNode fails, we also clean up the connection returned by
// GRPCUnvalidatedDial.
//
// See #37200.
func TestConnectionRemoveNodeIDZero(t *testing.T) {
defer leaktest.AfterTest(t)()
ctx := context.Background()
stopper := stop.NewStopper()
defer stopper.Stop(ctx)
clock := hlc.NewClock(hlc.UnixNano, time.Nanosecond)
clientCtx := newTestContext(uuid.MakeV4(), clock, stopper)
// Provoke an error.
_, err := clientCtx.GRPCDialNode("127.0.0.1:notaport", 1).Connect(context.Background())
if err == nil {
t.Fatal("expected some kind of error, got nil")
}
// NB: this takes a moment because GRPCDialRaw only gives up on the initial
// connection after 1s (more precisely, the redialChan gets closed only after
// 1s), which seems difficult to configure ad-hoc.
testutils.SucceedsSoon(t, func() error {
var keys []connKey
clientCtx.conns.Range(func(k, v interface{}) bool {
keys = append(keys, k.(connKey))
return true
})
if len(keys) > 0 {
return errors.Errorf("still have connections %v", keys)
}
return nil
})
}
type interceptingListener struct {
net.Listener
connCB func(net.Conn)
}
func (ln *interceptingListener) Accept() (net.Conn, error) {
conn, err := ln.Listener.Accept()
if err == nil {
ln.connCB(conn)
}
return conn, err
}
// TestHeartbeatHealth verifies that the health status changes after
// heartbeats succeed or fail due to transport failures.
func TestHeartbeatHealthTransport(t *testing.T) {
defer leaktest.AfterTest(t)()
stopper := stop.NewStopper()
defer stopper.Stop(context.TODO())
ctx := context.Background()
// Shared cluster ID by all RPC peers (this ensures that the peers
// don't talk to servers from unrelated tests by accident).
clusterID := uuid.MakeV4()
// Can't be zero because that'd be an empty offset.
clock := hlc.NewClock(timeutil.Unix(0, 1).UnixNano, time.Nanosecond)
serverCtx := newTestContext(clusterID, clock, stopper)
const serverNodeID = 1
serverCtx.NodeID.Set(context.TODO(), serverNodeID)
// newTestServer with a custom listener.
tlsConfig, err := serverCtx.GetServerTLSConfig()
if err != nil {
t.Fatal(err)
}
s := grpc.NewServer(grpc.Creds(credentials.NewTLS(tlsConfig)))
RegisterHeartbeatServer(s, &HeartbeatService{
clock: clock,
remoteClockMonitor: serverCtx.RemoteClocks,
clusterID: &serverCtx.ClusterID,
nodeID: &serverCtx.NodeID,
version: serverCtx.version,
})
mu := struct {
syncutil.Mutex
conns []net.Conn
autoClose bool
}{}
ln := func() *interceptingListener {
ln, err := net.Listen("tcp", util.TestAddr.String())
if err != nil {
t.Fatal(err)
}
return &interceptingListener{
Listener: ln,
connCB: func(conn net.Conn) {
mu.Lock()
if mu.autoClose {
_ = conn.Close()
} else {
mu.conns = append(mu.conns, conn)
}
mu.Unlock()
}}
}()
stopper.RunWorker(ctx, func(context.Context) {
<-stopper.ShouldQuiesce()
netutil.FatalIfUnexpected(ln.Close())
<-stopper.ShouldStop()
s.Stop()
})
stopper.RunWorker(ctx, func(context.Context) {
netutil.FatalIfUnexpected(s.Serve(ln))
})
remoteAddr := ln.Addr().String()
clientCtx := newTestContext(clusterID, clock, stopper)
// Make the interval shorter to speed up the test.
clientCtx.heartbeatInterval = 1 * time.Millisecond
if _, err := clientCtx.GRPCDialNode(remoteAddr, serverNodeID).Connect(context.Background()); err != nil {
t.Fatal(err)
}
// Everything is normal; should become healthy.
testutils.SucceedsSoon(t, func() error {
return clientCtx.TestingConnHealth(remoteAddr, serverNodeID)
})
closeConns := func() (numClosed int, _ error) {
mu.Lock()
defer mu.Unlock()
n := len(mu.conns)
for i := n - 1; i >= 0; i-- {
if err := mu.conns[i].Close(); err != nil {
return 0, err
}
mu.conns = mu.conns[:i]
}
return n, nil
}
isUnhealthy := func(err error) bool {
// Most of the time, an unhealthy connection will get
// ErrNotHeartbeated, but there are brief periods during which we
// could get one of the grpc errors below (while the old
// connection is in the middle of closing).
if err == ErrNotHeartbeated {
return true
}
// The expected code here is Unavailable, but at least on OSX you can also get
//
// rpc error: code = Internal desc = connection error: desc = "transport: authentication
// handshake failed: write tcp 127.0.0.1:53936->127.0.0.1:53934: write: broken pipe".
code := status.Code(err)
return code == codes.Unavailable || code == codes.Internal
}
// Close all the connections until we see a failure on the main goroutine.
done := make(chan struct{})
if err := stopper.RunAsyncTask(ctx, "busyloop-closer", func(ctx context.Context) {
for {
if _, err := closeConns(); err != nil {
log.Warning(ctx, err)
}
select {
case <-done:
return
default:
}
}
}); err != nil {
t.Fatal(err)
}
// We don't use SucceedsSoon because that internally uses doubling backoffs, and
// it doesn't need too much bad luck to run into the time limit.
for then := timeutil.Now(); ; {
err := func() error {
if err := clientCtx.TestingConnHealth(remoteAddr, serverNodeID); !isUnhealthy(err) {
return errors.Errorf("unexpected error: %v", err)
}
return nil
}()
if err == nil {
break
}
if timeutil.Since(then) > 45*time.Second {
t.Fatal(err)
}
time.Sleep(10 * time.Millisecond)
}
close(done)
// We can reconnect and the connection becomes healthy again.
testutils.SucceedsSoon(t, func() error {
if _, err := clientCtx.GRPCDialNode(remoteAddr, serverNodeID).Connect(context.Background()); err != nil {
return err
}
return clientCtx.TestingConnHealth(remoteAddr, serverNodeID)
})
// Close the listener and all the connections. Note that if we
// only closed the listener, recently-accepted-but-not-yet-handled
// connections could sneak in and randomly make the target healthy
// again. To avoid this, we flip the boolean below which is used in
// our handler callback to eagerly close any stragglers.
mu.Lock()
mu.autoClose = true
mu.Unlock()
if err := ln.Close(); err != nil {
t.Fatal(err)
}
// Also terminate any existing connections.
if _, err := closeConns(); err != nil {
t.Fatal(err)
}
// Should become unhealthy again now that the connection was closed.
testutils.SucceedsSoon(t, func() error {
err := clientCtx.TestingConnHealth(remoteAddr, serverNodeID)
if !isUnhealthy(err) {
return errors.Errorf("unexpected error: %v", err)
}
return nil
})
// Should stay unhealthy despite reconnection attempts.
for then := timeutil.Now(); timeutil.Since(then) < 50*clientCtx.heartbeatInterval; {
err := clientCtx.TestingConnHealth(remoteAddr, serverNodeID)
if !isUnhealthy(err) {
t.Fatal(err)
}
}
}
func TestOffsetMeasurement(t *testing.T) {
defer leaktest.AfterTest(t)()
stopper := stop.NewStopper()
defer stopper.Stop(context.TODO())
// Shared cluster ID by all RPC peers (this ensures that the peers
// don't talk to servers from unrelated tests by accident).
clusterID := uuid.MakeV4()
serverTime := timeutil.Unix(0, 20)
serverClock := hlc.NewClock(serverTime.UnixNano, time.Nanosecond)
serverCtx := newTestContext(clusterID, serverClock, stopper)
const serverNodeID = 1
serverCtx.NodeID.Set(context.TODO(), serverNodeID)
s := newTestServer(t, serverCtx)
RegisterHeartbeatServer(s, &HeartbeatService{
clock: serverClock,
remoteClockMonitor: serverCtx.RemoteClocks,
clusterID: &serverCtx.ClusterID,
nodeID: &serverCtx.NodeID,
version: serverCtx.version,
})
ln, err := netutil.ListenAndServeGRPC(serverCtx.Stopper, s, util.TestAddr)
if err != nil {
t.Fatal(err)
}
remoteAddr := ln.Addr().String()
// Create a client clock that is behind the server clock.
clientAdvancing := AdvancingClock{time: timeutil.Unix(0, 10)}
clientClock := hlc.NewClock(clientAdvancing.UnixNano, time.Nanosecond)
clientCtx := newTestContext(clusterID, clientClock, stopper)
// Make the interval shorter to speed up the test.
clientCtx.heartbeatInterval = 1 * time.Millisecond
clientCtx.RemoteClocks.offsetTTL = 5 * clientAdvancing.getAdvancementInterval()
if _, err := clientCtx.GRPCDialNode(remoteAddr, serverNodeID).Connect(context.Background()); err != nil {
t.Fatal(err)
}
expectedOffset := RemoteOffset{Offset: 10, Uncertainty: 0, MeasuredAt: 10}
testutils.SucceedsSoon(t, func() error {
clientCtx.RemoteClocks.mu.Lock()
defer clientCtx.RemoteClocks.mu.Unlock()
if o, ok := clientCtx.RemoteClocks.mu.offsets[remoteAddr]; !ok {
return errors.Errorf("expected offset of %s to be initialized, but it was not", remoteAddr)
} else if o != expectedOffset {
return errors.Errorf("expected:\n%v\nactual:\n%v", expectedOffset, o)
}
return nil
})
// Change the client such that it receives a heartbeat right after the
// maximum clock reading delay.
clientAdvancing.setAdvancementInterval(
maximumPingDurationMult*clientClock.MaxOffset() + 1*time.Nanosecond)
testutils.SucceedsSoon(t, func() error {
clientCtx.RemoteClocks.mu.Lock()
defer clientCtx.RemoteClocks.mu.Unlock()
if o, ok := clientCtx.RemoteClocks.mu.offsets[remoteAddr]; ok {
return errors.Errorf("expected offset to have been cleared, but found %s", o)
}
return nil
})
}
func TestFailedOffsetMeasurement(t *testing.T) {
defer leaktest.AfterTest(t)()
stopper := stop.NewStopper()
defer stopper.Stop(context.TODO())
// Shared cluster ID by all RPC peers (this ensures that the peers
// don't talk to servers from unrelated tests by accident).
clusterID := uuid.MakeV4()
// Can't be zero because that'd be an empty offset.
clock := hlc.NewClock(timeutil.Unix(0, 1).UnixNano, time.Nanosecond)
serverCtx := newTestContext(clusterID, clock, stopper)
const serverNodeID = 1
serverCtx.NodeID.Set(context.TODO(), serverNodeID)
s := newTestServer(t, serverCtx)
heartbeat := &ManualHeartbeatService{
clock: clock,
remoteClockMonitor: serverCtx.RemoteClocks,
ready: make(chan error),
stopper: stopper,
version: serverCtx.version,
nodeID: &serverCtx.NodeID,
}
RegisterHeartbeatServer(s, heartbeat)
ln, err := netutil.ListenAndServeGRPC(serverCtx.Stopper, s, util.TestAddr)
if err != nil {
t.Fatal(err)
}
remoteAddr := ln.Addr().String()
// Create a client that never receives a heartbeat after the first.
clientCtx := newTestContext(clusterID, clock, stopper)
// Remove the timeout so that failure arises from exceeding the maximum
// clock reading delay, not the timeout.
clientCtx.heartbeatTimeout = 0
go func() { heartbeat.ready <- nil }() // Allow one heartbeat for initialization.
if _, err := clientCtx.GRPCDialNode(remoteAddr, serverNodeID).Connect(context.Background()); err != nil {
t.Fatal(err)
}
testutils.SucceedsSoon(t, func() error {
clientCtx.RemoteClocks.mu.Lock()
defer clientCtx.RemoteClocks.mu.Unlock()
if _, ok := clientCtx.RemoteClocks.mu.offsets[remoteAddr]; !ok {
return errors.Errorf("expected offset of %s to be initialized, but it was not", remoteAddr)
}
return nil
})
testutils.SucceedsSoon(t, func() error {
serverCtx.RemoteClocks.mu.Lock()
defer serverCtx.RemoteClocks.mu.Unlock()
if o, ok := serverCtx.RemoteClocks.mu.offsets[remoteAddr]; ok {
return errors.Errorf("expected offset of %s to not be initialized, but it was: %v", remoteAddr, o)
}
return nil
})
}
type AdvancingClock struct {
syncutil.Mutex
time time.Time
advancementInterval atomic.Value // time.Duration
}
func (ac *AdvancingClock) setAdvancementInterval(d time.Duration) {
ac.advancementInterval.Store(d)
}
func (ac *AdvancingClock) getAdvancementInterval() time.Duration {
v := ac.advancementInterval.Load()
if v == nil {
return 0
}
return v.(time.Duration)
}
func (ac *AdvancingClock) UnixNano() int64 {
ac.Lock()
time := ac.time
ac.time = time.Add(ac.getAdvancementInterval())
ac.Unlock()
return time.UnixNano()
}
func TestRemoteOffsetUnhealthy(t *testing.T) {
defer leaktest.AfterTest(t)()
stopper := stop.NewStopper()
defer stopper.Stop(context.TODO())
const maxOffset = 100 * time.Millisecond
type nodeContext struct {
offset time.Duration
ctx *Context
errChan chan error
}
start := time.Date(2012, 12, 07, 0, 0, 0, 0, time.UTC)
nodeCtxs := []nodeContext{
{offset: 0},
{offset: 0},
{offset: 0},
// The minimum offset that actually triggers node death.
{offset: maxOffset + 1},
}
// Shared cluster ID by all RPC peers (this ensures that the peers
// don't talk to servers from unrelated tests by accident).
clusterID := uuid.MakeV4()
for i := range nodeCtxs {
clock := hlc.NewClock(start.Add(nodeCtxs[i].offset).UnixNano, maxOffset)
nodeCtxs[i].errChan = make(chan error, 1)
nodeCtxs[i].ctx = newTestContext(clusterID, clock, stopper)
nodeCtxs[i].ctx.heartbeatInterval = maxOffset
nodeCtxs[i].ctx.NodeID.Set(context.TODO(), roachpb.NodeID(i+1))
s := newTestServer(t, nodeCtxs[i].ctx)
RegisterHeartbeatServer(s, &HeartbeatService{
clock: clock,
remoteClockMonitor: nodeCtxs[i].ctx.RemoteClocks,
clusterID: &nodeCtxs[i].ctx.ClusterID,
nodeID: &nodeCtxs[i].ctx.NodeID,
version: nodeCtxs[i].ctx.version,
})
ln, err := netutil.ListenAndServeGRPC(nodeCtxs[i].ctx.Stopper, s, util.TestAddr)
if err != nil {
t.Fatal(err)
}
nodeCtxs[i].ctx.Addr = ln.Addr().String()
}
// Fully connect the nodes.
for i, clientNodeContext := range nodeCtxs {
for j, serverNodeContext := range nodeCtxs {
if i == j {
continue
}
if _, err := clientNodeContext.ctx.GRPCDialNode(
serverNodeContext.ctx.Addr,
serverNodeContext.ctx.NodeID.Get(),
).Connect(context.Background()); err != nil {
t.Fatal(err)
}
}
}
// Wait until all nodes are connected to all other nodes.
for _, nodeCtx := range nodeCtxs {
testutils.SucceedsSoon(t, func() error {
nodeCtx.ctx.RemoteClocks.mu.Lock()
defer nodeCtx.ctx.RemoteClocks.mu.Unlock()
if a, e := len(nodeCtx.ctx.RemoteClocks.mu.offsets), len(nodeCtxs)-1; a != e {
return errors.Errorf("not yet fully connected: have %d of %d connections: %v", a, e, nodeCtx.ctx.RemoteClocks.mu.offsets)
}
return nil
})
}
for i, nodeCtx := range nodeCtxs {
if nodeOffset := nodeCtx.offset; nodeOffset > maxOffset {
if err := nodeCtx.ctx.RemoteClocks.VerifyClockOffset(nodeCtx.ctx.masterCtx); testutils.IsError(err, errOffsetGreaterThanMaxOffset) {
t.Logf("max offset: %s - node %d with excessive clock offset of %s returned expected error: %s", maxOffset, i, nodeOffset, err)
} else {
t.Errorf("max offset: %s - node %d with excessive clock offset of %s returned unexpected error: %v", maxOffset, i, nodeOffset, err)
}
} else {
if err := nodeCtx.ctx.RemoteClocks.VerifyClockOffset(nodeCtx.ctx.masterCtx); err != nil {
t.Errorf("max offset: %s - node %d with acceptable clock offset of %s returned unexpected error: %s", maxOffset, i, nodeOffset, err)
} else {
t.Logf("max offset: %s - node %d with acceptable clock offset of %s did not return an error, as expected", maxOffset, i, nodeOffset)
}
}
}
}
// This is a smoketest for gRPC Keepalives: rpc.Context asks gRPC to perform
// periodic pings on the transport to check that it's still alive. If the ping
// doesn't get a pong within a timeout, the transport is supposed to be closed -
// that's what we're testing here. Likewise, serverside keepalive ensures that
// if a ping is not seen within a timeout, the transport will also be closed.
//
// In this test we use a TestingHeartbeatStreamService as oppposed to a standard
// HeartbeatService. This is important to test scenarios where the
// client->server connection is partitioned but the server->client connection is
// healthy, because a TestingHeartbeatStreamService will continue to respond on
// its response stream even if it doesn't get any new requests.
func TestGRPCKeepaliveFailureFailsInflightRPCs(t *testing.T) {
defer leaktest.AfterTest(t)()
t.Skip("Takes too long given https://github.com/grpc/grpc-go/pull/2642")
sc := log.Scope(t)
defer sc.Close(t)
testCases := []grpcKeepaliveTestCase{
// Keepalive doesn't matter if the network is fine.
{cKeepalive: false, sKeepalive: false, partitionC2S: false, partitionS2C: false, expClose: false},
// No keepalive. Never detects network issues.
{cKeepalive: false, sKeepalive: false, partitionC2S: true, partitionS2C: false, expClose: false},
{cKeepalive: false, sKeepalive: false, partitionC2S: false, partitionS2C: true, expClose: false},
{cKeepalive: false, sKeepalive: false, partitionC2S: true, partitionS2C: true, expClose: false},
// Client-only keepalive. Doesn't detect client->server partition.
{cKeepalive: true, sKeepalive: false, partitionC2S: true, partitionS2C: false, expClose: false},
{cKeepalive: true, sKeepalive: false, partitionC2S: false, partitionS2C: true, expClose: true},
{cKeepalive: true, sKeepalive: false, partitionC2S: true, partitionS2C: true, expClose: true},
// Server-only keepalive. Only detects server->client partition. The
// bi-directional partition case (third case) may be is surprising.
// The reason the client doesn't close the connection is because it
// does not receive the connection closed message sent by the server.
// This demonstrates why client keepalive is so important.
{cKeepalive: false, sKeepalive: true, partitionC2S: true, partitionS2C: false, expClose: true},
{cKeepalive: false, sKeepalive: true, partitionC2S: false, partitionS2C: true, expClose: false},
{cKeepalive: false, sKeepalive: true, partitionC2S: true, partitionS2C: true, expClose: false},
// Client and Server keepalive. Detects all partitions!
{cKeepalive: true, sKeepalive: true, partitionC2S: true, partitionS2C: false, expClose: true},
{cKeepalive: true, sKeepalive: true, partitionC2S: false, partitionS2C: true, expClose: true},
{cKeepalive: true, sKeepalive: true, partitionC2S: true, partitionS2C: true, expClose: true},
}
// For consistent spacing in test names.
fmtBool := func(b bool) string {
s := strconv.FormatBool(b)
if b {
s += " "
}
return s
}
connIcon := func(partition bool) string {
if partition {
return "-X->"
}
return "--->"
}
// Run all the tests.
var wg sync.WaitGroup
wg.Add(len(testCases))
errCh := make(chan error, len(testCases))
for testNum, c := range testCases {
kaName := fmt.Sprintf("clientKeepalive=%s,serverKeepalive=%s", fmtBool(c.cKeepalive), fmtBool(c.sKeepalive))
pName := fmt.Sprintf("client%sserver,server%sclient", connIcon(c.partitionC2S), connIcon(c.partitionS2C))
testName := fmt.Sprintf("%d/%s/%s", testNum, kaName, pName)
ctx := logtags.AddTag(context.Background(), testName, nil)
log.Infof(ctx, "starting sub-test")
go func(c grpcKeepaliveTestCase) {
errCh <- errors.Wrapf(grpcRunKeepaliveTestCase(ctx, c), "%+v", c)
wg.Done()
}(c)
}
log.Infof(context.Background(), "waiting for sub-tests to complete")
wg.Wait()
close(errCh)
for err := range errCh {
if err != nil {
t.Errorf("%+v", err)
}
}
}
type grpcKeepaliveTestCase struct {
cKeepalive, sKeepalive bool
partitionC2S, partitionS2C bool
expClose bool
}
func grpcRunKeepaliveTestCase(testCtx context.Context, c grpcKeepaliveTestCase) error {
var cKeepalive keepalive.ClientParameters
if c.cKeepalive {
cKeepalive = clientTestingKeepalive
}
var sKeepalive keepalive.ServerParameters
if c.sKeepalive {
sKeepalive = serverTestingKeepalive
}
stopper := stop.NewStopper()
defer stopper.Stop(context.TODO())
ctx, cancel := stopper.WithCancelOnQuiesce(testCtx)
defer cancel()
// Shared cluster ID by all RPC peers (this ensures that the peers
// don't talk to servers from unrelated tests by accident).
clusterID := uuid.MakeV4()
// Construct server with server-side keepalive.
log.Infof(ctx, "constructing server")
clock := hlc.NewClock(timeutil.Unix(0, 20).UnixNano, time.Nanosecond)
serverCtx := newTestContext(clusterID, clock, stopper)
const serverNodeID = 1
serverCtx.NodeID.Set(context.TODO(), serverNodeID)