-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
server.go
2093 lines (1860 loc) · 68.2 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.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
// implied. See the License for the specific language governing
// permissions and limitations under the License.
package server
import (
"compress/gzip"
"context"
"crypto/tls"
"fmt"
"io"
"io/ioutil"
"math"
"net"
"net/http"
"os"
"path/filepath"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/cockroachdb/cmux"
"github.com/cockroachdb/cockroach/pkg/base"
"github.com/cockroachdb/cockroach/pkg/gossip"
"github.com/cockroachdb/cockroach/pkg/internal/client"
"github.com/cockroachdb/cockroach/pkg/jobs"
"github.com/cockroachdb/cockroach/pkg/kv"
"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/settings"
"github.com/cockroachdb/cockroach/pkg/settings/cluster"
"github.com/cockroachdb/cockroach/pkg/sql"
"github.com/cockroachdb/cockroach/pkg/sql/distsqlpb"
"github.com/cockroachdb/cockroach/pkg/sql/distsqlrun"
"github.com/cockroachdb/cockroach/pkg/sql/pgwire"
"github.com/cockroachdb/cockroach/pkg/sql/querycache"
"github.com/cockroachdb/cockroach/pkg/sql/sem/tree"
"github.com/cockroachdb/cockroach/pkg/sql/sessiondata"
"github.com/cockroachdb/cockroach/pkg/sql/sqlutil"
"github.com/cockroachdb/cockroach/pkg/sql/stats"
"github.com/cockroachdb/cockroach/pkg/sqlmigrations"
"github.com/cockroachdb/cockroach/pkg/storage"
"github.com/cockroachdb/cockroach/pkg/storage/bulk"
"github.com/cockroachdb/cockroach/pkg/storage/closedts/container"
"github.com/cockroachdb/cockroach/pkg/storage/engine"
"github.com/cockroachdb/cockroach/pkg/storage/storagebase"
"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/log/logtags"
"github.com/cockroachdb/cockroach/pkg/util/metric"
"github.com/cockroachdb/cockroach/pkg/util/mon"
"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"
raven "github.com/getsentry/raven-go"
gwruntime "github.com/grpc-ecosystem/grpc-gateway/runtime"
opentracing "github.com/opentracing/opentracing-go"
"github.com/pkg/errors"
"google.golang.org/grpc"
)
var (
// Allocation pool for gzipResponseWriters.
gzipResponseWriterPool sync.Pool
// GracefulDrainModes is the standard succession of drain modes entered
// for a graceful shutdown.
GracefulDrainModes = []serverpb.DrainMode{serverpb.DrainMode_CLIENT, serverpb.DrainMode_LEASES}
queryWait = settings.RegisterDurationSetting(
"server.shutdown.query_wait",
"the server will wait for at least this amount of time for active queries to finish",
10*time.Second,
)
drainWait = settings.RegisterDurationSetting(
"server.shutdown.drain_wait",
"the amount of time a server waits in an unready state before proceeding with the rest "+
"of the shutdown process",
0*time.Second,
)
forwardClockJumpCheckEnabled = settings.RegisterBoolSetting(
"server.clock.forward_jump_check_enabled",
"if enabled, forward clock jumps > max_offset/2 will cause a panic",
false,
)
persistHLCUpperBoundInterval = settings.RegisterDurationSetting(
"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 {
nodeIDContainer base.NodeIDContainer
cfg Config
st *cluster.Settings
mux safeServeMux
clock *hlc.Clock
startTime time.Time
rpcContext *rpc.Context
// The gRPC server on which the different RPC handlers will be registered.
grpc *grpcServer
gossip *gossip.Gossip
nodeDialer *nodedialer.Dialer
nodeLiveness *storage.NodeLiveness
storePool *storage.StorePool
tcsFactory *kv.TxnCoordSenderFactory
distSender *kv.DistSender
db *client.DB
pgServer *pgwire.Server
distSQLServer *distsqlrun.ServerImpl
node *Node
registry *metric.Registry
recorder *status.MetricsRecorder
runtime *status.RuntimeStatSampler
admin *adminServer
status *statusServer
authentication *authenticationServer
initServer *initServer
tsDB *ts.DB
tsServer ts.Server
raftTransport *storage.RaftTransport
stopper *stop.Stopper
execCfg *sql.ExecutorConfig
internalExecutor *sql.InternalExecutor
leaseMgr *sql.LeaseManager
// sessionRegistry can be queried for info on running SQL sessions. It is
// shared between the sql.Server and the statusServer.
sessionRegistry *sql.SessionRegistry
jobRegistry *jobs.Registry
statsRefresher *stats.Refresher
engines Engines
internalMemMetrics sql.MemoryMetrics
adminMemMetrics sql.MemoryMetrics
// sqlMemMetrics are used to track memory usage of sql sessions.
sqlMemMetrics sql.MemoryMetrics
}
// 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"))
}
clock := hlc.NewClock(hlc.UnixNano, time.Duration(cfg.MaxOffset))
s := &Server{
st: st,
clock: clock,
stopper: stopper,
cfg: cfg,
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)
}
// Attempt to load TLS configs right away, failures are permanent.
if certMgr, err := cfg.InitializeNodeTLSConfigs(stopper); err != nil {
return nil, err
} else if certMgr != nil {
// The certificate manager is non-nil in secure mode.
s.registry.AddMetricStruct(certMgr.Metrics())
}
// 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.
s.cfg.AmbientCtx.AddLogTag("n", &s.nodeIDContainer)
ctx := s.AnnotateCtx(context.Background())
s.rpcContext = rpc.NewContext(s.cfg.AmbientCtx, s.cfg.Config, s.clock, s.stopper,
&cfg.Settings.Version)
s.rpcContext.HeartbeatCB = func() {
if err := s.rpcContext.RemoteClocks.VerifyClockOffset(ctx); err != nil {
log.Fatal(ctx, err)
}
}
s.registry.AddMetricStruct(s.rpcContext.Metrics())
s.grpc = newGRPCServer(s.rpcContext)
s.gossip = gossip.New(
s.cfg.AmbientCtx,
&s.rpcContext.ClusterID,
&s.nodeIDContainer,
s.rpcContext,
s.grpc.Server,
s.stopper,
s.registry,
s.cfg.Locality,
&s.cfg.DefaultZoneConfig,
)
s.nodeDialer = nodedialer.New(s.rpcContext, gossip.AddressResolver(s.gossip))
// 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 kv.ClientTestingKnobs
if kvKnobs := s.cfg.TestingKnobs.KVClient; kvKnobs != nil {
clientTestingKnobs = *kvKnobs.(*kv.ClientTestingKnobs)
}
retryOpts := s.cfg.RetryOptions
if retryOpts == (retry.Options{}) {
retryOpts = base.DefaultRetryOptions()
}
retryOpts.Closer = s.stopper.ShouldQuiesce()
distSenderCfg := kv.DistSenderConfig{
AmbientCtx: s.cfg.AmbientCtx,
Settings: st,
Clock: s.clock,
RPCContext: s.rpcContext,
RPCRetryOptions: &retryOpts,
TestingKnobs: clientTestingKnobs,
NodeDialer: s.nodeDialer,
}
s.distSender = kv.NewDistSender(distSenderCfg, s.gossip)
s.registry.AddMetricStruct(s.distSender.Metrics())
txnMetrics := kv.MakeTxnMetrics(s.cfg.HistogramWindowInterval())
s.registry.AddMetricStruct(txnMetrics)
txnCoordSenderFactoryCfg := kv.TxnCoordSenderFactoryConfig{
AmbientCtx: s.cfg.AmbientCtx,
Settings: st,
Clock: s.clock,
Stopper: s.stopper,
Linearizable: s.cfg.Linearizable,
Metrics: txnMetrics,
TestingKnobs: clientTestingKnobs,
}
s.tcsFactory = kv.NewTxnCoordSenderFactory(txnCoordSenderFactoryCfg, s.distSender)
dbCtx := client.DefaultDBContext()
dbCtx.NodeID = &s.nodeIDContainer
dbCtx.Stopper = s.stopper
s.db = client.NewDBWithContext(s.cfg.AmbientCtx, s.tcsFactory, s.clock, dbCtx)
nlActive, nlRenewal := s.cfg.NodeLivenessDurations()
s.nodeLiveness = storage.NewNodeLiveness(
s.cfg.AmbientCtx,
s.clock,
s.db,
s.engines,
s.gossip,
nlActive,
nlRenewal,
s.st,
s.cfg.HistogramWindowInterval(),
)
s.registry.AddMetricStruct(s.nodeLiveness.Metrics())
s.storePool = storage.NewStorePool(
s.cfg.AmbientCtx,
s.st,
s.gossip,
s.clock,
s.nodeLiveness.GetNodeCount,
storage.MakeStorePoolNodeLivenessFunc(s.nodeLiveness),
/* deterministic */ false,
)
s.raftTransport = storage.NewRaftTransport(
s.cfg.AmbientCtx, st, s.nodeDialer, s.grpc.Server, s.stopper,
)
// Set up internal memory metrics for use by internal SQL executors.
s.internalMemMetrics = sql.MakeMemMetrics("internal", cfg.HistogramWindowInterval())
s.registry.AddMetricStruct(s.internalMemMetrics)
// We do not set memory monitors or a noteworthy limit because the children of
// this monitor will be setting their own noteworthy limits.
rootSQLMemoryMonitor := mon.MakeMonitor(
"root",
mon.MemoryResource,
nil, /* curCount */
nil, /* maxHist */
-1, /* increment: use default increment */
math.MaxInt64, /* noteworthy */
st,
)
rootSQLMemoryMonitor.Start(context.Background(), nil, mon.MakeStandaloneBudget(s.cfg.SQLMemoryPoolSize))
// Set up the DistSQL temp engine.
useStoreSpec := cfg.Stores.Specs[s.cfg.TempStorageConfig.SpecIdx]
tempEngine, err := engine.NewTempEngine(s.cfg.TempStorageConfig, useStoreSpec)
if err != nil {
return nil, errors.Wrap(err, "could not create temp storage")
}
s.stopper.AddCloser(tempEngine)
// Remove temporary directory linked to tempEngine after closing
// tempEngine.
s.stopper.AddCloser(stop.CloserFn(func() {
firstStore := cfg.Stores.Specs[s.cfg.TempStorageConfig.SpecIdx]
var err error
if firstStore.InMemory {
// First store is in-memory so we remove the temp
// directory directly since there is no record file.
err = os.RemoveAll(s.cfg.TempStorageConfig.Path)
} else {
// If record file exists, we invoke CleanupTempDirs to
// also remove the record after the temp directory is
// removed.
recordPath := filepath.Join(firstStore.Path, TempDirsRecordFilename)
err = engine.CleanupTempDirs(recordPath)
}
if err != nil {
log.Errorf(context.TODO(), "could not remove temporary store directory: %v", err.Error())
}
}))
// Set up admin memory metrics for use by admin SQL executors.
s.adminMemMetrics = sql.MakeMemMetrics("admin", cfg.HistogramWindowInterval())
s.registry.AddMetricStruct(s.adminMemMetrics)
s.tsDB = ts.NewDB(s.db, s.cfg.Settings)
s.registry.AddMetricStruct(s.tsDB.Metrics())
nodeCountFn := func() int64 {
return s.nodeLiveness.Metrics().LiveNodes.Value()
}
s.tsServer = ts.MakeServer(s.cfg.AmbientCtx, s.tsDB, nodeCountFn, s.cfg.TimeSeriesServerConfig, s.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{}
// Similarly for execCfg.
var execCfg sql.ExecutorConfig
// TODO(bdarnell): make StoreConfig configurable.
storeCfg := storage.StoreConfig{
DefaultZoneConfig: &s.cfg.DefaultZoneConfig,
Settings: st,
AmbientCtx: s.cfg.AmbientCtx,
RaftConfig: s.cfg.RaftConfig,
Clock: s.clock,
DB: s.db,
Gossip: s.gossip,
NodeLiveness: s.nodeLiveness,
Transport: s.raftTransport,
NodeDialer: s.nodeDialer,
RPCContext: s.rpcContext,
ScanInterval: s.cfg.ScanInterval,
ScanMinIdleTime: s.cfg.ScanMinIdleTime,
ScanMaxIdleTime: s.cfg.ScanMaxIdleTime,
TimestampCachePageSize: s.cfg.TimestampCachePageSize,
HistogramWindowInterval: s.cfg.HistogramWindowInterval(),
StorePool: s.storePool,
SQLExecutor: internalExecutor,
LogRangeEvents: s.cfg.EventLogEnabled,
RangeDescriptorCache: s.distSender.RangeDescriptorCache(),
TimeSeriesDataStore: s.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: s.stopper,
Clock: s.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 := s.node.stores.GetReplicaForRangeID(rangeID)
if err != nil || repl == nil {
continue
}
repl.EmitMLAI()
}
},
Dialer: s.nodeDialer.CTDialer(),
}),
EnableEpochRangeLeases: true,
}
if storeTestingKnobs := s.cfg.TestingKnobs.Store; storeTestingKnobs != nil {
storeCfg.TestingKnobs = *storeTestingKnobs.(*storage.StoreTestingKnobs)
}
s.recorder = status.NewMetricsRecorder(s.clock, s.nodeLiveness, s.rpcContext, s.gossip, st)
s.registry.AddMetricStruct(s.rpcContext.RemoteClocks.Metrics())
s.runtime = status.NewRuntimeStatSampler(ctx, s.clock)
s.registry.AddMetricStruct(s.runtime)
s.node = NewNode(
storeCfg, s.recorder, s.registry, s.stopper,
txnMetrics, nil /* execCfg */, &s.rpcContext.ClusterID)
roachpb.RegisterInternalServer(s.grpc.Server, s.node)
storage.RegisterPerReplicaServer(s.grpc.Server, s.node.perReplicaServer)
s.node.storeCfg.ClosedTimestamp.RegisterClosedTimestampServer(s.grpc.Server)
s.sessionRegistry = sql.NewSessionRegistry()
s.jobRegistry = jobs.MakeRegistry(
s.cfg.AmbientCtx,
s.stopper,
s.clock,
s.db,
internalExecutor,
&s.nodeIDContainer,
st,
s.cfg.HistogramWindowInterval(),
func(opName, user string) (interface{}, func()) {
// This is a hack to get around a Go package dependency cycle. See comment
// in sql/jobs/registry.go on planHookMaker.
return sql.NewInternalPlanner(opName, nil, user, &sql.MemoryMetrics{}, &execCfg)
},
)
s.registry.AddMetricStruct(s.jobRegistry.MetricsStruct())
distSQLMetrics := distsqlrun.MakeDistSQLMetrics(cfg.HistogramWindowInterval())
s.registry.AddMetricStruct(distSQLMetrics)
// Set up Lease Manager
var lmKnobs sql.LeaseManagerTestingKnobs
if leaseManagerTestingKnobs := cfg.TestingKnobs.SQLLeaseManager; leaseManagerTestingKnobs != nil {
lmKnobs = *leaseManagerTestingKnobs.(*sql.LeaseManagerTestingKnobs)
}
s.leaseMgr = sql.NewLeaseManager(
s.cfg.AmbientCtx,
&s.nodeIDContainer,
s.db,
s.clock,
nil, /* internalExecutor - will be set later because of circular dependencies */
st,
lmKnobs,
s.stopper,
s.cfg.LeaseManagerConfig,
)
// Set up the DistSQL server.
distSQLCfg := distsqlrun.ServerConfig{
AmbientContext: s.cfg.AmbientCtx,
Settings: st,
RuntimeStats: s.runtime,
DB: s.db,
Executor: internalExecutor,
FlowDB: client.NewDB(s.cfg.AmbientCtx, s.tcsFactory, s.clock),
RPCContext: s.rpcContext,
Stopper: s.stopper,
NodeID: &s.nodeIDContainer,
ClusterID: &s.rpcContext.ClusterID,
TempStorage: tempEngine,
BulkAdder: func(ctx context.Context, db *client.DB, bufferSize, flushSize int64, ts hlc.Timestamp) (storagebase.BulkAdder, error) {
return bulk.MakeBulkAdder(db, s.distSender.RangeDescriptorCache(), bufferSize, flushSize, ts)
},
DiskMonitor: s.cfg.TempStorageConfig.Mon,
ParentMemoryMonitor: &rootSQLMemoryMonitor,
Metrics: &distSQLMetrics,
JobRegistry: s.jobRegistry,
Gossip: s.gossip,
NodeDialer: s.nodeDialer,
LeaseManager: s.leaseMgr,
}
if distSQLTestingKnobs := s.cfg.TestingKnobs.DistSQL; distSQLTestingKnobs != nil {
distSQLCfg.TestingKnobs = *distSQLTestingKnobs.(*distsqlrun.TestingKnobs)
}
s.distSQLServer = distsqlrun.NewServer(ctx, distSQLCfg)
distsqlpb.RegisterDistSQLServer(s.grpc.Server, s.distSQLServer)
s.admin = newAdminServer(s)
s.status = newStatusServer(
s.cfg.AmbientCtx,
st,
s.cfg.Config,
s.admin,
s.db,
s.gossip,
s.recorder,
s.nodeLiveness,
s.storePool,
s.rpcContext,
s.node.stores,
s.stopper,
s.sessionRegistry,
)
s.authentication = newAuthenticationServer(s)
for _, gw := range []grpcGatewayServer{s.admin, s.status, s.authentication, &s.tsServer} {
gw.RegisterService(s.grpc.Server)
}
// TODO(andrei): We're creating an initServer even through the inspection of
// our engines in Server.Start() might reveal that we're already bootstrapped
// and so we don't need to accept a Bootstrap RPC. The creation of this server
// early means that a Bootstrap RPC might erroneously succeed. We should
// figure out early if our engines are bootstrapped and, if they are, create a
// dummy implementation of the InitServer that rejects all RPCs.
s.initServer = newInitServer(s.gossip.Connected, s.stopper.ShouldStop())
serverpb.RegisterInitServer(s.grpc.Server, s.initServer)
nodeInfo := sql.NodeInfo{
AdminURL: cfg.AdminURL,
PGURL: cfg.PGURL,
ClusterID: s.ClusterID,
NodeID: &s.nodeIDContainer,
}
virtualSchemas, err := sql.NewVirtualSchemaHolder(ctx, st)
if err != nil {
log.Fatal(ctx, err)
}
// Set up Executor
var sqlExecutorTestingKnobs sql.ExecutorTestingKnobs
if k := s.cfg.TestingKnobs.SQLExecutor; k != nil {
sqlExecutorTestingKnobs = *k.(*sql.ExecutorTestingKnobs)
} else {
sqlExecutorTestingKnobs = sql.ExecutorTestingKnobs{}
}
loggerCtx, _ := s.stopper.WithCancelOnStop(ctx)
execCfg = sql.ExecutorConfig{
Settings: s.st,
NodeInfo: nodeInfo,
DefaultZoneConfig: &s.cfg.DefaultZoneConfig,
Locality: s.cfg.Locality,
AmbientCtx: s.cfg.AmbientCtx,
DB: s.db,
Gossip: s.gossip,
MetricsRecorder: s.recorder,
DistSender: s.distSender,
RPCContext: s.rpcContext,
LeaseManager: s.leaseMgr,
Clock: s.clock,
DistSQLSrv: s.distSQLServer,
StatusServer: s.status,
SessionRegistry: s.sessionRegistry,
JobRegistry: s.jobRegistry,
VirtualSchemas: virtualSchemas,
HistogramWindowInterval: s.cfg.HistogramWindowInterval(),
RangeDescriptorCache: s.distSender.RangeDescriptorCache(),
LeaseHolderCache: s.distSender.LeaseHolderCache(),
TestingKnobs: sqlExecutorTestingKnobs,
DistSQLPlanner: sql.NewDistSQLPlanner(
ctx,
distsqlrun.Version,
s.st,
// The node descriptor will be set later, once it is initialized.
roachpb.NodeDescriptor{},
s.rpcContext,
s.distSQLServer,
s.distSender,
s.gossip,
s.stopper,
s.nodeLiveness,
s.nodeDialer,
),
TableStatsCache: stats.NewTableStatisticsCache(
s.cfg.SQLTableStatCacheSize,
s.gossip,
s.db,
internalExecutor,
),
ExecLogger: log.NewSecondaryLogger(
loggerCtx, nil /* dirName */, "sql-exec", true /* enableGc */, false, /*forceSyncWrites*/
),
AuditLogger: log.NewSecondaryLogger(
loggerCtx, s.cfg.SQLAuditLogDirName, "sql-audit", true /*enableGc*/, true, /*forceSyncWrites*/
),
QueryCache: querycache.New(s.cfg.SQLQueryCacheSize),
}
if sqlSchemaChangerTestingKnobs := s.cfg.TestingKnobs.SQLSchemaChanger; sqlSchemaChangerTestingKnobs != nil {
execCfg.SchemaChangerTestingKnobs = sqlSchemaChangerTestingKnobs.(*sql.SchemaChangerTestingKnobs)
} else {
execCfg.SchemaChangerTestingKnobs = new(sql.SchemaChangerTestingKnobs)
}
if distSQLRunTestingKnobs := s.cfg.TestingKnobs.DistSQL; distSQLRunTestingKnobs != nil {
execCfg.DistSQLRunTestingKnobs = distSQLRunTestingKnobs.(*distsqlrun.TestingKnobs)
} else {
execCfg.DistSQLRunTestingKnobs = new(distsqlrun.TestingKnobs)
}
if sqlEvalContext := s.cfg.TestingKnobs.SQLEvalContext; sqlEvalContext != nil {
execCfg.EvalContextTestingKnobs = *sqlEvalContext.(*tree.EvalContextTestingKnobs)
}
if pgwireKnobs := s.cfg.TestingKnobs.PGWireTestingKnobs; pgwireKnobs != nil {
execCfg.PGWireTestingKnobs = pgwireKnobs.(*sql.PGWireTestingKnobs)
}
s.statsRefresher = stats.MakeRefresher(
s.st,
internalExecutor,
execCfg.TableStatsCache,
stats.DefaultAsOfTime,
)
execCfg.StatsRefresher = s.statsRefresher
// Set up internal memory metrics for use by internal SQL executors.
s.sqlMemMetrics = sql.MakeMemMetrics("sql", cfg.HistogramWindowInterval())
s.registry.AddMetricStruct(s.sqlMemMetrics)
s.pgServer = pgwire.MakeServer(
s.cfg.AmbientCtx,
s.cfg.Config,
s.ClusterSettings(),
s.sqlMemMetrics,
&rootSQLMemoryMonitor,
s.cfg.HistogramWindowInterval(),
&execCfg,
)
// Now that we have a pgwire.Server (which has a sql.Server), we can close a
// circular dependency between the distsqlrun.Server and sql.Server and set
// SessionBoundInternalExecutorFactory.
s.distSQLServer.ServerConfig.SessionBoundInternalExecutorFactory =
func(
ctx context.Context, sessionData *sessiondata.SessionData,
) sqlutil.InternalExecutor {
ie := sql.NewSessionBoundInternalExecutor(
ctx,
sessionData,
s.pgServer.SQLServer,
s.sqlMemMetrics,
s.st,
)
return ie
}
for _, m := range s.pgServer.Metrics() {
s.registry.AddMetricStruct(m)
}
*internalExecutor = sql.MakeInternalExecutor(
ctx, s.pgServer.SQLServer, s.internalMemMetrics, s.ClusterSettings(),
)
s.internalExecutor = internalExecutor
execCfg.InternalExecutor = internalExecutor
s.execCfg = &execCfg
s.leaseMgr.SetInternalExecutor(execCfg.InternalExecutor)
s.leaseMgr.RefreshLeases(s.stopper, s.db, s.gossip)
s.leaseMgr.PeriodicallyRefreshSomeLeases()
s.node.InitLogger(&execCfg)
s.cfg.DefaultZoneConfig = cfg.DefaultZoneConfig
return s, nil
}
// 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 {
error
Addr string
}
func inspectEngines(
ctx context.Context,
engines []engine.Engine,
minVersion, serverVersion roachpb.Version,
clusterIDContainer *base.ClusterIDContainer,
) (
bootstrappedEngines []engine.Engine,
emptyEngines []engine.Engine,
_ cluster.ClusterVersion,
_ error,
) {
for _, engine := range engines {
storeIdent, err := storage.ReadStoreIdent(ctx, engine)
if _, notBootstrapped := err.(*storage.NotBootstrappedError); notBootstrapped {
emptyEngines = append(emptyEngines, engine)
continue
} else if err != nil {
return nil, nil, cluster.ClusterVersion{}, err
}
clusterID := clusterIDContainer.Get()
if storeIdent.ClusterID != uuid.Nil {
if clusterID == uuid.Nil {
clusterIDContainer.Set(ctx, storeIdent.ClusterID)
} else if storeIdent.ClusterID != clusterID {
return nil, nil, cluster.ClusterVersion{},
errors.Errorf("conflicting store cluster IDs: %s, %s", storeIdent.ClusterID, clusterID)
}
}
bootstrappedEngines = append(bootstrappedEngines, engine)
}
cv, err := storage.SynthesizeClusterVersionFromEngines(ctx, bootstrappedEngines, minVersion, serverVersion)
if err != nil {
return nil, nil, cluster.ClusterVersion{}, err
}
return bootstrappedEngines, emptyEngines, cv, 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 {
listen string // the (RPC) listen address
advertise string // equals `listen` unless --advertise-addr is used
http 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.advertise-addr": li.advertise,
"cockroach.http-addr": li.http,
"cockroach.listen-addr": li.listen,
}
}
type singleListener struct {
conn net.Conn
}
func (s *singleListener) Accept() (net.Conn, error) {
if c := s.conn; c != nil {
s.conn = nil
return c, nil
}
return nil, io.EOF
}
func (s *singleListener) Close() error {
return nil
}
func (s *singleListener) Addr() net.Addr {
return s.conn.LocalAddr()
}
// startMonitoringForwardClockJumps starts a background task to monitor forward
// clock jumps based on a cluster setting
func (s *Server) startMonitoringForwardClockJumps(ctx context.Context) {
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(
forwardJumpCheckEnabled,
time.NewTicker,
nil, /* tick callback */
); err != nil {
log.Fatal(ctx, err)
}
log.Info(ctx, "monitoring forward clock jumps based on server.clock.forward_jump_check_enabled")
}
// 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.
// Don't have to sleep for monotonicity when using clockless reads
// (nor can we, for we would sleep forever).
if maxOffset := clock.MaxOffset(); maxOffset != timeutil.ClocklessMaxOffset {
sleepUntil = startTime.UnixNano() + int64(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()