/
CFMetaData.java
2300 lines (2009 loc) · 106 KB
/
CFMetaData.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.DataInput;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.nio.ByteBuffer;
import java.util.*;
import java.util.concurrent.ThreadLocalRandom;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Objects;
import com.google.common.base.Strings;
import com.google.common.collect.*;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.cassandra.cache.CachingOptions;
import org.apache.cassandra.cql3.ColumnIdentifier;
import org.apache.cassandra.cql3.QueryProcessor;
import org.apache.cassandra.cql3.UntypedResultSet;
import org.apache.cassandra.cql3.statements.CFStatement;
import org.apache.cassandra.cql3.statements.CreateTableStatement;
import org.apache.cassandra.db.*;
import org.apache.cassandra.db.compaction.*;
import org.apache.cassandra.db.composites.*;
import org.apache.cassandra.db.index.SecondaryIndex;
import org.apache.cassandra.db.marshal.*;
import org.apache.cassandra.exceptions.*;
import org.apache.cassandra.io.compress.CompressionParameters;
import org.apache.cassandra.io.compress.LZ4Compressor;
import org.apache.cassandra.io.sstable.Descriptor;
import org.apache.cassandra.serializers.MarshalException;
import org.apache.cassandra.thrift.CfDef;
import org.apache.cassandra.thrift.CqlResult;
import org.apache.cassandra.thrift.CqlRow;
import org.apache.cassandra.tracing.Tracing;
import org.apache.cassandra.utils.ByteBufferUtil;
import org.apache.cassandra.utils.FBUtilities;
import org.apache.cassandra.utils.Pair;
import org.apache.cassandra.utils.UUIDGen;
import org.github.jamm.Unmetered;
import static org.apache.cassandra.utils.FBUtilities.fromJsonList;
import static org.apache.cassandra.utils.FBUtilities.fromJsonMap;
import static org.apache.cassandra.utils.FBUtilities.json;
/**
* This class can be tricky to modify. Please read http://wiki.apache.org/cassandra/ConfigurationNotes for how to do so safely.
*/
@Unmetered
public final class CFMetaData
{
private static final Logger logger = LoggerFactory.getLogger(CFMetaData.class);
public final static double DEFAULT_READ_REPAIR_CHANCE = 0.0;
public final static double DEFAULT_DCLOCAL_READ_REPAIR_CHANCE = 0.1;
public final static int DEFAULT_GC_GRACE_SECONDS = 864000;
public final static int DEFAULT_MIN_COMPACTION_THRESHOLD = 4;
public final static int DEFAULT_MAX_COMPACTION_THRESHOLD = 32;
public final static Class<? extends AbstractCompactionStrategy> DEFAULT_COMPACTION_STRATEGY_CLASS = SizeTieredCompactionStrategy.class;
public final static CachingOptions DEFAULT_CACHING_STRATEGY = CachingOptions.KEYS_ONLY;
public final static int DEFAULT_DEFAULT_TIME_TO_LIVE = 0;
public final static SpeculativeRetry DEFAULT_SPECULATIVE_RETRY = new SpeculativeRetry(SpeculativeRetry.RetryType.PERCENTILE, 0.99);
public final static int DEFAULT_MIN_INDEX_INTERVAL = 128;
public final static int DEFAULT_MAX_INDEX_INTERVAL = 2048;
// Note that this is the default only for user created tables
public final static String DEFAULT_COMPRESSOR = LZ4Compressor.class.getCanonicalName();
// Note that this need to come *before* any CFMetaData is defined so before the compile below.
private static final Comparator<ColumnDefinition> regularColumnComparator = new Comparator<ColumnDefinition>()
{
public int compare(ColumnDefinition def1, ColumnDefinition def2)
{
return ByteBufferUtil.compareUnsigned(def1.name.bytes, def2.name.bytes);
}
};
public static final CFMetaData IndexCf = compile("CREATE TABLE \"" + SystemKeyspace.INDEX_CF + "\" ("
+ "table_name text,"
+ "index_name text,"
+ "PRIMARY KEY (table_name, index_name)"
+ ") WITH COMPACT STORAGE AND COMMENT='indexes that have been completed'");
public static final CFMetaData SchemaKeyspacesCf = compile("CREATE TABLE " + SystemKeyspace.SCHEMA_KEYSPACES_CF + " ("
+ "keyspace_name text PRIMARY KEY,"
+ "durable_writes boolean,"
+ "strategy_class text,"
+ "strategy_options text"
+ ") WITH COMPACT STORAGE AND COMMENT='keyspace definitions' AND gc_grace_seconds=604800");
public static final CFMetaData SchemaColumnFamiliesCf = compile("CREATE TABLE " + SystemKeyspace.SCHEMA_COLUMNFAMILIES_CF + " ("
+ "keyspace_name text,"
+ "columnfamily_name text,"
+ "cf_id uuid," // post-2.1 UUID cfid
+ "type text,"
+ "is_dense boolean,"
+ "comparator text,"
+ "subcomparator text,"
+ "comment text,"
+ "read_repair_chance double,"
+ "local_read_repair_chance double,"
+ "gc_grace_seconds int,"
+ "default_validator text,"
+ "key_validator text,"
+ "min_compaction_threshold int,"
+ "max_compaction_threshold int,"
+ "memtable_flush_period_in_ms int,"
+ "key_aliases text,"
+ "bloom_filter_fp_chance double,"
+ "caching text,"
+ "default_time_to_live int,"
+ "compaction_strategy_class text,"
+ "compression_parameters text,"
+ "value_alias text,"
+ "column_aliases text,"
+ "compaction_strategy_options text,"
+ "speculative_retry text,"
+ "index_interval int,"
+ "min_index_interval int,"
+ "max_index_interval int,"
+ "dropped_columns map<text, bigint>,"
+ "PRIMARY KEY (keyspace_name, columnfamily_name)"
+ ") WITH COMMENT='ColumnFamily definitions' AND gc_grace_seconds=604800");
public static final CFMetaData SchemaColumnsCf = compile("CREATE TABLE " + SystemKeyspace.SCHEMA_COLUMNS_CF + " ("
+ "keyspace_name text,"
+ "columnfamily_name text,"
+ "column_name text,"
+ "validator text,"
+ "index_type text,"
+ "index_options text,"
+ "index_name text,"
+ "component_index int,"
+ "type text,"
+ "PRIMARY KEY(keyspace_name, columnfamily_name, column_name)"
+ ") WITH COMMENT='ColumnFamily column attributes' AND gc_grace_seconds=604800");
public static final CFMetaData SchemaTriggersCf = compile("CREATE TABLE " + SystemKeyspace.SCHEMA_TRIGGERS_CF + " ("
+ "keyspace_name text,"
+ "columnfamily_name text,"
+ "trigger_name text,"
+ "trigger_options map<text, text>,"
+ "PRIMARY KEY (keyspace_name, columnfamily_name, trigger_name)"
+ ") WITH COMMENT='triggers metadata table' AND gc_grace_seconds=604800");
public static final CFMetaData SchemaUserTypesCf = compile("CREATE TABLE " + SystemKeyspace.SCHEMA_USER_TYPES_CF + " ("
+ "keyspace_name text,"
+ "type_name text,"
+ "field_names list<text>,"
+ "field_types list<text>,"
+ "PRIMARY KEY (keyspace_name, type_name)"
+ ") WITH COMMENT='Defined user types' AND gc_grace_seconds=604800");
public static final CFMetaData HintsCf = compile("CREATE TABLE " + SystemKeyspace.HINTS_CF + " ("
+ "target_id uuid,"
+ "hint_id timeuuid,"
+ "message_version int,"
+ "mutation blob,"
+ "PRIMARY KEY (target_id, hint_id, message_version)"
+ ") WITH COMPACT STORAGE "
+ "AND COMPACTION={'class' : 'SizeTieredCompactionStrategy', 'enabled' : false} "
+ "AND COMMENT='hints awaiting delivery'"
+ "AND gc_grace_seconds=0");
public static final CFMetaData PeersCf = compile("CREATE TABLE " + SystemKeyspace.PEERS_CF + " ("
+ "peer inet PRIMARY KEY,"
+ "host_id uuid,"
+ "tokens set<varchar>,"
+ "schema_version uuid,"
+ "release_version text,"
+ "rpc_address inet,"
+ "preferred_ip inet,"
+ "data_center text,"
+ "rack text"
+ ") WITH COMMENT='known peers in the cluster'");
public static final CFMetaData PeerEventsCf = compile("CREATE TABLE " + SystemKeyspace.PEER_EVENTS_CF + " ("
+ "peer inet PRIMARY KEY,"
+ "hints_dropped map<uuid, int>"
+ ") WITH COMMENT='cf contains events related to peers'");
public static final CFMetaData LocalCf = compile("CREATE TABLE " + SystemKeyspace.LOCAL_CF + " ("
+ "key text PRIMARY KEY,"
+ "tokens set<varchar>,"
+ "cluster_name text,"
+ "gossip_generation int,"
+ "bootstrapped text,"
+ "host_id uuid,"
+ "release_version text,"
+ "thrift_version text,"
+ "cql_version text,"
+ "native_protocol_version text,"
+ "data_center text,"
+ "rack text,"
+ "partitioner text,"
+ "schema_version uuid,"
+ "truncated_at map<uuid, blob>,"
+ "rpc_address inet,"
+ "broadcast_address inet,"
+ "listen_address inet"
+ ") WITH COMMENT='information about the local node'");
public static final CFMetaData TraceSessionsCf = compile("CREATE TABLE " + Tracing.SESSIONS_CF + " ("
+ "session_id uuid PRIMARY KEY,"
+ "coordinator inet,"
+ "request text,"
+ "started_at timestamp,"
+ "parameters map<text, text>,"
+ "duration int"
+ ") WITH COMMENT='traced sessions' AND default_time_to_live=86400",
Tracing.TRACE_KS);
public static final CFMetaData TraceEventsCf = compile("CREATE TABLE " + Tracing.EVENTS_CF + " ("
+ "session_id uuid,"
+ "event_id timeuuid,"
+ "source inet,"
+ "thread text,"
+ "activity text,"
+ "source_elapsed int,"
+ "PRIMARY KEY (session_id, event_id)"
+ ") WITH default_time_to_live=86400",
Tracing.TRACE_KS);
public static final CFMetaData BatchlogCf = compile("CREATE TABLE " + SystemKeyspace.BATCHLOG_CF + " ("
+ "id uuid PRIMARY KEY,"
+ "written_at timestamp,"
+ "data blob,"
+ "version int,"
+ ") WITH COMMENT='uncommited batches' AND gc_grace_seconds=0 "
+ "AND COMPACTION={'class' : 'SizeTieredCompactionStrategy', 'min_threshold' : 2}");
public static final CFMetaData RangeXfersCf = compile("CREATE TABLE " + SystemKeyspace.RANGE_XFERS_CF + " ("
+ "token_bytes blob PRIMARY KEY,"
+ "requested_at timestamp"
+ ") WITH COMMENT='ranges requested for transfer here'");
public static final CFMetaData CompactionLogCf = compile("CREATE TABLE " + SystemKeyspace.COMPACTION_LOG + " ("
+ "id uuid PRIMARY KEY,"
+ "keyspace_name text,"
+ "columnfamily_name text,"
+ "inputs set<int>"
+ ") WITH COMMENT='unfinished compactions'");
public static final CFMetaData PaxosCf = compile("CREATE TABLE " + SystemKeyspace.PAXOS_CF + " ("
+ "row_key blob,"
+ "cf_id UUID,"
+ "in_progress_ballot timeuuid,"
+ "proposal_ballot timeuuid,"
+ "proposal blob,"
+ "most_recent_commit_at timeuuid,"
+ "most_recent_commit blob,"
+ "PRIMARY KEY (row_key, cf_id)"
+ ") WITH COMMENT='in-progress paxos proposals' "
+ "AND COMPACTION={'class' : 'LeveledCompactionStrategy'}");
public static final CFMetaData SSTableActivityCF = compile("CREATE TABLE " + SystemKeyspace.SSTABLE_ACTIVITY_CF + " ("
+ "keyspace_name text,"
+ "columnfamily_name text,"
+ "generation int,"
+ "rate_15m double,"
+ "rate_120m double,"
+ "PRIMARY KEY ((keyspace_name, columnfamily_name, generation))"
+ ") WITH COMMENT='historic sstable read rates'");
public static final CFMetaData CompactionHistoryCf = compile("CREATE TABLE " + SystemKeyspace.COMPACTION_HISTORY_CF + " ("
+ "id uuid,"
+ "keyspace_name text,"
+ "columnfamily_name text,"
+ "compacted_at timestamp,"
+ "bytes_in bigint,"
+ "bytes_out bigint,"
+ "rows_merged map<int, bigint>,"
+ "PRIMARY KEY (id)"
+ ") WITH COMMENT='show all compaction history' AND DEFAULT_TIME_TO_LIVE=604800");
public static final CFMetaData SizeEstimatesCf = compile("CREATE TABLE " + SystemKeyspace.SIZE_ESTIMATES_CF + " ("
+ "keyspace_name text,"
+ "table_name text,"
+ "range_start text,"
+ "range_end text,"
+ "mean_partition_size bigint,"
+ "partitions_count bigint,"
+ "PRIMARY KEY ((keyspace_name), table_name, range_start, range_end)"
+ ") WITH COMMENT='per-table primary range size estimates' "
+ "AND gc_grace_seconds=0");
public static class SpeculativeRetry
{
public enum RetryType
{
NONE, CUSTOM, PERCENTILE, ALWAYS
}
public final RetryType type;
public final double value;
private SpeculativeRetry(RetryType type, double value)
{
this.type = type;
this.value = value;
}
public static SpeculativeRetry fromString(String retry) throws ConfigurationException
{
String name = retry.toUpperCase();
try
{
if (name.endsWith(RetryType.PERCENTILE.toString()))
{
double value = Double.parseDouble(name.substring(0, name.length() - 10));
if (value > 100 || value < 0)
throw new ConfigurationException("PERCENTILE should be between 0 and 100");
return new SpeculativeRetry(RetryType.PERCENTILE, (value / 100));
}
else if (name.endsWith("MS"))
{
double value = Double.parseDouble(name.substring(0, name.length() - 2));
return new SpeculativeRetry(RetryType.CUSTOM, value);
}
else
{
return new SpeculativeRetry(RetryType.valueOf(name), 0);
}
}
catch (IllegalArgumentException e)
{
// ignore to throw the below exception.
}
throw new ConfigurationException("invalid speculative_retry type: " + retry);
}
@Override
public boolean equals(Object obj)
{
if (!(obj instanceof SpeculativeRetry))
return false;
SpeculativeRetry rhs = (SpeculativeRetry) obj;
return Objects.equal(type, rhs.type) && Objects.equal(value, rhs.value);
}
@Override
public int hashCode()
{
return Objects.hashCode(type, value);
}
@Override
public String toString()
{
switch (type)
{
case PERCENTILE:
// TODO switch to BigDecimal so round-tripping isn't lossy
return (value * 100) + "PERCENTILE";
case CUSTOM:
return value + "ms";
default:
return type.toString();
}
}
}
//REQUIRED
public final UUID cfId; // internal id, never exposed to user
public final String ksName; // name of keyspace
public final String cfName; // name of this column family
public final Pair<String, String> ksAndCFName;
public final byte[] ksAndCFBytes;
public final ColumnFamilyType cfType; // standard, super
public volatile CellNameType comparator; // bytes, long, timeuuid, utf8, etc.
//OPTIONAL
private volatile String comment = "";
private volatile double readRepairChance = DEFAULT_READ_REPAIR_CHANCE;
private volatile double dcLocalReadRepairChance = DEFAULT_DCLOCAL_READ_REPAIR_CHANCE;
private volatile int gcGraceSeconds = DEFAULT_GC_GRACE_SECONDS;
private volatile AbstractType<?> defaultValidator = BytesType.instance;
private volatile AbstractType<?> keyValidator = BytesType.instance;
private volatile int minCompactionThreshold = DEFAULT_MIN_COMPACTION_THRESHOLD;
private volatile int maxCompactionThreshold = DEFAULT_MAX_COMPACTION_THRESHOLD;
private volatile Double bloomFilterFpChance = null;
private volatile CachingOptions caching = DEFAULT_CACHING_STRATEGY;
private volatile int minIndexInterval = DEFAULT_MIN_INDEX_INTERVAL;
private volatile int maxIndexInterval = DEFAULT_MAX_INDEX_INTERVAL;
private volatile int memtableFlushPeriod = 0;
private volatile int defaultTimeToLive = DEFAULT_DEFAULT_TIME_TO_LIVE;
private volatile SpeculativeRetry speculativeRetry = DEFAULT_SPECULATIVE_RETRY;
private volatile Map<ColumnIdentifier, Long> droppedColumns = new HashMap<>();
private volatile Map<String, TriggerDefinition> triggers = new HashMap<>();
private volatile boolean isPurged = false;
/*
* All CQL3 columns definition are stored in the columnMetadata map.
* On top of that, we keep separated collection of each kind of definition, to
* 1) allow easy access to each kind and 2) for the partition key and
* clustering key ones, those list are ordered by the "component index" of the
* elements.
*/
public static final String DEFAULT_KEY_ALIAS = "key";
public static final String DEFAULT_COLUMN_ALIAS = "column";
public static final String DEFAULT_VALUE_ALIAS = "value";
// We call dense a CF for which each component of the comparator is a clustering column, i.e. no
// component is used to store a regular column names. In other words, non-composite static "thrift"
// and CQL3 CF are *not* dense.
private volatile Boolean isDense; // null means "we don't know and need to infer from other data"
private volatile Map<ByteBuffer, ColumnDefinition> columnMetadata = new HashMap<>();
private volatile List<ColumnDefinition> partitionKeyColumns; // Always of size keyValidator.componentsCount, null padded if necessary
private volatile List<ColumnDefinition> clusteringColumns; // Of size comparator.componentsCount or comparator.componentsCount -1, null padded if necessary
private volatile SortedSet<ColumnDefinition> regularColumns; // We use a sorted set so iteration is of predictable order (for SELECT for instance)
private volatile SortedSet<ColumnDefinition> staticColumns; // Same as above
private volatile ColumnDefinition compactValueColumn;
public volatile Class<? extends AbstractCompactionStrategy> compactionStrategyClass = DEFAULT_COMPACTION_STRATEGY_CLASS;
public volatile Map<String, String> compactionStrategyOptions = new HashMap<>();
public volatile CompressionParameters compressionParameters = new CompressionParameters(null);
// attribute setters that return the modified CFMetaData instance
public CFMetaData comment(String prop) { comment = Strings.nullToEmpty(prop); return this;}
public CFMetaData readRepairChance(double prop) {readRepairChance = prop; return this;}
public CFMetaData dcLocalReadRepairChance(double prop) {dcLocalReadRepairChance = prop; return this;}
public CFMetaData gcGraceSeconds(int prop) {gcGraceSeconds = prop; return this;}
public CFMetaData defaultValidator(AbstractType<?> prop) {defaultValidator = prop; return this;}
public CFMetaData keyValidator(AbstractType<?> prop) {keyValidator = prop; return this;}
public CFMetaData minCompactionThreshold(int prop) {minCompactionThreshold = prop; return this;}
public CFMetaData maxCompactionThreshold(int prop) {maxCompactionThreshold = prop; return this;}
public CFMetaData compactionStrategyClass(Class<? extends AbstractCompactionStrategy> prop) {compactionStrategyClass = prop; return this;}
public CFMetaData compactionStrategyOptions(Map<String, String> prop) {compactionStrategyOptions = prop; return this;}
public CFMetaData compressionParameters(CompressionParameters prop) {compressionParameters = prop; return this;}
public CFMetaData bloomFilterFpChance(Double prop) {bloomFilterFpChance = prop; return this;}
public CFMetaData caching(CachingOptions prop) {caching = prop; return this;}
public CFMetaData minIndexInterval(int prop) {minIndexInterval = prop; return this;}
public CFMetaData maxIndexInterval(int prop) {maxIndexInterval = prop; return this;}
public CFMetaData memtableFlushPeriod(int prop) {memtableFlushPeriod = prop; return this;}
public CFMetaData defaultTimeToLive(int prop) {defaultTimeToLive = prop; return this;}
public CFMetaData speculativeRetry(SpeculativeRetry prop) {speculativeRetry = prop; return this;}
public CFMetaData droppedColumns(Map<ColumnIdentifier, Long> cols) {droppedColumns = cols; return this;}
public CFMetaData triggers(Map<String, TriggerDefinition> prop) {triggers = prop; return this;}
public CFMetaData isDense(Boolean prop) {isDense = prop; return this;}
/**
* Create new ColumnFamily metadata with generated random ID.
* When loading from existing schema, use CFMetaData
*
* @param keyspace keyspace name
* @param name column family name
* @param comp default comparator
*/
public CFMetaData(String keyspace, String name, ColumnFamilyType type, CellNameType comp)
{
this(keyspace, name, type, comp, null);
}
public CFMetaData(String keyspace, String name, ColumnFamilyType type, CellNameType comp, UUID id)
{
cfId = id != null ? id : UUIDGen.getTimeUUID();
ksName = keyspace;
cfName = name;
ksAndCFName = Pair.create(keyspace, name);
byte[] ksBytes = FBUtilities.toWriteUTFBytes(ksName);
byte[] cfBytes = FBUtilities.toWriteUTFBytes(cfName);
ksAndCFBytes = Arrays.copyOf(ksBytes, ksBytes.length + cfBytes.length);
System.arraycopy(cfBytes, 0, ksAndCFBytes, ksBytes.length, cfBytes.length);
cfType = type;
comparator = comp;
}
public static CFMetaData denseCFMetaData(String keyspace, String name, AbstractType<?> comp, AbstractType<?> subcc)
{
CellNameType cellNameType = CellNames.fromAbstractType(makeRawAbstractType(comp, subcc), true);
return new CFMetaData(keyspace, name, subcc == null ? ColumnFamilyType.Standard : ColumnFamilyType.Super, cellNameType);
}
public static CFMetaData sparseCFMetaData(String keyspace, String name, AbstractType<?> comp)
{
CellNameType cellNameType = CellNames.fromAbstractType(comp, false);
return new CFMetaData(keyspace, name, ColumnFamilyType.Standard, cellNameType);
}
public static CFMetaData denseCFMetaData(String keyspace, String name, AbstractType<?> comp)
{
return denseCFMetaData(keyspace, name, comp, null);
}
private static AbstractType<?> makeRawAbstractType(AbstractType<?> comparator, AbstractType<?> subComparator)
{
return subComparator == null ? comparator : CompositeType.getInstance(Arrays.asList(comparator, subComparator));
}
public Map<String, TriggerDefinition> getTriggers()
{
return triggers;
}
private static CFMetaData compile(String cql)
{
return compile(cql, Keyspace.SYSTEM_KS);
}
@VisibleForTesting
public static CFMetaData compile(String cql, String keyspace)
{
try
{
CFStatement parsed = (CFStatement)QueryProcessor.parseStatement(cql);
parsed.prepareKeyspace(keyspace);
CreateTableStatement statement = (CreateTableStatement) parsed.prepare().statement;
CFMetaData cfm = newSystemMetadata(keyspace, statement.columnFamily(), "", statement.comparator);
statement.applyPropertiesTo(cfm);
return cfm.rebuild();
}
catch (RequestValidationException e)
{
throw new RuntimeException(e);
}
}
/**
* Generates deterministic UUID from keyspace/columnfamily name pair.
* This is used to generate the same UUID for C* version < 2.1
*
* Since 2.1, this is only used for system columnfamilies and tests.
*/
public static UUID generateLegacyCfId(String ksName, String cfName)
{
return UUID.nameUUIDFromBytes(ArrayUtils.addAll(ksName.getBytes(), cfName.getBytes()));
}
private static CFMetaData newSystemMetadata(String keyspace, String cfName, String comment, CellNameType comparator)
{
return new CFMetaData(keyspace, cfName, ColumnFamilyType.Standard, comparator, generateLegacyCfId(keyspace, cfName))
.comment(comment)
.readRepairChance(0)
.dcLocalReadRepairChance(0)
.gcGraceSeconds(0)
.memtableFlushPeriod(3600 * 1000);
}
/**
* Creates CFMetaData for secondary index CF.
* Secondary index CF has the same CF ID as parent's.
*
* @param parent Parent CF where secondary index is created
* @param info Column definition containing secondary index definition
* @param indexComparator Comparator for secondary index
* @return CFMetaData for secondary index
*/
public static CFMetaData newIndexMetadata(CFMetaData parent, ColumnDefinition info, CellNameType indexComparator)
{
// Depends on parent's cache setting, turn on its index CF's cache.
// Row caching is never enabled; see CASSANDRA-5732
CachingOptions indexCaching = parent.getCaching().keyCache.isEnabled()
? CachingOptions.KEYS_ONLY
: CachingOptions.NONE;
return new CFMetaData(parent.ksName, parent.indexColumnFamilyName(info), ColumnFamilyType.Standard, indexComparator, parent.cfId)
.keyValidator(info.type)
.readRepairChance(0.0)
.dcLocalReadRepairChance(0.0)
.gcGraceSeconds(0)
.caching(indexCaching)
.speculativeRetry(parent.speculativeRetry)
.compactionStrategyClass(parent.compactionStrategyClass)
.compactionStrategyOptions(parent.compactionStrategyOptions)
.reloadSecondaryIndexMetadata(parent)
.rebuild();
}
public CFMetaData reloadSecondaryIndexMetadata(CFMetaData parent)
{
minCompactionThreshold(parent.minCompactionThreshold);
maxCompactionThreshold(parent.maxCompactionThreshold);
compactionStrategyClass(parent.compactionStrategyClass);
compactionStrategyOptions(parent.compactionStrategyOptions);
compressionParameters(parent.compressionParameters);
return this;
}
public CFMetaData copy()
{
return copyOpts(new CFMetaData(ksName, cfName, cfType, comparator, cfId), this);
}
/**
* Clones the CFMetaData, but sets a different cfId
*
* @param newCfId the cfId for the cloned CFMetaData
* @return the cloned CFMetaData instance with the new cfId
*/
public CFMetaData copy(UUID newCfId)
{
return copyOpts(new CFMetaData(ksName, cfName, cfType, comparator, newCfId), this);
}
static CFMetaData copyOpts(CFMetaData newCFMD, CFMetaData oldCFMD)
{
List<ColumnDefinition> clonedColumns = new ArrayList<>(oldCFMD.allColumns().size());
for (ColumnDefinition cd : oldCFMD.allColumns())
clonedColumns.add(cd.copy());
return newCFMD.addAllColumnDefinitions(clonedColumns)
.comment(oldCFMD.comment)
.readRepairChance(oldCFMD.readRepairChance)
.dcLocalReadRepairChance(oldCFMD.dcLocalReadRepairChance)
.gcGraceSeconds(oldCFMD.gcGraceSeconds)
.defaultValidator(oldCFMD.defaultValidator)
.keyValidator(oldCFMD.keyValidator)
.minCompactionThreshold(oldCFMD.minCompactionThreshold)
.maxCompactionThreshold(oldCFMD.maxCompactionThreshold)
.compactionStrategyClass(oldCFMD.compactionStrategyClass)
.compactionStrategyOptions(new HashMap<>(oldCFMD.compactionStrategyOptions))
.compressionParameters(oldCFMD.compressionParameters.copy())
.bloomFilterFpChance(oldCFMD.bloomFilterFpChance)
.caching(oldCFMD.caching)
.defaultTimeToLive(oldCFMD.defaultTimeToLive)
.minIndexInterval(oldCFMD.minIndexInterval)
.maxIndexInterval(oldCFMD.maxIndexInterval)
.speculativeRetry(oldCFMD.speculativeRetry)
.memtableFlushPeriod(oldCFMD.memtableFlushPeriod)
.droppedColumns(new HashMap<>(oldCFMD.droppedColumns))
.triggers(new HashMap<>(oldCFMD.triggers))
.isDense(oldCFMD.isDense)
.rebuild();
}
/**
* generate a column family name for an index corresponding to the given column.
* This is NOT the same as the index's name! This is only used in sstable filenames and is not exposed to users.
*
* @param info A definition of the column with index
*
* @return name of the index ColumnFamily
*/
public String indexColumnFamilyName(ColumnDefinition info)
{
// TODO simplify this when info.index_name is guaranteed to be set
return cfName + Directories.SECONDARY_INDEX_NAME_SEPARATOR + (info.getIndexName() == null ? ByteBufferUtil.bytesToHex(info.name.bytes) : info.getIndexName());
}
public String getComment()
{
return comment;
}
public boolean isSuper()
{
return cfType == ColumnFamilyType.Super;
}
/**
* The '.' char is the only way to identify if the CFMetadata is for a secondary index
*/
public boolean isSecondaryIndex()
{
return cfName.contains(".");
}
/**
*
* @return The name of the parent cf if this is a seconday index
*/
public String getParentColumnFamilyName()
{
return isSecondaryIndex() ? cfName.substring(0, cfName.indexOf('.')) : null;
}
public double getReadRepairChance()
{
return readRepairChance;
}
public double getDcLocalReadRepair()
{
return dcLocalReadRepairChance;
}
public ReadRepairDecision newReadRepairDecision()
{
double chance = ThreadLocalRandom.current().nextDouble();
if (getReadRepairChance() > chance)
return ReadRepairDecision.GLOBAL;
if (getDcLocalReadRepair() > chance)
return ReadRepairDecision.DC_LOCAL;
return ReadRepairDecision.NONE;
}
public int getGcGraceSeconds()
{
return gcGraceSeconds;
}
public AbstractType<?> getDefaultValidator()
{
return defaultValidator;
}
public AbstractType<?> getKeyValidator()
{
return keyValidator;
}
public Integer getMinCompactionThreshold()
{
return minCompactionThreshold;
}
public Integer getMaxCompactionThreshold()
{
return maxCompactionThreshold;
}
// Used by CQL2 only.
public String getCQL2KeyName()
{
if (partitionKeyColumns.size() > 1)
throw new IllegalStateException("Cannot acces column family with composite key from CQL < 3.0.0");
// For compatibility sake, we uppercase if it's the default alias as we used to return it that way in resultsets.
String str = partitionKeyColumns.get(0).name.toString();
return str.equalsIgnoreCase(DEFAULT_KEY_ALIAS) ? str.toUpperCase() : str;
}
public CompressionParameters compressionParameters()
{
return compressionParameters;
}
public Collection<ColumnDefinition> allColumns()
{
return columnMetadata.values();
}
// An iterator over all column definitions but that respect the order of a SELECT *.
public Iterator<ColumnDefinition> allColumnsInSelectOrder()
{
return new AbstractIterator<ColumnDefinition>()
{
private final Iterator<ColumnDefinition> partitionKeyIter = partitionKeyColumns.iterator();
private final Iterator<ColumnDefinition> clusteringIter = clusteringColumns.iterator();
private boolean valueDone;
private final Iterator<ColumnDefinition> staticIter = staticColumns.iterator();
private final Iterator<ColumnDefinition> regularIter = regularColumns.iterator();
protected ColumnDefinition computeNext()
{
if (partitionKeyIter.hasNext())
return partitionKeyIter.next();
if (clusteringIter.hasNext())
return clusteringIter.next();
if (staticIter.hasNext())
return staticIter.next();
if (compactValueColumn != null && !valueDone)
{
valueDone = true;
// If the compactValueColumn is empty, this means we have a dense table but
// with only a PK. As far as selects are concerned, we should ignore the value.
if (compactValueColumn.name.bytes.hasRemaining())
return compactValueColumn;
}
if (regularIter.hasNext())
return regularIter.next();
return endOfData();
}
};
}
public List<ColumnDefinition> partitionKeyColumns()
{
return partitionKeyColumns;
}
public List<ColumnDefinition> clusteringColumns()
{
return clusteringColumns;
}
public Set<ColumnDefinition> regularColumns()
{
return regularColumns;
}
public Set<ColumnDefinition> staticColumns()
{
return staticColumns;
}
public Iterable<ColumnDefinition> regularAndStaticColumns()
{
return Iterables.concat(staticColumns, regularColumns);
}
public ColumnDefinition compactValueColumn()
{
return compactValueColumn;
}
// TODO: we could use CType for key validation too to make this unnecessary but
// it's unclear it would be a win overall
public CType getKeyValidatorAsCType()
{
return keyValidator instanceof CompositeType
? new CompoundCType(((CompositeType) keyValidator).types)
: new SimpleCType(keyValidator);
}
public double getBloomFilterFpChance()
{
// we disallow bFFPC==null starting in 1.2.1 but tolerated it before that
return (bloomFilterFpChance == null || bloomFilterFpChance == 0)
? compactionStrategyClass == LeveledCompactionStrategy.class ? 0.1 : 0.01
: bloomFilterFpChance;
}
public CachingOptions getCaching()
{
return caching;
}
public int getMinIndexInterval()
{
return minIndexInterval;
}
public int getMaxIndexInterval()
{
return maxIndexInterval;
}
public SpeculativeRetry getSpeculativeRetry()
{
return speculativeRetry;
}
public int getMemtableFlushPeriod()
{
return memtableFlushPeriod;
}
public int getDefaultTimeToLive()
{
return defaultTimeToLive;
}
public Map<ColumnIdentifier, Long> getDroppedColumns()
{
return droppedColumns;
}
public Boolean getIsDense()
{
return isDense;
}
@Override
public boolean equals(Object o)
{
if (this == o)
return true;
if (!(o instanceof CFMetaData))
return false;
CFMetaData other = (CFMetaData) o;
return Objects.equal(cfId, other.cfId)
&& Objects.equal(ksName, other.ksName)
&& Objects.equal(cfName, other.cfName)
&& Objects.equal(cfType, other.cfType)
&& Objects.equal(comparator, other.comparator)
&& Objects.equal(comment, other.comment)
&& Objects.equal(readRepairChance, other.readRepairChance)
&& Objects.equal(dcLocalReadRepairChance, other.dcLocalReadRepairChance)
&& Objects.equal(gcGraceSeconds, other.gcGraceSeconds)
&& Objects.equal(defaultValidator, other.defaultValidator)
&& Objects.equal(keyValidator, other.keyValidator)
&& Objects.equal(minCompactionThreshold, other.minCompactionThreshold)
&& Objects.equal(maxCompactionThreshold, other.maxCompactionThreshold)
&& Objects.equal(columnMetadata, other.columnMetadata)
&& Objects.equal(compactionStrategyClass, other.compactionStrategyClass)
&& Objects.equal(compactionStrategyOptions, other.compactionStrategyOptions)
&& Objects.equal(compressionParameters, other.compressionParameters)
&& Objects.equal(bloomFilterFpChance, other.bloomFilterFpChance)
&& Objects.equal(memtableFlushPeriod, other.memtableFlushPeriod)
&& Objects.equal(caching, other.caching)
&& Objects.equal(defaultTimeToLive, other.defaultTimeToLive)
&& Objects.equal(minIndexInterval, other.minIndexInterval)
&& Objects.equal(maxIndexInterval, other.maxIndexInterval)
&& Objects.equal(speculativeRetry, other.speculativeRetry)
&& Objects.equal(droppedColumns, other.droppedColumns)
&& Objects.equal(triggers, other.triggers)
&& Objects.equal(isDense, other.isDense);
}
@Override
public int hashCode()
{
return new HashCodeBuilder(29, 1597)
.append(cfId)
.append(ksName)
.append(cfName)
.append(cfType)
.append(comparator)
.append(comment)
.append(readRepairChance)
.append(dcLocalReadRepairChance)
.append(gcGraceSeconds)
.append(defaultValidator)
.append(keyValidator)
.append(minCompactionThreshold)
.append(maxCompactionThreshold)
.append(columnMetadata)
.append(compactionStrategyClass)
.append(compactionStrategyOptions)
.append(compressionParameters)
.append(bloomFilterFpChance)
.append(memtableFlushPeriod)
.append(caching)
.append(defaultTimeToLive)
.append(minIndexInterval)
.append(maxIndexInterval)
.append(speculativeRetry)
.append(droppedColumns)
.append(triggers)
.append(isDense)
.toHashCode();
}
public AbstractType<?> getValueValidator(CellName cellName)
{
ColumnDefinition def = getColumnDefinition(cellName);
return def == null ? defaultValidator : def.type;
}
/** applies implicit defaults to cf definition. useful in updates */
private static void applyImplicitDefaults(org.apache.cassandra.thrift.CfDef cf_def)
{
if (!cf_def.isSetComment())
cf_def.setComment("");
if (!cf_def.isSetMin_compaction_threshold())
cf_def.setMin_compaction_threshold(CFMetaData.DEFAULT_MIN_COMPACTION_THRESHOLD);
if (!cf_def.isSetMax_compaction_threshold())
cf_def.setMax_compaction_threshold(CFMetaData.DEFAULT_MAX_COMPACTION_THRESHOLD);
if (cf_def.compaction_strategy == null)
cf_def.compaction_strategy = DEFAULT_COMPACTION_STRATEGY_CLASS.getSimpleName();
if (cf_def.compaction_strategy_options == null)
cf_def.compaction_strategy_options = Collections.emptyMap();
if (!cf_def.isSetCompression_options())
{
cf_def.setCompression_options(new HashMap<String, String>()
{{
if (DEFAULT_COMPRESSOR != null)
put(CompressionParameters.SSTABLE_COMPRESSION, DEFAULT_COMPRESSOR);
}});
}
if (!cf_def.isSetDefault_time_to_live())
cf_def.setDefault_time_to_live(CFMetaData.DEFAULT_DEFAULT_TIME_TO_LIVE);
if (!cf_def.isSetDclocal_read_repair_chance())
cf_def.setDclocal_read_repair_chance(CFMetaData.DEFAULT_DCLOCAL_READ_REPAIR_CHANCE);
// if index_interval was set, use that for the min_index_interval default
if (!cf_def.isSetMin_index_interval())
{
if (cf_def.isSetIndex_interval())
cf_def.setMin_index_interval(cf_def.getIndex_interval());
else
cf_def.setMin_index_interval(CFMetaData.DEFAULT_MIN_INDEX_INTERVAL);
}
if (!cf_def.isSetMax_index_interval())
{
// ensure the max is at least as large as the min