-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
node.go
2134 lines (1928 loc) · 73.6 KB
/
node.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 (
"bytes"
"context"
"fmt"
"net"
"sort"
"strings"
"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/config"
"github.com/cockroachdb/cockroach/pkg/config/zonepb"
"github.com/cockroachdb/cockroach/pkg/gossip"
"github.com/cockroachdb/cockroach/pkg/keys"
"github.com/cockroachdb/cockroach/pkg/keyvisualizer/keyvissettings"
"github.com/cockroachdb/cockroach/pkg/keyvisualizer/spanstatscollector"
"github.com/cockroachdb/cockroach/pkg/kv"
"github.com/cockroachdb/cockroach/pkg/kv/kvclient"
"github.com/cockroachdb/cockroach/pkg/kv/kvclient/kvcoord"
"github.com/cockroachdb/cockroach/pkg/kv/kvclient/kvtenant"
"github.com/cockroachdb/cockroach/pkg/kv/kvpb"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver/kvadmission"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver/kvstorage"
"github.com/cockroachdb/cockroach/pkg/multitenant"
"github.com/cockroachdb/cockroach/pkg/roachpb"
"github.com/cockroachdb/cockroach/pkg/rpc"
"github.com/cockroachdb/cockroach/pkg/server/status"
"github.com/cockroachdb/cockroach/pkg/server/tenantsettingswatcher"
"github.com/cockroachdb/cockroach/pkg/settings"
"github.com/cockroachdb/cockroach/pkg/settings/cluster"
"github.com/cockroachdb/cockroach/pkg/spanconfig"
"github.com/cockroachdb/cockroach/pkg/sql"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/bootstrap"
"github.com/cockroachdb/cockroach/pkg/sql/isql"
"github.com/cockroachdb/cockroach/pkg/storage"
"github.com/cockroachdb/cockroach/pkg/util"
"github.com/cockroachdb/cockroach/pkg/util/admission"
"github.com/cockroachdb/cockroach/pkg/util/admission/admissionpb"
"github.com/cockroachdb/cockroach/pkg/util/buildutil"
"github.com/cockroachdb/cockroach/pkg/util/future"
"github.com/cockroachdb/cockroach/pkg/util/hlc"
"github.com/cockroachdb/cockroach/pkg/util/log"
"github.com/cockroachdb/cockroach/pkg/util/log/eventpb"
"github.com/cockroachdb/cockroach/pkg/util/log/logpb"
"github.com/cockroachdb/cockroach/pkg/util/metric"
"github.com/cockroachdb/cockroach/pkg/util/pprofutil"
"github.com/cockroachdb/cockroach/pkg/util/startup"
"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/tracing/grpcinterceptor"
"github.com/cockroachdb/cockroach/pkg/util/tracing/tracingpb"
"github.com/cockroachdb/cockroach/pkg/util/uuid"
"github.com/cockroachdb/errors"
"github.com/cockroachdb/logtags"
"github.com/cockroachdb/redact"
"google.golang.org/grpc/codes"
grpcstatus "google.golang.org/grpc/status"
)
const (
// gossipStatusInterval is the interval for logging gossip status.
gossipStatusInterval = 1 * time.Minute
graphiteIntervalKey = "external.graphite.interval"
maxGraphiteInterval = 15 * time.Minute
)
// Metric names.
var (
metaExecLatency = metric.Metadata{
Name: "exec.latency",
Help: `Latency of batch KV requests (including errors) executed on this node.
This measures requests already addressed to a single replica, from the moment
at which they arrive at the internal gRPC endpoint to the moment at which the
response (or an error) is returned.
This latency includes in particular commit waits, conflict resolution and replication,
and end-users can easily produce high measurements via long-running transactions that
conflict with foreground traffic. This metric thus does not provide a good signal for
understanding the health of the KV layer.
`,
Measurement: "Latency",
Unit: metric.Unit_NANOSECONDS,
}
metaExecSuccess = metric.Metadata{
Name: "exec.success",
Help: `Number of batch KV requests executed successfully on this node.
A request is considered to have executed 'successfully' if it either returns a result
or a transaction restart/abort error.
`,
Measurement: "Batch KV Requests",
Unit: metric.Unit_COUNT,
}
metaExecError = metric.Metadata{
Name: "exec.error",
Help: `Number of batch KV requests that failed to execute on this node.
This count excludes transaction restart/abort errors. However, it will include
other errors expected during normal operation, such as ConditionFailedError.
This metric is thus not an indicator of KV health.`,
Measurement: "Batch KV Requests",
Unit: metric.Unit_COUNT,
}
metaDiskStalls = metric.Metadata{
Name: "engine.stalls",
Help: "Number of disk stalls detected on this node",
Measurement: "Disk stalls detected",
Unit: metric.Unit_COUNT,
}
metaInternalBatchRPCMethodCount = metric.Metadata{
Name: "rpc.method.%s.recv",
Help: "Number of %s requests processed",
Measurement: "RPCs",
Unit: metric.Unit_COUNT,
}
metaInternalBatchRPCCount = metric.Metadata{
Name: "rpc.batches.recv",
Help: "Number of batches processed",
Measurement: "Batches",
Unit: metric.Unit_COUNT,
}
)
// Cluster settings.
var (
// graphiteEndpoint is host:port, if any, of Graphite metrics server.
graphiteEndpoint = settings.RegisterStringSetting(
settings.TenantWritable,
"external.graphite.endpoint",
"if nonempty, push server metrics to the Graphite or Carbon server at the specified host:port",
"",
).WithPublic()
// graphiteInterval is how often metrics are pushed to Graphite, if enabled.
graphiteInterval = settings.RegisterDurationSetting(
settings.TenantWritable,
graphiteIntervalKey,
"the interval at which metrics are pushed to Graphite (if enabled)",
10*time.Second,
settings.NonNegativeDurationWithMaximum(maxGraphiteInterval),
).WithPublic()
RedactServerTracesForSecondaryTenants = settings.RegisterBoolSetting(
settings.SystemOnly,
"server.secondary_tenants.redact_trace.enabled",
"controls if server side traces are redacted for tenant operations",
true,
).WithPublic()
slowRequestHistoricalStackThreshold = settings.RegisterDurationSetting(
settings.SystemOnly,
"kv.trace.slow_request_stacks.threshold",
`duration spent in processing above any available stack history is appended to its trace, if automatic trace snapshots are enabled`,
time.Second*30,
)
)
type nodeMetrics struct {
Latency metric.IHistogram
Success *metric.Counter
Err *metric.Counter
DiskStalls *metric.Counter
BatchCount *metric.Counter
MethodCounts [kvpb.NumMethods]*metric.Counter
}
func makeNodeMetrics(reg *metric.Registry, histogramWindow time.Duration) nodeMetrics {
nm := nodeMetrics{
Latency: metric.NewHistogram(metric.HistogramOptions{
Mode: metric.HistogramModePreferHdrLatency,
Metadata: metaExecLatency,
Duration: histogramWindow,
Buckets: metric.IOLatencyBuckets,
}),
Success: metric.NewCounter(metaExecSuccess),
Err: metric.NewCounter(metaExecError),
DiskStalls: metric.NewCounter(metaDiskStalls),
BatchCount: metric.NewCounter(metaInternalBatchRPCCount),
}
for i := range nm.MethodCounts {
method := kvpb.Method(i).String()
meta := metaInternalBatchRPCMethodCount
meta.Name = fmt.Sprintf(meta.Name, strings.ToLower(method))
meta.Help = fmt.Sprintf(meta.Help, method)
nm.MethodCounts[i] = metric.NewCounter(meta)
}
reg.AddMetricStruct(nm)
return nm
}
// callComplete records very high-level metrics about the number of completed
// calls and their latency. Currently, this only records statistics at the batch
// level; stats on specific lower-level kv operations are not recorded.
func (nm nodeMetrics) callComplete(d time.Duration, pErr *kvpb.Error) {
if pErr != nil && pErr.TransactionRestart() == kvpb.TransactionRestart_NONE {
nm.Err.Inc(1)
} else {
nm.Success.Inc(1)
}
nm.Latency.RecordValue(d.Nanoseconds())
}
// A Node manages a map of stores (by store ID) for which it serves
// traffic. A node is the top-level data structure. There is one node
// instance per process. A node accepts incoming RPCs and services
// them by directing the commands contained within RPCs to local
// stores, which in turn direct the commands to specific ranges. Each
// node has access to the global, monolithic Key-Value abstraction via
// its client.DB reference. Nodes use this to allocate node and store
// IDs for bootstrapping the node itself or initializing new stores as
// they're added on subsequent instantiations.
type Node struct {
stopper *stop.Stopper
clusterID *base.ClusterIDContainer // UUID for Cockroach cluster
Descriptor roachpb.NodeDescriptor // Node ID, network/physical topology
storeCfg kvserver.StoreConfig // Config to use and pass to stores
execCfg *sql.ExecutorConfig // For event logging
stores *kvserver.Stores // Access to node-local stores
metrics nodeMetrics
recorder *status.MetricsRecorder
startedAt int64
lastUp int64
initialStart bool // true if this is the first time this node has started
txnMetrics kvcoord.TxnMetrics
// Used to signal when additional stores, if any, have been initialized.
additionalStoreInitCh chan struct{}
perReplicaServer kvserver.Server
tenantUsage multitenant.TenantUsageServer
tenantSettingsWatcher *tenantsettingswatcher.Watcher
spanConfigAccessor spanconfig.KVAccessor // powers the span configuration RPCs
spanConfigReporter spanconfig.Reporter // powers the span configuration RPCs
// Turns `Node.writeNodeStatus` into a no-op. This is a hack to enable the
// COCKROACH_DEBUG_TS_IMPORT_FILE env var.
suppressNodeStatus syncutil.AtomicBool
diskStatsMap diskStatsMap
testingErrorEvent func(context.Context, *kvpb.BatchRequest, error)
// Used to collect samples for the key visualizer.
spanStatsCollector *spanstatscollector.SpanStatsCollector
}
var _ kvpb.InternalServer = &Node{}
// allocateNodeID increments the node id generator key to allocate
// a new, unique node id.
func allocateNodeID(ctx context.Context, db *kv.DB) (roachpb.NodeID, error) {
val, err := kv.IncrementValRetryable(ctx, db, keys.NodeIDGenerator, 1)
if err != nil {
return 0, errors.Wrap(err, "unable to allocate node ID")
}
return roachpb.NodeID(val), nil
}
// allocateStoreIDs increments the store id generator key for the
// specified node to allocate count new, unique store ids. The
// first ID in a contiguous range is returned on success.
func allocateStoreIDs(
ctx context.Context, nodeID roachpb.NodeID, count int64, db *kv.DB,
) (roachpb.StoreID, error) {
val, err := kv.IncrementValRetryable(ctx, db, keys.StoreIDGenerator, count)
if err != nil {
return 0, errors.Wrapf(err, "unable to allocate %d store IDs for node %d", count, nodeID)
}
return roachpb.StoreID(val - count + 1), nil
}
// GetBootstrapSchema returns the schema which will be used to bootstrap a new
// server.
func GetBootstrapSchema(
defaultZoneConfig *zonepb.ZoneConfig, defaultSystemZoneConfig *zonepb.ZoneConfig,
) bootstrap.MetadataSchema {
return bootstrap.MakeMetadataSchema(keys.SystemSQLCodec, defaultZoneConfig, defaultSystemZoneConfig)
}
// bootstrapCluster initializes the passed-in engines for a new cluster.
// Returns the cluster ID.
//
// The first engine will contain ranges for various static split points (i.e.
// various system ranges and system tables). Note however that many of these
// ranges cannot be accessed by KV in regular means until the node liveness is
// written, since epoch-based leases cannot be granted until then. All other
// engines are initialized with their StoreIdent.
func bootstrapCluster(
ctx context.Context, engines []storage.Engine, initCfg initServerCfg,
) (*initState, error) {
clusterID := uuid.MakeV4()
// TODO(andrei): It'd be cool if this method wouldn't do anything to engines
// other than the first one, and let regular node startup code deal with them.
var bootstrapVersion clusterversion.ClusterVersion
for i, eng := range engines {
cv := eng.MinVersion()
if cv.Major == 0 {
return nil, errors.Errorf("missing bootstrap version")
}
// bootstrapCluster requires matching cluster versions on all engines.
if i == 0 {
bootstrapVersion.Version = cv
} else if bootstrapVersion.Version != cv {
return nil, errors.Errorf("found cluster versions %s and %s", bootstrapVersion, cv)
}
sIdent := roachpb.StoreIdent{
ClusterID: clusterID,
NodeID: kvstorage.FirstNodeID,
StoreID: kvstorage.FirstStoreID + roachpb.StoreID(i),
}
// Initialize the engine backing the store with the store ident and cluster
// version.
if err := kvstorage.InitEngine(ctx, eng, sIdent); err != nil {
return nil, err
}
// Create first range, writing directly to engine. Note this does
// not create the range, just its data. Only do this if this is the
// first store.
if i == 0 {
initialValuesOpts := bootstrap.InitialValuesOpts{
DefaultZoneConfig: &initCfg.defaultZoneConfig,
DefaultSystemZoneConfig: &initCfg.defaultSystemZoneConfig,
Codec: keys.SystemSQLCodec,
}
if initCfg.testingKnobs.Server != nil {
knobs := initCfg.testingKnobs.Server.(*TestingKnobs)
// If BinaryVersionOverride is set, and our `binaryMinSupportedVersion`
// is at its default value, we must populate the cluster with initial
// data from the `binaryMinSupportedVersion`. This cluster will then run
// the necessary upgrades until `BinaryVersionOverride` before being
// ready to use in the test.
if knobs.BinaryVersionOverride != (roachpb.Version{}) {
if initCfg.binaryMinSupportedVersion.Equal(
clusterversion.ByKey(clusterversion.BinaryMinSupportedVersionKey)) {
initialValuesOpts.OverrideKey = clusterversion.BinaryMinSupportedVersionKey
}
}
if knobs.BootstrapVersionKeyOverride != 0 {
initialValuesOpts.OverrideKey = initCfg.testingKnobs.Server.(*TestingKnobs).BootstrapVersionKeyOverride
}
}
initialValues, tableSplits, err := initialValuesOpts.GetInitialValuesCheckForOverrides()
if err != nil {
return nil, err
}
splits := append(config.StaticSplits(), tableSplits...)
sort.Slice(splits, func(i, j int) bool {
return splits[i].Less(splits[j])
})
var storeKnobs kvserver.StoreTestingKnobs
if kn, ok := initCfg.testingKnobs.Store.(*kvserver.StoreTestingKnobs); ok {
storeKnobs = *kn
}
if err := kvserver.WriteInitialClusterData(
ctx, eng, initialValues,
bootstrapVersion.Version, len(engines), splits,
timeutil.Now().UnixNano(), storeKnobs,
); err != nil {
return nil, err
}
}
}
return inspectEngines(ctx, engines, initCfg.binaryVersion, initCfg.binaryMinSupportedVersion)
}
// NewNode returns a new instance of Node.
//
// InitLogger() needs to be called before the Node is used.
func NewNode(
cfg kvserver.StoreConfig,
recorder *status.MetricsRecorder,
reg *metric.Registry,
stopper *stop.Stopper,
txnMetrics kvcoord.TxnMetrics,
stores *kvserver.Stores,
clusterID *base.ClusterIDContainer,
kvAdmissionQ *admission.WorkQueue,
elasticCPUGrantCoord *admission.ElasticCPUGrantCoordinator,
storeGrantCoords *admission.StoreGrantCoordinators,
tenantUsage multitenant.TenantUsageServer,
tenantSettingsWatcher *tenantsettingswatcher.Watcher,
spanConfigAccessor spanconfig.KVAccessor,
spanConfigReporter spanconfig.Reporter,
) *Node {
n := &Node{
storeCfg: cfg,
stopper: stopper,
recorder: recorder,
metrics: makeNodeMetrics(reg, cfg.HistogramWindowInterval),
stores: stores,
txnMetrics: txnMetrics,
execCfg: nil, // filled in later by InitLogger()
clusterID: clusterID,
tenantUsage: tenantUsage,
tenantSettingsWatcher: tenantSettingsWatcher,
spanConfigAccessor: spanConfigAccessor,
spanConfigReporter: spanConfigReporter,
testingErrorEvent: cfg.TestingKnobs.TestingResponseErrorEvent,
spanStatsCollector: spanstatscollector.New(cfg.Settings),
}
n.storeCfg.KVAdmissionController = kvadmission.MakeController(
kvAdmissionQ, elasticCPUGrantCoord, storeGrantCoords, cfg.Settings,
)
n.storeCfg.SchedulerLatencyListener = elasticCPUGrantCoord.SchedulerLatencyListener
n.perReplicaServer = kvserver.MakeServer(&n.Descriptor, n.stores)
return n
}
// InitLogger connects the Node to the Executor to be used for event
// logging.
func (n *Node) InitLogger(execCfg *sql.ExecutorConfig) {
n.execCfg = execCfg
}
// String implements fmt.Stringer.
func (n *Node) String() string {
return fmt.Sprintf("node=%d", n.Descriptor.NodeID)
}
// AnnotateCtx is a convenience wrapper; see AmbientContext.
func (n *Node) AnnotateCtx(ctx context.Context) context.Context {
return n.storeCfg.AmbientCtx.AnnotateCtx(ctx)
}
// AnnotateCtxWithSpan is a convenience wrapper; see AmbientContext.
func (n *Node) AnnotateCtxWithSpan(
ctx context.Context, opName string,
) (context.Context, *tracing.Span) {
return n.storeCfg.AmbientCtx.AnnotateCtxWithSpan(ctx, opName)
}
// start starts the node by registering the storage instance for the RPC
// service "Node" and initializing stores for each specified engine.
// Launches periodic store gossiping in a goroutine.
//
// addr, sqlAddr, and httpAddr are used to populate the Address,
// SQLAddress, and HTTPAddress fields respectively of the
// NodeDescriptor. If sqlAddr is not provided or empty, it is assumed
// that SQL connections are accepted at addr. Neither is ever assumed
// to carry HTTP, only if httpAddr is non-null will this node accept
// proxied traffic from other nodes.
func (n *Node) start(
ctx, workersCtx context.Context,
addr, sqlAddr, httpAddr net.Addr,
state initState,
initialStart bool,
clusterName string,
attrs roachpb.Attributes,
locality roachpb.Locality,
localityAddress []roachpb.LocalityAddress,
) error {
n.initialStart = initialStart
n.startedAt = n.storeCfg.Clock.Now().WallTime
n.Descriptor = roachpb.NodeDescriptor{
NodeID: state.nodeID,
Address: util.MakeUnresolvedAddr(addr.Network(), addr.String()),
SQLAddress: util.MakeUnresolvedAddr(sqlAddr.Network(), sqlAddr.String()),
Attrs: attrs,
Locality: locality,
LocalityAddress: localityAddress,
ClusterName: clusterName,
ServerVersion: n.storeCfg.Settings.Version.BinaryVersion(),
BuildTag: build.GetInfo().Tag,
StartedAt: n.startedAt,
HTTPAddress: util.MakeUnresolvedAddr(httpAddr.Network(), httpAddr.String()),
}
// Gossip the node descriptor to make this node addressable by node ID.
n.storeCfg.Gossip.NodeID.Set(ctx, n.Descriptor.NodeID)
if err := n.storeCfg.Gossip.SetNodeDescriptor(&n.Descriptor); err != nil {
return errors.Wrapf(err, "couldn't gossip descriptor for node %d", n.Descriptor.NodeID)
}
// Create stores from the engines that were already initialized.
for _, e := range state.initializedEngines {
s := kvserver.NewStore(ctx, n.storeCfg, e, &n.Descriptor)
if err := s.Start(workersCtx, n.stopper); err != nil {
return errors.Wrap(err, "failed to start store")
}
n.addStore(ctx, s)
log.Infof(ctx, "initialized store s%s", s.StoreID())
}
// Verify all initialized stores agree on cluster and node IDs.
if err := n.validateStores(ctx); err != nil {
return err
}
log.VEventf(ctx, 2, "validated stores")
// Compute the time this node was last up; this is done by reading the
// "last up time" from every store and choosing the most recent timestamp.
var mostRecentTimestamp hlc.Timestamp
if err := n.stores.VisitStores(func(s *kvserver.Store) error {
timestamp, err := s.ReadLastUpTimestamp(ctx)
if err != nil {
return err
}
if mostRecentTimestamp.Less(timestamp) {
mostRecentTimestamp = timestamp
}
return nil
}); err != nil {
return errors.Wrapf(err, "failed to read last up timestamp from stores")
}
n.lastUp = mostRecentTimestamp.WallTime
// Set the stores map as the gossip persistent storage, so that
// gossip can bootstrap using the most recently persisted set of
// node addresses.
if err := n.storeCfg.Gossip.SetStorage(n.stores); err != nil {
return errors.Wrap(err, "failed to initialize the gossip interface")
}
// Initialize remaining stores/engines, if any.
if len(state.uninitializedEngines) > 0 {
// We need to initialize any remaining stores asynchronously.
// Consider the range that houses the store ID allocator. When we
// restart the set of nodes that holds a quorum of these replicas,
// specifically when we restart them with auxiliary stores, these stores
// will require store IDs during initialization[1]. But if we're gating
// node start up (specifically the opening up of RPC floodgates) on
// having all stores in the node fully initialized, we'll simply hang
// when trying to allocate store IDs. See
// TestAddNewStoresToExistingNodes and #39415 for more details.
//
// So instead we opt to initialize additional stores asynchronously, and
// rely on the blocking function n.waitForAdditionalStoreInit() to
// signal to the caller that all stores have been fully initialized.
//
// [1]: It's important to note that store IDs are allocated via a
// sequence ID generator stored in a system key.
n.additionalStoreInitCh = make(chan struct{})
if err := n.stopper.RunAsyncTask(workersCtx, "initialize-additional-stores", func(ctx context.Context) {
if err := n.initializeAdditionalStores(ctx, state.uninitializedEngines, n.stopper); err != nil {
log.Fatalf(ctx, "while initializing additional stores: %v", err)
}
close(n.additionalStoreInitCh)
}); err != nil {
close(n.additionalStoreInitCh)
return err
}
}
n.startComputePeriodicMetrics(n.stopper, base.DefaultMetricsSampleInterval)
// Stores have been created, so can start providing tenant weights.
n.storeCfg.KVAdmissionController.SetTenantWeightProvider(n, n.stopper)
// Be careful about moving this line above where we start stores; store
// upgrades rely on the fact that the cluster version has not been updated
// via Gossip (we have upgrades that want to run only if the server starts
// with a given cluster version, but not if the server starts with a lower
// one and gets bumped immediately, which would be possible if gossip got
// started earlier).
n.startGossiping(workersCtx, n.stopper)
var terminateCollector func() = nil
if keyvissettings.Enabled.Get(&n.storeCfg.Settings.SV) {
terminateCollector = n.enableSpanStatsCollector(ctx)
}
keyvissettings.Enabled.SetOnChange(&n.storeCfg.Settings.SV, func(ctx context.Context) {
enabled := keyvissettings.Enabled.Get(&n.storeCfg.Settings.SV)
if enabled {
terminateCollector = n.enableSpanStatsCollector(ctx)
} else if terminateCollector != nil {
terminateCollector()
}
})
allEngines := append([]storage.Engine(nil), state.initializedEngines...)
allEngines = append(allEngines, state.uninitializedEngines...)
for _, e := range allEngines {
t := e.Type()
log.Infof(ctx, "started with engine type %v", t)
}
log.Infof(ctx, "started with attributes %v", attrs.Attrs)
return nil
}
func (n *Node) enableSpanStatsCollector(ctx context.Context) func() {
collectorCtx, terminate := context.WithCancel(ctx)
n.spanStatsCollector.Start(collectorCtx, n.stopper)
return terminate
}
// waitForAdditionalStoreInit blocks until all additional empty stores,
// if any, have been initialized.
func (n *Node) waitForAdditionalStoreInit() {
if n.additionalStoreInitCh != nil {
<-n.additionalStoreInitCh
}
}
// IsDraining returns true if at least one Store housed on this Node is not
// currently allowing range leases to be procured or extended.
func (n *Node) IsDraining() bool {
var isDraining bool
if err := n.stores.VisitStores(func(s *kvserver.Store) error {
isDraining = isDraining || s.IsDraining()
return nil
}); err != nil {
panic(err)
}
return isDraining
}
// SetDraining sets the draining mode on all of the node's underlying stores.
// The reporter callback, if non-nil, is called on a best effort basis
// to report work that needed to be done and which may or may not have
// been done by the time this call returns. See the explanation in
// pkg/server/drain.go for details.
func (n *Node) SetDraining(drain bool, reporter func(int, redact.SafeString), verbose bool) error {
return n.stores.VisitStores(func(s *kvserver.Store) error {
s.SetDraining(drain, reporter, verbose)
return nil
})
}
// SetHLCUpperBound sets the upper bound of the HLC wall time on all of the
// node's underlying stores.
func (n *Node) SetHLCUpperBound(ctx context.Context, hlcUpperBound int64) error {
return n.stores.VisitStores(func(s *kvserver.Store) error {
return s.WriteHLCUpperBound(ctx, hlcUpperBound)
})
}
func (n *Node) addStore(ctx context.Context, store *kvserver.Store) {
cv := store.TODOEngine().MinVersion()
if cv == (roachpb.Version{}) {
// The store should have had a version written to it during the store
// initialization process.
log.Fatal(ctx, "attempting to add a store without a version")
}
n.stores.AddStore(store)
n.recorder.AddStore(store)
}
// validateStores iterates over all stores, verifying they agree on node ID.
// The node's ident is initialized based on the agreed-upon node ID. Note that
// cluster ID consistency is checked elsewhere in inspectEngines.
//
// TODO(tbg): remove this, we already validate everything in inspectEngines now.
func (n *Node) validateStores(ctx context.Context) error {
return n.stores.VisitStores(func(s *kvserver.Store) error {
if n.Descriptor.NodeID != s.Ident.NodeID {
return errors.Errorf("store %s node ID doesn't match node ID: %d", s, n.Descriptor.NodeID)
}
return nil
})
}
// initializeAdditionalStores initializes the given set of engines once the
// cluster and node ID have been established for this node. Store IDs are
// allocated via a sequence id generator stored at a system key per node. The
// new stores are added to n.stores.
func (n *Node) initializeAdditionalStores(
ctx context.Context, engines []storage.Engine, stopper *stop.Stopper,
) error {
if n.clusterID.Get() == uuid.Nil {
return errors.New("missing cluster ID during initialization of additional store")
}
{
// Initialize all waiting stores by allocating a new store id for each
// and invoking kvserver.InitEngine() to persist it. We'll then
// construct a new store out of the initialized engine and attach it to
// ourselves.
storeIDAlloc := int64(len(engines))
startID, err := allocateStoreIDs(ctx, n.Descriptor.NodeID, storeIDAlloc, n.storeCfg.DB)
if err != nil {
return errors.Wrap(err, "error allocating store ids")
}
sIdent := roachpb.StoreIdent{
ClusterID: n.clusterID.Get(),
NodeID: n.Descriptor.NodeID,
StoreID: startID,
}
for _, eng := range engines {
if err := kvstorage.InitEngine(ctx, eng, sIdent); err != nil {
return err
}
s := kvserver.NewStore(ctx, n.storeCfg, eng, &n.Descriptor)
if err := s.Start(ctx, stopper); err != nil {
return err
}
n.addStore(ctx, s)
log.Infof(ctx, "initialized store s%s", s.StoreID())
// Done regularly in Node.startGossiping, but this cuts down the time
// until this store is used for range allocations.
if err := s.GossipStore(ctx, false /* useCached */); err != nil {
log.Warningf(ctx, "error doing initial gossiping: %s", err)
}
sIdent.StoreID++
}
}
// Write a new status summary after all stores have been initialized; this
// helps the UI remain responsive when new nodes are added.
if err := n.writeNodeStatus(ctx, 0 /* alertTTL */, false /* mustExist */); err != nil {
log.Warningf(ctx, "error writing node summary after store bootstrap: %s", err)
}
return nil
}
// startGossiping loops on a periodic ticker to gossip node-related
// information. Starts a goroutine to loop until the node is closed.
func (n *Node) startGossiping(ctx context.Context, stopper *stop.Stopper) {
ctx = n.AnnotateCtx(ctx)
_ = stopper.RunAsyncTask(ctx, "start-gossip", func(ctx context.Context) {
// Verify we've already gossiped our node descriptor.
//
// TODO(tbg): see if we really needed to do this earlier already. We
// probably needed to (this call has to come late for ... reasons I
// still need to look into) and nobody can talk to this node until
// the descriptor is in Gossip.
if _, err := n.storeCfg.Gossip.GetNodeDescriptor(n.Descriptor.NodeID); err != nil {
panic(err)
}
// NB: Gossip may not be connected at this point. That's fine though,
// we can still gossip something; Gossip sends it out reactively once
// it can.
statusTicker := time.NewTicker(gossipStatusInterval)
storesTicker := time.NewTicker(gossip.StoresInterval)
nodeTicker := time.NewTicker(gossip.NodeDescriptorInterval)
defer func() {
nodeTicker.Stop()
storesTicker.Stop()
statusTicker.Stop()
}()
n.gossipStores(ctx) // one-off run before going to sleep
for {
select {
case <-statusTicker.C:
n.storeCfg.Gossip.LogStatus()
case <-storesTicker.C:
n.gossipStores(ctx)
case <-nodeTicker.C:
if err := n.storeCfg.Gossip.SetNodeDescriptor(&n.Descriptor); err != nil {
log.Warningf(ctx, "couldn't gossip descriptor for node %d: %s", n.Descriptor.NodeID, err)
}
case <-stopper.ShouldQuiesce():
return
}
}
})
}
// gossipStores broadcasts each store and dead replica to the gossip network.
func (n *Node) gossipStores(ctx context.Context) {
if err := n.stores.VisitStores(func(s *kvserver.Store) error {
return s.GossipStore(ctx, false /* useCached */)
}); err != nil {
log.Warningf(ctx, "%v", err)
}
}
// startComputePeriodicMetrics starts a loop which periodically instructs each
// store to compute the value of metrics which cannot be incrementally
// maintained.
func (n *Node) startComputePeriodicMetrics(stopper *stop.Stopper, interval time.Duration) {
ctx := n.AnnotateCtx(context.Background())
_ = stopper.RunAsyncTask(ctx, "compute-metrics", func(ctx context.Context) {
// Compute periodic stats at the same frequency as metrics are sampled.
ticker := time.NewTicker(interval)
previousMetrics := make(map[*kvserver.Store]*storage.MetricsForInterval)
defer ticker.Stop()
for tick := 0; ; tick++ {
select {
case <-ticker.C:
if err := n.computeMetricsPeriodically(ctx, previousMetrics, tick); err != nil {
log.Errorf(ctx, "failed computing periodic metrics: %s", err)
}
case <-stopper.ShouldQuiesce():
return
}
}
})
}
// computeMetricsPeriodically instructs each store to compute the value of
// complicated metrics.
func (n *Node) computeMetricsPeriodically(
ctx context.Context, storeToMetrics map[*kvserver.Store]*storage.MetricsForInterval, tick int,
) error {
return n.stores.VisitStores(func(store *kvserver.Store) error {
if newMetrics, err := store.ComputeMetricsPeriodically(ctx, storeToMetrics[store], tick); err != nil {
log.Warningf(ctx, "%s: unable to compute metrics: %s", store, err)
} else {
if storeToMetrics[store] == nil {
storeToMetrics[store] = &storage.MetricsForInterval{
FlushWriteThroughput: newMetrics.LogWriter.WriteThroughput,
}
} else {
storeToMetrics[store].FlushWriteThroughput = newMetrics.Flush.WriteThroughput
}
if err := newMetrics.LogWriter.FsyncLatency.Write(&storeToMetrics[store].WALFsyncLatency); err != nil {
return err
}
}
return nil
})
}
// UpdateIOThreshold relays the supplied IOThreshold to the same method on the
// designated Store.
func (n *Node) UpdateIOThreshold(id roachpb.StoreID, threshold *admissionpb.IOThreshold) {
s, err := n.stores.GetStore(id)
if err != nil {
log.Errorf(n.AnnotateCtx(context.Background()), "%v", err)
}
s.UpdateIOThreshold(threshold)
}
// diskStatsMap encapsulates all the logic for populating DiskStats for
// admission.StoreMetrics.
type diskStatsMap struct {
provisionedRate map[roachpb.StoreID]base.ProvisionedRateSpec
diskNameToStoreID map[string]roachpb.StoreID
}
func (dsm *diskStatsMap) tryPopulateAdmissionDiskStats(
ctx context.Context,
clusterProvisionedBandwidth int64,
diskStatsFunc func(context.Context) ([]status.DiskStats, error),
) (stats map[roachpb.StoreID]admission.DiskStats, err error) {
if dsm.empty() {
return stats, nil
}
diskStats, err := diskStatsFunc(ctx)
if err != nil {
return stats, err
}
stats = make(map[roachpb.StoreID]admission.DiskStats)
for id, spec := range dsm.provisionedRate {
s := admission.DiskStats{ProvisionedBandwidth: clusterProvisionedBandwidth}
if spec.ProvisionedBandwidth > 0 {
s.ProvisionedBandwidth = spec.ProvisionedBandwidth
}
stats[id] = s
}
for i := range diskStats {
if id, ok := dsm.diskNameToStoreID[diskStats[i].Name]; ok {
s := stats[id]
s.BytesRead = uint64(diskStats[i].ReadBytes)
s.BytesWritten = uint64(diskStats[i].WriteBytes)
stats[id] = s
}
}
return stats, nil
}
func (dsm *diskStatsMap) empty() bool {
return len(dsm.provisionedRate) == 0
}
func (dsm *diskStatsMap) initDiskStatsMap(specs []base.StoreSpec, engines []storage.Engine) error {
*dsm = diskStatsMap{
provisionedRate: make(map[roachpb.StoreID]base.ProvisionedRateSpec),
diskNameToStoreID: make(map[string]roachpb.StoreID),
}
for i := range engines {
id, err := kvstorage.ReadStoreIdent(context.Background(), engines[i])
if err != nil {
return err
}
if len(specs[i].ProvisionedRateSpec.DiskName) > 0 {
dsm.provisionedRate[id.StoreID] = specs[i].ProvisionedRateSpec
dsm.diskNameToStoreID[specs[i].ProvisionedRateSpec.DiskName] = id.StoreID
}
}
return nil
}
func (n *Node) registerEnginesForDiskStatsMap(
specs []base.StoreSpec, engines []storage.Engine,
) error {
return n.diskStatsMap.initDiskStatsMap(specs, engines)
}
// GetPebbleMetrics implements admission.PebbleMetricsProvider.
func (n *Node) GetPebbleMetrics() []admission.StoreMetrics {
clusterProvisionedBandwidth := kvadmission.ProvisionedBandwidth.Get(
&n.storeCfg.Settings.SV)
storeIDToDiskStats, err := n.diskStatsMap.tryPopulateAdmissionDiskStats(
context.Background(), clusterProvisionedBandwidth, status.GetDiskCounters)
if err != nil {
log.Warningf(context.Background(), "%v",
errors.Wrapf(err, "unable to populate disk stats"))
}
var metrics []admission.StoreMetrics
_ = n.stores.VisitStores(func(store *kvserver.Store) error {
m := store.TODOEngine().GetMetrics()
diskStats := admission.DiskStats{ProvisionedBandwidth: clusterProvisionedBandwidth}
if s, ok := storeIDToDiskStats[store.StoreID()]; ok {
diskStats = s
}
metrics = append(metrics, admission.StoreMetrics{
StoreID: store.StoreID(),
Metrics: m.Metrics,
WriteStallCount: m.WriteStallCount,
DiskStats: diskStats})
return nil
})
return metrics
}
// GetTenantWeights implements kvserver.TenantWeightProvider.
func (n *Node) GetTenantWeights() kvadmission.TenantWeights {
weights := kvadmission.TenantWeights{
Node: make(map[uint64]uint32),
}
_ = n.stores.VisitStores(func(store *kvserver.Store) error {
sw := make(map[uint64]uint32)
weights.Stores = append(weights.Stores, kvadmission.TenantWeightsForStore{
StoreID: store.StoreID(),
Weights: sw,
})
store.VisitReplicas(func(r *kvserver.Replica) bool {
tid, valid := r.TenantID()
if valid {
weights.Node[tid.ToUint64()]++
sw[tid.ToUint64()]++
}
return true
})
return nil
})
return weights
}
func startGraphiteStatsExporter(
ctx context.Context,
stopper *stop.Stopper,
recorder *status.MetricsRecorder,
st *cluster.Settings,
) {
ctx = logtags.AddTag(ctx, "graphite stats exporter", nil)
pm := metric.MakePrometheusExporter()
_ = stopper.RunAsyncTask(ctx, "graphite-exporter", func(ctx context.Context) {
var timer timeutil.Timer
defer timer.Stop()
for {
timer.Reset(graphiteInterval.Get(&st.SV))
select {
case <-stopper.ShouldQuiesce():
return
case <-timer.C:
timer.Read = true
endpoint := graphiteEndpoint.Get(&st.SV)
if endpoint != "" {
if err := recorder.ExportToGraphite(ctx, endpoint, &pm); err != nil {
log.Infof(ctx, "error pushing metrics to graphite: %s\n", err)
}