-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
config.go
1048 lines (917 loc) · 36.3 KB
/
config.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2015 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0, included in the file
// licenses/APL.txt.
package server
import (
"bytes"
"context"
"fmt"
"net"
"runtime"
"strconv"
"strings"
"sync/atomic"
"text/tabwriter"
"time"
"github.com/cockroachdb/cockroach/pkg/base"
"github.com/cockroachdb/cockroach/pkg/config/zonepb"
"github.com/cockroachdb/cockroach/pkg/docs"
"github.com/cockroachdb/cockroach/pkg/kv/kvclient/rangefeed"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver"
"github.com/cockroachdb/cockroach/pkg/roachpb"
"github.com/cockroachdb/cockroach/pkg/server/status"
"github.com/cockroachdb/cockroach/pkg/settings/cluster"
"github.com/cockroachdb/cockroach/pkg/storage"
"github.com/cockroachdb/cockroach/pkg/storage/enginepb"
"github.com/cockroachdb/cockroach/pkg/ts"
"github.com/cockroachdb/cockroach/pkg/util"
"github.com/cockroachdb/cockroach/pkg/util/admission"
"github.com/cockroachdb/cockroach/pkg/util/envutil"
"github.com/cockroachdb/cockroach/pkg/util/humanizeutil"
"github.com/cockroachdb/cockroach/pkg/util/log"
"github.com/cockroachdb/cockroach/pkg/util/netutil"
"github.com/cockroachdb/cockroach/pkg/util/retry"
"github.com/cockroachdb/cockroach/pkg/util/tracing"
"github.com/cockroachdb/cockroach/pkg/util/uuid"
"github.com/cockroachdb/errors"
"github.com/cockroachdb/pebble"
"github.com/cockroachdb/pebble/bloom"
"github.com/cockroachdb/pebble/vfs"
"github.com/cockroachdb/redact"
)
// Context defaults.
const (
// DefaultCacheSize is the default size of the RocksDB and Pebble caches. We
// default the cache size and SQL memory pool size to 128 MiB. Larger values
// might provide significantly better performance, but we're not sure what
// type of system we're running on (development or production or some shared
// environment). Production users should almost certainly override these
// settings and we'll warn in the logs about doing so.
DefaultCacheSize = 128 << 20 // 128 MB
defaultSQLMemoryPoolSize = 128 << 20 // 128 MB
defaultScanInterval = 10 * time.Minute
defaultScanMinIdleTime = 10 * time.Millisecond
defaultScanMaxIdleTime = 1 * time.Second
DefaultStorePath = "cockroach-data"
// TempDirPrefix is the filename prefix of any temporary subdirectory
// created.
TempDirPrefix = "cockroach-temp"
// TempDirsRecordFilename is the filename for the record file
// that keeps track of the paths of the temporary directories created.
TempDirsRecordFilename = "temp-dirs-record.txt"
defaultEventLogEnabled = true
maximumMaxClockOffset = 5 * time.Second
minimumNetworkFileDescriptors = 256
recommendedNetworkFileDescriptors = 5000
defaultSQLTableStatCacheSize = 256
// This comes out to 1024 cache entries.
defaultSQLQueryCacheSize = 8 * 1024 * 1024
)
var productionSettingsWebpage = fmt.Sprintf(
"please see %s for more details",
docs.URL("recommended-production-settings.html"),
)
// MaxOffsetType stores the configured MaxOffset.
type MaxOffsetType time.Duration
// Type implements the pflag.Value interface.
func (mo *MaxOffsetType) Type() string {
return "MaxOffset"
}
// Set implements the pflag.Value interface.
func (mo *MaxOffsetType) Set(v string) error {
nanos, err := time.ParseDuration(v)
if err != nil {
return err
}
if nanos > maximumMaxClockOffset {
return errors.Errorf("%s is not a valid max offset, must be less than %v.", v, maximumMaxClockOffset)
}
*mo = MaxOffsetType(nanos)
return nil
}
// String implements the pflag.Value interface.
func (mo *MaxOffsetType) String() string {
return time.Duration(*mo).String()
}
// BaseConfig holds parameters that are needed to setup either a KV or a SQL
// server.
type BaseConfig struct {
Settings *cluster.Settings
*base.Config
Tracer *tracing.Tracer
// idProvider is an interface that makes the logging package
// able to peek into the server IDs defined by this configuration.
idProvider *idProvider
// IDContainer is the Node ID / SQL Instance ID container
// that will contain the ID for the server to instantiate.
IDContainer *base.NodeIDContainer
// ClusterIDContainer is the Cluster ID container for the server to
// instantiate.
ClusterIDContainer *base.ClusterIDContainer
// AmbientCtx is used to annotate contexts used inside the server.
AmbientCtx log.AmbientContext
// Maximum allowed clock offset for the cluster. If observed clock
// offsets exceed this limit, inconsistency may result, and servers
// will panic to minimize the likelihood of inconsistent data.
// Increasing this value will increase time to recovery after
// failures, and increase the frequency and impact of
// ReadWithinUncertaintyIntervalError.
MaxOffset MaxOffsetType
// GoroutineDumpDirName is the directory name for goroutine dumps using
// goroutinedumper.
GoroutineDumpDirName string
// HeapProfileDirName is the directory name for heap profiles using
// heapprofiler. If empty, no heap profiles will be collected.
HeapProfileDirName string
// CPUProfileDirName is the directory name for CPU profile dumps.
CPUProfileDirName string
// InflightTraceDirName is the directory name for job traces.
InflightTraceDirName string
// DefaultZoneConfig is used to set the default zone config inside the server.
// It can be overridden during tests by setting the DefaultZoneConfigOverride
// server testing knob. Whatever is installed here is in turn used to
// initialize stores, which need a default span config.
DefaultZoneConfig zonepb.ZoneConfig
// Locality is a description of the topography of the server.
Locality roachpb.Locality
// StorageEngine specifies the engine type (eg. rocksdb, pebble) to use to
// instantiate stores.
StorageEngine enginepb.EngineType
// SpanConfigsDisabled disables the use of the span configs infrastructure.
//
// Environment Variable: COCKROACH_DISABLE_SPAN_CONFIGS
SpanConfigsDisabled bool
// Disables the default test tenant.
DisableDefaultTestTenant bool
// TestingKnobs is used for internal test controls only.
TestingKnobs base.TestingKnobs
// EnableWebSessionAuthentication enables session-based authentication for
// the Admin API's HTTP endpoints.
EnableWebSessionAuthentication bool
// EnableDemoLoginEndpoint enables the HTTP GET endpoint for user logins,
// which a feature unique to the demo shell.
EnableDemoLoginEndpoint bool
// ReadyFn is called when the server has started listening on its
// sockets.
//
// The bool parameter is true if the server is not bootstrapped yet, will not
// bootstrap itself and will be waiting for an `init` command or accept
// bootstrapping from a joined node.
//
// This method is invoked from the main start goroutine, so it should not
// do nontrivial work.
ReadyFn func(waitForInit bool)
// Stores is specified to enable durable key-value storage.
Stores base.StoreSpecList
// StartDiagnosticsReporting starts the asynchronous goroutine that
// checks for CockroachDB upgrades and periodically reports
// diagnostics to Cockroach Labs.
// Should remain disabled during unit testing.
StartDiagnosticsReporting bool
// DisableOwnHTTPListener prevents this server from starting a TCP
// listener for the HTTP service. Instead, it is expected
// that some other service (typically, the server controller)
// will accept and route requests instead.
DisableOwnHTTPListener bool
}
// MakeBaseConfig returns a BaseConfig with default values.
func MakeBaseConfig(st *cluster.Settings, tr *tracing.Tracer, storeSpec base.StoreSpec) BaseConfig {
if tr == nil {
panic("nil Tracer")
}
baseCfg := BaseConfig{Config: new(base.Config)}
baseCfg.SetDefaults(st, tr, storeSpec)
return baseCfg
}
// SetDefaults resets the values in BaseConfig but while preserving
// the Config reference. Enables running tests multiple times.
func (cfg *BaseConfig) SetDefaults(
st *cluster.Settings, tr *tracing.Tracer, storeSpec base.StoreSpec,
) {
baseCfg := cfg.Config
*cfg = BaseConfig{Config: baseCfg}
cfg.Tracer = tr
cfg.Settings = st
idsProvider := &idProvider{
clusterID: &base.ClusterIDContainer{},
serverID: &base.NodeIDContainer{},
}
disableWebLogin := envutil.EnvOrDefaultBool("COCKROACH_DISABLE_WEB_LOGIN", false)
cfg.idProvider = idsProvider
cfg.IDContainer = idsProvider.serverID
cfg.ClusterIDContainer = idsProvider.clusterID
cfg.AmbientCtx = log.MakeServerAmbientContext(tr, idsProvider)
cfg.MaxOffset = MaxOffsetType(base.DefaultMaxClockOffset)
cfg.DefaultZoneConfig = zonepb.DefaultZoneConfig()
cfg.StorageEngine = storage.DefaultStorageEngine
cfg.EnableWebSessionAuthentication = !disableWebLogin
cfg.Stores = base.StoreSpecList{
Specs: []base.StoreSpec{storeSpec},
}
// We use the tag "n" here for both KV nodes and SQL instances,
// using the knowledge that the value part of a SQL instance ID
// container will prefix the value with the string "sql", resulting
// in a tag that is prefixed with "nsql".
cfg.AmbientCtx.AddLogTag("n", cfg.IDContainer)
cfg.Config.InitDefaults()
cfg.InitTestingKnobs()
}
// InitTestingKnobs sets up any testing knobs based on e.g. envvars.
func (cfg *BaseConfig) InitTestingKnobs() {
// If requested, write an MVCC range tombstone at the bottom of the SQL table
// data keyspace during cluster bootstrapping, for performance and correctness
// testing. This shouldn't affect data written above it, but activates range
// key-specific code paths in the storage layer. We'll also have to tweak
// rangefeeds and batcheval to not choke on it.
if envutil.EnvOrDefaultBool("COCKROACH_GLOBAL_MVCC_RANGE_TOMBSTONE", false) {
if cfg.TestingKnobs.Store == nil {
cfg.TestingKnobs.Store = &kvserver.StoreTestingKnobs{}
}
if cfg.TestingKnobs.RangeFeed == nil {
cfg.TestingKnobs.RangeFeed = &rangefeed.TestingKnobs{}
}
storeKnobs := cfg.TestingKnobs.Store.(*kvserver.StoreTestingKnobs)
storeKnobs.GlobalMVCCRangeTombstone = true
storeKnobs.EvalKnobs.DisableInitPutFailOnTombstones = true
cfg.TestingKnobs.RangeFeed.(*rangefeed.TestingKnobs).IgnoreOnDeleteRangeError = true
}
// If requested, replace point tombstones with range tombstones on a best-effort
// basis.
if envutil.EnvOrDefaultBool("COCKROACH_MVCC_RANGE_TOMBSTONES_FOR_POINT_DELETES", false) {
if cfg.TestingKnobs.Store == nil {
cfg.TestingKnobs.Store = &kvserver.StoreTestingKnobs{}
}
if cfg.TestingKnobs.RangeFeed == nil {
cfg.TestingKnobs.RangeFeed = &rangefeed.TestingKnobs{}
}
storeKnobs := cfg.TestingKnobs.Store.(*kvserver.StoreTestingKnobs)
storeKnobs.EvalKnobs.UseRangeTombstonesForPointDeletes = true
cfg.TestingKnobs.RangeFeed.(*rangefeed.TestingKnobs).IgnoreOnDeleteRangeError = true
}
}
// Config holds the parameters needed to set up a combined KV and SQL server.
type Config struct {
BaseConfig
KVConfig
SQLConfig
}
// KVConfig holds the parameters that (together with a BaseConfig) allow setting
// up a KV server.
type KVConfig struct {
base.RaftConfig
// Attrs specifies a colon-separated list of node topography or machine
// capabilities, used to match capabilities or location preferences specified
// in zone configs.
Attrs string
// JoinList is a list of node addresses that is used to form a network of KV
// servers. Assuming a connected graph, it suffices to initialize any server
// in the network.
JoinList base.JoinListType
// JoinPreferSRVRecords, if set, causes the lookup logic for the
// names in JoinList to prefer SRV records from DNS, if available,
// to A/AAAA records.
JoinPreferSRVRecords bool
// RetryOptions controls the retry behavior of the server.
//
// TODO(tbg): this is only ever used in one test. Make it a testing knob.
RetryOptions retry.Options
// CacheSize is the amount of memory in bytes to use for caching data.
// The value is split evenly between the stores if there are more than one.
CacheSize int64
// SoftSlotGranter can be optionally passed into a store to allow the store
// to perform additional CPU bound work.
SoftSlotGranter *admission.SoftSlotGranter
// TimeSeriesServerConfig contains configuration specific to the time series
// server.
TimeSeriesServerConfig ts.ServerConfig
// Parsed values.
// NodeAttributes is the parsed representation of Attrs.
NodeAttributes roachpb.Attributes
// GossipBootstrapAddresses is a list of gossip addresses used
// to find bootstrap nodes for connecting to the gossip network.
GossipBootstrapAddresses []util.UnresolvedAddr
// The following values can only be set via environment variables and are
// for testing only. They are not meant to be set by the end user.
// ScanInterval determines a duration during which each range should be
// visited approximately once by the range scanner. Set to 0 to disable.
// Environment Variable: COCKROACH_SCAN_INTERVAL
ScanInterval time.Duration
// ScanMinIdleTime is the minimum time the scanner will be idle between ranges.
// If enabled (> 0), the scanner may complete in more than ScanInterval for large
// stores.
// Environment Variable: COCKROACH_SCAN_MIN_IDLE_TIME
ScanMinIdleTime time.Duration
// ScanMaxIdleTime is the maximum time the scanner will be idle between ranges.
// If enabled (> 0), the scanner may complete in less than ScanInterval for small
// stores.
// Environment Variable: COCKROACH_SCAN_MAX_IDLE_TIME
ScanMaxIdleTime time.Duration
// DefaultSystemZoneConfig is used to set the default system zone config
// inside the server. It can be overridden during tests by setting the
// DefaultSystemZoneConfigOverride server testing knob.
DefaultSystemZoneConfig zonepb.ZoneConfig
// LocalityAddresses contains private IP addresses the can only be accessed
// in the corresponding locality.
LocalityAddresses []roachpb.LocalityAddress
// EventLogEnabled is a switch which enables recording into cockroach's SQL
// event log tables. These tables record transactional events about changes
// to cluster metadata, such as DDL statements and range rebalancing
// actions.
EventLogEnabled bool
// DelayedBootstrapFn is called if the bootstrap process does not complete
// in a timely fashion, typically 30s after the server starts listening.
DelayedBootstrapFn func()
enginesCreated bool
// SnapshotSendLimit is the number of concurrent snapshots a store will send.
SnapshotSendLimit int64
// SnapshotApplyLimit is the number of concurrent snapshots a store will
// apply. The send limit is typically higher than the apply limit for a few
// reasons. One is that it keeps "pipelining" of requests in the case where
// there is only a single sender and single receiver. As soon as a receiver
// finishes a request, there will be another one to start. The performance
// impact of sending snapshots is lower than applying. Finally, snapshots are
// not sent until the receiver is ready to apply, so the cost of sending is
// low until the receiver is ready.
SnapshotApplyLimit int64
}
// MakeKVConfig returns a KVConfig with default values.
func MakeKVConfig() KVConfig {
kvCfg := KVConfig{}
kvCfg.SetDefaults()
return kvCfg
}
// SetDefaults resets the values in KVConfig. Enables running tests
// multiple times.
func (kvCfg *KVConfig) SetDefaults() {
*kvCfg = KVConfig{}
kvCfg.RaftConfig.SetDefaults()
kvCfg.DefaultSystemZoneConfig = zonepb.DefaultSystemZoneConfig()
kvCfg.CacheSize = DefaultCacheSize
kvCfg.ScanInterval = defaultScanInterval
kvCfg.ScanMinIdleTime = defaultScanMinIdleTime
kvCfg.ScanMaxIdleTime = defaultScanMaxIdleTime
kvCfg.EventLogEnabled = defaultEventLogEnabled
kvCfg.SnapshotSendLimit = kvserver.DefaultSnapshotSendLimit
kvCfg.SnapshotApplyLimit = kvserver.DefaultSnapshotApplyLimit
}
// SQLConfig holds the parameters that (together with a BaseConfig) allow
// setting up a SQL server.
type SQLConfig struct {
// The tenant that the SQL server runs on the behalf of.
TenantID roachpb.TenantID
// TempStorageConfig is used to configure temp storage, which stores
// ephemeral data when processing large queries.
TempStorageConfig base.TempStorageConfig
// ExternalIODirConfig is used to configure external storage
// access (http://, nodelocal://, etc)
ExternalIODirConfig base.ExternalIODirConfig
// MemoryPoolSize is the amount of memory in bytes that can be
// used by SQL clients to store row data in server RAM.
MemoryPoolSize int64
// TableStatCacheSize is the size (number of tables) of the table
// statistics cache.
TableStatCacheSize int
// QueryCacheSize is the memory size (in bytes) of the query plan cache.
QueryCacheSize int64
// TenantKVAddrs are the entry points to the KV layer.
//
// Only applies when the SQL server is deployed individually.
TenantKVAddrs []string
// The following values can only be set via environment variables and are
// for testing only. They are not meant to be set by the end user.
// Enables linearizable behavior of operations on this node by making sure
// that no commit timestamp is reported back to the client until all other
// node clocks have necessarily passed it.
// Environment Variable: COCKROACH_EXPERIMENTAL_LINEARIZABLE
Linearizable bool
}
// MakeSQLConfig returns a SQLConfig with default values.
func MakeSQLConfig(tenID roachpb.TenantID, tempStorageCfg base.TempStorageConfig) SQLConfig {
sqlCfg := SQLConfig{
TenantID: tenID,
}
sqlCfg.SetDefaults(tempStorageCfg)
return sqlCfg
}
// SetDefaults resets the values in SQLConfig. Enables running tests
// multiple times.
func (sqlCfg *SQLConfig) SetDefaults(tempStorageCfg base.TempStorageConfig) {
tenID := sqlCfg.TenantID
*sqlCfg = SQLConfig{TenantID: tenID}
sqlCfg.MemoryPoolSize = defaultSQLMemoryPoolSize
sqlCfg.TableStatCacheSize = defaultSQLTableStatCacheSize
sqlCfg.QueryCacheSize = defaultSQLQueryCacheSize
sqlCfg.TempStorageConfig = tempStorageCfg
}
// setOpenFileLimit sets the soft limit for open file descriptors to the hard
// limit if needed. Returns an error if the hard limit is too low. Returns the
// value to set maxOpenFiles to for each store.
//
// # Minimum - 1700 per store, 256 saved for networking
//
// # Constrained - 256 saved for networking, rest divided evenly per store
//
// # Constrained (network only) - 10000 per store, rest saved for networking
//
// # Recommended - 10000 per store, 5000 for network
//
// Please note that current and max limits are commonly referred to as the soft
// and hard limits respectively.
//
// On Windows there is no need to change the file descriptor, known as handles,
// limit. This limit cannot be changed and is approximately 16,711,680. See
// https://blogs.technet.microsoft.com/markrussinovich/2009/09/29/pushing-the-limits-of-windows-handles/
func setOpenFileLimit(physicalStoreCount int) (uint64, error) {
return setOpenFileLimitInner(physicalStoreCount)
}
// SetOpenFileLimitForOneStore sets the soft limit for open file descriptors
// when there is only one store.
func SetOpenFileLimitForOneStore() (uint64, error) {
return setOpenFileLimit(1)
}
// MakeConfig returns a Config for the system tenant with default values.
func MakeConfig(ctx context.Context, st *cluster.Settings) Config {
storeSpec, tempStorageCfg := makeStorageCfg(ctx, st)
sqlCfg := MakeSQLConfig(roachpb.SystemTenantID, tempStorageCfg)
tr := tracing.NewTracerWithOpt(ctx, tracing.WithClusterSettings(&st.SV))
baseCfg := MakeBaseConfig(st, tr, storeSpec)
kvCfg := MakeKVConfig()
cfg := Config{
BaseConfig: baseCfg,
KVConfig: kvCfg,
SQLConfig: sqlCfg,
}
return cfg
}
// SetDefaults initializes the Config to its default value while
// preserving the base.Config reference. Enables running tests
// multiple times.
func (cfg *Config) SetDefaults(ctx context.Context, st *cluster.Settings) {
storeSpec, tempStorageCfg := makeStorageCfg(ctx, st)
cfg.SQLConfig.SetDefaults(tempStorageCfg)
cfg.KVConfig.SetDefaults()
tr := tracing.NewTracerWithOpt(ctx, tracing.WithClusterSettings(&st.SV))
cfg.BaseConfig.SetDefaults(st, tr, storeSpec)
}
func makeStorageCfg(
ctx context.Context, st *cluster.Settings,
) (base.StoreSpec, base.TempStorageConfig) {
storeSpec, err := base.NewStoreSpec(DefaultStorePath)
if err != nil {
panic(err)
}
tempStorageCfg := base.TempStorageConfigFromEnv(
ctx, st, storeSpec, "" /* parentDir */, base.DefaultTempStorageMaxSizeBytes)
return storeSpec, tempStorageCfg
}
// String implements the fmt.Stringer interface.
func (cfg *Config) String() string {
var buf bytes.Buffer
w := tabwriter.NewWriter(&buf, 2, 1, 2, ' ', 0)
fmt.Fprintln(w, "max offset\t", cfg.MaxOffset)
fmt.Fprintln(w, "cache size\t", humanizeutil.IBytes(cfg.CacheSize))
fmt.Fprintln(w, "SQL memory pool size\t", humanizeutil.IBytes(cfg.MemoryPoolSize))
fmt.Fprintln(w, "scan interval\t", cfg.ScanInterval)
fmt.Fprintln(w, "scan min idle time\t", cfg.ScanMinIdleTime)
fmt.Fprintln(w, "scan max idle time\t", cfg.ScanMaxIdleTime)
fmt.Fprintln(w, "event log enabled\t", cfg.EventLogEnabled)
if cfg.Linearizable {
fmt.Fprintln(w, "linearizable\t", cfg.Linearizable)
}
if !cfg.SpanConfigsDisabled {
fmt.Fprintln(w, "span configs enabled\t", !cfg.SpanConfigsDisabled)
}
_ = w.Flush()
return buf.String()
}
// Report logs an overview of the server configuration parameters via
// the given context.
func (cfg *Config) Report(ctx context.Context) {
if memSize, err := status.GetTotalMemory(ctx); err != nil {
log.Infof(ctx, "unable to retrieve system total memory: %v", err)
} else {
log.Infof(ctx, "system total memory: %s", humanizeutil.IBytes(memSize))
}
log.Infof(ctx, "server configuration:\n%s", log.SafeManaged(cfg))
}
// Engines is a container of engines, allowing convenient closing.
type Engines []storage.Engine
// Close closes all the Engines.
// This method has a pointer receiver so that the following pattern works:
//
// func f() {
// engines := Engines(engineSlice)
// defer engines.Close() // make sure the engines are Closed if this
// // function returns early.
// ... do something with engines, pass ownership away...
// engines = nil // neutralize the preceding defer
// }
func (e *Engines) Close() {
for _, eng := range *e {
eng.Close()
}
*e = nil
}
// cpuWorkPermissionGranter implements the pebble.CPUWorkPermissionGranter
// interface.
//type cpuWorkPermissionGranter struct {
//*admission.SoftSlotGranter
//}
//func (c *cpuWorkPermissionGranter) TryGetProcs(count int) int {
//return c.TryGetSlots(count)
//}
//func (c *cpuWorkPermissionGranter) ReturnProcs(count int) {
//c.ReturnSlots(count)
//}
// CreateEngines creates Engines based on the specs in cfg.Stores.
func (cfg *Config) CreateEngines(ctx context.Context) (Engines, error) {
engines := Engines(nil)
defer engines.Close()
if cfg.enginesCreated {
return Engines{}, errors.Errorf("engines already created")
}
cfg.enginesCreated = true
details := []redact.RedactableString{redact.Sprintf("Pebble cache size: %s", humanizeutil.IBytes(cfg.CacheSize))}
pebbleCache := pebble.NewCache(cfg.CacheSize)
defer pebbleCache.Unref()
var physicalStores int
for _, spec := range cfg.Stores.Specs {
if !spec.InMemory {
physicalStores++
}
}
openFileLimitPerStore, err := setOpenFileLimit(physicalStores)
if err != nil {
return Engines{}, err
}
log.Event(ctx, "initializing engines")
var tableCache *pebble.TableCache
if physicalStores > 0 {
perStoreLimit := pebble.TableCacheSize(int(openFileLimitPerStore))
totalFileLimit := perStoreLimit * physicalStores
tableCache = pebble.NewTableCache(pebbleCache, runtime.GOMAXPROCS(0), totalFileLimit)
}
var storeKnobs kvserver.StoreTestingKnobs
if s := cfg.TestingKnobs.Store; s != nil {
storeKnobs = *s.(*kvserver.StoreTestingKnobs)
}
for i, spec := range cfg.Stores.Specs {
log.Eventf(ctx, "initializing %+v", spec)
var sizeInBytes = spec.Size.InBytes
if spec.InMemory {
if spec.Size.Percent > 0 {
sysMem, err := status.GetTotalMemory(ctx)
if err != nil {
return Engines{}, errors.Errorf("could not retrieve system memory")
}
sizeInBytes = int64(float64(sysMem) * spec.Size.Percent / 100)
}
if sizeInBytes != 0 && !storeKnobs.SkipMinSizeCheck && sizeInBytes < base.MinimumStoreSize {
return Engines{}, errors.Errorf("%f%% of memory is only %s bytes, which is below the minimum requirement of %s",
spec.Size.Percent, humanizeutil.IBytes(sizeInBytes), humanizeutil.IBytes(base.MinimumStoreSize))
}
details = append(details, redact.Sprintf("store %d: in-memory, size %s",
i, humanizeutil.IBytes(sizeInBytes)))
if spec.StickyInMemoryEngineID != "" {
if cfg.TestingKnobs.Server == nil {
return Engines{}, errors.AssertionFailedf("Could not create a sticky " +
"engine no server knobs available to get a registry. " +
"Please use Knobs.Server.StickyEngineRegistry to provide one.")
}
knobs := cfg.TestingKnobs.Server.(*TestingKnobs)
if knobs.StickyEngineRegistry == nil {
return Engines{}, errors.Errorf("Could not create a sticky " +
"engine no registry available. Please use " +
"Knobs.Server.StickyEngineRegistry to provide one.")
}
e, err := knobs.StickyEngineRegistry.GetOrCreateStickyInMemEngine(ctx, cfg, spec)
if err != nil {
return Engines{}, err
}
details = append(details, redact.Sprintf("store %d: %+v", i, e.Properties()))
engines = append(engines, e)
} else {
storageConfigs := []storage.ConfigOption{
storage.Attributes(spec.Attributes),
storage.CacheSize(cfg.CacheSize),
storage.MaxSize(sizeInBytes),
storage.EncryptionAtRest(spec.EncryptionOptions),
storage.Settings(cfg.Settings),
storage.If(storeKnobs.SmallEngineBlocks, storage.BlockSize(1)),
}
if len(storeKnobs.EngineKnobs) > 0 {
storageConfigs = append(storageConfigs, storeKnobs.EngineKnobs...)
}
e, err := storage.Open(ctx,
storage.InMemory(),
storageConfigs...,
)
if err != nil {
return Engines{}, err
}
engines = append(engines, e)
}
} else {
if err := vfs.Default.MkdirAll(spec.Path, 0755); err != nil {
return Engines{}, errors.Wrap(err, "creating store directory")
}
du, err := vfs.Default.GetDiskUsage(spec.Path)
if err != nil {
return Engines{}, errors.Wrap(err, "retrieving disk usage")
}
if spec.Size.Percent > 0 {
sizeInBytes = int64(float64(du.TotalBytes) * spec.Size.Percent / 100)
}
if sizeInBytes != 0 && !storeKnobs.SkipMinSizeCheck && sizeInBytes < base.MinimumStoreSize {
return Engines{}, errors.Errorf("%f%% of %s's total free space is only %s bytes, which is below the minimum requirement of %s",
spec.Size.Percent, spec.Path, humanizeutil.IBytes(sizeInBytes), humanizeutil.IBytes(base.MinimumStoreSize))
}
details = append(details, redact.Sprintf("store %d: max size %s, max open file limit %d",
i, humanizeutil.IBytes(sizeInBytes), openFileLimitPerStore))
storageConfig := base.StorageConfig{
Attrs: spec.Attributes,
Dir: spec.Path,
MaxSize: sizeInBytes,
BallastSize: storage.BallastSizeBytes(spec, du),
Settings: cfg.Settings,
UseFileRegistry: spec.UseFileRegistry,
EncryptionOptions: spec.EncryptionOptions,
}
pebbleConfig := storage.PebbleConfig{
StorageConfig: storageConfig,
Opts: storage.DefaultPebbleOptions(),
}
pebbleConfig.Opts.Cache = pebbleCache
pebbleConfig.Opts.TableCache = tableCache
pebbleConfig.Opts.MaxOpenFiles = int(openFileLimitPerStore)
pebbleConfig.Opts.Experimental.MaxWriterConcurrency = 2
// TODO(jackson): Implement the new pebble.CPUWorkPermissionGranter
// interface.
//pebbleConfig.Opts.Experimental.CPUWorkPermissionGranter = &cpuWorkPermissionGranter{
//cfg.SoftSlotGranter,
//}
if storeKnobs.SmallEngineBlocks {
for i := range pebbleConfig.Opts.Levels {
pebbleConfig.Opts.Levels[i].BlockSize = 1
pebbleConfig.Opts.Levels[i].IndexBlockSize = 1
}
}
// If the spec contains Pebble options, set those too.
if len(spec.PebbleOptions) > 0 {
err := pebbleConfig.Opts.Parse(spec.PebbleOptions, &pebble.ParseHooks{
NewFilterPolicy: func(name string) (pebble.FilterPolicy, error) {
switch name {
case "none":
return nil, nil
case "rocksdb.BuiltinBloomFilter":
return bloom.FilterPolicy(10), nil
}
return nil, nil
},
})
if err != nil {
return nil, err
}
}
if len(spec.RocksDBOptions) > 0 {
return nil, errors.Errorf("store %d: using Pebble storage engine but StoreSpec provides RocksDB options", i)
}
eng, err := storage.NewPebble(ctx, pebbleConfig)
if err != nil {
return Engines{}, err
}
details = append(details, redact.Sprintf("store %d: %+v", i, eng.Properties()))
engines = append(engines, eng)
}
}
if tableCache != nil {
// Unref the table cache now that the engines hold references to it.
if err := tableCache.Unref(); err != nil {
return nil, err
}
}
log.Infof(ctx, "%d storage engine%s initialized",
len(engines), redact.Safe(util.Pluralize(int64(len(engines)))))
for _, s := range details {
log.Infof(ctx, "%v", s)
}
enginesCopy := engines
engines = nil
return enginesCopy, nil
}
// InitSQLServer finalizes the configuration of a SQL-only node.
// It initializes additional configuration flags from the environment.
func (cfg *Config) InitSQLServer(ctx context.Context) error {
cfg.readSQLEnvironmentVariables()
return nil
}
// InitNode finalizes the configuration of a KV node.
// It parses node attributes and bootstrap addresses and
// initializes additional configuration flags from the environment.
func (cfg *Config) InitNode(ctx context.Context) error {
cfg.readEnvironmentVariables()
// Initialize attributes.
cfg.NodeAttributes = parseAttributes(cfg.Attrs)
// Get the gossip bootstrap addresses.
addresses, err := cfg.parseGossipBootstrapAddresses(ctx)
if err != nil {
return err
}
if len(addresses) > 0 {
cfg.GossipBootstrapAddresses = addresses
}
return nil
}
// FilterGossipBootstrapAddresses removes any gossip bootstrap addresses which
// match either this node's listen address or its advertised host address.
func (cfg *Config) FilterGossipBootstrapAddresses(ctx context.Context) []util.UnresolvedAddr {
var listen, advert net.Addr
listen = util.NewUnresolvedAddr("tcp", cfg.Addr)
advert = util.NewUnresolvedAddr("tcp", cfg.AdvertiseAddr)
filtered := make([]util.UnresolvedAddr, 0, len(cfg.GossipBootstrapAddresses))
addrs := make([]string, 0, len(cfg.GossipBootstrapAddresses))
for _, addr := range cfg.GossipBootstrapAddresses {
if addr.String() == advert.String() || addr.String() == listen.String() {
if log.V(1) {
log.Infof(ctx, "skipping -join address %q, because a node cannot join itself", addr)
}
} else {
filtered = append(filtered, addr)
addrs = append(addrs, addr.String())
}
}
if log.V(1) {
log.Infof(ctx, "initial addresses: %v", addrs)
}
return filtered
}
// RequireWebSession indicates whether the server should require authentication
// sessions when serving admin API requests.
func (cfg *BaseConfig) RequireWebSession() bool {
return !cfg.Insecure && cfg.EnableWebSessionAuthentication
}
func (cfg *Config) readSQLEnvironmentVariables() {
cfg.SpanConfigsDisabled = envutil.EnvOrDefaultBool("COCKROACH_DISABLE_SPAN_CONFIGS", cfg.SpanConfigsDisabled)
cfg.Linearizable = envutil.EnvOrDefaultBool("COCKROACH_EXPERIMENTAL_LINEARIZABLE", cfg.Linearizable)
}
// readEnvironmentVariables populates all context values that are environment
// variable based. Note that this only happens when initializing a node and not
// when NewContext is called.
func (cfg *Config) readEnvironmentVariables() {
cfg.readSQLEnvironmentVariables()
cfg.ScanInterval = envutil.EnvOrDefaultDuration("COCKROACH_SCAN_INTERVAL", cfg.ScanInterval)
cfg.ScanMinIdleTime = envutil.EnvOrDefaultDuration("COCKROACH_SCAN_MIN_IDLE_TIME", cfg.ScanMinIdleTime)
cfg.ScanMaxIdleTime = envutil.EnvOrDefaultDuration("COCKROACH_SCAN_MAX_IDLE_TIME", cfg.ScanMaxIdleTime)
cfg.SnapshotSendLimit = envutil.EnvOrDefaultInt64("COCKROACH_CONCURRENT_SNAPSHOT_SEND_LIMIT", cfg.SnapshotSendLimit)
cfg.SnapshotApplyLimit = envutil.EnvOrDefaultInt64("COCKROACH_CONCURRENT_SNAPSHOT_APPLY_LIMIT", cfg.SnapshotApplyLimit)
}
// parseGossipBootstrapAddresses parses list of gossip bootstrap addresses.
func (cfg *Config) parseGossipBootstrapAddresses(
ctx context.Context,
) ([]util.UnresolvedAddr, error) {
var bootstrapAddresses []util.UnresolvedAddr
for _, address := range cfg.JoinList {
if address == "" {
continue
}
if cfg.JoinPreferSRVRecords {
// The following code substitutes the entry in --join by the
// result of SRV resolution, if suitable SRV records are found
// for that name.
//
// TODO(knz): Delay this lookup. The logic for "regular" addresses
// is delayed until the point the connection is attempted, so that
// fresh DNS records are used for a new connection. This makes
// it possible to update DNS records without restarting the node.
// The SRV logic here does not have this property (yet).
srvAddrs, err := netutil.SRV(ctx, address)
if err != nil {
return nil, err
}
if len(srvAddrs) > 0 {
for _, sa := range srvAddrs {
bootstrapAddresses = append(bootstrapAddresses,
util.MakeUnresolvedAddrWithDefaults("tcp", sa, base.DefaultPort))
}
continue
}
}
// Otherwise, use the address.
bootstrapAddresses = append(bootstrapAddresses,
util.MakeUnresolvedAddrWithDefaults("tcp", address, base.DefaultPort))
}
return bootstrapAddresses, nil
}
// parseAttributes parses a colon-separated list of strings,
// filtering empty strings (i.e. "::" will yield no attributes.
// Returns the list of strings as Attributes.
func parseAttributes(attrsStr string) roachpb.Attributes {
var filtered []string
for _, attr := range strings.Split(attrsStr, ":") {
if len(attr) != 0 {
filtered = append(filtered, attr)
}
}
return roachpb.Attributes{Attrs: filtered}
}
// idProvider connects the server ID containers in this
// package to the logging package.
//
// For each of the "main" data items, it also memoizes its
// representation as a string (the one needed by the
// log.ServerIdentificationPayload interface) as soon as the value is
// initialized. This saves on conversion costs.
type idProvider struct {
// clusterID contains the cluster ID (initialized late).
clusterID *base.ClusterIDContainer
// clusterStr is the memoized representation of clusterID, once known.
clusterStr atomic.Value
// tenantID is the tenant ID for this server.
tenantID roachpb.TenantID
// tenantStr is the memoized representation of tenantID.
tenantStr atomic.Value
// serverID contains the node ID for KV nodes (when tenantID.IsSet() ==
// false), or the SQL instance ID for SQL-only servers (when
// tenantID.IsSet() == true).
serverID *base.NodeIDContainer
// serverStr is the memoized representation of serverID.
serverStr atomic.Value
}
var _ log.ServerIdentificationPayload = (*idProvider)(nil)
// ServerIdentityString implements the log.ServerIdentificationPayload interface.
func (s *idProvider) ServerIdentityString(key log.ServerIdentificationKey) string {
switch key {
case log.IdentifyClusterID:
c := s.clusterStr.Load()
cs, ok := c.(string)
if !ok {
cid := s.clusterID.Get()
if cid != uuid.Nil {
cs = cid.String()
s.clusterStr.Store(cs)
}
}
return cs
case log.IdentifyTenantID:
t := s.tenantStr.Load()
ts, ok := t.(string)
if !ok {
tid := s.tenantID
if tid.IsSet() {
ts = strconv.FormatUint(tid.ToUint64(), 10)
s.tenantStr.Store(ts)
}
}
return ts
case log.IdentifyInstanceID:
// If tenantID is not set, this is a KV node and it has no SQL