-
Notifications
You must be signed in to change notification settings - Fork 3.6k
/
DatabaseDescriptor.java
3297 lines (2744 loc) · 112 KB
/
DatabaseDescriptor.java
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
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 org.apache.cassandra.config;
import java.io.File;
import java.io.IOException;
import java.net.*;
import java.nio.file.FileStore;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.function.Supplier;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableSet;
import com.google.common.primitives.Ints;
import com.google.common.primitives.Longs;
import com.google.common.util.concurrent.RateLimiter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.cassandra.audit.AuditLogOptions;
import org.apache.cassandra.fql.FullQueryLoggerOptions;
import org.apache.cassandra.auth.AllowAllInternodeAuthenticator;
import org.apache.cassandra.auth.AuthConfig;
import org.apache.cassandra.auth.IAuthenticator;
import org.apache.cassandra.auth.IAuthorizer;
import org.apache.cassandra.auth.IInternodeAuthenticator;
import org.apache.cassandra.auth.INetworkAuthorizer;
import org.apache.cassandra.auth.IRoleManager;
import org.apache.cassandra.config.Config.CommitLogSync;
import org.apache.cassandra.db.ConsistencyLevel;
import org.apache.cassandra.db.commitlog.AbstractCommitLogSegmentManager;
import org.apache.cassandra.db.commitlog.CommitLog;
import org.apache.cassandra.db.commitlog.CommitLogSegmentManagerCDC;
import org.apache.cassandra.db.commitlog.CommitLogSegmentManagerStandard;
import org.apache.cassandra.dht.IPartitioner;
import org.apache.cassandra.exceptions.ConfigurationException;
import org.apache.cassandra.io.FSWriteError;
import org.apache.cassandra.io.util.DiskOptimizationStrategy;
import org.apache.cassandra.io.util.FileUtils;
import org.apache.cassandra.io.util.SpinningDiskOptimizationStrategy;
import org.apache.cassandra.io.util.SsdDiskOptimizationStrategy;
import org.apache.cassandra.locator.DynamicEndpointSnitch;
import org.apache.cassandra.locator.EndpointSnitchInfo;
import org.apache.cassandra.locator.IEndpointSnitch;
import org.apache.cassandra.locator.InetAddressAndPort;
import org.apache.cassandra.locator.Replica;
import org.apache.cassandra.locator.SeedProvider;
import org.apache.cassandra.security.EncryptionContext;
import org.apache.cassandra.security.SSLFactory;
import org.apache.cassandra.service.CacheService.CacheType;
import org.apache.cassandra.utils.FBUtilities;
import org.apache.commons.lang3.StringUtils;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static org.apache.cassandra.config.CassandraRelevantProperties.OS_ARCH;
import static org.apache.cassandra.config.CassandraRelevantProperties.SUN_ARCH_DATA_MODEL;
import static org.apache.cassandra.io.util.FileUtils.ONE_GB;
import static org.apache.cassandra.io.util.FileUtils.ONE_MB;
public class DatabaseDescriptor
{
static
{
// This static block covers most usages
FBUtilities.preventIllegalAccessWarnings();
System.setProperty("io.netty.transport.estimateSizeOnSubmit", "false");
}
private static final Logger logger = LoggerFactory.getLogger(DatabaseDescriptor.class);
/**
* Tokens are serialized in a Gossip VersionedValue String. VV are restricted to 64KB
* when we send them over the wire, which works out to about 1700 tokens.
*/
private static final int MAX_NUM_TOKENS = 1536;
private static Config conf;
/**
* Request timeouts can not be less than below defined value (see CASSANDRA-9375)
*/
static final long LOWEST_ACCEPTED_TIMEOUT = 10L;
private static IEndpointSnitch snitch;
private static InetAddress listenAddress; // leave null so we can fall through to getLocalHost
private static InetAddress broadcastAddress;
private static InetAddress rpcAddress;
private static InetAddress broadcastRpcAddress;
private static SeedProvider seedProvider;
private static IInternodeAuthenticator internodeAuthenticator = new AllowAllInternodeAuthenticator();
/* Hashing strategy Random or OPHF */
private static IPartitioner partitioner;
private static String paritionerName;
private static Config.DiskAccessMode indexAccessMode;
private static IAuthenticator authenticator;
private static IAuthorizer authorizer;
private static INetworkAuthorizer networkAuthorizer;
// Don't initialize the role manager until applying config. The options supported by CassandraRoleManager
// depend on the configured IAuthenticator, so defer creating it until that's been set.
private static IRoleManager roleManager;
private static long preparedStatementsCacheSizeInMB;
private static long keyCacheSizeInMB;
private static long counterCacheSizeInMB;
private static long indexSummaryCapacityInMB;
private static String localDC;
private static Comparator<Replica> localComparator;
private static EncryptionContext encryptionContext;
private static boolean hasLoggedConfig;
private static DiskOptimizationStrategy diskOptimizationStrategy;
private static boolean clientInitialized;
private static boolean toolInitialized;
private static boolean daemonInitialized;
private static final int searchConcurrencyFactor = Integer.parseInt(System.getProperty(Config.PROPERTY_PREFIX + "search_concurrency_factor", "1"));
private static volatile boolean disableSTCSInL0 = Boolean.getBoolean(Config.PROPERTY_PREFIX + "disable_stcs_in_l0");
private static final boolean unsafeSystem = Boolean.getBoolean(Config.PROPERTY_PREFIX + "unsafesystem");
// turns some warnings into exceptions for testing
private static final boolean strictRuntimeChecks = Boolean.getBoolean("cassandra.strict.runtime.checks");
public static volatile boolean allowUnlimitedConcurrentValidations = Boolean.getBoolean("cassandra.allow_unlimited_concurrent_validations");
private static Function<CommitLog, AbstractCommitLogSegmentManager> commitLogSegmentMgrProvider = c -> DatabaseDescriptor.isCDCEnabled()
? new CommitLogSegmentManagerCDC(c, DatabaseDescriptor.getCommitLogLocation())
: new CommitLogSegmentManagerStandard(c, DatabaseDescriptor.getCommitLogLocation());
public static void daemonInitialization() throws ConfigurationException
{
daemonInitialization(DatabaseDescriptor::loadConfig);
}
public static void daemonInitialization(Supplier<Config> config) throws ConfigurationException
{
if (toolInitialized)
throw new AssertionError("toolInitialization() already called");
if (clientInitialized)
throw new AssertionError("clientInitialization() already called");
// Some unit tests require this :(
if (daemonInitialized)
return;
daemonInitialized = true;
setConfig(config.get());
applyAll();
AuthConfig.applyAuth();
}
/**
* Equivalent to {@link #toolInitialization(boolean) toolInitialization(true)}.
*/
public static void toolInitialization()
{
toolInitialization(true);
}
/**
* Initializes this class as a tool, which means that the configuration is loaded
* using {@link #loadConfig()} and all non-daemon configuration parts will be setup.
*
* @param failIfDaemonOrClient if {@code true} and a call to {@link #daemonInitialization()} or
* {@link #clientInitialization()} has been performed before, an
* {@link AssertionError} will be thrown.
*/
public static void toolInitialization(boolean failIfDaemonOrClient)
{
if (!failIfDaemonOrClient && (daemonInitialized || clientInitialized))
{
return;
}
else
{
if (daemonInitialized)
throw new AssertionError("daemonInitialization() already called");
if (clientInitialized)
throw new AssertionError("clientInitialization() already called");
}
if (toolInitialized)
return;
toolInitialized = true;
setConfig(loadConfig());
applySimpleConfig();
applyPartitioner();
applySnitch();
applyEncryptionContext();
}
/**
* Equivalent to {@link #clientInitialization(boolean) clientInitialization(true)}.
*/
public static void clientInitialization()
{
clientInitialization(true);
}
/**
* Initializes this class as a client, which means that just an empty configuration will
* be used.
*
* @param failIfDaemonOrTool if {@code true} and a call to {@link #daemonInitialization()} or
* {@link #toolInitialization()} has been performed before, an
* {@link AssertionError} will be thrown.
*/
public static void clientInitialization(boolean failIfDaemonOrTool)
{
if (!failIfDaemonOrTool && (daemonInitialized || toolInitialized))
{
return;
}
else
{
if (daemonInitialized)
throw new AssertionError("daemonInitialization() already called");
if (toolInitialized)
throw new AssertionError("toolInitialization() already called");
}
if (clientInitialized)
return;
clientInitialized = true;
Config.setClientMode(true);
conf = new Config();
diskOptimizationStrategy = new SpinningDiskOptimizationStrategy();
}
public static boolean isClientInitialized()
{
return clientInitialized;
}
public static boolean isToolInitialized()
{
return toolInitialized;
}
public static boolean isClientOrToolInitialized()
{
return clientInitialized || toolInitialized;
}
public static boolean isDaemonInitialized()
{
return daemonInitialized;
}
public static Config getRawConfig()
{
return conf;
}
@VisibleForTesting
public static Config loadConfig() throws ConfigurationException
{
if (Config.getOverrideLoadConfig() != null)
return Config.getOverrideLoadConfig().get();
String loaderClass = System.getProperty(Config.PROPERTY_PREFIX + "config.loader");
ConfigurationLoader loader = loaderClass == null
? new YamlConfigurationLoader()
: FBUtilities.construct(loaderClass, "configuration loading");
Config config = loader.loadConfig();
if (!hasLoggedConfig)
{
hasLoggedConfig = true;
Config.log(config);
}
return config;
}
private static InetAddress getNetworkInterfaceAddress(String intf, String configName, boolean preferIPv6) throws ConfigurationException
{
try
{
NetworkInterface ni = NetworkInterface.getByName(intf);
if (ni == null)
throw new ConfigurationException("Configured " + configName + " \"" + intf + "\" could not be found", false);
Enumeration<InetAddress> addrs = ni.getInetAddresses();
if (!addrs.hasMoreElements())
throw new ConfigurationException("Configured " + configName + " \"" + intf + "\" was found, but had no addresses", false);
/*
* Try to return the first address of the preferred type, otherwise return the first address
*/
InetAddress retval = null;
while (addrs.hasMoreElements())
{
InetAddress temp = addrs.nextElement();
if (preferIPv6 && temp instanceof Inet6Address) return temp;
if (!preferIPv6 && temp instanceof Inet4Address) return temp;
if (retval == null) retval = temp;
}
return retval;
}
catch (SocketException e)
{
throw new ConfigurationException("Configured " + configName + " \"" + intf + "\" caused an exception", e);
}
}
private static void setConfig(Config config)
{
conf = config;
}
private static void applyAll() throws ConfigurationException
{
//InetAddressAndPort cares that applySimpleConfig runs first
applySimpleConfig();
applyPartitioner();
applyAddressConfig();
applySnitch();
applyTokensConfig();
applySeedProvider();
applyEncryptionContext();
applySslContext();
}
private static void applySimpleConfig()
{
//Doing this first before all other things in case other pieces of config want to construct
//InetAddressAndPort and get the right defaults
InetAddressAndPort.initializeDefaultPort(getStoragePort());
if (conf.commitlog_sync == null)
{
throw new ConfigurationException("Missing required directive CommitLogSync", false);
}
if (conf.commitlog_sync == Config.CommitLogSync.batch)
{
if (conf.commitlog_sync_period_in_ms != 0)
{
throw new ConfigurationException("Batch sync specified, but commitlog_sync_period_in_ms found. Only specify commitlog_sync_batch_window_in_ms when using batch sync", false);
}
logger.debug("Syncing log with batch mode");
}
else if (conf.commitlog_sync == CommitLogSync.group)
{
if (Double.isNaN(conf.commitlog_sync_group_window_in_ms) || conf.commitlog_sync_group_window_in_ms <= 0d)
{
throw new ConfigurationException("Missing value for commitlog_sync_group_window_in_ms: positive double value expected.", false);
}
else if (conf.commitlog_sync_period_in_ms != 0)
{
throw new ConfigurationException("Group sync specified, but commitlog_sync_period_in_ms found. Only specify commitlog_sync_group_window_in_ms when using group sync", false);
}
logger.debug("Syncing log with a group window of {}", conf.commitlog_sync_period_in_ms);
}
else
{
if (conf.commitlog_sync_period_in_ms <= 0)
{
throw new ConfigurationException("Missing value for commitlog_sync_period_in_ms: positive integer expected", false);
}
else if (!Double.isNaN(conf.commitlog_sync_batch_window_in_ms))
{
throw new ConfigurationException("commitlog_sync_period_in_ms specified, but commitlog_sync_batch_window_in_ms found. Only specify commitlog_sync_period_in_ms when using periodic sync.", false);
}
logger.debug("Syncing log with a period of {}", conf.commitlog_sync_period_in_ms);
}
/* evaluate the DiskAccessMode Config directive, which also affects indexAccessMode selection */
if (conf.disk_access_mode == Config.DiskAccessMode.auto)
{
conf.disk_access_mode = hasLargeAddressSpace() ? Config.DiskAccessMode.mmap : Config.DiskAccessMode.standard;
indexAccessMode = conf.disk_access_mode;
logger.info("DiskAccessMode 'auto' determined to be {}, indexAccessMode is {}", conf.disk_access_mode, indexAccessMode);
}
else if (conf.disk_access_mode == Config.DiskAccessMode.mmap_index_only)
{
conf.disk_access_mode = Config.DiskAccessMode.standard;
indexAccessMode = Config.DiskAccessMode.mmap;
logger.info("DiskAccessMode is {}, indexAccessMode is {}", conf.disk_access_mode, indexAccessMode);
}
else
{
indexAccessMode = conf.disk_access_mode;
logger.info("DiskAccessMode is {}, indexAccessMode is {}", conf.disk_access_mode, indexAccessMode);
}
if (conf.gc_warn_threshold_in_ms < 0)
{
throw new ConfigurationException("gc_warn_threshold_in_ms must be a positive integer");
}
/* phi convict threshold for FailureDetector */
if (conf.phi_convict_threshold < 5 || conf.phi_convict_threshold > 16)
{
throw new ConfigurationException("phi_convict_threshold must be between 5 and 16, but was " + conf.phi_convict_threshold, false);
}
/* Thread per pool */
if (conf.concurrent_reads < 2)
{
throw new ConfigurationException("concurrent_reads must be at least 2, but was " + conf.concurrent_reads, false);
}
if (conf.concurrent_writes < 2 && System.getProperty("cassandra.test.fail_mv_locks_count", "").isEmpty())
{
throw new ConfigurationException("concurrent_writes must be at least 2, but was " + conf.concurrent_writes, false);
}
if (conf.concurrent_counter_writes < 2)
throw new ConfigurationException("concurrent_counter_writes must be at least 2, but was " + conf.concurrent_counter_writes, false);
if (conf.concurrent_replicates != null)
logger.warn("concurrent_replicates has been deprecated and should be removed from cassandra.yaml");
if (conf.networking_cache_size_in_mb == null)
conf.networking_cache_size_in_mb = Math.min(128, (int) (Runtime.getRuntime().maxMemory() / (16 * 1048576)));
if (conf.file_cache_size_in_mb == null)
conf.file_cache_size_in_mb = Math.min(512, (int) (Runtime.getRuntime().maxMemory() / (4 * 1048576)));
// round down for SSDs and round up for spinning disks
if (conf.file_cache_round_up == null)
conf.file_cache_round_up = conf.disk_optimization_strategy == Config.DiskOptimizationStrategy.spinning;
if (conf.memtable_offheap_space_in_mb == null)
conf.memtable_offheap_space_in_mb = (int) (Runtime.getRuntime().maxMemory() / (4 * 1048576));
if (conf.memtable_offheap_space_in_mb < 0)
throw new ConfigurationException("memtable_offheap_space_in_mb must be positive, but was " + conf.memtable_offheap_space_in_mb, false);
// for the moment, we default to twice as much on-heap space as off-heap, as heap overhead is very large
if (conf.memtable_heap_space_in_mb == null)
conf.memtable_heap_space_in_mb = (int) (Runtime.getRuntime().maxMemory() / (4 * 1048576));
if (conf.memtable_heap_space_in_mb <= 0)
throw new ConfigurationException("memtable_heap_space_in_mb must be positive, but was " + conf.memtable_heap_space_in_mb, false);
logger.info("Global memtable on-heap threshold is enabled at {}MB", conf.memtable_heap_space_in_mb);
if (conf.memtable_offheap_space_in_mb == 0)
logger.info("Global memtable off-heap threshold is disabled, HeapAllocator will be used instead");
else
logger.info("Global memtable off-heap threshold is enabled at {}MB", conf.memtable_offheap_space_in_mb);
if (conf.repair_session_max_tree_depth != null)
{
logger.warn("repair_session_max_tree_depth has been deprecated and should be removed from cassandra.yaml. Use repair_session_space_in_mb instead");
if (conf.repair_session_max_tree_depth < 10)
throw new ConfigurationException("repair_session_max_tree_depth should not be < 10, but was " + conf.repair_session_max_tree_depth);
if (conf.repair_session_max_tree_depth > 20)
logger.warn("repair_session_max_tree_depth of " + conf.repair_session_max_tree_depth + " > 20 could lead to excessive memory usage");
}
else
{
conf.repair_session_max_tree_depth = 20;
}
if (conf.repair_session_space_in_mb == null)
conf.repair_session_space_in_mb = Math.max(1, (int) (Runtime.getRuntime().maxMemory() / (16 * 1048576)));
if (conf.repair_session_space_in_mb < 1)
throw new ConfigurationException("repair_session_space_in_mb must be > 0, but was " + conf.repair_session_space_in_mb);
else if (conf.repair_session_space_in_mb > (int) (Runtime.getRuntime().maxMemory() / (4 * 1048576)))
logger.warn("A repair_session_space_in_mb of " + conf.repair_session_space_in_mb + " megabytes is likely to cause heap pressure");
checkForLowestAcceptedTimeouts(conf);
checkValidForByteConversion(conf.native_transport_max_frame_size_in_mb,
"native_transport_max_frame_size_in_mb", ByteUnit.MEBI_BYTES);
checkValidForByteConversion(conf.column_index_size_in_kb,
"column_index_size_in_kb", ByteUnit.KIBI_BYTES);
checkValidForByteConversion(conf.column_index_cache_size_in_kb,
"column_index_cache_size_in_kb", ByteUnit.KIBI_BYTES);
checkValidForByteConversion(conf.batch_size_warn_threshold_in_kb,
"batch_size_warn_threshold_in_kb", ByteUnit.KIBI_BYTES);
if (conf.native_transport_max_negotiable_protocol_version != null)
logger.warn("The configuration option native_transport_max_negotiable_protocol_version has been deprecated " +
"and should be removed from cassandra.yaml as it has no longer has any effect.");
// if data dirs, commitlog dir, or saved caches dir are set in cassandra.yaml, use that. Otherwise,
// use -Dcassandra.storagedir (set in cassandra-env.sh) as the parent dir for data/, commitlog/, and saved_caches/
if (conf.commitlog_directory == null)
{
conf.commitlog_directory = storagedirFor("commitlog");
}
if (conf.hints_directory == null)
{
conf.hints_directory = storagedirFor("hints");
}
if (conf.native_transport_max_concurrent_requests_in_bytes <= 0)
{
conf.native_transport_max_concurrent_requests_in_bytes = Runtime.getRuntime().maxMemory() / 10;
}
if (conf.native_transport_max_concurrent_requests_in_bytes_per_ip <= 0)
{
conf.native_transport_max_concurrent_requests_in_bytes_per_ip = Runtime.getRuntime().maxMemory() / 40;
}
if (conf.commitlog_total_space_in_mb == null)
{
final int preferredSizeInMB = 8192;
try
{
// use 1/4 of available space. See discussion on #10013 and #10199
final long totalSpaceInBytes = guessFileStore(conf.commitlog_directory).getTotalSpace();
conf.commitlog_total_space_in_mb = calculateDefaultSpaceInMB("commitlog",
conf.commitlog_directory,
"commitlog_total_space_in_mb",
preferredSizeInMB,
totalSpaceInBytes, 1, 4);
}
catch (IOException e)
{
logger.debug("Error checking disk space", e);
throw new ConfigurationException(String.format("Unable to check disk space available to '%s'. Perhaps the Cassandra user does not have the necessary permissions",
conf.commitlog_directory), e);
}
}
if (conf.cdc_enabled)
{
// Windows memory-mapped CommitLog files is incompatible with CDC as we hard-link files in cdc_raw. Confirm we don't have both enabled.
if (FBUtilities.isWindows && conf.commitlog_compression == null)
throw new ConfigurationException("Cannot enable cdc on Windows with uncompressed commitlog.");
if (conf.cdc_raw_directory == null)
{
conf.cdc_raw_directory = storagedirFor("cdc_raw");
}
if (conf.cdc_total_space_in_mb == 0)
{
final int preferredSizeInMB = 4096;
try
{
// use 1/8th of available space. See discussion on #10013 and #10199 on the CL, taking half that for CDC
final long totalSpaceInBytes = guessFileStore(conf.cdc_raw_directory).getTotalSpace();
conf.cdc_total_space_in_mb = calculateDefaultSpaceInMB("cdc",
conf.cdc_raw_directory,
"cdc_total_space_in_mb",
preferredSizeInMB,
totalSpaceInBytes, 1, 8);
}
catch (IOException e)
{
logger.debug("Error checking disk space", e);
throw new ConfigurationException(String.format("Unable to check disk space available to '%s'. Perhaps the Cassandra user does not have the necessary permissions",
conf.cdc_raw_directory), e);
}
}
logger.info("cdc_enabled is true. Starting casssandra node with Change-Data-Capture enabled.");
}
if (conf.saved_caches_directory == null)
{
conf.saved_caches_directory = storagedirFor("saved_caches");
}
if (conf.data_file_directories == null || conf.data_file_directories.length == 0)
{
conf.data_file_directories = new String[]{ storagedir("data_file_directories") + File.separator + "data" };
}
long dataFreeBytes = 0;
/* data file and commit log directories. they get created later, when they're needed. */
for (String datadir : conf.data_file_directories)
{
if (datadir == null)
throw new ConfigurationException("data_file_directories must not contain empty entry", false);
if (datadir.equals(conf.commitlog_directory))
throw new ConfigurationException("commitlog_directory must not be the same as any data_file_directories", false);
if (datadir.equals(conf.hints_directory))
throw new ConfigurationException("hints_directory must not be the same as any data_file_directories", false);
if (datadir.equals(conf.saved_caches_directory))
throw new ConfigurationException("saved_caches_directory must not be the same as any data_file_directories", false);
try
{
dataFreeBytes = saturatedSum(dataFreeBytes, guessFileStore(datadir).getUnallocatedSpace());
}
catch (IOException e)
{
logger.debug("Error checking disk space", e);
throw new ConfigurationException(String.format("Unable to check disk space available to %s. Perhaps the Cassandra user does not have the necessary permissions",
datadir), e);
}
}
if (dataFreeBytes < 64 * ONE_GB) // 64 GB
logger.warn("Only {} free across all data volumes. Consider adding more capacity to your cluster or removing obsolete snapshots",
FBUtilities.prettyPrintMemory(dataFreeBytes));
if (conf.commitlog_directory.equals(conf.saved_caches_directory))
throw new ConfigurationException("saved_caches_directory must not be the same as the commitlog_directory", false);
if (conf.commitlog_directory.equals(conf.hints_directory))
throw new ConfigurationException("hints_directory must not be the same as the commitlog_directory", false);
if (conf.hints_directory.equals(conf.saved_caches_directory))
throw new ConfigurationException("saved_caches_directory must not be the same as the hints_directory", false);
if (conf.memtable_flush_writers == 0)
{
conf.memtable_flush_writers = conf.data_file_directories.length == 1 ? 2 : 1;
}
if (conf.memtable_flush_writers < 1)
throw new ConfigurationException("memtable_flush_writers must be at least 1, but was " + conf.memtable_flush_writers, false);
if (conf.memtable_cleanup_threshold == null)
{
conf.memtable_cleanup_threshold = (float) (1.0 / (1 + conf.memtable_flush_writers));
}
else
{
logger.warn("memtable_cleanup_threshold has been deprecated and should be removed from cassandra.yaml");
}
if (conf.memtable_cleanup_threshold < 0.01f)
throw new ConfigurationException("memtable_cleanup_threshold must be >= 0.01, but was " + conf.memtable_cleanup_threshold, false);
if (conf.memtable_cleanup_threshold > 0.99f)
throw new ConfigurationException("memtable_cleanup_threshold must be <= 0.99, but was " + conf.memtable_cleanup_threshold, false);
if (conf.memtable_cleanup_threshold < 0.1f)
logger.warn("memtable_cleanup_threshold is set very low [{}], which may cause performance degradation", conf.memtable_cleanup_threshold);
if (conf.concurrent_compactors == null)
conf.concurrent_compactors = Math.min(8, Math.max(2, Math.min(FBUtilities.getAvailableProcessors(), conf.data_file_directories.length)));
if (conf.concurrent_compactors <= 0)
throw new ConfigurationException("concurrent_compactors should be strictly greater than 0, but was " + conf.concurrent_compactors, false);
applyConcurrentValidations(conf);
applyRepairCommandPoolSize(conf);
if (conf.concurrent_materialized_view_builders <= 0)
throw new ConfigurationException("concurrent_materialized_view_builders should be strictly greater than 0, but was " + conf.concurrent_materialized_view_builders, false);
if (conf.num_tokens != null && conf.num_tokens > MAX_NUM_TOKENS)
throw new ConfigurationException(String.format("A maximum number of %d tokens per node is supported", MAX_NUM_TOKENS), false);
try
{
// if prepared_statements_cache_size_mb option was set to "auto" then size of the cache should be "max(1/256 of Heap (in MB), 10MB)"
preparedStatementsCacheSizeInMB = (conf.prepared_statements_cache_size_mb == null)
? Math.max(10, (int) (Runtime.getRuntime().maxMemory() / 1024 / 1024 / 256))
: conf.prepared_statements_cache_size_mb;
if (preparedStatementsCacheSizeInMB <= 0)
throw new NumberFormatException(); // to escape duplicating error message
}
catch (NumberFormatException e)
{
throw new ConfigurationException("prepared_statements_cache_size_mb option was set incorrectly to '"
+ conf.prepared_statements_cache_size_mb + "', supported values are <integer> >= 0.", false);
}
try
{
// if key_cache_size_in_mb option was set to "auto" then size of the cache should be "min(5% of Heap (in MB), 100MB)
keyCacheSizeInMB = (conf.key_cache_size_in_mb == null)
? Math.min(Math.max(1, (int) (Runtime.getRuntime().totalMemory() * 0.05 / 1024 / 1024)), 100)
: conf.key_cache_size_in_mb;
if (keyCacheSizeInMB < 0)
throw new NumberFormatException(); // to escape duplicating error message
}
catch (NumberFormatException e)
{
throw new ConfigurationException("key_cache_size_in_mb option was set incorrectly to '"
+ conf.key_cache_size_in_mb + "', supported values are <integer> >= 0.", false);
}
try
{
// if counter_cache_size_in_mb option was set to "auto" then size of the cache should be "min(2.5% of Heap (in MB), 50MB)
counterCacheSizeInMB = (conf.counter_cache_size_in_mb == null)
? Math.min(Math.max(1, (int) (Runtime.getRuntime().totalMemory() * 0.025 / 1024 / 1024)), 50)
: conf.counter_cache_size_in_mb;
if (counterCacheSizeInMB < 0)
throw new NumberFormatException(); // to escape duplicating error message
}
catch (NumberFormatException e)
{
throw new ConfigurationException("counter_cache_size_in_mb option was set incorrectly to '"
+ conf.counter_cache_size_in_mb + "', supported values are <integer> >= 0.", false);
}
// if set to empty/"auto" then use 5% of Heap size
indexSummaryCapacityInMB = (conf.index_summary_capacity_in_mb == null)
? Math.max(1, (int) (Runtime.getRuntime().totalMemory() * 0.05 / 1024 / 1024))
: conf.index_summary_capacity_in_mb;
if (indexSummaryCapacityInMB < 0)
throw new ConfigurationException("index_summary_capacity_in_mb option was set incorrectly to '"
+ conf.index_summary_capacity_in_mb + "', it should be a non-negative integer.", false);
if (conf.user_defined_function_fail_timeout < 0)
throw new ConfigurationException("user_defined_function_fail_timeout must not be negative", false);
if (conf.user_defined_function_warn_timeout < 0)
throw new ConfigurationException("user_defined_function_warn_timeout must not be negative", false);
if (conf.user_defined_function_fail_timeout < conf.user_defined_function_warn_timeout)
throw new ConfigurationException("user_defined_function_warn_timeout must less than user_defined_function_fail_timeout", false);
if (conf.commitlog_segment_size_in_mb <= 0)
throw new ConfigurationException("commitlog_segment_size_in_mb must be positive, but was "
+ conf.commitlog_segment_size_in_mb, false);
else if (conf.commitlog_segment_size_in_mb >= 2048)
throw new ConfigurationException("commitlog_segment_size_in_mb must be smaller than 2048, but was "
+ conf.commitlog_segment_size_in_mb, false);
if (conf.max_mutation_size_in_kb == null)
conf.max_mutation_size_in_kb = conf.commitlog_segment_size_in_mb * 1024 / 2;
else if (conf.commitlog_segment_size_in_mb * 1024 < 2 * conf.max_mutation_size_in_kb)
throw new ConfigurationException("commitlog_segment_size_in_mb must be at least twice the size of max_mutation_size_in_kb / 1024", false);
// native transport encryption options
if (conf.client_encryption_options != null)
{
conf.client_encryption_options.applyConfig();
if (conf.native_transport_port_ssl != null
&& conf.native_transport_port_ssl != conf.native_transport_port
&& conf.client_encryption_options.tlsEncryptionPolicy() == EncryptionOptions.TlsEncryptionPolicy.UNENCRYPTED)
{
throw new ConfigurationException("Encryption must be enabled in client_encryption_options for native_transport_port_ssl", false);
}
}
if (conf.snapshot_links_per_second < 0)
throw new ConfigurationException("snapshot_links_per_second must be >= 0");
if (conf.max_value_size_in_mb <= 0)
throw new ConfigurationException("max_value_size_in_mb must be positive", false);
else if (conf.max_value_size_in_mb >= 2048)
throw new ConfigurationException("max_value_size_in_mb must be smaller than 2048, but was "
+ conf.max_value_size_in_mb, false);
switch (conf.disk_optimization_strategy)
{
case ssd:
diskOptimizationStrategy = new SsdDiskOptimizationStrategy(conf.disk_optimization_page_cross_chance);
break;
case spinning:
diskOptimizationStrategy = new SpinningDiskOptimizationStrategy();
break;
}
if (conf.otc_coalescing_enough_coalesced_messages > 128)
throw new ConfigurationException("otc_coalescing_enough_coalesced_messages must be smaller than 128", false);
if (conf.otc_coalescing_enough_coalesced_messages <= 0)
throw new ConfigurationException("otc_coalescing_enough_coalesced_messages must be positive", false);
if (conf.server_encryption_options != null)
{
conf.server_encryption_options.applyConfig();
if (conf.server_encryption_options.enable_legacy_ssl_storage_port &&
conf.server_encryption_options.tlsEncryptionPolicy() == EncryptionOptions.TlsEncryptionPolicy.UNENCRYPTED)
{
throw new ConfigurationException("enable_legacy_ssl_storage_port is true (enabled) with internode encryption disabled (none). Enable encryption or disable the legacy ssl storage port.");
}
}
Integer maxMessageSize = conf.internode_max_message_size_in_bytes;
if (maxMessageSize != null)
{
if (maxMessageSize > conf.internode_application_receive_queue_reserve_endpoint_capacity_in_bytes)
throw new ConfigurationException("internode_max_message_size_in_mb must no exceed internode_application_receive_queue_reserve_endpoint_capacity_in_bytes", false);
if (maxMessageSize > conf.internode_application_receive_queue_reserve_global_capacity_in_bytes)
throw new ConfigurationException("internode_max_message_size_in_mb must no exceed internode_application_receive_queue_reserve_global_capacity_in_bytes", false);
if (maxMessageSize > conf.internode_application_send_queue_reserve_endpoint_capacity_in_bytes)
throw new ConfigurationException("internode_max_message_size_in_mb must no exceed internode_application_send_queue_reserve_endpoint_capacity_in_bytes", false);
if (maxMessageSize > conf.internode_application_send_queue_reserve_global_capacity_in_bytes)
throw new ConfigurationException("internode_max_message_size_in_mb must no exceed internode_application_send_queue_reserve_global_capacity_in_bytes", false);
}
else
{
conf.internode_max_message_size_in_bytes =
Math.min(conf.internode_application_receive_queue_reserve_endpoint_capacity_in_bytes,
conf.internode_application_send_queue_reserve_endpoint_capacity_in_bytes);
}
validateMaxConcurrentAutoUpgradeTasksConf(conf.max_concurrent_automatic_sstable_upgrades);
}
@VisibleForTesting
static void applyConcurrentValidations(Config config)
{
if (config.concurrent_validations < 1)
{
config.concurrent_validations = config.concurrent_compactors;
}
else if (config.concurrent_validations > config.concurrent_compactors && !allowUnlimitedConcurrentValidations)
{
throw new ConfigurationException("To set concurrent_validations > concurrent_compactors, " +
"set the system property cassandra.allow_unlimited_concurrent_validations=true");
}
}
@VisibleForTesting
static void applyRepairCommandPoolSize(Config config)
{
if (config.repair_command_pool_size < 1)
config.repair_command_pool_size = config.concurrent_validations;
}
private static String storagedirFor(String type)
{
return storagedir(type + "_directory") + File.separator + type;
}
private static String storagedir(String errMsgType)
{
String storagedir = System.getProperty(Config.PROPERTY_PREFIX + "storagedir", null);
if (storagedir == null)
throw new ConfigurationException(errMsgType + " is missing and -Dcassandra.storagedir is not set", false);
return storagedir;
}
static int calculateDefaultSpaceInMB(String type, String path, String setting, int preferredSizeInMB, long totalSpaceInBytes, long totalSpaceNumerator, long totalSpaceDenominator)
{
final long totalSizeInMB = totalSpaceInBytes / ONE_MB;
final int minSizeInMB = Ints.saturatedCast(totalSpaceNumerator * totalSizeInMB / totalSpaceDenominator);
if (minSizeInMB < preferredSizeInMB)
{
logger.warn("Small {} volume detected at '{}'; setting {} to {}. You can override this in cassandra.yaml",
type, path, setting, minSizeInMB);
return minSizeInMB;
}
else
{
return preferredSizeInMB;
}
}
public static void applyAddressConfig() throws ConfigurationException
{
applyAddressConfig(conf);
}
public static void applyAddressConfig(Config config) throws ConfigurationException
{
listenAddress = null;
rpcAddress = null;
broadcastAddress = null;
broadcastRpcAddress = null;
/* Local IP, hostname or interface to bind services to */
if (config.listen_address != null && config.listen_interface != null)
{
throw new ConfigurationException("Set listen_address OR listen_interface, not both", false);
}
else if (config.listen_address != null)
{
try
{
listenAddress = InetAddress.getByName(config.listen_address);
}
catch (UnknownHostException e)
{
throw new ConfigurationException("Unknown listen_address '" + config.listen_address + '\'', false);
}
if (listenAddress.isAnyLocalAddress())
throw new ConfigurationException("listen_address cannot be a wildcard address (" + config.listen_address + ")!", false);
}
else if (config.listen_interface != null)
{
listenAddress = getNetworkInterfaceAddress(config.listen_interface, "listen_interface", config.listen_interface_prefer_ipv6);
}
/* Gossip Address to broadcast */
if (config.broadcast_address != null)
{
try
{
broadcastAddress = InetAddress.getByName(config.broadcast_address);
}
catch (UnknownHostException e)
{
throw new ConfigurationException("Unknown broadcast_address '" + config.broadcast_address + '\'', false);
}
if (broadcastAddress.isAnyLocalAddress())
throw new ConfigurationException("broadcast_address cannot be a wildcard address (" + config.broadcast_address + ")!", false);
}
/* Local IP, hostname or interface to bind RPC server to */
if (config.rpc_address != null && config.rpc_interface != null)
{
throw new ConfigurationException("Set rpc_address OR rpc_interface, not both", false);
}
else if (config.rpc_address != null)
{
try
{
rpcAddress = InetAddress.getByName(config.rpc_address);
}
catch (UnknownHostException e)
{
throw new ConfigurationException("Unknown host in rpc_address " + config.rpc_address, false);
}
}
else if (config.rpc_interface != null)
{
rpcAddress = getNetworkInterfaceAddress(config.rpc_interface, "rpc_interface", config.rpc_interface_prefer_ipv6);
}
else
{
rpcAddress = FBUtilities.getJustLocalAddress();
}
/* RPC address to broadcast */
if (config.broadcast_rpc_address != null)
{
try
{
broadcastRpcAddress = InetAddress.getByName(config.broadcast_rpc_address);
}
catch (UnknownHostException e)
{
throw new ConfigurationException("Unknown broadcast_rpc_address '" + config.broadcast_rpc_address + '\'', false);
}
if (broadcastRpcAddress.isAnyLocalAddress())
throw new ConfigurationException("broadcast_rpc_address cannot be a wildcard address (" + config.broadcast_rpc_address + ")!", false);
}
else
{
if (rpcAddress.isAnyLocalAddress())
throw new ConfigurationException("If rpc_address is set to a wildcard address (" + config.rpc_address + "), then " +
"you must set broadcast_rpc_address to a value other than " + config.rpc_address, false);
}
}
public static void applyEncryptionContext()
{
// always attempt to load the cipher factory, as we could be in the situation where the user has disabled encryption,
// but has existing commitlogs and sstables on disk that are still encrypted (and still need to be read)
encryptionContext = new EncryptionContext(conf.transparent_data_encryption_options);
}
public static void applySslContext()
{
try
{
SSLFactory.validateSslContext("Internode messaging", conf.server_encryption_options, true, true);
SSLFactory.validateSslContext("Native transport", conf.client_encryption_options, conf.client_encryption_options.require_client_auth, true);
SSLFactory.initHotReloading(conf.server_encryption_options, conf.client_encryption_options, false);
}
catch (IOException e)
{