/
LegacyLayout.java
2647 lines (2272 loc) · 114 KB
/
LegacyLayout.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.db;
import java.io.DataInput;
import java.io.IOException;
import java.io.IOError;
import java.nio.ByteBuffer;
import java.security.MessageDigest;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import org.apache.cassandra.cql3.ColumnIdentifier;
import org.apache.cassandra.cql3.SuperColumnCompatibility;
import org.apache.cassandra.utils.AbstractIterator;
import com.google.common.collect.Iterators;
import com.google.common.collect.Lists;
import com.google.common.collect.PeekingIterator;
import org.apache.cassandra.config.CFMetaData;
import org.apache.cassandra.config.ColumnDefinition;
import org.apache.cassandra.db.filter.ColumnFilter;
import org.apache.cassandra.db.filter.DataLimits;
import org.apache.cassandra.db.rows.*;
import org.apache.cassandra.db.partitions.*;
import org.apache.cassandra.db.context.CounterContext;
import org.apache.cassandra.db.marshal.*;
import org.apache.cassandra.io.util.DataInputPlus;
import org.apache.cassandra.io.util.DataOutputPlus;
import org.apache.cassandra.net.MessagingService;
import org.apache.cassandra.utils.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static com.google.common.collect.Iterables.all;
import static org.apache.cassandra.utils.ByteBufferUtil.bytes;
/**
* Functions to deal with the old format.
*/
public abstract class LegacyLayout
{
private static final Logger logger = LoggerFactory.getLogger(LegacyLayout.class);
private static final NoSpamLogger noSpamLogger = NoSpamLogger.getLogger(logger, 1L, TimeUnit.MINUTES);
public final static int MAX_CELL_NAME_LENGTH = FBUtilities.MAX_UNSIGNED_SHORT;
public final static int STATIC_PREFIX = 0xFFFF;
public final static int DELETION_MASK = 0x01;
public final static int EXPIRATION_MASK = 0x02;
public final static int COUNTER_MASK = 0x04;
public final static int COUNTER_UPDATE_MASK = 0x08;
private final static int RANGE_TOMBSTONE_MASK = 0x10;
// Used in decodeBound if the number of components in the legacy bound is greater than the clustering size,
// indicating a complex column deletion (i.e. a collection tombstone), but the referenced column is either
// not present in the current table metadata, or is not currently a complex column. In that case, we'll
// check the dropped columns for the table which should contain the previous column definition. If that
// previous definition is also not complex (indicating that the column may have been dropped and re-added
// with different types multiple times), we use this fake definition to ensure that the complex deletion
// can be safely processed. This resulting deletion should be filtered out of any row created by a
// CellGrouper by the dropped column check, but this gives us an extra level of confidence as that check
// is timestamp based and so is fallible in the face of clock drift.
private static final ColumnDefinition INVALID_DROPPED_COMPLEX_SUBSTITUTE_COLUMN =
new ColumnDefinition("",
"",
ColumnIdentifier.getInterned(ByteBufferUtil.EMPTY_BYTE_BUFFER, UTF8Type.instance),
SetType.getInstance(UTF8Type.instance, true),
ColumnDefinition.NO_POSITION,
ColumnDefinition.Kind.REGULAR);
private LegacyLayout() {}
public static AbstractType<?> makeLegacyComparator(CFMetaData metadata)
{
ClusteringComparator comparator = metadata.comparator;
if (!metadata.isCompound())
{
assert comparator.size() == 1;
return comparator.subtype(0);
}
boolean hasCollections = metadata.hasCollectionColumns() || metadata.hasDroppedCollectionColumns();
List<AbstractType<?>> types = new ArrayList<>(comparator.size() + (metadata.isDense() ? 0 : 1) + (hasCollections ? 1 : 0));
types.addAll(comparator.subtypes());
if (!metadata.isDense())
{
types.add(UTF8Type.instance);
if (hasCollections)
{
Map<ByteBuffer, CollectionType> defined = new HashMap<>();
for (CFMetaData.DroppedColumn def : metadata.getDroppedColumns().values())
if (def.type instanceof CollectionType && def.type.isMultiCell())
defined.put(bytes(def.name), (CollectionType) def.type);
for (ColumnDefinition def : metadata.partitionColumns())
if (def.type instanceof CollectionType && def.type.isMultiCell())
defined.put(def.name.bytes, (CollectionType) def.type);
types.add(ColumnToCollectionType.getInstance(defined));
}
}
return CompositeType.getInstance(types);
}
public static LegacyCellName decodeCellName(CFMetaData metadata, ByteBuffer superColumnName, ByteBuffer cellname)
throws UnknownColumnException
{
assert cellname != null;
if (metadata.isSuper())
{
assert superColumnName != null;
return decodeForSuperColumn(metadata, new Clustering(superColumnName), cellname);
}
assert superColumnName == null;
return decodeCellName(metadata, cellname);
}
private static LegacyCellName decodeForSuperColumn(CFMetaData metadata, Clustering clustering, ByteBuffer subcol)
{
ColumnDefinition def = metadata.getColumnDefinition(subcol);
if (def != null)
{
// it's a statically defined subcolumn
return new LegacyCellName(clustering, def, null);
}
def = metadata.compactValueColumn();
assert def != null && def.type instanceof MapType;
return new LegacyCellName(clustering, def, subcol);
}
public static LegacyCellName decodeCellName(CFMetaData metadata, ByteBuffer cellname) throws UnknownColumnException
{
return decodeCellName(metadata, cellname, false);
}
public static LegacyCellName decodeCellName(CFMetaData metadata, ByteBuffer cellname, boolean readAllAsDynamic) throws UnknownColumnException
{
Clustering clustering = decodeClustering(metadata, cellname);
if (metadata.isSuper())
return decodeForSuperColumn(metadata, clustering, CompositeType.extractComponent(cellname, 1));
if (metadata.isDense() || (metadata.isCompactTable() && readAllAsDynamic))
return new LegacyCellName(clustering, metadata.compactValueColumn(), null);
ByteBuffer column = metadata.isCompound() ? CompositeType.extractComponent(cellname, metadata.comparator.size()) : cellname;
if (column == null)
{
// Tables for composite 2ndary indexes used to be compound but dense, but we've transformed them into regular tables
// (non compact ones) but with no regular column (i.e. we only care about the clustering). So we'll get here
// in that case, and what we want to return is basically a row marker.
if (metadata.partitionColumns().isEmpty())
return new LegacyCellName(clustering, null, null);
// Otherwise, we shouldn't get there
throw new IllegalArgumentException("No column name component found in cell name");
}
// Row marker, this is ok
if (!column.hasRemaining())
return new LegacyCellName(clustering, null, null);
ColumnDefinition def = metadata.getColumnDefinition(column);
if (metadata.isCompactTable())
{
if (def == null || def.isPrimaryKeyColumn())
// If it's a compact table, it means the column is in fact a "dynamic" one
return new LegacyCellName(new Clustering(column), metadata.compactValueColumn(), null);
}
else if (def == null)
{
throw new UnknownColumnException(metadata, column);
}
ByteBuffer collectionElement = metadata.isCompound() ? CompositeType.extractComponent(cellname, metadata.comparator.size() + 1) : null;
// Note that because static compact columns are translated to static defs in the new world order, we need to force a static
// clustering if the definition is static (as it might not be in this case).
return new LegacyCellName(def.isStatic() ? Clustering.STATIC_CLUSTERING : clustering, def, collectionElement);
}
public static LegacyBound decodeSliceBound(CFMetaData metadata, ByteBuffer bound, boolean isStart)
{
return decodeBound(metadata, bound, isStart, false);
}
public static LegacyBound decodeTombstoneBound(CFMetaData metadata, ByteBuffer bound, boolean isStart)
{
return decodeBound(metadata, bound, isStart, true);
}
private static LegacyBound decodeBound(CFMetaData metadata, ByteBuffer bound, boolean isStart, boolean isDeletion)
{
if (!bound.hasRemaining())
return isStart ? LegacyBound.BOTTOM : LegacyBound.TOP;
if (!metadata.isCompound())
{
// The non compound case is a lot easier, in that there is no EOC nor collection to worry about, so dealing
// with that first.
return new LegacyBound(isStart ? Slice.Bound.inclusiveStartOf(bound) : Slice.Bound.inclusiveEndOf(bound), false, null);
}
int clusteringSize = metadata.comparator.size();
boolean isStatic = metadata.isCompound() && CompositeType.isStaticName(bound);
List<ByteBuffer> components = CompositeType.splitName(bound);
byte eoc = CompositeType.lastEOC(bound);
// if the bound we have decoded is static, 2.2 format requires there to be N empty clusterings
assert !isStatic ||
(components.size() >= clusteringSize
&& all(components.subList(0, clusteringSize), ByteBufferUtil.EMPTY_BYTE_BUFFER::equals));
ColumnDefinition collectionName = null;
if (components.size() > clusteringSize)
{
// For a deletion, there can be more components than the clustering size only in the case this is the
// bound of a collection range tombstone. In such a case, there is exactly one more component, and that
// component is the name of the collection being deleted, since we do not support collection range deletions.
// If the bound is not part of a deletion, it is from slice query filter. The column name may be:
// - a valid, non-collection column; in this case we expect a single extra component
// - an empty buffer, representing a row marker; in this case we also expect a single extra empty component
// - a valid collection column and the first part of a cell path; in this case we expect exactly two extra components
// In any of these slice cases, these items are unnecessary for the bound we construct,
// so we can simply remove them, after corroborating we have encountered one of these scenario.
assert !metadata.isCompactTable() : toDebugHex(components);
// In all cases, the element straight after the clusterings should contain the name of a column.
if (components.size() > clusteringSize + 1)
{
// we accept bounds from paging state that occur inside a complex column - in this case, we expect
// two excess components, the first of which is a column name, the second a key into the collection
if (isDeletion)
throw new IllegalArgumentException("Invalid bound " + toDebugHex(components) + ": deletion can have at most one extra component");
if (clusteringSize + 2 != components.size())
throw new IllegalArgumentException("Invalid bound " + toDebugHex(components) + ": complex slices require exactly two extra components");
// decode simply to verify that we have (or may have had) a complex column; we assume the collection key is valid
decodeBoundLookupComplexColumn(metadata, components, clusteringSize, isStatic);
components.remove(clusteringSize + 1);
}
else if (isDeletion)
{
collectionName = decodeBoundLookupComplexColumn(metadata, components, clusteringSize, isStatic);
}
else if (components.get(clusteringSize).hasRemaining())
{
decodeBoundVerifySimpleColumn(metadata, components, clusteringSize, isStatic);
}
components.remove(clusteringSize);
}
boolean isInclusive;
if (isStart)
{
isInclusive = eoc <= 0;
}
else
{
isInclusive = eoc >= 0;
// for an end bound, if we only have a prefix of all the components and the final EOC is zero,
// then it should only match up to the prefix but no further, that is, it is an inclusive bound
// of the exact prefix but an exclusive bound of anything beyond it, so adding an empty
// composite value ensures this behavior, see CASSANDRA-12423 for more details
if (eoc == 0 && components.size() < clusteringSize)
{
components.add(ByteBufferUtil.EMPTY_BYTE_BUFFER);
isInclusive = false;
}
}
Slice.Bound.Kind boundKind = Slice.Bound.boundKind(isStart, isInclusive);
Slice.Bound sb = Slice.Bound.create(boundKind, components.toArray(new ByteBuffer[components.size()]));
return new LegacyBound(sb, isStatic, collectionName);
}
// finds the simple column definition associated with components.get(clusteringSize)
// if no such columns exists, or ever existed, we throw an exception; if we do not know, we return a dummy column definition
private static ColumnDefinition decodeBoundLookupComplexColumn(CFMetaData metadata, List<ByteBuffer> components, int clusteringSize, boolean isStatic)
{
ByteBuffer columnNameBytes = components.get(clusteringSize);
ColumnDefinition columnName = metadata.getColumnDefinition(columnNameBytes);
if (columnName == null || !columnName.isComplex())
{
columnName = metadata.getDroppedColumnDefinition(columnNameBytes, isStatic);
// if no record of the column having ever existed is found, something is badly wrong
if (columnName == null)
throw new IllegalArgumentException("Invalid bound " + toDebugHex(components) + ": expected complex column at position " + clusteringSize);
// if we do have a record of dropping this column but it wasn't previously complex, use a fake
// column definition for safety (see the comment on the constant declaration for details)
if (!columnName.isComplex())
columnName = INVALID_DROPPED_COMPLEX_SUBSTITUTE_COLUMN;
}
return columnName;
}
// finds the simple column definition associated with components.get(clusteringSize)
// if no such columns exists, and definitely never existed, we throw an exception
private static void decodeBoundVerifySimpleColumn(CFMetaData metadata, List<ByteBuffer> components, int clusteringSize, boolean isStatic)
{
ByteBuffer columnNameBytes = components.get(clusteringSize);
ColumnDefinition columnName = metadata.getColumnDefinition(columnNameBytes);
if (columnName == null || !columnName.isSimple())
{
columnName = metadata.getDroppedColumnDefinition(columnNameBytes, isStatic);
// if no record of the column having ever existed is found, something is badly wrong
if (columnName == null)
throw new IllegalArgumentException("Invalid bound " + toDebugHex(components) + ": expected simple column at position " + clusteringSize);
}
}
private static String toDebugHex(Collection<ByteBuffer> buffers)
{
return buffers.stream().map(ByteBufferUtil::bytesToHex).collect(Collectors.joining());
}
public static ByteBuffer encodeBound(CFMetaData metadata, Slice.Bound bound, boolean isStart)
{
if (bound == Slice.Bound.BOTTOM || bound == Slice.Bound.TOP || metadata.comparator.size() == 0)
return ByteBufferUtil.EMPTY_BYTE_BUFFER;
ClusteringPrefix clustering = bound.clustering();
if (!metadata.isCompound())
{
assert clustering.size() == 1;
return clustering.get(0);
}
CompositeType ctype = CompositeType.getInstance(metadata.comparator.subtypes());
CompositeType.Builder builder = ctype.builder();
for (int i = 0; i < clustering.size(); i++)
builder.add(clustering.get(i));
if (isStart)
return bound.isInclusive() ? builder.build() : builder.buildAsEndOfRange();
else
return bound.isInclusive() ? builder.buildAsEndOfRange() : builder.build();
}
public static ByteBuffer encodeCellName(CFMetaData metadata, ClusteringPrefix clustering, ByteBuffer columnName, ByteBuffer collectionElement)
{
boolean isStatic = clustering == Clustering.STATIC_CLUSTERING;
if (!metadata.isCompound())
{
if (isStatic)
return columnName;
assert clustering.size() == 1 : "Expected clustering size to be 1, but was " + clustering.size();
return clustering.get(0);
}
// We use comparator.size() rather than clustering.size() because of static clusterings
int clusteringSize = metadata.comparator.size();
int size = clusteringSize + (metadata.isDense() ? 0 : 1) + (collectionElement == null ? 0 : 1);
if (metadata.isSuper())
size = clusteringSize + 1;
ByteBuffer[] values = new ByteBuffer[size];
for (int i = 0; i < clusteringSize; i++)
{
if (isStatic)
{
values[i] = ByteBufferUtil.EMPTY_BYTE_BUFFER;
continue;
}
ByteBuffer v = clustering.get(i);
// we can have null (only for dense compound tables for backward compatibility reasons) but that
// means we're done and should stop there as far as building the composite is concerned.
if (v == null)
return CompositeType.build(Arrays.copyOfRange(values, 0, i));
values[i] = v;
}
if (metadata.isSuper())
{
// We need to set the "column" (in thrift terms) name, i.e. the value corresponding to the subcomparator.
// What it is depends if this a cell for a declared "static" column or a "dynamic" column part of the
// super-column internal map.
assert columnName != null; // This should never be null for supercolumns, see decodeForSuperColumn() above
values[clusteringSize] = columnName.equals(SuperColumnCompatibility.SUPER_COLUMN_MAP_COLUMN)
? collectionElement
: columnName;
}
else
{
if (!metadata.isDense())
values[clusteringSize] = columnName;
if (collectionElement != null)
values[clusteringSize + 1] = collectionElement;
}
return CompositeType.build(isStatic, values);
}
public static Clustering decodeClustering(CFMetaData metadata, ByteBuffer value)
{
int csize = metadata.comparator.size();
if (csize == 0)
return Clustering.EMPTY;
if (metadata.isCompound() && CompositeType.isStaticName(value))
return Clustering.STATIC_CLUSTERING;
List<ByteBuffer> components = metadata.isCompound()
? CompositeType.splitName(value)
: Collections.singletonList(value);
return new Clustering(components.subList(0, Math.min(csize, components.size())).toArray(new ByteBuffer[csize]));
}
public static ByteBuffer encodeClustering(CFMetaData metadata, ClusteringPrefix clustering)
{
if (clustering.size() == 0)
return ByteBufferUtil.EMPTY_BYTE_BUFFER;
if (!metadata.isCompound())
{
assert clustering.size() == 1;
return clustering.get(0);
}
ByteBuffer[] values = new ByteBuffer[clustering.size()];
for (int i = 0; i < clustering.size(); i++)
values[i] = clustering.get(i);
return CompositeType.build(values);
}
/**
* The maximum number of cells to include per partition when converting to the old format.
* <p>
* We already apply the limit during the actual query, but for queries that counts cells and not rows (thrift queries
* and distinct queries as far as old nodes are concerned), we may still include a little bit more than requested
* because {@link DataLimits} always include full rows. So if the limit ends in the middle of a queried row, the
* full row will be part of our result. This would confuse old nodes however so we make sure to truncate it to
* what's expected before writting it on the wire.
*
* @param command the read commmand for which to determine the maximum cells per partition. This can be {@code null}
* in which case {@code Integer.MAX_VALUE} is returned.
* @return the maximum number of cells per partition that should be enforced according to the read command if
* post-query limitation are in order (see above). This will be {@code Integer.MAX_VALUE} if no such limits are
* necessary.
*/
private static int maxCellsPerPartition(ReadCommand command)
{
if (command == null)
return Integer.MAX_VALUE;
DataLimits limits = command.limits();
// There is 2 types of DISTINCT queries: those that includes only the partition key, and those that include static columns.
// On old nodes, the latter expects the first row in term of CQL count, which is what we already have and there is no additional
// limit to apply. The former however expect only one cell per partition and rely on it (See CASSANDRA-10762).
if (limits.isDistinct())
return command.columnFilter().fetchedColumns().statics.isEmpty() ? 1 : Integer.MAX_VALUE;
switch (limits.kind())
{
case THRIFT_LIMIT:
case SUPER_COLUMN_COUNTING_LIMIT:
return limits.perPartitionCount();
default:
return Integer.MAX_VALUE;
}
}
// For serializing to old wire format
public static LegacyUnfilteredPartition fromUnfilteredRowIterator(ReadCommand command, UnfilteredRowIterator iterator)
{
// we need to extract the range tombstone so materialize the partition. Since this is
// used for the on-wire format, this is not worst than it used to be.
final ImmutableBTreePartition partition = ImmutableBTreePartition.create(iterator);
DeletionInfo info = partition.deletionInfo();
Pair<LegacyRangeTombstoneList, Iterator<LegacyCell>> pair = fromRowIterator(partition.metadata(), partition.iterator(), partition.staticRow());
LegacyLayout.LegacyRangeTombstoneList rtl = pair.left;
// Processing the cell iterator results in the LegacyRangeTombstoneList being populated, so we do this
// before we use the LegacyRangeTombstoneList at all
List<LegacyLayout.LegacyCell> cells = Lists.newArrayList(pair.right);
int maxCellsPerPartition = maxCellsPerPartition(command);
if (cells.size() > maxCellsPerPartition)
cells = cells.subList(0, maxCellsPerPartition);
// The LegacyRangeTombstoneList already has range tombstones for the single-row deletions and complex
// deletions. Go through our normal range tombstones and add then to the LegacyRTL so that the range
// tombstones all get merged and sorted properly.
if (info.hasRanges())
{
Iterator<RangeTombstone> rangeTombstoneIterator = info.rangeIterator(false);
while (rangeTombstoneIterator.hasNext())
{
RangeTombstone rt = rangeTombstoneIterator.next();
Slice slice = rt.deletedSlice();
LegacyLayout.LegacyBound start = new LegacyLayout.LegacyBound(slice.start(), false, null);
LegacyLayout.LegacyBound end = new LegacyLayout.LegacyBound(slice.end(), false, null);
rtl.add(start, end, rt.deletionTime().markedForDeleteAt(), rt.deletionTime().localDeletionTime());
}
}
return new LegacyUnfilteredPartition(info.getPartitionDeletion(), rtl, cells);
}
public static void serializeAsLegacyPartition(ReadCommand command, UnfilteredRowIterator partition, DataOutputPlus out, int version) throws IOException
{
assert version < MessagingService.VERSION_30;
out.writeBoolean(true);
LegacyLayout.LegacyUnfilteredPartition legacyPartition = LegacyLayout.fromUnfilteredRowIterator(command, partition);
UUIDSerializer.serializer.serialize(partition.metadata().cfId, out, version);
DeletionTime.serializer.serialize(legacyPartition.partitionDeletion, out);
legacyPartition.rangeTombstones.serialize(out, partition.metadata());
// begin cell serialization
out.writeInt(legacyPartition.cells.size());
for (LegacyLayout.LegacyCell cell : legacyPartition.cells)
{
ByteBufferUtil.writeWithShortLength(cell.name.encode(partition.metadata()), out);
out.writeByte(cell.serializationFlags());
if (cell.isExpiring())
{
out.writeInt(cell.ttl);
out.writeInt(cell.localDeletionTime);
}
else if (cell.isTombstone())
{
out.writeLong(cell.timestamp);
out.writeInt(TypeSizes.sizeof(cell.localDeletionTime));
out.writeInt(cell.localDeletionTime);
continue;
}
else if (cell.isCounterUpdate())
{
out.writeLong(cell.timestamp);
long count = CounterContext.instance().getUpdateCount(cell.value);
ByteBufferUtil.writeWithLength(ByteBufferUtil.bytes(count), out);
continue;
}
else if (cell.isCounter())
{
out.writeLong(Long.MIN_VALUE); // timestampOfLastDelete (not used, and MIN_VALUE is the default)
}
out.writeLong(cell.timestamp);
ByteBufferUtil.writeWithLength(cell.value, out);
}
}
// For the old wire format
// Note: this can return null if an empty partition is serialized!
public static UnfilteredRowIterator deserializeLegacyPartition(DataInputPlus in, int version, SerializationHelper.Flag flag, ByteBuffer key) throws IOException
{
assert version < MessagingService.VERSION_30;
// This is only used in mutation, and mutation have never allowed "null" column families
boolean present = in.readBoolean();
if (!present)
return null;
CFMetaData metadata = CFMetaData.serializer.deserialize(in, version);
LegacyDeletionInfo info = LegacyDeletionInfo.deserialize(metadata, in);
int size = in.readInt();
Iterator<LegacyCell> cells = deserializeCells(metadata, in, flag, size);
SerializationHelper helper = new SerializationHelper(metadata, version, flag);
return onWireCellstoUnfilteredRowIterator(metadata, metadata.partitioner.decorateKey(key), info, cells, false, helper);
}
// For the old wire format
public static long serializedSizeAsLegacyPartition(ReadCommand command, UnfilteredRowIterator partition, int version)
{
assert version < MessagingService.VERSION_30;
if (partition.isEmpty())
return TypeSizes.sizeof(false);
long size = TypeSizes.sizeof(true);
LegacyLayout.LegacyUnfilteredPartition legacyPartition = LegacyLayout.fromUnfilteredRowIterator(command, partition);
size += UUIDSerializer.serializer.serializedSize(partition.metadata().cfId, version);
size += DeletionTime.serializer.serializedSize(legacyPartition.partitionDeletion);
size += legacyPartition.rangeTombstones.serializedSize(partition.metadata());
// begin cell serialization
size += TypeSizes.sizeof(legacyPartition.cells.size());
for (LegacyLayout.LegacyCell cell : legacyPartition.cells)
{
size += ByteBufferUtil.serializedSizeWithShortLength(cell.name.encode(partition.metadata()));
size += 1; // serialization flags
if (cell.isExpiring())
{
size += TypeSizes.sizeof(cell.ttl);
size += TypeSizes.sizeof(cell.localDeletionTime);
}
else if (cell.isTombstone())
{
size += TypeSizes.sizeof(cell.timestamp);
// localDeletionTime replaces cell.value as the body
size += TypeSizes.sizeof(TypeSizes.sizeof(cell.localDeletionTime));
size += TypeSizes.sizeof(cell.localDeletionTime);
continue;
}
else if (cell.isCounterUpdate())
{
size += TypeSizes.sizeof(cell.timestamp);
long count = CounterContext.instance().getUpdateCount(cell.value);
size += ByteBufferUtil.serializedSizeWithLength(ByteBufferUtil.bytes(count));
continue;
}
else if (cell.isCounter())
{
size += TypeSizes.sizeof(Long.MIN_VALUE); // timestampOfLastDelete
}
size += TypeSizes.sizeof(cell.timestamp);
size += ByteBufferUtil.serializedSizeWithLength(cell.value);
}
return size;
}
// For thrift sake
public static UnfilteredRowIterator toUnfilteredRowIterator(CFMetaData metadata,
DecoratedKey key,
LegacyDeletionInfo delInfo,
Iterator<LegacyCell> cells)
{
SerializationHelper helper = new SerializationHelper(metadata, 0, SerializationHelper.Flag.LOCAL);
return toUnfilteredRowIterator(metadata, key, delInfo, cells, false, helper);
}
// For deserializing old wire format
public static UnfilteredRowIterator onWireCellstoUnfilteredRowIterator(CFMetaData metadata,
DecoratedKey key,
LegacyDeletionInfo delInfo,
Iterator<LegacyCell> cells,
boolean reversed,
SerializationHelper helper)
{
// If the table is a static compact, the "column_metadata" are now internally encoded as
// static. This has already been recognized by decodeCellName, but it means the cells
// provided are not in the expected order (the "static" cells are not necessarily at the front).
// So sort them to make sure toUnfilteredRowIterator works as expected.
// Further, if the query is reversed, then the on-wire format still has cells in non-reversed
// order, but we need to have them reverse in the final UnfilteredRowIterator. So reverse them.
if (metadata.isStaticCompactTable() || reversed)
{
List<LegacyCell> l = new ArrayList<>();
Iterators.addAll(l, cells);
Collections.sort(l, legacyCellComparator(metadata, reversed));
cells = l.iterator();
}
return toUnfilteredRowIterator(metadata, key, delInfo, cells, reversed, helper);
}
private static UnfilteredRowIterator toUnfilteredRowIterator(CFMetaData metadata,
DecoratedKey key,
LegacyDeletionInfo delInfo,
Iterator<LegacyCell> cells,
boolean reversed,
SerializationHelper helper)
{
// A reducer that basically does nothing, we know the 2 merged iterators can't have conflicting atoms (since we merge cells with range tombstones).
MergeIterator.Reducer<LegacyAtom, LegacyAtom> reducer = new MergeIterator.Reducer<LegacyAtom, LegacyAtom>()
{
private LegacyAtom atom;
public void reduce(int idx, LegacyAtom current)
{
// We're merging cell with range tombstones, so we should always only have a single atom to reduce.
assert atom == null;
atom = current;
}
protected LegacyAtom getReduced()
{
return atom;
}
protected void onKeyChange()
{
atom = null;
}
};
List<Iterator<LegacyAtom>> iterators = Arrays.asList(asLegacyAtomIterator(cells), asLegacyAtomIterator(delInfo.inRowRangeTombstones()));
PeekingIterator<LegacyAtom> atoms = Iterators.peekingIterator(MergeIterator.get(iterators, legacyAtomComparator(metadata), reducer));
// Check if we have some static
Row staticRow = atoms.hasNext() && atoms.peek().isStatic()
? getNextRow(CellGrouper.staticGrouper(metadata, helper), atoms)
: Rows.EMPTY_STATIC_ROW;
Iterator<Row> rows = convertToRows(new CellGrouper(metadata, helper), atoms);
Iterator<RangeTombstone> ranges = delInfo.deletionInfo.rangeIterator(reversed);
return new RowAndDeletionMergeIterator(metadata,
key,
delInfo.deletionInfo.getPartitionDeletion(),
ColumnFilter.all(metadata),
staticRow,
reversed,
EncodingStats.NO_STATS,
rows,
ranges,
true);
}
public static Row extractStaticColumns(CFMetaData metadata, DataInputPlus in, Columns statics) throws IOException
{
assert !statics.isEmpty();
assert metadata.isCompactTable();
if (metadata.isSuper())
// TODO: there is in practice nothing to do here, but we need to handle the column_metadata for super columns somewhere else
throw new UnsupportedOperationException();
Set<ByteBuffer> columnsToFetch = new HashSet<>(statics.size());
for (ColumnDefinition column : statics)
columnsToFetch.add(column.name.bytes);
Row.Builder builder = BTreeRow.unsortedBuilder(FBUtilities.nowInSeconds());
builder.newRow(Clustering.STATIC_CLUSTERING);
boolean foundOne = false;
LegacyAtom atom;
while ((atom = readLegacyAtomSkippingUnknownColumn(metadata,in)) != null)
{
if (atom.isCell())
{
LegacyCell cell = atom.asCell();
if (!columnsToFetch.contains(cell.name.encode(metadata)))
continue;
foundOne = true;
builder.addCell(new BufferCell(cell.name.column, cell.timestamp, cell.ttl, cell.localDeletionTime, cell.value, null));
}
else
{
LegacyRangeTombstone tombstone = atom.asRangeTombstone();
// TODO: we need to track tombstones and potentially ignore cells that are
// shadowed (or even better, replace them by tombstones).
throw new UnsupportedOperationException();
}
}
return foundOne ? builder.build() : Rows.EMPTY_STATIC_ROW;
}
private static LegacyAtom readLegacyAtomSkippingUnknownColumn(CFMetaData metadata, DataInputPlus in)
throws IOException
{
while (true)
{
try
{
return readLegacyAtom(metadata, in, false);
}
catch (UnknownColumnException e)
{
// Simply skip, as the method name implies.
}
}
}
private static Row getNextRow(CellGrouper grouper, PeekingIterator<? extends LegacyAtom> cells)
{
if (!cells.hasNext())
return null;
grouper.reset();
while (cells.hasNext() && grouper.addAtom(cells.peek()))
{
// We've added the cell already in the grouper, so just skip it
cells.next();
}
return grouper.getRow();
}
@SuppressWarnings("unchecked")
private static Iterator<LegacyAtom> asLegacyAtomIterator(Iterator<? extends LegacyAtom> iter)
{
return (Iterator<LegacyAtom>)iter;
}
private static Iterator<Row> convertToRows(final CellGrouper grouper, final PeekingIterator<LegacyAtom> atoms)
{
return new AbstractIterator<Row>()
{
protected Row computeNext()
{
if (!atoms.hasNext())
return endOfData();
return getNextRow(grouper, atoms);
}
};
}
public static Pair<LegacyRangeTombstoneList, Iterator<LegacyCell>> fromRowIterator(final RowIterator iterator)
{
return fromRowIterator(iterator.metadata(), iterator, iterator.staticRow());
}
private static Pair<LegacyRangeTombstoneList, Iterator<LegacyCell>> fromRowIterator(final CFMetaData metadata, final Iterator<Row> iterator, final Row staticRow)
{
LegacyRangeTombstoneList deletions = new LegacyRangeTombstoneList(new LegacyBoundComparator(metadata.comparator), 10);
Iterator<LegacyCell> cells = new AbstractIterator<LegacyCell>()
{
private Iterator<LegacyCell> currentRow = initializeRow();
private Iterator<LegacyCell> initializeRow()
{
if (staticRow == null || staticRow.isEmpty())
return Collections.<LegacyLayout.LegacyCell>emptyIterator();
Pair<LegacyRangeTombstoneList, Iterator<LegacyCell>> row = fromRow(metadata, staticRow);
deletions.addAll(row.left);
return row.right;
}
protected LegacyCell computeNext()
{
while (true)
{
if (currentRow.hasNext())
return currentRow.next();
if (!iterator.hasNext())
return endOfData();
Pair<LegacyRangeTombstoneList, Iterator<LegacyCell>> row = fromRow(metadata, iterator.next());
deletions.addAll(row.left);
currentRow = row.right;
}
}
};
return Pair.create(deletions, cells);
}
private static Pair<LegacyRangeTombstoneList, Iterator<LegacyCell>> fromRow(final CFMetaData metadata, final Row row)
{
// convert any complex deletions or row deletion into normal range tombstones so that we can build and send a proper RangeTombstoneList
// to legacy nodes
LegacyRangeTombstoneList deletions = new LegacyRangeTombstoneList(new LegacyBoundComparator(metadata.comparator), 10);
if (!row.deletion().isLive())
{
Clustering clustering = row.clustering();
Slice.Bound startBound = Slice.Bound.inclusiveStartOf(clustering);
Slice.Bound endBound = Slice.Bound.inclusiveEndOf(clustering);
LegacyBound start = new LegacyLayout.LegacyBound(startBound, false, null);
LegacyBound end = new LegacyLayout.LegacyBound(endBound, false, null);
deletions.add(start, end, row.deletion().time().markedForDeleteAt(), row.deletion().time().localDeletionTime());
}
for (ColumnData cd : row)
{
ColumnDefinition col = cd.column();
if (col.isSimple())
continue;
DeletionTime delTime = ((ComplexColumnData)cd).complexDeletion();
if (!delTime.isLive())
{
Clustering clustering = row.clustering();
boolean isStatic = clustering == Clustering.STATIC_CLUSTERING;
assert isStatic == col.isStatic();
Slice.Bound startBound = isStatic
? LegacyDeletionInfo.staticBound(metadata, true)
: Slice.Bound.inclusiveStartOf(clustering);
Slice.Bound endBound = isStatic
? LegacyDeletionInfo.staticBound(metadata, false)
: Slice.Bound.inclusiveEndOf(clustering);
LegacyLayout.LegacyBound start = new LegacyLayout.LegacyBound(startBound, isStatic, col);
LegacyLayout.LegacyBound end = new LegacyLayout.LegacyBound(endBound, isStatic, col);
deletions.add(start, end, delTime.markedForDeleteAt(), delTime.localDeletionTime());
}
}
Iterator<LegacyCell> cells = new AbstractIterator<LegacyCell>()
{
private final Iterator<Cell> cells = row.cellsInLegacyOrder(metadata, false).iterator();
// we don't have (and shouldn't have) row markers for compact tables.
private boolean hasReturnedRowMarker = metadata.isCompactTable();
protected LegacyCell computeNext()
{
if (!hasReturnedRowMarker)
{
hasReturnedRowMarker = true;
// don't include a row marker if there's no timestamp on the primary key; this is the 3.0+ equivalent
// of a row marker
if (!row.primaryKeyLivenessInfo().isEmpty())
{
LegacyCellName cellName = new LegacyCellName(row.clustering(), null, null);
LivenessInfo info = row.primaryKeyLivenessInfo();
return new LegacyCell(info.isExpiring() ? LegacyCell.Kind.EXPIRING : LegacyCell.Kind.REGULAR, cellName, ByteBufferUtil.EMPTY_BYTE_BUFFER, info.timestamp(), info.localExpirationTime(), info.ttl());
}
}
if (!cells.hasNext())
return endOfData();
return makeLegacyCell(row.clustering(), cells.next());
}
};
return Pair.create(deletions, cells);
}
private static LegacyCell makeLegacyCell(Clustering clustering, Cell cell)
{
LegacyCell.Kind kind;
if (cell.isCounterCell())
kind = LegacyCell.Kind.COUNTER;
else if (cell.isTombstone())
kind = LegacyCell.Kind.DELETED;
else if (cell.isExpiring())
kind = LegacyCell.Kind.EXPIRING;
else
kind = LegacyCell.Kind.REGULAR;
CellPath path = cell.path();
assert path == null || path.size() == 1;
LegacyCellName name = new LegacyCellName(clustering, cell.column(), path == null ? null : path.get(0));
return new LegacyCell(kind, name, cell.value(), cell.timestamp(), cell.localDeletionTime(), cell.ttl());
}
public static RowIterator toRowIterator(final CFMetaData metadata,
final DecoratedKey key,
final Iterator<LegacyCell> cells,
final int nowInSec)
{
SerializationHelper helper = new SerializationHelper(metadata, 0, SerializationHelper.Flag.LOCAL);
return UnfilteredRowIterators.filter(toUnfilteredRowIterator(metadata, key, LegacyDeletionInfo.live(), cells, false, helper), nowInSec);
}
public static Comparator<LegacyCell> legacyCellComparator(CFMetaData metadata)
{
return legacyCellComparator(metadata, false);
}
public static Comparator<LegacyCell> legacyCellComparator(final CFMetaData metadata, final boolean reversed)
{
final Comparator<LegacyCellName> cellNameComparator = legacyCellNameComparator(metadata, reversed);
return new Comparator<LegacyCell>()
{
public int compare(LegacyCell cell1, LegacyCell cell2)
{
LegacyCellName c1 = cell1.name;
LegacyCellName c2 = cell2.name;
int c = cellNameComparator.compare(c1, c2);
if (c != 0)
return c;