-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
server.go
2239 lines (2011 loc) · 76.6 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 (
"compress/gzip"
"context"
"crypto/tls"
"fmt"
"io"
"io/ioutil"
"net"
"net/http"
"os"
"path/filepath"
"reflect"
"runtime"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/cockroachdb/cmux"
"github.com/cockroachdb/cockroach/pkg/base"
"github.com/cockroachdb/cockroach/pkg/blobs"
"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/kv"
"github.com/cockroachdb/cockroach/pkg/kv/kvclient/kvcoord"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver/closedts/container"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver/kvserverpb"
"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"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver/reports"
"github.com/cockroachdb/cockroach/pkg/roachpb"
"github.com/cockroachdb/cockroach/pkg/rpc"
"github.com/cockroachdb/cockroach/pkg/rpc/nodedialer"
"github.com/cockroachdb/cockroach/pkg/server/debug"
"github.com/cockroachdb/cockroach/pkg/server/goroutinedumper"
"github.com/cockroachdb/cockroach/pkg/server/heapprofiler"
"github.com/cockroachdb/cockroach/pkg/server/serverpb"
"github.com/cockroachdb/cockroach/pkg/server/status"
"github.com/cockroachdb/cockroach/pkg/server/telemetry"
"github.com/cockroachdb/cockroach/pkg/settings"
"github.com/cockroachdb/cockroach/pkg/settings/cluster"
"github.com/cockroachdb/cockroach/pkg/sql"
_ "github.com/cockroachdb/cockroach/pkg/sql/gcjob" // register jobs declared outside of pkg/sql
"github.com/cockroachdb/cockroach/pkg/sql/pgwire"
"github.com/cockroachdb/cockroach/pkg/sql/sqlbase"
"github.com/cockroachdb/cockroach/pkg/storage"
"github.com/cockroachdb/cockroach/pkg/storage/cloud"
"github.com/cockroachdb/cockroach/pkg/storage/cloudimpl"
"github.com/cockroachdb/cockroach/pkg/storage/enginepb"
"github.com/cockroachdb/cockroach/pkg/ts"
"github.com/cockroachdb/cockroach/pkg/ui"
"github.com/cockroachdb/cockroach/pkg/util"
"github.com/cockroachdb/cockroach/pkg/util/envutil"
"github.com/cockroachdb/cockroach/pkg/util/hlc"
"github.com/cockroachdb/cockroach/pkg/util/httputil"
"github.com/cockroachdb/cockroach/pkg/util/log"
"github.com/cockroachdb/cockroach/pkg/util/metric"
"github.com/cockroachdb/cockroach/pkg/util/netutil"
"github.com/cockroachdb/cockroach/pkg/util/protoutil"
"github.com/cockroachdb/cockroach/pkg/util/retry"
"github.com/cockroachdb/cockroach/pkg/util/stop"
"github.com/cockroachdb/cockroach/pkg/util/syncutil"
"github.com/cockroachdb/cockroach/pkg/util/timeutil"
"github.com/cockroachdb/cockroach/pkg/util/tracing"
"github.com/cockroachdb/cockroach/pkg/util/uuid"
"github.com/cockroachdb/errors"
"github.com/cockroachdb/logtags"
"github.com/cockroachdb/sentry-go"
gwruntime "github.com/grpc-ecosystem/grpc-gateway/runtime"
"github.com/opentracing/opentracing-go"
"google.golang.org/grpc"
"google.golang.org/grpc/metadata"
)
var (
// Allocation pool for gzipResponseWriters.
gzipResponseWriterPool sync.Pool
forwardClockJumpCheckEnabled = settings.RegisterPublicBoolSetting(
"server.clock.forward_jump_check_enabled",
"if enabled, forward clock jumps > max_offset/2 will cause a panic",
false,
)
persistHLCUpperBoundInterval = settings.RegisterPublicDurationSetting(
"server.clock.persist_upper_bound_interval",
"the interval between persisting the wall time upper bound of the clock. The clock "+
"does not generate a wall time greater than the persisted timestamp and will panic if "+
"it sees a wall time greater than this value. When cockroach starts, it waits for the "+
"wall time to catch-up till this persisted timestamp. This guarantees monotonic wall "+
"time across server restarts. Not setting this or setting a value of 0 disables this "+
"feature.",
0,
)
)
// TODO(peter): Until go1.11, ServeMux.ServeHTTP was not safe to call
// concurrently with ServeMux.Handle. So we provide our own wrapper with proper
// locking. Slightly less efficient because it locks unnecessarily, but
// safe. See TestServeMuxConcurrency. Should remove once we've upgraded to
// go1.11.
type safeServeMux struct {
mu syncutil.RWMutex
mux http.ServeMux
}
func (mux *safeServeMux) Handle(pattern string, handler http.Handler) {
mux.mu.Lock()
mux.mux.Handle(pattern, handler)
mux.mu.Unlock()
}
func (mux *safeServeMux) ServeHTTP(w http.ResponseWriter, r *http.Request) {
mux.mu.RLock()
mux.mux.ServeHTTP(w, r)
mux.mu.RUnlock()
}
// Server is the cockroach server node.
type Server struct {
// The following fields are populated in NewServer.
nodeIDContainer *base.NodeIDContainer
cfg Config
st *cluster.Settings
mux safeServeMux
clock *hlc.Clock
rpcContext *rpc.Context
// The gRPC server on which the different RPC handlers will be registered.
grpc *grpcServer
gossip *gossip.Gossip
nodeDialer *nodedialer.Dialer
nodeLiveness *kvserver.NodeLiveness
storePool *kvserver.StorePool
tcsFactory *kvcoord.TxnCoordSenderFactory
distSender *kvcoord.DistSender
db *kv.DB
node *Node
registry *metric.Registry
recorder *status.MetricsRecorder
runtime *status.RuntimeStatSampler
admin *adminServer
status *statusServer
authentication *authenticationServer
tsDB *ts.DB
tsServer *ts.Server
raftTransport *kvserver.RaftTransport
stopper *stop.Stopper
debug *debug.Server
replicationReporter *reports.Reporter
protectedtsProvider protectedts.Provider
protectedtsReconciler *ptreconcile.Reconciler
sqlServer *sqlServer
// Created in NewServer but initialized (made usable) in `(*Server).Start`.
externalStorageBuilder *externalStorageBuilder
// The following fields are populated at start time, i.e. in `(*Server).Start`.
startTime time.Time
engines Engines
}
// externalStorageBuilder is a wrapper around the ExternalStorage factory
// methods. It allows us to separate the creation and initialization of the
// builder between NewServer() and Start() respectively.
// TODO(adityamaru): Consider moving this to pkg/storage/cloudimpl at a future
// stage of the ongoing refactor.
type externalStorageBuilder struct {
conf base.ExternalIODirConfig
settings *cluster.Settings
blobClientFactory blobs.BlobClientFactory
initCalled bool
ie *sql.InternalExecutor
db *kv.DB
}
func (e *externalStorageBuilder) init(
conf base.ExternalIODirConfig,
settings *cluster.Settings,
blobClientFactory blobs.BlobClientFactory,
ie *sql.InternalExecutor,
db *kv.DB,
) {
e.conf = conf
e.settings = settings
e.blobClientFactory = blobClientFactory
e.initCalled = true
e.ie = ie
e.db = db
}
func (e *externalStorageBuilder) makeExternalStorage(
ctx context.Context, dest roachpb.ExternalStorage,
) (cloud.ExternalStorage, error) {
if !e.initCalled {
return nil, errors.New("cannot create external storage before init")
}
return cloudimpl.MakeExternalStorage(ctx, dest, e.conf, e.settings, e.blobClientFactory, e.ie,
e.db)
}
func (e *externalStorageBuilder) makeExternalStorageFromURI(
ctx context.Context, uri string, user string,
) (cloud.ExternalStorage, error) {
if !e.initCalled {
return nil, errors.New("cannot create external storage before init")
}
return cloudimpl.ExternalStorageFromURI(ctx, uri, e.conf, e.settings, e.blobClientFactory, user, e.ie, e.db)
}
// NewServer creates a Server from a server.Config.
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 != "" {
clockSrc, err := hlc.MakeClockSource(context.Background(), cfg.ClockDevicePath)
if err != nil {
return nil, errors.Wrap(err, "instantiating clock source")
}
clock = hlc.NewClock(clockSrc.UnixNano, time.Duration(cfg.MaxOffset))
} else {
clock = hlc.NewClock(hlc.UnixNano, time.Duration(cfg.MaxOffset))
}
registry := metric.NewRegistry()
// If the tracer has a Close function, call it after the server stops.
if tr, ok := cfg.AmbientCtx.Tracer.(stop.Closer); ok {
stopper.AddCloser(tr)
}
// 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 := &base.NodeIDContainer{}
cfg.AmbientCtx.AddLogTag("n", nodeIDContainer)
const sqlInstanceID = base.SQLInstanceID(0)
idContainer := base.NewSQLIDContainer(sqlInstanceID, nodeIDContainer, true /* exposed */)
ctx := cfg.AmbientCtx.AnnotateCtx(context.Background())
rpcCtxOpts := rpc.ContextOptions{
TenantID: roachpb.SystemTenantID,
AmbientCtx: cfg.AmbientCtx,
Config: cfg.Config,
Clock: clock,
Stopper: stopper,
Settings: cfg.Settings,
}
if knobs := cfg.TestingKnobs.Server; knobs != nil {
serverKnobs := knobs.(*TestingKnobs)
rpcCtxOpts.Knobs = serverKnobs.ContextTestingKnobs
}
rpcContext := rpc.NewContext(rpcCtxOpts)
rpcContext.HeartbeatCB = func() {
if err := rpcContext.RemoteClocks.VerifyClockOffset(ctx); err != nil {
log.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
}
cm.RegisterSignalHandler(stopper)
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)
grpc := newGRPCServer(rpcContext)
g := gossip.New(
cfg.AmbientCtx,
&rpcContext.ClusterID,
nodeIDContainer,
rpcContext,
grpc.Server,
stopper,
registry,
cfg.Locality,
&cfg.DefaultZoneConfig,
)
nodeDialer := nodedialer.New(rpcContext, gossip.AddressResolver(g))
runtimeSampler := status.NewRuntimeStatSampler(ctx, clock)
registry.AddMetricStruct(runtimeSampler)
// 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,
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)
dbCtx := kv.DefaultDBContext(stopper)
dbCtx.NodeID = idContainer
dbCtx.Stopper = stopper
db := kv.NewDBWithContext(cfg.AmbientCtx, tcsFactory, clock, dbCtx)
nlActive, nlRenewal := cfg.NodeLivenessDurations()
nodeLiveness := kvserver.NewNodeLiveness(
cfg.AmbientCtx,
clock,
db,
g,
nlActive,
nlRenewal,
st,
cfg.HistogramWindowInterval(),
)
registry.AddMetricStruct(nodeLiveness.Metrics())
storePool := kvserver.NewStorePool(
cfg.AmbientCtx,
st,
g,
clock,
nodeLiveness.GetNodeCount,
kvserver.MakeStorePoolNodeLivenessFunc(nodeLiveness),
/* deterministic */ false,
)
raftTransport := kvserver.NewRaftTransport(
cfg.AmbientCtx, st, nodeDialer, grpc.Server, stopper,
)
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, stopper)
// The InternalExecutor will be further initialized later, as we create more
// of the server's components. There's a circular dependency - many things
// need an InternalExecutor, but the InternalExecutor needs an ExecutorConfig,
// which in turn needs many things. That's why everybody that needs an
// InternalExecutor uses this one instance.
internalExecutor := &sql.InternalExecutor{}
jobRegistry := &jobs.Registry{} // ditto
// Create an ExternalStorageBuilder. This is only usable after Start() where
// we initialize all the configuration params.
externalStorageBuilder := &externalStorageBuilder{}
externalStorage := func(ctx context.Context, dest roachpb.ExternalStorage) (cloud.
ExternalStorage, error) {
return externalStorageBuilder.makeExternalStorage(ctx, dest)
}
externalStorageFromURI := func(ctx context.Context, uri string,
user string) (cloud.ExternalStorage, error) {
return externalStorageBuilder.makeExternalStorageFromURI(ctx, uri, user)
}
protectedtsProvider, err := ptprovider.New(ptprovider.Config{
DB: db,
InternalExecutor: internalExecutor,
Settings: st,
})
if err != nil {
return nil, err
}
// Break a circular dependency: we need a Node to make a StoreConfig (for
// ClosedTimestamp), but the Node needs a StoreConfig to be made.
var lateBoundNode *Node
storeCfg := kvserver.StoreConfig{
DefaultZoneConfig: &cfg.DefaultZoneConfig,
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,
SQLExecutor: internalExecutor,
LogRangeEvents: cfg.EventLogEnabled,
RangeDescriptorCache: distSender.RangeDescriptorCache(),
TimeSeriesDataStore: tsDB,
// Initialize the closed timestamp subsystem. Note that it won't
// be ready until it is .Start()ed, but the grpc server can be
// registered early.
ClosedTimestamp: container.NewContainer(container.Config{
Settings: st,
Stopper: stopper,
Clock: nodeLiveness.AsLiveClock(),
// NB: s.node is not defined at this point, but it will be
// before this is ever called.
Refresh: func(rangeIDs ...roachpb.RangeID) {
for _, rangeID := range rangeIDs {
repl, _, err := lateBoundNode.stores.GetReplicaForRangeID(rangeID)
if err != nil || repl == nil {
continue
}
repl.EmitMLAI()
}
},
Dialer: nodeDialer.CTDialer(),
}),
ExternalStorage: externalStorage,
ExternalStorageFromURI: externalStorageFromURI,
ProtectedTimestampCache: protectedtsProvider,
}
if storeTestingKnobs := cfg.TestingKnobs.Store; storeTestingKnobs != nil {
storeCfg.TestingKnobs = *storeTestingKnobs.(*kvserver.StoreTestingKnobs)
}
recorder := status.NewMetricsRecorder(clock, nodeLiveness, rpcContext, g, st)
registry.AddMetricStruct(rpcContext.RemoteClocks.Metrics())
node := NewNode(
storeCfg, recorder, registry, stopper,
txnMetrics, nil /* execCfg */, &rpcContext.ClusterID)
lateBoundNode = node
roachpb.RegisterInternalServer(grpc.Server, node)
kvserver.RegisterPerReplicaServer(grpc.Server, node.perReplicaServer)
node.storeCfg.ClosedTimestamp.RegisterClosedTimestampServer(grpc.Server)
replicationReporter := reports.NewReporter(
db, node.stores, storePool, st, nodeLiveness, internalExecutor)
protectedtsReconciler := ptreconcile.NewReconciler(ptreconcile.Config{
Settings: st,
Stores: node.stores,
DB: db,
Storage: protectedtsProvider,
Cache: protectedtsProvider,
StatusFuncs: ptreconcile.StatusFuncs{
jobsprotectedts.MetaType: jobsprotectedts.MakeStatusFunc(jobRegistry),
},
})
registry.AddMetricStruct(protectedtsReconciler.Metrics())
lateBoundServer := &Server{}
// TODO(tbg): give adminServer only what it needs (and avoid circular deps).
sAdmin := newAdminServer(lateBoundServer)
sessionRegistry := sql.NewSessionRegistry()
sStatus := newStatusServer(
cfg.AmbientCtx,
st,
cfg.Config,
sAdmin,
db,
g,
recorder,
nodeLiveness,
storePool,
rpcContext,
node.stores,
stopper,
sessionRegistry,
internalExecutor,
)
// TODO(tbg): don't pass all of Server into this to avoid this hack.
sAuth := newAuthenticationServer(lateBoundServer)
for i, gw := range []grpcGatewayServer{sAdmin, sStatus, sAuth, &sTS} {
if reflect.ValueOf(gw).IsNil() {
return nil, errors.Errorf("%d: nil", i)
}
gw.RegisterService(grpc.Server)
}
var jobAdoptionStopFile string
for _, spec := range cfg.Stores.Specs {
if !spec.InMemory && spec.Path != "" {
jobAdoptionStopFile = filepath.Join(spec.Path, jobs.PreventAdoptionFile)
break
}
}
sqlServer, err := newSQLServer(ctx, sqlServerArgs{
sqlServerOptionalKVArgs: sqlServerOptionalKVArgs{
statusServer: serverpb.MakeOptionalStatusServer(sStatus),
nodeLiveness: sqlbase.MakeOptionalNodeLiveness(nodeLiveness),
gossip: gossip.MakeOptionalGossip(g),
grpcServer: grpc.Server,
recorder: recorder,
nodeIDContainer: idContainer,
externalStorage: externalStorage,
externalStorageFromURI: externalStorageFromURI,
isMeta1Leaseholder: node.stores.IsMeta1Leaseholder,
},
SQLConfig: &cfg.SQLConfig,
BaseConfig: &cfg.BaseConfig,
stopper: stopper,
clock: clock,
runtime: runtimeSampler,
rpcContext: rpcContext,
nodeDescs: g,
systemConfigProvider: g,
nodeDialer: nodeDialer,
distSender: distSender,
db: db,
registry: registry,
sessionRegistry: sessionRegistry,
circularInternalExecutor: internalExecutor,
circularJobRegistry: jobRegistry,
jobAdoptionStopFile: jobAdoptionStopFile,
protectedtsProvider: protectedtsProvider,
})
if err != nil {
return nil, err
}
sStatus.setStmtDiagnosticsRequester(sqlServer.execCfg.StmtDiagnosticsRecorder)
debugServer := debug.NewServer(st, sqlServer.pgServer.HBADebugFn())
node.InitLogger(sqlServer.execCfg)
*lateBoundServer = Server{
nodeIDContainer: nodeIDContainer,
cfg: cfg,
st: st,
clock: clock,
rpcContext: rpcContext,
grpc: grpc,
gossip: g,
nodeDialer: nodeDialer,
nodeLiveness: nodeLiveness,
storePool: storePool,
tcsFactory: tcsFactory,
distSender: distSender,
db: db,
node: node,
registry: registry,
recorder: recorder,
runtime: runtimeSampler,
admin: sAdmin,
status: sStatus,
authentication: sAuth,
tsDB: tsDB,
tsServer: &sTS,
raftTransport: raftTransport,
stopper: stopper,
debug: debugServer,
replicationReporter: replicationReporter,
protectedtsProvider: protectedtsProvider,
protectedtsReconciler: protectedtsReconciler,
sqlServer: sqlServer,
externalStorageBuilder: externalStorageBuilder,
}
return lateBoundServer, err
}
// ClusterSettings returns the cluster settings.
func (s *Server) ClusterSettings() *cluster.Settings {
return s.st
}
// AnnotateCtx is a convenience wrapper; see AmbientContext.
func (s *Server) AnnotateCtx(ctx context.Context) context.Context {
return s.cfg.AmbientCtx.AnnotateCtx(ctx)
}
// AnnotateCtxWithSpan is a convenience wrapper; see AmbientContext.
func (s *Server) AnnotateCtxWithSpan(
ctx context.Context, opName string,
) (context.Context, opentracing.Span) {
return s.cfg.AmbientCtx.AnnotateCtxWithSpan(ctx, opName)
}
// ClusterID returns the ID of the cluster this server is a part of.
func (s *Server) ClusterID() uuid.UUID {
return s.rpcContext.ClusterID.Get()
}
// NodeID returns the ID of this node within its cluster.
func (s *Server) NodeID() roachpb.NodeID {
return s.node.Descriptor.NodeID
}
// InitialBoot returns whether this is the first time the node has booted.
// Only intended to help print debugging info during server startup.
func (s *Server) InitialBoot() bool {
return s.node.initialBoot
}
// grpcGatewayServer represents a grpc service with HTTP endpoints through GRPC
// gateway.
type grpcGatewayServer interface {
RegisterService(g *grpc.Server)
RegisterGateway(
ctx context.Context,
mux *gwruntime.ServeMux,
conn *grpc.ClientConn,
) error
}
// ListenError is returned from Start when we fail to start listening on either
// the main Cockroach port or the HTTP port, so that the CLI can instruct the
// user on what might have gone wrong.
type ListenError struct {
cause error
Addr string
}
// Error implements error.
func (l *ListenError) Error() string { return l.cause.Error() }
// Unwrap is because ListenError is a wrapper.
func (l *ListenError) Unwrap() error { return l.cause }
// inspectEngines goes through engines and populates in initDiskState. It also
// calls SynthesizeClusterVersionFromEngines, which selects and backfills the
// cluster version to all initialized engines.
//
// The initDiskState returned by this method will reflect a zero NodeID if none
// has been assigned yet (i.e. if none of the engines is initialized).
func inspectEngines(
ctx context.Context,
engines []storage.Engine,
binaryVersion, binaryMinSupportedVersion roachpb.Version,
) (*initDiskState, error) {
state := &initDiskState{}
for _, eng := range engines {
storeIdent, err := kvserver.ReadStoreIdent(ctx, eng)
if errors.HasType(err, (*kvserver.NotBootstrappedError)(nil)) {
state.newEngines = append(state.newEngines, eng)
continue
} else if err != nil {
return nil, err
}
if state.clusterID != uuid.Nil && state.clusterID != storeIdent.ClusterID {
return nil, errors.Errorf("conflicting store ClusterIDs: %s, %s", storeIdent.ClusterID, state.clusterID)
}
state.clusterID = storeIdent.ClusterID
if storeIdent.StoreID == 0 || storeIdent.NodeID == 0 || storeIdent.ClusterID == uuid.Nil {
return nil, errors.Errorf("partially initialized store: %+v", storeIdent)
}
if state.nodeID != 0 && state.nodeID != storeIdent.NodeID {
return nil, errors.Errorf("conflicting store NodeIDs: %s, %s", storeIdent.NodeID, state.nodeID)
}
state.nodeID = storeIdent.NodeID
state.initializedEngines = append(state.initializedEngines, eng)
}
cv, err := kvserver.SynthesizeClusterVersionFromEngines(ctx, state.initializedEngines, binaryVersion, binaryMinSupportedVersion)
if err != nil {
return nil, err
}
state.clusterVersion = cv
return state, nil
}
// listenerInfo is a helper used to write files containing various listener
// information to the store directories. In contrast to the "listening url
// file", these are written once the listeners are available, before the server
// is necessarily ready to serve.
type listenerInfo struct {
listenRPC string // the (RPC) listen address, rewritten after name resolution and port allocation
advertiseRPC string // contains the original addr part of --listen/--advertise, with actual port number after port allocation if original was 0
listenSQL string // the SQL endpoint, rewritten after name resolution and port allocation
advertiseSQL string // contains the original addr part of --sql-addr, with actual port number after port allocation if original was 0
listenHTTP string // the HTTP endpoint
}
// Iter returns a mapping of file names to desired contents.
func (li listenerInfo) Iter() map[string]string {
return map[string]string{
"cockroach.listen-addr": li.listenRPC,
"cockroach.advertise-addr": li.advertiseRPC,
"cockroach.sql-addr": li.listenSQL,
"cockroach.advertise-sql-addr": li.advertiseSQL,
"cockroach.http-addr": li.listenHTTP,
}
}
// startMonitoringForwardClockJumps starts a background task to monitor forward
// clock jumps based on a cluster setting
func (s *Server) startMonitoringForwardClockJumps(ctx context.Context) error {
forwardJumpCheckEnabled := make(chan bool, 1)
s.stopper.AddCloser(stop.CloserFn(func() { close(forwardJumpCheckEnabled) }))
forwardClockJumpCheckEnabled.SetOnChange(&s.st.SV, func() {
forwardJumpCheckEnabled <- forwardClockJumpCheckEnabled.Get(&s.st.SV)
})
if err := s.clock.StartMonitoringForwardClockJumps(
ctx,
forwardJumpCheckEnabled,
time.NewTicker,
nil, /* tick callback */
); err != nil {
return errors.Wrap(err, "monitoring forward clock jumps")
}
log.Info(ctx, "monitoring forward clock jumps based on server.clock.forward_jump_check_enabled")
return nil
}
// ensureClockMonotonicity sleeps till the wall time reaches
// prevHLCUpperBound. prevHLCUpperBound > 0 implies we need to guarantee HLC
// monotonicity across server restarts. prevHLCUpperBound is the last
// successfully persisted timestamp greater then any wall time used by the
// server.
//
// If prevHLCUpperBound is 0, the function sleeps up to max offset
func ensureClockMonotonicity(
ctx context.Context,
clock *hlc.Clock,
startTime time.Time,
prevHLCUpperBound int64,
sleepUntilFn func(until int64, currTime func() int64),
) {
var sleepUntil int64
if prevHLCUpperBound != 0 {
// Sleep until previous HLC upper bound to ensure wall time monotonicity
sleepUntil = prevHLCUpperBound + 1
} else {
// Previous HLC Upper bound is not known
// We might have to sleep a bit to protect against this node producing non-
// monotonic timestamps. Before restarting, its clock might have been driven
// by other nodes' fast clocks, but when we restarted, we lost all this
// information. For example, a client might have written a value at a
// timestamp that's in the future of the restarted node's clock, and if we
// don't do something, the same client's read would not return the written
// value. So, we wait up to MaxOffset; we couldn't have served timestamps more
// than MaxOffset in the future (assuming that MaxOffset was not changed, see
// #9733).
//
// As an optimization for tests, we don't sleep if all the stores are brand
// new. In this case, the node will not serve anything anyway until it
// synchronizes with other nodes.
sleepUntil = startTime.UnixNano() + int64(clock.MaxOffset()) + 1
}
currentWallTimeFn := func() int64 { /* function to report current time */
return clock.Now().WallTime
}
currentWallTime := currentWallTimeFn()
delta := time.Duration(sleepUntil - currentWallTime)
if delta > 0 {
log.Infof(
ctx,
"Sleeping till wall time %v to catches up to %v to ensure monotonicity. Delta: %v",
currentWallTime,
sleepUntil,
delta,
)
sleepUntilFn(sleepUntil, currentWallTimeFn)
}
}
// periodicallyPersistHLCUpperBound periodically persists an upper bound of
// the HLC's wall time. The interval for persisting is read from
// persistHLCUpperBoundIntervalCh. An interval of 0 disables persisting.
//
// persistHLCUpperBoundFn is used to persist the hlc upper bound, and should
// return an error if the persist fails.
//
// tickerFn is used to create the ticker used for persisting
//
// tickCallback is called whenever a tick is processed
func periodicallyPersistHLCUpperBound(
clock *hlc.Clock,
persistHLCUpperBoundIntervalCh chan time.Duration,
persistHLCUpperBoundFn func(int64) error,
tickerFn func(d time.Duration) *time.Ticker,
stopCh <-chan struct{},
tickCallback func(),
) {
// Create a ticker which can be used in selects.
// This ticker is turned on / off based on persistHLCUpperBoundIntervalCh
ticker := tickerFn(time.Hour)
ticker.Stop()
// persistInterval is the interval used for persisting the
// an upper bound of the HLC
var persistInterval time.Duration
var ok bool
persistHLCUpperBound := func() {
if err := clock.RefreshHLCUpperBound(
persistHLCUpperBoundFn,
int64(persistInterval*3), /* delta to compute upper bound */
); err != nil {
log.Fatalf(
context.Background(),
"error persisting HLC upper bound: %v",
err,
)
}
}
for {
select {
case persistInterval, ok = <-persistHLCUpperBoundIntervalCh:
ticker.Stop()
if !ok {
return
}
if persistInterval > 0 {
ticker = tickerFn(persistInterval)
persistHLCUpperBound()
log.Info(context.Background(), "persisting HLC upper bound is enabled")
} else {
if err := clock.ResetHLCUpperBound(persistHLCUpperBoundFn); err != nil {
log.Fatalf(
context.Background(),
"error resetting hlc upper bound: %v",
err,
)
}
log.Info(context.Background(), "persisting HLC upper bound is disabled")
}
case <-ticker.C:
if persistInterval > 0 {
persistHLCUpperBound()
}
case <-stopCh:
ticker.Stop()
return
}
if tickCallback != nil {
tickCallback()
}
}
}
// startPersistingHLCUpperBound starts a goroutine to persist an upper bound
// to the HLC.
//
// persistHLCUpperBoundFn is used to persist upper bound of the HLC, and should
// return an error if the persist fails
//
// tickerFn is used to create a new ticker
//
// tickCallback is called whenever persistHLCUpperBoundCh or a ticker tick is
// processed
func (s *Server) startPersistingHLCUpperBound(
ctx context.Context,
hlcUpperBoundExists bool,
persistHLCUpperBoundFn func(int64) error,
tickerFn func(d time.Duration) *time.Ticker,
) error {
persistHLCUpperBoundIntervalCh := make(chan time.Duration, 1)
persistHLCUpperBoundInterval.SetOnChange(&s.st.SV, func() {
persistHLCUpperBoundIntervalCh <- persistHLCUpperBoundInterval.Get(&s.st.SV)
})
if hlcUpperBoundExists {
// The feature to persist upper bounds to wall times is enabled.
// Persist a new upper bound to continue guaranteeing monotonicity
// Going forward the goroutine launched below will take over persisting
// the upper bound
if err := s.clock.RefreshHLCUpperBound(
persistHLCUpperBoundFn,
int64(5*time.Second),
); err != nil {
return errors.Wrap(err, "refreshing HLC upper bound")
}
}
s.stopper.RunWorker(
ctx,
func(context.Context) {
periodicallyPersistHLCUpperBound(
s.clock,
persistHLCUpperBoundIntervalCh,
persistHLCUpperBoundFn,
tickerFn,
s.stopper.ShouldStop(),
nil, /* tick callback */
)
},
)
return nil
}
// Start starts the server on the specified port, starts gossip and initializes
// the node using the engines from the server's context. This is complex since
// it sets up the listeners and the associated port muxing, but especially since
// it has to solve the "bootstrapping problem": nodes need to connect to Gossip
// fairly early, but what drives Gossip connectivity are the first range
// replicas in the kv store. This in turn suggests opening the Gossip server
// early. However, naively doing so also serves most other services prematurely,
// which exposes a large surface of potentially underinitialized services. This
// is avoided with some additional complexity that can be summarized as follows:
//
// - before blocking trying to connect to the Gossip network, we already open
// the admin UI (so that its diagnostics are available)
// - we also allow our Gossip and our connection health Ping service
// - everything else returns Unavailable errors (which are retryable)
// - once the node has started, unlock all RPCs.