-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
Copy pathcontext.go
1523 lines (1354 loc) · 51.4 KB
/
context.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 2015 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 (
"bytes"
"context"
"crypto/tls"
"encoding/binary"
"fmt"
"io"
"math"
"net"
"sync"
"sync/atomic"
"time"
circuit "github.com/cockroachdb/circuitbreaker"
"github.com/cockroachdb/cockroach/pkg/base"
"github.com/cockroachdb/cockroach/pkg/clusterversion"
"github.com/cockroachdb/cockroach/pkg/roachpb"
"github.com/cockroachdb/cockroach/pkg/security"
"github.com/cockroachdb/cockroach/pkg/settings/cluster"
"github.com/cockroachdb/cockroach/pkg/util/contextutil"
"github.com/cockroachdb/cockroach/pkg/util/envutil"
"github.com/cockroachdb/cockroach/pkg/util/growstack"
"github.com/cockroachdb/cockroach/pkg/util/grpcutil"
"github.com/cockroachdb/cockroach/pkg/util/hlc"
"github.com/cockroachdb/cockroach/pkg/util/log"
"github.com/cockroachdb/cockroach/pkg/util/netutil"
"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/errors"
"github.com/cockroachdb/logtags"
"github.com/cockroachdb/redact"
"go.opentelemetry.io/otel/attribute"
"golang.org/x/sync/syncmap"
"google.golang.org/grpc"
"google.golang.org/grpc/backoff"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/encoding"
"google.golang.org/grpc/metadata"
grpcstatus "google.golang.org/grpc/status"
)
func init() {
// Disable GRPC tracing. This retains a subset of messages for
// display on /debug/requests, which is very expensive for
// snapshots. Until we can be more selective about what is retained
// in traces, we must disable tracing entirely.
// https://github.com/grpc/grpc-go/issues/695
grpc.EnableTracing = false
}
const (
// The coefficient by which the maximum offset is multiplied to determine the
// maximum acceptable measurement latency.
maximumPingDurationMult = 2
)
const (
defaultWindowSize = 65535
)
func getWindowSize(name string, c ConnectionClass, defaultSize int) int32 {
const maxWindowSize = defaultWindowSize * 32
s := envutil.EnvOrDefaultInt(name, defaultSize)
if s > maxWindowSize {
log.Warningf(context.Background(), "%s value too large; trimmed to %d", name, maxWindowSize)
s = maxWindowSize
}
if s <= defaultWindowSize {
log.Warningf(context.Background(),
"%s RPC will use dynamic window sizes due to %s value lower than %d", c, name, defaultSize)
}
return int32(s)
}
var (
// for an RPC
initialWindowSize = getWindowSize(
"COCKROACH_RPC_INITIAL_WINDOW_SIZE", DefaultClass, defaultWindowSize*32)
initialConnWindowSize = initialWindowSize * 16 // for a connection
// for RangeFeed RPC
rangefeedInitialWindowSize = getWindowSize(
"COCKROACH_RANGEFEED_RPC_INITIAL_WINDOW_SIZE", RangefeedClass, 2*defaultWindowSize /* 128K */)
)
// GRPC Dialer connection timeout. 20s matches default value that is
// suppressed when backoff config is provided.
const minConnectionTimeout = 20 * time.Second
// errDialRejected is returned from client interceptors when the server's
// stopper is quiescing. The error is constructed to return true in
// `grpcutil.IsConnectionRejected` which prevents infinite retry loops during
// cluster shutdown, especially in unit testing.
var errDialRejected = grpcstatus.Error(codes.PermissionDenied, "refusing to dial; node is quiescing")
// sourceAddr is the environment-provided local address for outgoing
// connections.
var sourceAddr = func() net.Addr {
const envKey = "COCKROACH_SOURCE_IP_ADDRESS"
if sourceAddr, ok := envutil.EnvString(envKey, 0); ok {
sourceIP := net.ParseIP(sourceAddr)
if sourceIP == nil {
panic(fmt.Sprintf("unable to parse %s '%s' as IP address", envKey, sourceAddr))
}
return &net.TCPAddr{
IP: sourceIP,
}
}
return nil
}()
var enableRPCCompression = envutil.EnvOrDefaultBool("COCKROACH_ENABLE_RPC_COMPRESSION", true)
type serverOpts struct {
interceptor func(fullMethod string) error
}
// ServerOption is a configuration option passed to NewServer.
type ServerOption func(*serverOpts)
// WithInterceptor adds an additional interceptor. The interceptor is called before
// streaming and unary RPCs and may inject an error.
func WithInterceptor(f func(fullMethod string) error) ServerOption {
return func(opts *serverOpts) {
if opts.interceptor == nil {
opts.interceptor = f
} else {
f := opts.interceptor
opts.interceptor = func(fullMethod string) error {
if err := f(fullMethod); err != nil {
return err
}
return f(fullMethod)
}
}
}
}
// NewServer sets up an RPC server. Depending on the ServerOptions, the Server
// either expects incoming connections from KV nodes, or from tenant SQL
// servers.
func NewServer(rpcCtx *Context, opts ...ServerOption) *grpc.Server {
var o serverOpts
for _, f := range opts {
f(&o)
}
grpcOpts := []grpc.ServerOption{
// The limiting factor for lowering the max message size is the fact
// that a single large kv can be sent over the network in one message.
// Our maximum kv size is unlimited, so we need this to be very large.
//
// TODO(peter,tamird): need tests before lowering.
grpc.MaxRecvMsgSize(math.MaxInt32),
grpc.MaxSendMsgSize(math.MaxInt32),
// Adjust the stream and connection window sizes. The gRPC defaults are too
// low for high latency connections.
grpc.InitialWindowSize(initialWindowSize),
grpc.InitialConnWindowSize(initialConnWindowSize),
// The default number of concurrent streams/requests on a client connection
// is 100, while the server is unlimited. The client setting can only be
// controlled by adjusting the server value. Set a very large value for the
// server value so that we have no fixed limit on the number of concurrent
// streams/requests on either the client or server.
grpc.MaxConcurrentStreams(math.MaxInt32),
grpc.KeepaliveParams(serverKeepalive),
grpc.KeepaliveEnforcementPolicy(serverEnforcement),
// A stats handler to measure server network stats.
grpc.StatsHandler(&rpcCtx.stats),
}
if !rpcCtx.Config.Insecure {
tlsConfig, err := rpcCtx.GetServerTLSConfig()
if err != nil {
panic(err)
}
grpcOpts = append(grpcOpts, grpc.Creds(credentials.NewTLS(tlsConfig)))
}
// These interceptors will be called in the order in which they appear, i.e.
// The last element will wrap the actual handler. The first interceptor
// guards RPC endpoints for use after Stopper.Drain() by handling the RPC
// inside a stopper task.
var unaryInterceptor []grpc.UnaryServerInterceptor
var streamInterceptor []grpc.StreamServerInterceptor
unaryInterceptor = append(unaryInterceptor, func(
ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler,
) (interface{}, error) {
var resp interface{}
if err := rpcCtx.Stopper.RunTaskWithErr(ctx, info.FullMethod, func(ctx context.Context) error {
var err error
resp, err = handler(ctx, req)
return err
}); err != nil {
return nil, err
}
return resp, nil
})
streamInterceptor = append(streamInterceptor, func(srv interface{}, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error {
return rpcCtx.Stopper.RunTaskWithErr(ss.Context(), info.FullMethod, func(ctx context.Context) error {
return handler(srv, ss)
})
})
if !rpcCtx.Config.Insecure {
a := kvAuth{
tenant: tenantAuthorizer{
tenantID: rpcCtx.tenID,
},
}
unaryInterceptor = append(unaryInterceptor, a.AuthUnary())
streamInterceptor = append(streamInterceptor, a.AuthStream())
}
if o.interceptor != nil {
unaryInterceptor = append(unaryInterceptor, func(
ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler,
) (interface{}, error) {
if err := o.interceptor(info.FullMethod); err != nil {
return nil, err
}
return handler(ctx, req)
})
streamInterceptor = append(streamInterceptor, func(
srv interface{}, stream grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler,
) error {
if err := o.interceptor(info.FullMethod); err != nil {
return err
}
return handler(srv, stream)
})
}
if tracer := rpcCtx.Stopper.Tracer(); tracer != nil {
unaryInterceptor = append(unaryInterceptor, tracing.ServerInterceptor(tracer))
streamInterceptor = append(streamInterceptor, tracing.StreamServerInterceptor(tracer))
}
grpcOpts = append(grpcOpts, grpc.ChainUnaryInterceptor(unaryInterceptor...))
grpcOpts = append(grpcOpts, grpc.ChainStreamInterceptor(streamInterceptor...))
s := grpc.NewServer(grpcOpts...)
RegisterHeartbeatServer(s, rpcCtx.NewHeartbeatService())
return s
}
type heartbeatResult struct {
everSucceeded bool // true if the heartbeat has ever succeeded
err error // heartbeat error, initialized to ErrNotHeartbeated
}
// state is a helper to return the heartbeatState implied by a heartbeatResult.
func (hr heartbeatResult) state() (s heartbeatState) {
switch {
case !hr.everSucceeded && hr.err != nil:
s = heartbeatInitializing
case hr.everSucceeded && hr.err == nil:
s = heartbeatNominal
case hr.everSucceeded && hr.err != nil:
s = heartbeatFailed
}
return s
}
// Connection is a wrapper around grpc.ClientConn. It prevents the underlying
// connection from being used until it has been validated via heartbeat.
type Connection struct {
grpcConn *grpc.ClientConn
dialErr error // error while dialing; if set, connection is unusable
heartbeatResult atomic.Value // result of latest heartbeat
initialHeartbeatDone chan struct{} // closed after first heartbeat
stopper *stop.Stopper
// remoteNodeID implies checking the remote node ID. 0 when unknown,
// non-zero to check with remote node. This is constant throughout
// the lifetime of a Connection object.
remoteNodeID roachpb.NodeID
initOnce sync.Once
}
func newConnectionToNodeID(stopper *stop.Stopper, remoteNodeID roachpb.NodeID) *Connection {
c := &Connection{
initialHeartbeatDone: make(chan struct{}),
stopper: stopper,
remoteNodeID: remoteNodeID,
}
c.heartbeatResult.Store(heartbeatResult{err: ErrNotHeartbeated})
return c
}
// Connect returns the underlying grpc.ClientConn after it has been validated,
// or an error if dialing or validation fails.
func (c *Connection) Connect(ctx context.Context) (*grpc.ClientConn, error) {
if c.dialErr != nil {
return nil, c.dialErr
}
// Wait for initial heartbeat.
select {
case <-c.initialHeartbeatDone:
case <-c.stopper.ShouldQuiesce():
return nil, errors.Errorf("stopped")
case <-ctx.Done():
return nil, ctx.Err()
}
// If connection is invalid, return latest heartbeat error.
h := c.heartbeatResult.Load().(heartbeatResult)
if !h.everSucceeded {
// If we've never succeeded, h.err will be ErrNotHeartbeated.
return nil, netutil.NewInitialHeartBeatFailedError(h.err)
}
return c.grpcConn, nil
}
// Health returns an error indicating the success or failure of the
// connection's latest heartbeat. Returns ErrNotHeartbeated if the
// first heartbeat has not completed.
func (c *Connection) Health() error {
return c.heartbeatResult.Load().(heartbeatResult).err
}
// Context contains the fields required by the rpc framework.
//
// TODO(tbg): rename at the very least the `ctx` receiver, but possibly the whole
// thing.
type Context struct {
ContextOptions
SecurityContext
breakerClock breakerClock
RemoteClocks *RemoteClockMonitor
masterCtx context.Context
heartbeatTimeout time.Duration
HeartbeatCB func()
rpcCompression bool
localInternalClient roachpb.InternalClient
conns syncmap.Map
stats StatsHandler
metrics Metrics
// For unittesting.
BreakerFactory func() *circuit.Breaker
testingDialOpts []grpc.DialOption
// For testing. See the comment on the same field in HeartbeatService.
TestingAllowNamedRPCToAnonymousServer bool
}
// connKey is used as key in the Context.conns map.
// Connections which carry a different class but share a target and nodeID
// will always specify distinct connections. Different remote node IDs get
// distinct *Connection objects to ensure that we don't mis-route RPC
// requests in the face of address reuse. Gossip connections and other
// non-Internal users of the Context are free to dial nodes without
// specifying a node ID (see GRPCUnvalidatedDial()) however later calls to
// Dial with the same target and class with a node ID will create a new
// underlying connection. The inverse however is not true, a connection
// dialed without a node ID will use an existing connection to a matching
// (targetAddr, class) pair.
type connKey struct {
targetAddr string
// Note: this ought to be renamed, see:
// https://github.com/cockroachdb/cockroach/pull/73309
nodeID roachpb.NodeID
class ConnectionClass
}
var _ redact.SafeFormatter = connKey{}
// SafeFormat implements the redact.SafeFormatter interface.
func (c connKey) SafeFormat(p redact.SafePrinter, _ rune) {
p.Printf("{n%d: %s (%v)}", c.nodeID, c.targetAddr, c.class)
}
// ContextOptions are passed to NewContext to set up a new *Context.
// All pointer fields and TenantID are required.
type ContextOptions struct {
TenantID roachpb.TenantID
Config *base.Config
Clock *hlc.Clock
Stopper *stop.Stopper
Settings *cluster.Settings
// OnIncomingPing is called when handling a PingRequest, after
// preliminary checks but before recording clock offset information.
//
// It can inject an error.
OnIncomingPing func(*PingRequest) error
// OnOutgoingPing intercepts outgoing PingRequests. It may inject an
// error.
OnOutgoingPing func(*PingRequest) error
Knobs ContextTestingKnobs
// NodeID is the node ID / SQL instance ID container shared
// with the remainder of the server. If unset in the options,
// the RPC context will instantiate its own separate container
// (this is useful in tests).
// Note: this ought to be renamed, see:
// https://github.com/cockroachdb/cockroach/pull/73309
NodeID *base.NodeIDContainer
// ClusterID is the cluster ID shared with the remainder of the
// server. If unset in the options, the RPC context will instantiate
// its own separate container (this is useful in tests).
ClusterID *base.ClusterIDContainer
// ClientOnly indicates that this RPC context is run by a CLI
// utility, not a server, and thus misses server configuration, a
// cluster version, a node ID, etc.
ClientOnly bool
}
func (c ContextOptions) validate() error {
if c.TenantID == (roachpb.TenantID{}) {
return errors.New("must specify TenantID")
}
if c.Config == nil {
return errors.New("Config must be set")
}
if c.Clock == nil {
return errors.New("Clock must be set")
}
if c.Stopper == nil {
return errors.New("Stopper must be set")
}
if c.Settings == nil {
return errors.New("Settings must be set")
}
// NB: OnOutgoingPing and OnIncomingPing default to noops.
// This is used both for testing and the cli.
_, _ = c.OnOutgoingPing, c.OnIncomingPing
return nil
}
// NewContext creates an rpc.Context with the supplied values.
func NewContext(ctx context.Context, opts ContextOptions) *Context {
if err := opts.validate(); err != nil {
panic(err)
}
if opts.NodeID == nil {
// Tests rely on NewContext to generate its own ID container.
var c base.NodeIDContainer
opts.NodeID = &c
}
if opts.ClusterID == nil {
// Tests rely on NewContext to generate its own ID container.
var c base.ClusterIDContainer
opts.ClusterID = &c
}
masterCtx, cancel := context.WithCancel(ctx)
rpcCtx := &Context{
ContextOptions: opts,
SecurityContext: MakeSecurityContext(opts.Config, security.ClusterTLSSettings(opts.Settings), opts.TenantID),
breakerClock: breakerClock{
clock: opts.Clock,
},
RemoteClocks: newRemoteClockMonitor(
opts.Clock, 10*opts.Config.RPCHeartbeatInterval, opts.Config.HistogramWindowInterval()),
rpcCompression: enableRPCCompression,
masterCtx: masterCtx,
metrics: makeMetrics(),
heartbeatTimeout: 2 * opts.Config.RPCHeartbeatInterval,
}
if id := opts.Knobs.ClusterID; id != nil {
rpcCtx.ClusterID.Set(masterCtx, *id)
}
waitQuiesce := func(context.Context) {
<-rpcCtx.Stopper.ShouldQuiesce()
cancel()
rpcCtx.conns.Range(func(k, v interface{}) bool {
conn := v.(*Connection)
conn.initOnce.Do(func() {
// Make sure initialization is not in progress when we're removing the
// conn. We need to set the error in case we win the race against the
// real initialization code.
if conn.dialErr == nil {
conn.dialErr = errDialRejected
}
})
rpcCtx.removeConn(conn, k.(connKey))
return true
})
}
if err := rpcCtx.Stopper.RunAsyncTask(rpcCtx.masterCtx, "wait-rpcctx-quiesce", waitQuiesce); err != nil {
waitQuiesce(rpcCtx.masterCtx)
}
return rpcCtx
}
// ClusterName retrieves the configured cluster name.
func (rpcCtx *Context) ClusterName() string {
if rpcCtx == nil {
// This is used in tests.
return "<MISSING RPC CONTEXT>"
}
return rpcCtx.Config.ClusterName
}
// GetStatsMap returns a map of network statistics maintained by the
// internal stats handler. The map is from the remote network address
// (in string form) to an rpc.Stats object.
func (rpcCtx *Context) GetStatsMap() *syncmap.Map {
return &rpcCtx.stats.stats
}
// Metrics returns the Context's Metrics struct.
func (rpcCtx *Context) Metrics() *Metrics {
return &rpcCtx.metrics
}
// GetLocalInternalClientForAddr returns the context's internal batch client
// for target, if it exists.
// Note: the node ID ought to be retyped, see
// https://github.com/cockroachdb/cockroach/pull/73309
func (rpcCtx *Context) GetLocalInternalClientForAddr(
target string, nodeID roachpb.NodeID,
) roachpb.InternalClient {
if target == rpcCtx.Config.AdvertiseAddr && nodeID == rpcCtx.NodeID.Get() {
return rpcCtx.localInternalClient
}
return nil
}
type internalClientAdapter struct {
server roachpb.InternalServer
}
// Batch implements the roachpb.InternalClient interface.
func (a internalClientAdapter) Batch(
ctx context.Context, ba *roachpb.BatchRequest, _ ...grpc.CallOption,
) (*roachpb.BatchResponse, error) {
// Mark this as originating locally, which is useful for the decision about
// memory allocation tracking.
ba.AdmissionHeader.SourceLocation = roachpb.AdmissionHeader_LOCAL
return a.server.Batch(ctx, ba)
}
// RangeLookup implements the roachpb.InternalClient interface.
func (a internalClientAdapter) RangeLookup(
ctx context.Context, rl *roachpb.RangeLookupRequest, _ ...grpc.CallOption,
) (*roachpb.RangeLookupResponse, error) {
return a.server.RangeLookup(ctx, rl)
}
// Join implements the roachpb.InternalClient interface.
func (a internalClientAdapter) Join(
ctx context.Context, req *roachpb.JoinNodeRequest, _ ...grpc.CallOption,
) (*roachpb.JoinNodeResponse, error) {
return a.server.Join(ctx, req)
}
// ResetQuorum is part of the roachpb.InternalClient interface.
func (a internalClientAdapter) ResetQuorum(
ctx context.Context, req *roachpb.ResetQuorumRequest, _ ...grpc.CallOption,
) (*roachpb.ResetQuorumResponse, error) {
return a.server.ResetQuorum(ctx, req)
}
// TokenBucket is part of the roachpb.InternalClient interface.
func (a internalClientAdapter) TokenBucket(
ctx context.Context, in *roachpb.TokenBucketRequest, opts ...grpc.CallOption,
) (*roachpb.TokenBucketResponse, error) {
return a.server.TokenBucket(ctx, in)
}
// GetSpanConfigs is part of the roachpb.InternalClient interface.
func (a internalClientAdapter) GetSpanConfigs(
ctx context.Context, req *roachpb.GetSpanConfigsRequest, _ ...grpc.CallOption,
) (*roachpb.GetSpanConfigsResponse, error) {
return a.server.GetSpanConfigs(ctx, req)
}
// UpdateSpanConfigs is part of the roachpb.InternalClient interface.
func (a internalClientAdapter) UpdateSpanConfigs(
ctx context.Context, req *roachpb.UpdateSpanConfigsRequest, _ ...grpc.CallOption,
) (*roachpb.UpdateSpanConfigsResponse, error) {
return a.server.UpdateSpanConfigs(ctx, req)
}
type respStreamClientAdapter struct {
ctx context.Context
respC chan interface{}
errC chan error
}
func makeRespStreamClientAdapter(ctx context.Context) respStreamClientAdapter {
return respStreamClientAdapter{
ctx: ctx,
respC: make(chan interface{}, 128),
errC: make(chan error, 1),
}
}
// grpc.ClientStream methods.
func (respStreamClientAdapter) Header() (metadata.MD, error) { panic("unimplemented") }
func (respStreamClientAdapter) Trailer() metadata.MD { panic("unimplemented") }
func (respStreamClientAdapter) CloseSend() error { panic("unimplemented") }
// grpc.ServerStream methods.
func (respStreamClientAdapter) SetHeader(metadata.MD) error { panic("unimplemented") }
func (respStreamClientAdapter) SendHeader(metadata.MD) error { panic("unimplemented") }
func (respStreamClientAdapter) SetTrailer(metadata.MD) { panic("unimplemented") }
// grpc.Stream methods.
func (a respStreamClientAdapter) Context() context.Context { return a.ctx }
func (respStreamClientAdapter) SendMsg(m interface{}) error { panic("unimplemented") }
func (respStreamClientAdapter) RecvMsg(m interface{}) error { panic("unimplemented") }
func (a respStreamClientAdapter) recvInternal() (interface{}, error) {
// Prioritize respC. Both channels are buffered and the only guarantee we
// have is that once an error is sent on errC no other events will be sent
// on respC again.
select {
case e := <-a.respC:
return e, nil
case err := <-a.errC:
select {
case e := <-a.respC:
a.errC <- err
return e, nil
default:
return nil, err
}
}
}
func (a respStreamClientAdapter) sendInternal(e interface{}) error {
select {
case a.respC <- e:
return nil
case <-a.ctx.Done():
return a.ctx.Err()
}
}
type rangeFeedClientAdapter struct {
respStreamClientAdapter
}
// roachpb.Internal_RangeFeedServer methods.
func (a rangeFeedClientAdapter) Recv() (*roachpb.RangeFeedEvent, error) {
e, err := a.recvInternal()
if err != nil {
return nil, err
}
return e.(*roachpb.RangeFeedEvent), nil
}
// roachpb.Internal_RangeFeedServer methods.
func (a rangeFeedClientAdapter) Send(e *roachpb.RangeFeedEvent) error {
return a.sendInternal(e)
}
var _ roachpb.Internal_RangeFeedClient = rangeFeedClientAdapter{}
var _ roachpb.Internal_RangeFeedServer = rangeFeedClientAdapter{}
// RangeFeed implements the roachpb.InternalClient interface.
func (a internalClientAdapter) RangeFeed(
ctx context.Context, args *roachpb.RangeFeedRequest, _ ...grpc.CallOption,
) (roachpb.Internal_RangeFeedClient, error) {
ctx, cancel := context.WithCancel(ctx)
ctx, sp := tracing.ChildSpan(ctx, "/cockroach.roachpb.Internal/RangeFeed")
rfAdapter := rangeFeedClientAdapter{
respStreamClientAdapter: makeRespStreamClientAdapter(ctx),
}
// Mark this as originating locally.
args.AdmissionHeader.SourceLocation = roachpb.AdmissionHeader_LOCAL
go func() {
defer cancel()
defer sp.Finish()
err := a.server.RangeFeed(args, rfAdapter)
if err == nil {
err = io.EOF
}
rfAdapter.errC <- err
}()
return rfAdapter, nil
}
type gossipSubscriptionClientAdapter struct {
respStreamClientAdapter
}
// roachpb.Internal_GossipSubscriptionServer methods.
func (a gossipSubscriptionClientAdapter) Recv() (*roachpb.GossipSubscriptionEvent, error) {
e, err := a.recvInternal()
if err != nil {
return nil, err
}
return e.(*roachpb.GossipSubscriptionEvent), nil
}
// roachpb.Internal_GossipSubscriptionServer methods.
func (a gossipSubscriptionClientAdapter) Send(e *roachpb.GossipSubscriptionEvent) error {
return a.sendInternal(e)
}
var _ roachpb.Internal_GossipSubscriptionClient = gossipSubscriptionClientAdapter{}
var _ roachpb.Internal_GossipSubscriptionServer = gossipSubscriptionClientAdapter{}
// GossipSubscription is part of the roachpb.InternalClient interface.
func (a internalClientAdapter) GossipSubscription(
ctx context.Context, args *roachpb.GossipSubscriptionRequest, _ ...grpc.CallOption,
) (roachpb.Internal_GossipSubscriptionClient, error) {
ctx, cancel := context.WithCancel(ctx)
ctx, sp := tracing.ChildSpan(ctx, "/cockroach.roachpb.Internal/GossipSubscription")
gsAdapter := gossipSubscriptionClientAdapter{
respStreamClientAdapter: makeRespStreamClientAdapter(ctx),
}
go func() {
defer cancel()
defer sp.Finish()
err := a.server.GossipSubscription(args, gsAdapter)
if err == nil {
err = io.EOF
}
gsAdapter.errC <- err
}()
return gsAdapter, nil
}
type tenantSettingsClientAdapter struct {
respStreamClientAdapter
}
// roachpb.Internal_TenantSettingsServer methods.
func (a tenantSettingsClientAdapter) Recv() (*roachpb.TenantSettingsEvent, error) {
e, err := a.recvInternal()
if err != nil {
return nil, err
}
return e.(*roachpb.TenantSettingsEvent), nil
}
// roachpb.Internal_TenantSettingsServer methods.
func (a tenantSettingsClientAdapter) Send(e *roachpb.TenantSettingsEvent) error {
return a.sendInternal(e)
}
var _ roachpb.Internal_TenantSettingsClient = tenantSettingsClientAdapter{}
var _ roachpb.Internal_TenantSettingsServer = tenantSettingsClientAdapter{}
// TenantSettings is part of the roachpb.InternalClient interface.
func (a internalClientAdapter) TenantSettings(
ctx context.Context, args *roachpb.TenantSettingsRequest, _ ...grpc.CallOption,
) (roachpb.Internal_TenantSettingsClient, error) {
ctx, cancel := context.WithCancel(ctx)
gsAdapter := tenantSettingsClientAdapter{
respStreamClientAdapter: makeRespStreamClientAdapter(ctx),
}
go func() {
defer cancel()
err := a.server.TenantSettings(args, gsAdapter)
if err == nil {
err = io.EOF
}
gsAdapter.errC <- err
}()
return gsAdapter, nil
}
var _ roachpb.InternalClient = internalClientAdapter{}
// IsLocal returns true if the given InternalClient is local.
func IsLocal(iface roachpb.InternalClient) bool {
_, ok := iface.(internalClientAdapter)
return ok // internalClientAdapter is used for local connections.
}
// SetLocalInternalServer sets the context's local internal batch server.
func (rpcCtx *Context) SetLocalInternalServer(internalServer roachpb.InternalServer) {
rpcCtx.localInternalClient = internalClientAdapter{internalServer}
}
// removeConn removes the given connection from the pool. The supplied connKeys
// must represent *all* the keys under among which the connection was shared.
func (rpcCtx *Context) removeConn(conn *Connection, keys ...connKey) {
for _, key := range keys {
rpcCtx.conns.Delete(key)
}
log.Health.Infof(rpcCtx.masterCtx, "closing %+v", keys)
if grpcConn := conn.grpcConn; grpcConn != nil {
err := grpcConn.Close() // nolint:grpcconnclose
if err != nil && !grpcutil.IsClosedConnection(err) {
log.Health.Warningf(rpcCtx.masterCtx, "failed to close client connection: %v", err)
}
}
}
// ConnHealth returns nil if we have an open connection of the request
// class to the given node that succeeded on its most recent heartbeat.
// Note: the node ID ought to be retyped, see
// https://github.com/cockroachdb/cockroach/pull/73309
func (rpcCtx *Context) ConnHealth(
target string, nodeID roachpb.NodeID, class ConnectionClass,
) error {
// The local client is always considered healthy.
if rpcCtx.GetLocalInternalClientForAddr(target, nodeID) != nil {
return nil
}
if value, ok := rpcCtx.conns.Load(connKey{target, nodeID, class}); ok {
return value.(*Connection).Health()
}
return ErrNoConnection
}
// GRPCDialOptions returns the minimal `grpc.DialOption`s necessary to connect
// to a server created with `NewServer`.
//
// At the time of writing, this is being used for making net.Pipe-based
// connections, so only those options that affect semantics are included. In
// particular, performance tuning options are omitted. Decompression is
// necessarily included to support compression-enabled servers, and compression
// is included for symmetry. These choices are admittedly subjective.
func (rpcCtx *Context) GRPCDialOptions() ([]grpc.DialOption, error) {
return rpcCtx.grpcDialOptions("", DefaultClass)
}
// grpcDialOptions extends GRPCDialOptions to support a connection class for use
// with TestingKnobs.
func (rpcCtx *Context) grpcDialOptions(
target string, class ConnectionClass,
) ([]grpc.DialOption, error) {
var dialOpts []grpc.DialOption
if rpcCtx.Config.Insecure {
//lint:ignore SA1019 grpc.WithInsecure is deprecated
dialOpts = append(dialOpts, grpc.WithInsecure())
} else {
var tlsConfig *tls.Config
var err error
if rpcCtx.tenID == roachpb.SystemTenantID {
tlsConfig, err = rpcCtx.GetClientTLSConfig()
} else {
tlsConfig, err = rpcCtx.GetTenantTLSConfig()
}
if err != nil {
return nil, err
}
dialOpts = append(dialOpts, grpc.WithTransportCredentials(credentials.NewTLS(tlsConfig)))
}
// The limiting factor for lowering the max message size is the fact
// that a single large kv can be sent over the network in one message.
// Our maximum kv size is unlimited, so we need this to be very large.
//
// TODO(peter,tamird): need tests before lowering.
dialOpts = append(dialOpts, grpc.WithDefaultCallOptions(
grpc.MaxCallRecvMsgSize(math.MaxInt32),
grpc.MaxCallSendMsgSize(math.MaxInt32),
))
// Compression is enabled separately from decompression to allow staged
// rollout.
if rpcCtx.rpcCompression {
dialOpts = append(dialOpts, grpc.WithDefaultCallOptions(grpc.UseCompressor((snappyCompressor{}).Name())))
}
// GRPC uses the HTTPS_PROXY environment variable by default[1]. This is
// surprising, and likely undesirable for CRDB because it turns the proxy
// into an availability risk and a throughput bottleneck. We disable the use
// of proxies by default.
//
// [1]: https://github.com/grpc/grpc-go/blob/c0736608/Documentation/proxy.md
dialOpts = append(dialOpts, grpc.WithNoProxy())
var unaryInterceptors []grpc.UnaryClientInterceptor
var streamInterceptors []grpc.StreamClientInterceptor
if tracer := rpcCtx.Stopper.Tracer(); tracer != nil {
// TODO(tbg): re-write all of this for our tracer.
// We use a decorator to set the "node" tag. All other spans get the
// node tag from context log tags.
//
// Unfortunately we cannot use the corresponding interceptor on the
// server-side of gRPC to set this tag on server spans because that
// interceptor runs too late - after a traced RPC's recording had
// already been collected. So, on the server-side, the equivalent code
// is in setupSpanForIncomingRPC().
//
tagger := func(span *tracing.Span) {
span.SetTag("node", attribute.IntValue(int(rpcCtx.NodeID.Get())))
}
compatMode := func(reqCtx context.Context) bool {
return !rpcCtx.ContextOptions.Settings.Version.IsActive(reqCtx, clusterversion.SelectRPCsTakeTracingInfoInband)
}
if rpcCtx.ClientOnly {
// client-only RPC contexts don't have a node ID to report nor a
// cluster version to check against.
tagger = func(span *tracing.Span) {}
compatMode = func(_ context.Context) bool { return false }
}
unaryInterceptors = append(unaryInterceptors,
tracing.ClientInterceptor(tracer, tagger, compatMode))
streamInterceptors = append(streamInterceptors,
tracing.StreamClientInterceptor(tracer, tagger))
}
if rpcCtx.Knobs.UnaryClientInterceptor != nil {
testingUnaryInterceptor := rpcCtx.Knobs.UnaryClientInterceptor(target, class)
if testingUnaryInterceptor != nil {
unaryInterceptors = append(unaryInterceptors, testingUnaryInterceptor)
}
}
if rpcCtx.Knobs.StreamClientInterceptor != nil {
testingStreamInterceptor := rpcCtx.Knobs.StreamClientInterceptor(target, class)
if testingStreamInterceptor != nil {
streamInterceptors = append(streamInterceptors, testingStreamInterceptor)
}
}
if rpcCtx.Knobs.ArtificialLatencyMap != nil {
dialerFunc := func(ctx context.Context, target string) (net.Conn, error) {
dialer := net.Dialer{
LocalAddr: sourceAddr,
}
return dialer.DialContext(ctx, "tcp", target)
}
latency := rpcCtx.Knobs.ArtificialLatencyMap[target]
log.VEventf(rpcCtx.masterCtx, 1, "connecting to node %s with simulated latency %dms", target, latency)
dialer := artificialLatencyDialer{
dialerFunc: dialerFunc,
latencyMS: latency,
}
dialerFunc = dialer.dial
dialOpts = append(dialOpts, grpc.WithContextDialer(dialerFunc))
}
if len(unaryInterceptors) > 0 {
dialOpts = append(dialOpts, grpc.WithChainUnaryInterceptor(unaryInterceptors...))
}
if len(streamInterceptors) > 0 {
dialOpts = append(dialOpts, grpc.WithChainStreamInterceptor(streamInterceptors...))
}
return dialOpts, nil
}
// growStackCodec wraps the default grpc/encoding/proto codec to detect
// BatchRequest rpcs and grow the stack prior to Unmarshaling.
type growStackCodec struct {
encoding.Codec
}
// Unmarshal detects BatchRequests and calls growstack.Grow before calling
// through to the underlying codec.
func (c growStackCodec) Unmarshal(data []byte, v interface{}) error {
if _, ok := v.(*roachpb.BatchRequest); ok {
growstack.Grow()
}
return c.Codec.Unmarshal(data, v)
}
// Install the growStackCodec over the default proto codec in order to grow the
// stack for BatchRequest RPCs prior to unmarshaling.
func init() {
encoding.RegisterCodec(growStackCodec{Codec: codec{}})
}
// onlyOnceDialer implements the grpc.WithDialer interface but only
// allows a single connection attempt. If a reconnection is attempted,
// redialChan is closed to signal a higher-level retry loop. This
// ensures that our initial heartbeat (and its version/clusterID
// validation) occurs on every new connection.
type onlyOnceDialer struct {