-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
server.go
2073 lines (1856 loc) · 75.7 KB
/
server.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 server
import (
"context"
"fmt"
"net"
"os"
"path/filepath"
"reflect"
"strconv"
"sync"
"time"
"github.com/cockroachdb/cockroach/pkg/base"
"github.com/cockroachdb/cockroach/pkg/build"
"github.com/cockroachdb/cockroach/pkg/clusterversion"
"github.com/cockroachdb/cockroach/pkg/gossip"
"github.com/cockroachdb/cockroach/pkg/jobs"
"github.com/cockroachdb/cockroach/pkg/jobs/jobsprotectedts"
"github.com/cockroachdb/cockroach/pkg/keys"
"github.com/cockroachdb/cockroach/pkg/keyvisualizer/keyvispb"
"github.com/cockroachdb/cockroach/pkg/keyvisualizer/keyvissubscriber"
"github.com/cockroachdb/cockroach/pkg/keyvisualizer/spanstatskvaccessor"
"github.com/cockroachdb/cockroach/pkg/kv"
"github.com/cockroachdb/cockroach/pkg/kv/kvclient/kvcoord"
"github.com/cockroachdb/cockroach/pkg/kv/kvclient/rangefeed"
"github.com/cockroachdb/cockroach/pkg/kv/kvclient/rangestats"
"github.com/cockroachdb/cockroach/pkg/kv/kvclient/spanstats/spanstatsaccessor"
"github.com/cockroachdb/cockroach/pkg/kv/kvprober"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver/allocator/storepool"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver/closedts/ctpb"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver/closedts/sidetransport"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver/kvserverbase"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver/liveness"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver/liveness/livenesspb"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver/loqrecovery"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver/protectedts"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver/protectedts/ptprovider"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver/protectedts/ptreconcile"
serverrangefeed "github.com/cockroachdb/cockroach/pkg/kv/kvserver/rangefeed"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver/rangelog"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver/reports"
"github.com/cockroachdb/cockroach/pkg/obs"
"github.com/cockroachdb/cockroach/pkg/obsservice/obspb"
"github.com/cockroachdb/cockroach/pkg/roachpb"
"github.com/cockroachdb/cockroach/pkg/rpc"
"github.com/cockroachdb/cockroach/pkg/rpc/nodedialer"
"github.com/cockroachdb/cockroach/pkg/security/clientsecopts"
"github.com/cockroachdb/cockroach/pkg/security/username"
"github.com/cockroachdb/cockroach/pkg/server/debug"
"github.com/cockroachdb/cockroach/pkg/server/diagnostics"
"github.com/cockroachdb/cockroach/pkg/server/serverpb"
"github.com/cockroachdb/cockroach/pkg/server/serverrules"
"github.com/cockroachdb/cockroach/pkg/server/status"
"github.com/cockroachdb/cockroach/pkg/server/systemconfigwatcher"
"github.com/cockroachdb/cockroach/pkg/server/telemetry"
"github.com/cockroachdb/cockroach/pkg/server/tenantsettingswatcher"
"github.com/cockroachdb/cockroach/pkg/settings/cluster"
"github.com/cockroachdb/cockroach/pkg/spanconfig"
_ "github.com/cockroachdb/cockroach/pkg/spanconfig/spanconfigjob" // register jobs declared outside of pkg/sql
"github.com/cockroachdb/cockroach/pkg/spanconfig/spanconfigkvaccessor"
"github.com/cockroachdb/cockroach/pkg/spanconfig/spanconfigkvsubscriber"
"github.com/cockroachdb/cockroach/pkg/spanconfig/spanconfigptsreader"
"github.com/cockroachdb/cockroach/pkg/spanconfig/spanconfigreporter"
"github.com/cockroachdb/cockroach/pkg/sql"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/catalogkeys"
_ "github.com/cockroachdb/cockroach/pkg/sql/catalog/schematelemetry" // register schedules declared outside of pkg/sql
"github.com/cockroachdb/cockroach/pkg/sql/catalog/systemschema"
"github.com/cockroachdb/cockroach/pkg/sql/flowinfra"
_ "github.com/cockroachdb/cockroach/pkg/sql/gcjob" // register jobs declared outside of pkg/sql
_ "github.com/cockroachdb/cockroach/pkg/sql/importer" // register jobs/planHooks declared outside of pkg/sql
"github.com/cockroachdb/cockroach/pkg/sql/optionalnodeliveness"
"github.com/cockroachdb/cockroach/pkg/sql/pgwire"
_ "github.com/cockroachdb/cockroach/pkg/sql/schemachanger/scjob" // register jobs declared outside of pkg/sql
"github.com/cockroachdb/cockroach/pkg/sql/sem/builtins"
"github.com/cockroachdb/cockroach/pkg/sql/sem/catconstants"
"github.com/cockroachdb/cockroach/pkg/sql/sessiondatapb"
_ "github.com/cockroachdb/cockroach/pkg/sql/ttl/ttljob" // register jobs declared outside of pkg/sql
_ "github.com/cockroachdb/cockroach/pkg/sql/ttl/ttlschedule" // register schedules declared outside of pkg/sql
"github.com/cockroachdb/cockroach/pkg/storage"
"github.com/cockroachdb/cockroach/pkg/storage/enginepb"
"github.com/cockroachdb/cockroach/pkg/ts"
"github.com/cockroachdb/cockroach/pkg/util"
"github.com/cockroachdb/cockroach/pkg/util/admission"
"github.com/cockroachdb/cockroach/pkg/util/goschedstats"
"github.com/cockroachdb/cockroach/pkg/util/hlc"
"github.com/cockroachdb/cockroach/pkg/util/log"
"github.com/cockroachdb/cockroach/pkg/util/metric"
"github.com/cockroachdb/cockroach/pkg/util/mon"
"github.com/cockroachdb/cockroach/pkg/util/rangedesc"
"github.com/cockroachdb/cockroach/pkg/util/retry"
"github.com/cockroachdb/cockroach/pkg/util/schedulerlatency"
"github.com/cockroachdb/cockroach/pkg/util/stop"
"github.com/cockroachdb/cockroach/pkg/util/timeutil"
"github.com/cockroachdb/cockroach/pkg/util/timeutil/ptp"
"github.com/cockroachdb/cockroach/pkg/util/tracing"
"github.com/cockroachdb/cockroach/pkg/util/uuid"
"github.com/cockroachdb/errors"
"github.com/cockroachdb/redact"
sentry "github.com/getsentry/sentry-go"
"google.golang.org/grpc/codes"
)
// Server is the cockroach server node.
type Server struct {
// The following fields are populated in NewServer.
nodeIDContainer *base.NodeIDContainer
cfg Config
st *cluster.Settings
clock *hlc.Clock
rpcContext *rpc.Context
engines Engines
// The gRPC server on which the different RPC handlers will be registered.
grpc *grpcServer
gossip *gossip.Gossip
nodeDialer *nodedialer.Dialer
nodeLiveness *liveness.NodeLiveness
storePool *storepool.StorePool
tcsFactory *kvcoord.TxnCoordSenderFactory
distSender *kvcoord.DistSender
db *kv.DB
node *Node
registry *metric.Registry
recorder *status.MetricsRecorder
runtime *status.RuntimeStatSampler
ruleRegistry *metric.RuleRegistry
promRuleExporter *metric.PrometheusRuleExporter
updates *diagnostics.UpdateChecker
ctSender *sidetransport.Sender
http *httpServer
adminAuthzCheck *adminPrivilegeChecker
admin *systemAdminServer
status *systemStatusServer
drain *drainServer
decomNodeMap *decommissioningNodeMap
authentication *authenticationServer
migrationServer *migrationServer
tsDB *ts.DB
tsServer *ts.Server
// keyVisualizerServer implements `keyvispb.KeyVisualizerServer`
keyVisualizerServer *KeyVisualizerServer
// The Observability Server, used by the Observability Service to subscribe to
// CRDB data.
eventsServer *obs.EventsServer
recoveryServer *loqrecovery.Server
raftTransport *kvserver.RaftTransport
stopper *stop.Stopper
stopTrigger *stopTrigger
debug *debug.Server
kvProber *kvprober.Prober
replicationReporter *reports.Reporter
protectedtsProvider protectedts.Provider
spanConfigSubscriber spanconfig.KVSubscriber
spanConfigReporter spanconfig.Reporter
// spanStatsServer services internal requests for span stats.
spanStatsServer *spanStatsServer
// pgL is the SQL listener.
pgL net.Listener
// pgPreServer handles SQL connections prior to routing them to a
// specific tenant.
pgPreServer *pgwire.PreServeConnHandler
// TODO(knz): pull this down under the serverController.
sqlServer *SQLServer
// serverController is responsible for on-demand instantiation
// of services.
serverController *serverController
// Created in NewServer but initialized (made usable) in `(*Server).PreStart`.
externalStorageBuilder *externalStorageBuilder
storeGrantCoords *admission.StoreGrantCoordinators
// kvMemoryMonitor is a child of the rootSQLMemoryMonitor and is used to
// account for and bound the memory used for request processing in the KV
// layer.
kvMemoryMonitor *mon.BytesMonitor
// The following fields are populated at start time, i.e. in `(*Server).Start`.
startTime time.Time
}
// NewServer creates a Server from a server.Config.
//
// The caller is responsible for listening on the server's ShutdownRequested()
// channel and calling stopper.Stop().
func NewServer(cfg Config, stopper *stop.Stopper) (*Server, error) {
if err := cfg.ValidateAddrs(context.Background()); err != nil {
return nil, err
}
st := cfg.Settings
if cfg.AmbientCtx.Tracer == nil {
panic(errors.New("no tracer set in AmbientCtx"))
}
var clock *hlc.Clock
if cfg.ClockDevicePath != "" {
ptpClock, err := ptp.MakeClock(context.Background(), cfg.ClockDevicePath)
if err != nil {
return nil, errors.Wrap(err, "instantiating clock source")
}
clock = hlc.NewClock(ptpClock, time.Duration(cfg.MaxOffset))
} else if cfg.TestingKnobs.Server != nil &&
cfg.TestingKnobs.Server.(*TestingKnobs).WallClock != nil {
clock = hlc.NewClock(cfg.TestingKnobs.Server.(*TestingKnobs).WallClock,
time.Duration(cfg.MaxOffset))
} else {
clock = hlc.NewClockWithSystemTimeSource(time.Duration(cfg.MaxOffset))
}
registry := metric.NewRegistry()
ruleRegistry := metric.NewRuleRegistry()
promRuleExporter := metric.NewPrometheusRuleExporter(ruleRegistry)
stopper.SetTracer(cfg.AmbientCtx.Tracer)
stopper.AddCloser(cfg.AmbientCtx.Tracer)
// Add a dynamic log tag value for the node ID.
//
// We need to pass an ambient context to the various server components, but we
// won't know the node ID until we Start(). At that point it's too late to
// change the ambient contexts in the components (various background processes
// will have already started using them).
//
// NodeIDContainer allows us to add the log tag to the context now and update
// the value asynchronously. It's not significantly more expensive than a
// regular tag since it's just doing an (atomic) load when a log/trace message
// is constructed. The node ID is set by the Store if this host was
// bootstrapped; otherwise a new one is allocated in Node.
nodeIDContainer := cfg.IDContainer
idContainer := base.NewSQLIDContainerForNode(nodeIDContainer)
ctx := cfg.AmbientCtx.AnnotateCtx(context.Background())
admissionOptions := admission.DefaultOptions
if opts, ok := cfg.TestingKnobs.AdmissionControl.(*admission.Options); ok {
admissionOptions.Override(opts)
}
gcoords := admission.NewGrantCoordinators(cfg.AmbientCtx, st, admissionOptions, registry)
engines, err := cfg.CreateEngines(ctx)
if err != nil {
return nil, errors.Wrap(err, "failed to create engines")
}
stopper.AddCloser(&engines)
nodeTombStorage, checkPingFor := getPingCheckDecommissionFn(engines)
g := gossip.New(
cfg.AmbientCtx,
cfg.ClusterIDContainer,
nodeIDContainer,
stopper,
registry,
cfg.Locality,
&cfg.DefaultZoneConfig,
)
rpcCtxOpts := rpc.ContextOptions{
TenantID: roachpb.SystemTenantID,
NodeID: cfg.IDContainer,
StorageClusterID: cfg.ClusterIDContainer,
Config: cfg.Config,
Clock: clock.WallClock(),
MaxOffset: clock.MaxOffset(),
Stopper: stopper,
Settings: cfg.Settings,
OnOutgoingPing: func(ctx context.Context, req *rpc.PingRequest) error {
// Outgoing ping will block requests with codes.FailedPrecondition to
// notify caller that this replica is decommissioned but others could
// still be tried as caller node is valid, but not the destination.
return checkPingFor(ctx, req.TargetNodeID, codes.FailedPrecondition)
},
OnIncomingPing: func(ctx context.Context, req *rpc.PingRequest) error {
// Decommission state is only tracked for the system tenant.
if tenantID, isTenant := roachpb.ClientTenantFromContext(ctx); isTenant &&
!roachpb.IsSystemTenantID(tenantID.ToUint64()) {
return nil
}
// Incoming ping will reject requests with codes.PermissionDenied to
// signal remote node that it is not considered valid anymore and
// operations should fail immediately.
return checkPingFor(ctx, req.OriginNodeID, codes.PermissionDenied)
},
}
if knobs := cfg.TestingKnobs.Server; knobs != nil {
serverKnobs := knobs.(*TestingKnobs)
rpcCtxOpts.Knobs = serverKnobs.ContextTestingKnobs
}
rpcContext := rpc.NewContext(ctx, rpcCtxOpts)
rpcContext.HeartbeatCB = func() {
if err := rpcContext.RemoteClocks.VerifyClockOffset(ctx); err != nil {
log.Ops.Fatalf(ctx, "%v", err)
}
}
registry.AddMetricStruct(rpcContext.Metrics())
// Attempt to load TLS configs right away, failures are permanent.
if !cfg.Insecure {
// TODO(peter): Call methods on CertificateManager directly. Need to call
// base.wrapError or similar on the resulting error.
if _, err := rpcContext.GetServerTLSConfig(); err != nil {
return nil, err
}
if _, err := rpcContext.GetUIServerTLSConfig(); err != nil {
return nil, err
}
if _, err := rpcContext.GetClientTLSConfig(); err != nil {
return nil, err
}
cm, err := rpcContext.GetCertificateManager()
if err != nil {
return nil, err
}
// Expose cert expirations in metrics.
registry.AddMetricStruct(cm.Metrics())
}
// Check the compatibility between the configured addresses and that
// provided in certificates. This also logs the certificate
// addresses in all cases to aid troubleshooting.
// This must be called after the certificate manager was initialized
// and after ValidateAddrs().
rpcContext.CheckCertificateAddrs(ctx)
grpcServer := newGRPCServer(rpcContext)
gossip.RegisterGossipServer(grpcServer.Server, g)
var dialerKnobs nodedialer.DialerTestingKnobs
if dk := cfg.TestingKnobs.DialerKnobs; dk != nil {
dialerKnobs = dk.(nodedialer.DialerTestingKnobs)
}
nodeDialer := nodedialer.NewWithOpt(rpcContext, gossip.AddressResolver(g),
nodedialer.DialerOpt{TestingKnobs: dialerKnobs})
runtimeSampler := status.NewRuntimeStatSampler(ctx, clock)
registry.AddMetricStruct(runtimeSampler)
// Save a reference to this sampler for use by additional servers
// started via the server controller.
cfg.RuntimeStatSampler = runtimeSampler
registry.AddMetric(base.LicenseTTL)
clusterVersionMetrics := clusterversion.MakeMetrics()
registry.AddMetricStruct(clusterVersionMetrics)
clusterversion.RegisterOnVersionChangeCallback(&st.SV)
err = base.UpdateMetricOnLicenseChange(ctx, cfg.Settings, base.LicenseTTL, timeutil.DefaultTimeSource{}, stopper)
if err != nil {
log.Errorf(ctx, "unable to initialize periodic license metric update: %v", err)
}
// Create and add KV metric rules.
kvserver.CreateAndAddRules(ctx, ruleRegistry)
// Create and add server metric rules.
serverrules.CreateAndAddRules(ctx, ruleRegistry)
// A custom RetryOptions is created which uses stopper.ShouldQuiesce() as
// the Closer. This prevents infinite retry loops from occurring during
// graceful server shutdown
//
// Such a loop occurs when the DistSender attempts a connection to the
// local server during shutdown, and receives an internal server error (HTTP
// Code 5xx). This is the correct error for a server to return when it is
// shutting down, and is normally retryable in a cluster environment.
// However, on a single-node setup (such as a test), retries will never
// succeed because the only server has been shut down; thus, the
// DistSender needs to know that it should not retry in this situation.
var clientTestingKnobs kvcoord.ClientTestingKnobs
if kvKnobs := cfg.TestingKnobs.KVClient; kvKnobs != nil {
clientTestingKnobs = *kvKnobs.(*kvcoord.ClientTestingKnobs)
}
retryOpts := cfg.RetryOptions
if retryOpts == (retry.Options{}) {
retryOpts = base.DefaultRetryOptions()
}
retryOpts.Closer = stopper.ShouldQuiesce()
distSenderCfg := kvcoord.DistSenderConfig{
AmbientCtx: cfg.AmbientCtx,
Settings: st,
Clock: clock,
NodeDescs: g,
RPCContext: rpcContext,
RPCRetryOptions: &retryOpts,
NodeDialer: nodeDialer,
FirstRangeProvider: g,
Locality: cfg.Locality,
TestingKnobs: clientTestingKnobs,
}
distSender := kvcoord.NewDistSender(distSenderCfg)
registry.AddMetricStruct(distSender.Metrics())
txnMetrics := kvcoord.MakeTxnMetrics(cfg.HistogramWindowInterval())
registry.AddMetricStruct(txnMetrics)
txnCoordSenderFactoryCfg := kvcoord.TxnCoordSenderFactoryConfig{
AmbientCtx: cfg.AmbientCtx,
Settings: st,
Clock: clock,
Stopper: stopper,
Linearizable: cfg.Linearizable,
Metrics: txnMetrics,
TestingKnobs: clientTestingKnobs,
}
tcsFactory := kvcoord.NewTxnCoordSenderFactory(txnCoordSenderFactoryCfg, distSender)
cbID := goschedstats.RegisterRunnableCountCallback(gcoords.Regular.CPULoad)
stopper.AddCloser(stop.CloserFn(func() {
goschedstats.UnregisterRunnableCountCallback(cbID)
}))
stopper.AddCloser(gcoords)
dbCtx := kv.DefaultDBContext(stopper)
dbCtx.NodeID = idContainer
dbCtx.Stopper = stopper
db := kv.NewDBWithContext(cfg.AmbientCtx, tcsFactory, clock, dbCtx)
db.SQLKVResponseAdmissionQ = gcoords.Regular.GetWorkQueue(admission.SQLKVResponseWork)
nlActive, nlRenewal := cfg.NodeLivenessDurations()
if knobs := cfg.TestingKnobs.NodeLiveness; knobs != nil {
nlKnobs := knobs.(kvserver.NodeLivenessTestingKnobs)
if duration := nlKnobs.LivenessDuration; duration != 0 {
nlActive = duration
}
if duration := nlKnobs.RenewalDuration; duration != 0 {
nlRenewal = duration
}
}
rangeFeedKnobs, _ := cfg.TestingKnobs.RangeFeed.(*rangefeed.TestingKnobs)
rangeFeedFactory, err := rangefeed.NewFactory(stopper, db, st, rangeFeedKnobs)
if err != nil {
return nil, err
}
stores := kvserver.NewStores(cfg.AmbientCtx, clock)
decomNodeMap := &decommissioningNodeMap{
nodes: make(map[roachpb.NodeID]interface{}),
}
nodeLiveness := liveness.NewNodeLiveness(liveness.NodeLivenessOptions{
AmbientCtx: cfg.AmbientCtx,
Stopper: stopper,
Clock: clock,
DB: db,
Gossip: g,
LivenessThreshold: nlActive,
RenewalDuration: nlRenewal,
Settings: st,
HistogramWindowInterval: cfg.HistogramWindowInterval(),
// When we learn that a node is decommissioning, we want to proactively
// enqueue the ranges we have that also have a replica on the
// decommissioning node.
OnNodeDecommissioning: decomNodeMap.makeOnNodeDecommissioningCallback(stores),
OnNodeDecommissioned: func(liveness livenesspb.Liveness) {
if knobs, ok := cfg.TestingKnobs.Server.(*TestingKnobs); ok && knobs.OnDecommissionedCallback != nil {
knobs.OnDecommissionedCallback(liveness)
}
if err := nodeTombStorage.SetDecommissioned(
ctx, liveness.NodeID, timeutil.Unix(0, liveness.Expiration.WallTime).UTC(),
); err != nil {
log.Fatalf(ctx, "unable to add tombstone for n%d: %s", liveness.NodeID, err)
}
decomNodeMap.onNodeDecommissioned(liveness.NodeID)
},
})
registry.AddMetricStruct(nodeLiveness.Metrics())
nodeLivenessFn := storepool.MakeStorePoolNodeLivenessFunc(nodeLiveness)
if nodeLivenessKnobs, ok := cfg.TestingKnobs.NodeLiveness.(kvserver.NodeLivenessTestingKnobs); ok &&
nodeLivenessKnobs.StorePoolNodeLivenessFn != nil {
nodeLivenessFn = nodeLivenessKnobs.StorePoolNodeLivenessFn
}
storePool := storepool.NewStorePool(
cfg.AmbientCtx,
st,
g,
clock,
nodeLiveness.GetNodeCount,
nodeLivenessFn,
/* deterministic */ false,
)
raftTransport := kvserver.NewRaftTransport(
cfg.AmbientCtx, st, cfg.AmbientCtx.Tracer, nodeDialer, grpcServer.Server, stopper,
)
registry.AddMetricStruct(raftTransport.Metrics())
ctSender := sidetransport.NewSender(stopper, st, clock, nodeDialer)
ctReceiver := sidetransport.NewReceiver(nodeIDContainer, stopper, stores, nil /* testingKnobs */)
// The Executor will be further initialized later, as we create more
// of the server's components. There's a circular dependency - many things
// need an Executor, but the Executor needs an executorConfig,
// which in turn needs many things. That's why everybody that needs an
// Executor uses this one instance.
internalExecutor := &sql.InternalExecutor{}
insqlDB := sql.NewShimInternalDB(db)
jobRegistry := &jobs.Registry{} // ditto
// Create an ExternalStorageBuilder. This is only usable after Start() where
// we initialize all the configuration params.
externalStorageBuilder := &externalStorageBuilder{}
externalStorage := externalStorageBuilder.makeExternalStorage
externalStorageFromURI := externalStorageBuilder.makeExternalStorageFromURI
protectedtsKnobs, _ := cfg.TestingKnobs.ProtectedTS.(*protectedts.TestingKnobs)
protectedtsProvider, err := ptprovider.New(ptprovider.Config{
DB: insqlDB,
Settings: st,
Knobs: protectedtsKnobs,
ReconcileStatusFuncs: ptreconcile.StatusFuncs{
jobsprotectedts.GetMetaType(jobsprotectedts.Jobs): jobsprotectedts.MakeStatusFunc(
jobRegistry, jobsprotectedts.Jobs,
),
jobsprotectedts.GetMetaType(jobsprotectedts.Schedules): jobsprotectedts.MakeStatusFunc(
jobRegistry, jobsprotectedts.Schedules,
),
},
})
if err != nil {
return nil, err
}
registry.AddMetricStruct(protectedtsProvider.Metrics())
// Break a circular dependency: we need the rootSQLMemoryMonitor to construct
// the KV memory monitor for the StoreConfig.
sqlMonitorAndMetrics := newRootSQLMemoryMonitor(monitorAndMetricsOptions{
memoryPoolSize: cfg.MemoryPoolSize,
histogramWindowInterval: cfg.HistogramWindowInterval(),
settings: cfg.Settings,
})
kvMemoryMonitor := mon.NewMonitorInheritWithLimit(
"kv-mem", 0 /* limit */, sqlMonitorAndMetrics.rootSQLMemoryMonitor)
kvMemoryMonitor.StartNoReserved(ctx, sqlMonitorAndMetrics.rootSQLMemoryMonitor)
rangeReedBudgetFactory := serverrangefeed.NewBudgetFactory(
ctx,
serverrangefeed.CreateBudgetFactoryConfig(
kvMemoryMonitor,
cfg.MemoryPoolSize,
cfg.HistogramWindowInterval(),
func(limit int64) int64 {
if !serverrangefeed.RangefeedBudgetsEnabled.Get(&st.SV) {
return 0
}
if raftCmdLimit := kvserverbase.MaxCommandSize.Get(&st.SV); raftCmdLimit > limit {
return raftCmdLimit
}
return limit
},
&st.SV))
if rangeReedBudgetFactory != nil {
registry.AddMetricStruct(rangeReedBudgetFactory.Metrics())
}
// Closer order is important with BytesMonitor.
stopper.AddCloser(stop.CloserFn(func() {
rangeReedBudgetFactory.Stop(ctx)
}))
stopper.AddCloser(stop.CloserFn(func() {
kvMemoryMonitor.Stop(ctx)
}))
tsDB := ts.NewDB(db, cfg.Settings)
registry.AddMetricStruct(tsDB.Metrics())
nodeCountFn := func() int64 {
return nodeLiveness.Metrics().LiveNodes.Value()
}
sTS := ts.MakeServer(
cfg.AmbientCtx, tsDB, nodeCountFn, cfg.TimeSeriesServerConfig,
sqlMonitorAndMetrics.rootSQLMemoryMonitor, stopper,
)
systemConfigWatcher := systemconfigwatcher.New(
keys.SystemSQLCodec, clock, rangeFeedFactory, &cfg.DefaultZoneConfig,
)
var spanConfig struct {
// kvAccessor powers the span configuration RPCs and the host tenant's
// reconciliation job.
kvAccessor spanconfig.KVAccessor
// reporter is used to report over span config conformance.
reporter spanconfig.Reporter
// subscriber is used by stores to subscribe to span configuration updates.
subscriber spanconfig.KVSubscriber
// kvAccessorForTenantRecords is when creating/destroying secondary
// tenant records.
kvAccessorForTenantRecords spanconfig.KVAccessor
}
if !cfg.SpanConfigsDisabled {
spanConfigKnobs, _ := cfg.TestingKnobs.SpanConfig.(*spanconfig.TestingKnobs)
if spanConfigKnobs != nil && spanConfigKnobs.StoreKVSubscriberOverride != nil {
spanConfig.subscriber = spanConfigKnobs.StoreKVSubscriberOverride
} else {
// We use the span configs infra to control whether rangefeeds are
// enabled on a given range. At the moment this only applies to
// system tables (on both host and secondary tenants). We need to
// consider two things:
// - The sql-side reconciliation process runs asynchronously. When
// the config for a given range is requested, we might not yet have
// it, thus falling back to the static config below.
// - Various internal subsystems rely on rangefeeds to function.
//
// Consequently, we configure our static fallback config to actually
// allow rangefeeds. As the sql-side reconciliation process kicks
// off, it'll install the actual configs that we'll later consult.
// For system table ranges we install configs that allow for
// rangefeeds. Until then, we simply allow rangefeeds when a more
// targeted config is not found.
fallbackConf := cfg.DefaultZoneConfig.AsSpanConfig()
fallbackConf.RangefeedEnabled = true
// We do the same for opting out of strict GC enforcement; it
// really only applies to user table ranges
fallbackConf.GCPolicy.IgnoreStrictEnforcement = true
spanConfig.subscriber = spanconfigkvsubscriber.New(
clock,
rangeFeedFactory,
keys.SpanConfigurationsTableID,
1<<20, /* 1 MB */
fallbackConf,
cfg.Settings,
spanConfigKnobs,
registry,
)
}
scKVAccessor := spanconfigkvaccessor.New(
db, internalExecutor, cfg.Settings, clock,
systemschema.SpanConfigurationsTableName.FQString(),
spanConfigKnobs,
)
spanConfig.kvAccessor, spanConfig.kvAccessorForTenantRecords = scKVAccessor, scKVAccessor
spanConfig.reporter = spanconfigreporter.New(
nodeLiveness,
storePool,
spanConfig.subscriber,
rangedesc.NewScanner(db),
cfg.Settings,
spanConfigKnobs,
)
} else {
// If the spanconfigs infrastructure is disabled, there should be no
// reconciliation jobs or RPCs issued against the infrastructure. Plug
// in a disabled spanconfig.KVAccessor that would error out for
// unexpected use.
spanConfig.kvAccessor = spanconfigkvaccessor.DisabledKVAccessor
// Ditto for the spanconfig.Reporter.
spanConfig.reporter = spanconfigreporter.DisabledReporter
// Use a no-op accessor where tenant records are created/destroyed.
spanConfig.kvAccessorForTenantRecords = spanconfigkvaccessor.NoopKVAccessor
spanConfig.subscriber = spanconfigkvsubscriber.NewNoopSubscriber(clock)
}
var protectedTSReader spanconfig.ProtectedTSReader
if cfg.TestingKnobs.SpanConfig != nil &&
cfg.TestingKnobs.SpanConfig.(*spanconfig.TestingKnobs).ProtectedTSReaderOverrideFn != nil {
fn := cfg.TestingKnobs.SpanConfig.(*spanconfig.TestingKnobs).ProtectedTSReaderOverrideFn
protectedTSReader = fn(clock)
} else {
protectedTSReader = spanconfigptsreader.NewAdapter(protectedtsProvider.(*ptprovider.Provider).Cache, spanConfig.subscriber)
}
rangeLogWriter := rangelog.NewWriter(
keys.SystemSQLCodec,
func() int64 {
return int64(builtins.GenerateUniqueInt(
builtins.ProcessUniqueID(nodeIDContainer.Get()),
))
},
)
storeCfg := kvserver.StoreConfig{
DefaultSpanConfig: cfg.DefaultZoneConfig.AsSpanConfig(),
Settings: st,
AmbientCtx: cfg.AmbientCtx,
RaftConfig: cfg.RaftConfig,
Clock: clock,
DB: db,
Gossip: g,
NodeLiveness: nodeLiveness,
Transport: raftTransport,
NodeDialer: nodeDialer,
RPCContext: rpcContext,
ScanInterval: cfg.ScanInterval,
ScanMinIdleTime: cfg.ScanMinIdleTime,
ScanMaxIdleTime: cfg.ScanMaxIdleTime,
HistogramWindowInterval: cfg.HistogramWindowInterval(),
StorePool: storePool,
LogRangeAndNodeEvents: cfg.EventLogEnabled,
RangeDescriptorCache: distSender.RangeDescriptorCache(),
TimeSeriesDataStore: tsDB,
ClosedTimestampSender: ctSender,
ClosedTimestampReceiver: ctReceiver,
ProtectedTimestampReader: protectedTSReader,
KVMemoryMonitor: kvMemoryMonitor,
RangefeedBudgetFactory: rangeReedBudgetFactory,
SystemConfigProvider: systemConfigWatcher,
SpanConfigSubscriber: spanConfig.subscriber,
SpanConfigsDisabled: cfg.SpanConfigsDisabled,
SnapshotApplyLimit: cfg.SnapshotApplyLimit,
SnapshotSendLimit: cfg.SnapshotSendLimit,
RangeLogWriter: rangeLogWriter,
}
if storeTestingKnobs := cfg.TestingKnobs.Store; storeTestingKnobs != nil {
storeCfg.TestingKnobs = *storeTestingKnobs.(*kvserver.StoreTestingKnobs)
}
systemTenantNameContainer := roachpb.NewTenantNameContainer(catconstants.SystemTenantName)
recorder := status.NewMetricsRecorder(
clock,
nodeLiveness,
rpcContext,
st,
systemTenantNameContainer,
)
registry.AddMetricStruct(rpcContext.RemoteClocks.Metrics())
updates := &diagnostics.UpdateChecker{
StartTime: timeutil.Now(),
AmbientCtx: &cfg.AmbientCtx,
Config: cfg.BaseConfig.Config,
Settings: cfg.Settings,
StorageClusterID: rpcContext.StorageClusterID.Get,
LogicalClusterID: rpcContext.LogicalClusterID.Get,
NodeID: nodeIDContainer.Get,
SQLInstanceID: idContainer.SQLInstanceID,
}
if cfg.TestingKnobs.Server != nil {
updates.TestingKnobs = &cfg.TestingKnobs.Server.(*TestingKnobs).DiagnosticsTestingKnobs
}
tenantUsage := NewTenantUsageServer(st, db, insqlDB)
registry.AddMetricStruct(tenantUsage.Metrics())
tenantSettingsWatcher := tenantsettingswatcher.New(
clock, rangeFeedFactory, stopper, st,
)
node := NewNode(
storeCfg,
recorder,
registry,
stopper,
txnMetrics,
stores,
cfg.ClusterIDContainer,
gcoords.Regular.GetWorkQueue(admission.KVWork),
gcoords.Elastic,
gcoords.Stores,
tenantUsage,
tenantSettingsWatcher,
spanConfig.kvAccessor,
spanConfig.reporter,
)
roachpb.RegisterInternalServer(grpcServer.Server, node)
kvserver.RegisterPerReplicaServer(grpcServer.Server, node.perReplicaServer)
kvserver.RegisterPerStoreServer(grpcServer.Server, node.perReplicaServer)
ctpb.RegisterSideTransportServer(grpcServer.Server, ctReceiver)
{ // wire up admission control's scheduler latency listener
slcbID := schedulerlatency.RegisterCallback(
node.storeCfg.SchedulerLatencyListener.SchedulerLatency,
)
stopper.AddCloser(stop.CloserFn(func() {
schedulerlatency.UnregisterCallback(slcbID)
}))
}
replicationReporter := reports.NewReporter(
db, node.stores, storePool, st, nodeLiveness, internalExecutor, systemConfigWatcher,
)
lateBoundServer := &Server{}
// The following initialization is mirrored in NewTenantServer().
// Please keep them in sync.
// Instantiate the API privilege checker.
//
// TODO(tbg): give adminServer only what it needs (and avoid circular deps).
adminAuthzCheck := &adminPrivilegeChecker{
ie: internalExecutor,
st: st,
makePlanner: nil,
}
// Instantiate the HTTP server.
// These callbacks help us avoid a dependency on gossip in httpServer.
parseNodeIDFn := func(s string) (roachpb.NodeID, bool, error) {
return parseNodeID(g, s)
}
getNodeIDHTTPAddressFn := func(id roachpb.NodeID) (*util.UnresolvedAddr, error) {
return g.GetNodeIDHTTPAddress(id)
}
sHTTP := newHTTPServer(cfg.BaseConfig, rpcContext, parseNodeIDFn, getNodeIDHTTPAddressFn)
// Instantiate the SQL session registry.
sessionRegistry := sql.NewSessionRegistry()
// Instantiate the cache of closed SQL sessions.
closedSessionCache := sql.NewClosedSessionCache(cfg.Settings, sqlMonitorAndMetrics.rootSQLMemoryMonitor, time.Now)
// Instantiate the distSQL remote flow runner.
remoteFlowRunnerAcc := sqlMonitorAndMetrics.rootSQLMemoryMonitor.MakeBoundAccount()
remoteFlowRunner := flowinfra.NewRemoteFlowRunner(cfg.AmbientCtx, stopper, &remoteFlowRunnerAcc)
serverIterator := &kvFanoutClient{
gossip: g,
rpcCtx: rpcContext,
db: db,
nodeLiveness: nodeLiveness,
clock: clock,
st: st,
ambientCtx: cfg.AmbientCtx,
}
// Instantiate the span stats server. There is a circular dependency
// between server.spanStatsServer and server.systemStatusServer.
spanStats := &spanStatsServer{
fetcher: rangestats.NewFetcher(db),
distSender: distSender,
statusServer: nil, // Circular dependency. Set below.
node: node,
}
spanStatsLocalAccessor := spanstatsaccessor.New(spanStats)
// Instantiate the status API server.
sStatus := newSystemStatusServer(
cfg.AmbientCtx,
st,
cfg.Config,
adminAuthzCheck,
db,
g,
recorder,
nodeLiveness,
storePool,
rpcContext,
node.stores,
stopper,
sessionRegistry,
closedSessionCache,
remoteFlowRunner,
internalExecutor,
serverIterator,
spanConfig.reporter,
clock,
distSender,
spanStatsLocalAccessor,
)
// The spanStatsServer needs a reference to the status server.
spanStats.statusServer = sStatus
keyVisualizerServer := &KeyVisualizerServer{
ie: internalExecutor,
settings: st,
nodeDialer: nodeDialer,
status: sStatus,
node: node,
}
keyVisServerAccessor := spanstatskvaccessor.New(keyVisualizerServer)
// Instantiate the KV prober
kvProber := kvprober.NewProber(kvprober.Opts{
Tracer: cfg.AmbientCtx.Tracer,
DB: db,
Settings: st,
HistogramWindowInterval: cfg.HistogramWindowInterval(),
})
registry.AddMetricStruct(kvProber.Metrics())
// Create the Obs Server. We'll call SetResourceInfo() on it and register it
// with gRPC later.
eventsServer := obs.NewEventServer(
cfg.AmbientCtx,
timeutil.DefaultTimeSource{},
stopper,
5*time.Second, // maxStaleness
1<<20, // triggerSizeBytes - 1MB
10*1<<20, // maxBufferSizeBytes - 10MB
sqlMonitorAndMetrics.rootSQLMemoryMonitor, // memMonitor - this is not "SQL" usage, but we don't have another memory pool,
)
if knobs := cfg.TestingKnobs.EventExporter; knobs != nil {
eventsServer.TestingKnobs = knobs.(obs.EventServerTestingKnobs)
}
// The settings cache writer is responsible for persisting the
// cluster settings on KV nodes across restarts.
settingsWriter := newSettingsCacheWriter(engines[0], stopper)
stopTrigger := newStopTrigger()
// Initialize the pgwire pre-server, which initializes connections,
// sets up TLS and reads client status parameters.
pgPreServer := pgwire.MakePreServeConnHandler(
cfg.AmbientCtx,
cfg.Config,
cfg.Settings,
rpcContext.GetServerTLSConfig,
cfg.HistogramWindowInterval(),
sqlMonitorAndMetrics.rootSQLMemoryMonitor,
true, /* acceptTenantName */
)
for _, m := range pgPreServer.Metrics() {
registry.AddMetricStruct(m)
}
// Instantiate the SQL server proper.
sqlServer, err := newSQLServer(ctx, sqlServerArgs{
sqlServerOptionalKVArgs: sqlServerOptionalKVArgs{
nodesStatusServer: serverpb.MakeOptionalNodesStatusServer(sStatus),
nodeLiveness: optionalnodeliveness.MakeContainer(nodeLiveness),
gossip: gossip.MakeOptionalGossip(g),
grpcServer: grpcServer.Server,
nodeIDContainer: idContainer,
externalStorage: externalStorage,
externalStorageFromURI: externalStorageFromURI,
isMeta1Leaseholder: node.stores.IsMeta1Leaseholder,
sqlSQLResponseAdmissionQ: gcoords.Regular.GetWorkQueue(admission.SQLSQLResponseWork),
spanConfigKVAccessor: spanConfig.kvAccessorForTenantRecords,
kvStoresIterator: kvserver.MakeStoresIterator(node.stores),
},
SQLConfig: &cfg.SQLConfig,
BaseConfig: &cfg.BaseConfig,
stopper: stopper,
stopTrigger: stopTrigger,
clock: clock,
runtime: runtimeSampler,
rpcContext: rpcContext,
nodeDescs: g,
systemConfigWatcher: systemConfigWatcher,
spanConfigAccessor: spanConfig.kvAccessor,
keyVisServerAccessor: keyVisServerAccessor,
spanStatsAccessor: spanStatsLocalAccessor,
nodeDialer: nodeDialer,
distSender: distSender,
db: db,
registry: registry,
recorder: recorder,
sessionRegistry: sessionRegistry,
closedSessionCache: closedSessionCache,
remoteFlowRunner: remoteFlowRunner,
circularInternalExecutor: internalExecutor,
internalDB: insqlDB,
circularJobRegistry: jobRegistry,
protectedtsProvider: protectedtsProvider,
rangeFeedFactory: rangeFeedFactory,
sqlStatusServer: sStatus,
tenantStatusServer: sStatus,
tenantUsageServer: tenantUsage,
monitorAndMetrics: sqlMonitorAndMetrics,
settingsStorage: settingsWriter,
eventsServer: eventsServer,
admissionPacerFactory: gcoords.Elastic,
rangeDescIteratorFactory: rangedesc.NewIteratorFactory(db),
})
if err != nil {
return nil, err
}
// Tell the authz server how to connect to SQL.
adminAuthzCheck.makePlanner = func(opName string) (interface{}, func()) {
// This is a hack to get around a Go package dependency cycle. See comment
// in sql/jobs/registry.go on planHookMaker.
txn := db.NewTxn(ctx, "check-system-privilege")
return sql.NewInternalPlanner(
opName,
txn,
username.RootUserName(),
&sql.MemoryMetrics{},
sqlServer.execCfg,
sessiondatapb.SessionData{},