1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package org.apache.hadoop.hbase.filter;
19
20 import java.util.ArrayList;
21 import java.util.Arrays;
22 import java.util.Comparator;
23 import java.util.List;
24 import java.util.Objects;
25 import java.util.PriorityQueue;
26
27 import org.apache.hadoop.hbase.Cell;
28 import org.apache.hadoop.hbase.KeyValueUtil;
29 import org.apache.hadoop.hbase.classification.InterfaceAudience;
30 import org.apache.hadoop.hbase.classification.InterfaceStability;
31 import org.apache.hadoop.hbase.exceptions.DeserializationException;
32 import org.apache.hadoop.hbase.protobuf.generated.FilterProtos;
33 import org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.BytesBytesPair;
34 import org.apache.hadoop.hbase.util.ByteStringer;
35 import org.apache.hadoop.hbase.util.Bytes;
36 import org.apache.hadoop.hbase.util.Pair;
37 import org.apache.hadoop.hbase.util.UnsafeAccess;
38 import org.apache.hadoop.hbase.util.UnsafeAvailChecker;
39
40 import com.google.common.annotations.VisibleForTesting;
41 import com.google.protobuf.InvalidProtocolBufferException;
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61 @InterfaceAudience.Public
62 @InterfaceStability.Evolving
63 public class FuzzyRowFilter extends FilterBase {
64 private static final boolean UNSAFE_UNALIGNED = UnsafeAvailChecker.unaligned();
65 private List<Pair<byte[], byte[]>> fuzzyKeysData;
66 private boolean done = false;
67
68
69
70
71
72
73 private int lastFoundIndex = -1;
74
75
76
77
78 private RowTracker tracker;
79
80 public FuzzyRowFilter(List<Pair<byte[], byte[]>> fuzzyKeysData) {
81 List<Pair<byte[], byte[]>> fuzzyKeyDataCopy = new ArrayList<>(fuzzyKeysData.size());
82
83 for (Pair<byte[], byte[]> aFuzzyKeysData : fuzzyKeysData) {
84 if (aFuzzyKeysData.getFirst().length != aFuzzyKeysData.getSecond().length) {
85 Pair<String, String> readable =
86 new Pair<>(Bytes.toStringBinary(aFuzzyKeysData.getFirst()), Bytes.toStringBinary(aFuzzyKeysData.getSecond()));
87 throw new IllegalArgumentException("Fuzzy pair lengths do not match: " + readable);
88 }
89
90 Pair<byte[], byte[]> p = new Pair<>();
91
92 p.setFirst(Arrays.copyOf(aFuzzyKeysData.getFirst(), aFuzzyKeysData.getFirst().length));
93 p.setSecond(Arrays.copyOf(aFuzzyKeysData.getSecond(), aFuzzyKeysData.getSecond().length));
94
95
96 p.setSecond(preprocessMask(p.getSecond()));
97 preprocessSearchKey(p);
98
99 fuzzyKeyDataCopy.add(p);
100 }
101 this.fuzzyKeysData = fuzzyKeyDataCopy;
102 this.tracker = new RowTracker();
103 }
104
105 private void preprocessSearchKey(Pair<byte[], byte[]> p) {
106 if (!UNSAFE_UNALIGNED) {
107 return;
108 }
109 byte[] key = p.getFirst();
110 byte[] mask = p.getSecond();
111 for (int i = 0; i < mask.length; i++) {
112
113 if (mask[i] == 2) {
114 key[i] = 0;
115 }
116 }
117 }
118
119
120
121
122
123
124
125 private byte[] preprocessMask(byte[] mask) {
126 if (!UNSAFE_UNALIGNED) {
127 return mask;
128 }
129 if (isPreprocessedMask(mask)) return mask;
130 for (int i = 0; i < mask.length; i++) {
131 if (mask[i] == 0) {
132 mask[i] = -1;
133 } else if (mask[i] == 1) {
134 mask[i] = 2;
135 }
136 }
137 return mask;
138 }
139
140 private boolean isPreprocessedMask(byte[] mask) {
141 for (int i = 0; i < mask.length; i++) {
142 if (mask[i] != -1 && mask[i] != 2) {
143 return false;
144 }
145 }
146 return true;
147 }
148
149 @Override
150 public ReturnCode filterKeyValue(Cell c) {
151 final int startIndex = lastFoundIndex >= 0 ? lastFoundIndex : 0;
152 final int size = fuzzyKeysData.size();
153 for (int i = startIndex; i < size + startIndex; i++) {
154 final int index = i % size;
155 Pair<byte[], byte[]> fuzzyData = fuzzyKeysData.get(index);
156
157 for (int j = 0; j < fuzzyData.getSecond().length; j++) {
158 fuzzyData.getSecond()[j] >>= 2;
159 }
160 SatisfiesCode satisfiesCode =
161 satisfies(isReversed(), c.getRowArray(), c.getRowOffset(), c.getRowLength(),
162 fuzzyData.getFirst(), fuzzyData.getSecond());
163 if (satisfiesCode == SatisfiesCode.YES) {
164 lastFoundIndex = index;
165 return ReturnCode.INCLUDE;
166 }
167 }
168
169 lastFoundIndex = -1;
170
171 return ReturnCode.SEEK_NEXT_USING_HINT;
172
173 }
174
175 @Override
176 public Cell getNextCellHint(Cell currentCell) {
177 boolean result = tracker.updateTracker(currentCell);
178 if (result == false) {
179 done = true;
180 return null;
181 }
182 byte[] nextRowKey = tracker.nextRow();
183 return KeyValueUtil.createFirstOnRow(nextRowKey);
184 }
185
186
187
188
189
190
191
192
193
194 private class RowTracker {
195 private final PriorityQueue<Pair<byte[], Pair<byte[], byte[]>>> nextRows;
196 private boolean initialized = false;
197
198 RowTracker() {
199 nextRows =
200 new PriorityQueue<Pair<byte[], Pair<byte[], byte[]>>>(fuzzyKeysData.size(),
201 new Comparator<Pair<byte[], Pair<byte[], byte[]>>>() {
202 @Override
203 public int compare(Pair<byte[], Pair<byte[], byte[]>> o1,
204 Pair<byte[], Pair<byte[], byte[]>> o2) {
205 return isReversed()? Bytes.compareTo(o2.getFirst(), o1.getFirst()):
206 Bytes.compareTo(o1.getFirst(), o2.getFirst());
207 }
208 });
209 }
210
211 byte[] nextRow() {
212 if (nextRows.isEmpty()) {
213 throw new IllegalStateException(
214 "NextRows should not be empty, make sure to call nextRow() after updateTracker() return true");
215 } else {
216 return nextRows.peek().getFirst();
217 }
218 }
219
220 boolean updateTracker(Cell currentCell) {
221 if (!initialized) {
222 for (Pair<byte[], byte[]> fuzzyData : fuzzyKeysData) {
223 updateWith(currentCell, fuzzyData);
224 }
225 initialized = true;
226 } else {
227 while (!nextRows.isEmpty() && !lessThan(currentCell, nextRows.peek().getFirst())) {
228 Pair<byte[], Pair<byte[], byte[]>> head = nextRows.poll();
229 Pair<byte[], byte[]> fuzzyData = head.getSecond();
230 updateWith(currentCell, fuzzyData);
231 }
232 }
233 return !nextRows.isEmpty();
234 }
235
236 boolean lessThan(Cell currentCell, byte[] nextRowKey) {
237 int compareResult =
238 Bytes.compareTo(currentCell.getRowArray(), currentCell.getRowOffset(),
239 currentCell.getRowLength(), nextRowKey, 0, nextRowKey.length);
240 return (!isReversed() && compareResult < 0) || (isReversed() && compareResult > 0);
241 }
242
243 void updateWith(Cell currentCell, Pair<byte[], byte[]> fuzzyData) {
244 byte[] nextRowKeyCandidate =
245 getNextForFuzzyRule(isReversed(), currentCell.getRowArray(), currentCell.getRowOffset(),
246 currentCell.getRowLength(), fuzzyData.getFirst(), fuzzyData.getSecond());
247 if (nextRowKeyCandidate != null) {
248 nextRows.add(new Pair<byte[], Pair<byte[], byte[]>>(nextRowKeyCandidate, fuzzyData));
249 }
250 }
251
252 }
253
254 @Override
255 public boolean filterAllRemaining() {
256 return done;
257 }
258
259
260
261
262 @Override
263 public byte[] toByteArray() {
264 FilterProtos.FuzzyRowFilter.Builder builder = FilterProtos.FuzzyRowFilter.newBuilder();
265 for (Pair<byte[], byte[]> fuzzyData : fuzzyKeysData) {
266 BytesBytesPair.Builder bbpBuilder = BytesBytesPair.newBuilder();
267 bbpBuilder.setFirst(ByteStringer.wrap(fuzzyData.getFirst()));
268 bbpBuilder.setSecond(ByteStringer.wrap(fuzzyData.getSecond()));
269 builder.addFuzzyKeysData(bbpBuilder);
270 }
271 return builder.build().toByteArray();
272 }
273
274
275
276
277
278
279
280 public static FuzzyRowFilter parseFrom(final byte[] pbBytes) throws DeserializationException {
281 FilterProtos.FuzzyRowFilter proto;
282 try {
283 proto = FilterProtos.FuzzyRowFilter.parseFrom(pbBytes);
284 } catch (InvalidProtocolBufferException e) {
285 throw new DeserializationException(e);
286 }
287 int count = proto.getFuzzyKeysDataCount();
288 ArrayList<Pair<byte[], byte[]>> fuzzyKeysData = new ArrayList<Pair<byte[], byte[]>>(count);
289 for (int i = 0; i < count; ++i) {
290 BytesBytesPair current = proto.getFuzzyKeysData(i);
291 byte[] keyBytes = current.getFirst().toByteArray();
292 byte[] keyMeta = current.getSecond().toByteArray();
293 fuzzyKeysData.add(new Pair<byte[], byte[]>(keyBytes, keyMeta));
294 }
295 return new FuzzyRowFilter(fuzzyKeysData);
296 }
297
298 @Override
299 public String toString() {
300 final StringBuilder sb = new StringBuilder();
301 sb.append("FuzzyRowFilter");
302 sb.append("{fuzzyKeysData=");
303 for (Pair<byte[], byte[]> fuzzyData : fuzzyKeysData) {
304 sb.append('{').append(Bytes.toStringBinary(fuzzyData.getFirst())).append(":");
305 sb.append(Bytes.toStringBinary(fuzzyData.getSecond())).append('}');
306 }
307 sb.append("}, ");
308 return sb.toString();
309 }
310
311
312
313 static enum SatisfiesCode {
314
315 YES,
316
317 NEXT_EXISTS,
318
319 NO_NEXT
320 }
321
322 @VisibleForTesting
323 static SatisfiesCode satisfies(byte[] row, byte[] fuzzyKeyBytes, byte[] fuzzyKeyMeta) {
324 return satisfies(false, row, 0, row.length, fuzzyKeyBytes, fuzzyKeyMeta);
325 }
326
327 @VisibleForTesting
328 static SatisfiesCode satisfies(boolean reverse, byte[] row, byte[] fuzzyKeyBytes,
329 byte[] fuzzyKeyMeta) {
330 return satisfies(reverse, row, 0, row.length, fuzzyKeyBytes, fuzzyKeyMeta);
331 }
332
333 static SatisfiesCode satisfies(boolean reverse, byte[] row, int offset, int length,
334 byte[] fuzzyKeyBytes, byte[] fuzzyKeyMeta) {
335
336 if (!UNSAFE_UNALIGNED) {
337 return satisfiesNoUnsafe(reverse, row, offset, length, fuzzyKeyBytes, fuzzyKeyMeta);
338 }
339
340 if (row == null) {
341
342 return SatisfiesCode.YES;
343 }
344 length = Math.min(length, fuzzyKeyBytes.length);
345 int numWords = length / Bytes.SIZEOF_LONG;
346 int offsetAdj = offset + UnsafeAccess.BYTE_ARRAY_BASE_OFFSET;
347
348 int j = numWords << 3;
349
350 for (int i = 0; i < j; i += Bytes.SIZEOF_LONG) {
351
352 long fuzzyBytes =
353 UnsafeAccess.theUnsafe.getLong(fuzzyKeyBytes, UnsafeAccess.BYTE_ARRAY_BASE_OFFSET
354 + (long) i);
355 long fuzzyMeta =
356 UnsafeAccess.theUnsafe.getLong(fuzzyKeyMeta, UnsafeAccess.BYTE_ARRAY_BASE_OFFSET
357 + (long) i);
358 long rowValue = UnsafeAccess.theUnsafe.getLong(row, offsetAdj + (long) i);
359 if ((rowValue & fuzzyMeta) != (fuzzyBytes)) {
360
361 return SatisfiesCode.NEXT_EXISTS;
362 }
363 }
364
365 int off = j;
366
367 if (length - off >= Bytes.SIZEOF_INT) {
368 int fuzzyBytes =
369 UnsafeAccess.theUnsafe.getInt(fuzzyKeyBytes, UnsafeAccess.BYTE_ARRAY_BASE_OFFSET
370 + (long) off);
371 int fuzzyMeta =
372 UnsafeAccess.theUnsafe.getInt(fuzzyKeyMeta, UnsafeAccess.BYTE_ARRAY_BASE_OFFSET
373 + (long) off);
374 int rowValue = UnsafeAccess.theUnsafe.getInt(row, offsetAdj + (long) off);
375 if ((rowValue & fuzzyMeta) != (fuzzyBytes)) {
376
377 return SatisfiesCode.NEXT_EXISTS;
378 }
379 off += Bytes.SIZEOF_INT;
380 }
381
382 if (length - off >= Bytes.SIZEOF_SHORT) {
383 short fuzzyBytes =
384 UnsafeAccess.theUnsafe.getShort(fuzzyKeyBytes, UnsafeAccess.BYTE_ARRAY_BASE_OFFSET
385 + (long) off);
386 short fuzzyMeta =
387 UnsafeAccess.theUnsafe.getShort(fuzzyKeyMeta, UnsafeAccess.BYTE_ARRAY_BASE_OFFSET
388 + (long) off);
389 short rowValue = UnsafeAccess.theUnsafe.getShort(row, offsetAdj + (long) off);
390 if ((rowValue & fuzzyMeta) != (fuzzyBytes)) {
391
392
393
394 return SatisfiesCode.NEXT_EXISTS;
395 }
396 off += Bytes.SIZEOF_SHORT;
397 }
398
399 if (length - off >= Bytes.SIZEOF_BYTE) {
400 int fuzzyBytes = fuzzyKeyBytes[off] & 0xff;
401 int fuzzyMeta = fuzzyKeyMeta[off] & 0xff;
402 int rowValue = row[offset + off] & 0xff;
403 if ((rowValue & fuzzyMeta) != (fuzzyBytes)) {
404
405 return SatisfiesCode.NEXT_EXISTS;
406 }
407 }
408 return SatisfiesCode.YES;
409 }
410
411 static SatisfiesCode satisfiesNoUnsafe(boolean reverse, byte[] row, int offset, int length,
412 byte[] fuzzyKeyBytes, byte[] fuzzyKeyMeta) {
413 if (row == null) {
414
415 return SatisfiesCode.YES;
416 }
417
418 Order order = Order.orderFor(reverse);
419 boolean nextRowKeyCandidateExists = false;
420
421 for (int i = 0; i < fuzzyKeyMeta.length && i < length; i++) {
422
423 boolean byteAtPositionFixed = fuzzyKeyMeta[i] == 0;
424 boolean fixedByteIncorrect = byteAtPositionFixed && fuzzyKeyBytes[i] != row[i + offset];
425 if (fixedByteIncorrect) {
426
427 if (nextRowKeyCandidateExists) {
428 return SatisfiesCode.NEXT_EXISTS;
429 }
430
431
432
433
434 boolean rowByteLessThanFixed = (row[i + offset] & 0xFF) < (fuzzyKeyBytes[i] & 0xFF);
435 if (rowByteLessThanFixed && !reverse) {
436 return SatisfiesCode.NEXT_EXISTS;
437 } else if (!rowByteLessThanFixed && reverse) {
438 return SatisfiesCode.NEXT_EXISTS;
439 } else {
440 return SatisfiesCode.NO_NEXT;
441 }
442 }
443
444
445
446
447
448
449
450 if (fuzzyKeyMeta[i] == 1 && !order.isMax(fuzzyKeyBytes[i])) {
451 nextRowKeyCandidateExists = true;
452 }
453 }
454 return SatisfiesCode.YES;
455 }
456
457 @VisibleForTesting
458 static byte[] getNextForFuzzyRule(byte[] row, byte[] fuzzyKeyBytes, byte[] fuzzyKeyMeta) {
459 return getNextForFuzzyRule(false, row, 0, row.length, fuzzyKeyBytes, fuzzyKeyMeta);
460 }
461
462 @VisibleForTesting
463 static byte[] getNextForFuzzyRule(boolean reverse, byte[] row, byte[] fuzzyKeyBytes,
464 byte[] fuzzyKeyMeta) {
465 return getNextForFuzzyRule(reverse, row, 0, row.length, fuzzyKeyBytes, fuzzyKeyMeta);
466 }
467
468
469 private enum Order {
470 ASC {
471 @Override
472 public boolean lt(int lhs, int rhs) {
473 return lhs < rhs;
474 }
475
476 @Override
477 public boolean gt(int lhs, int rhs) {
478 return lhs > rhs;
479 }
480
481 @Override
482 public byte inc(byte val) {
483
484 return (byte) (val + 1);
485 }
486
487 @Override
488 public boolean isMax(byte val) {
489 return val == (byte) 0xff;
490 }
491
492 @Override
493 public byte min() {
494 return 0;
495 }
496 },
497 DESC {
498 @Override
499 public boolean lt(int lhs, int rhs) {
500 return lhs > rhs;
501 }
502
503 @Override
504 public boolean gt(int lhs, int rhs) {
505 return lhs < rhs;
506 }
507
508 @Override
509 public byte inc(byte val) {
510
511 return (byte) (val - 1);
512 }
513
514 @Override
515 public boolean isMax(byte val) {
516 return val == 0;
517 }
518
519 @Override
520 public byte min() {
521 return (byte) 0xFF;
522 }
523 };
524
525 public static Order orderFor(boolean reverse) {
526 return reverse ? DESC : ASC;
527 }
528
529
530 public abstract boolean lt(int lhs, int rhs);
531
532
533 public abstract boolean gt(int lhs, int rhs);
534
535
536 public abstract byte inc(byte val);
537
538
539 public abstract boolean isMax(byte val);
540
541
542 public abstract byte min();
543 }
544
545
546
547
548
549 @VisibleForTesting
550 static byte[] getNextForFuzzyRule(boolean reverse, byte[] row, int offset, int length,
551 byte[] fuzzyKeyBytes, byte[] fuzzyKeyMeta) {
552
553
554
555
556
557
558
559
560 byte[] result =
561 Arrays.copyOf(fuzzyKeyBytes, length > fuzzyKeyBytes.length ? length : fuzzyKeyBytes.length);
562 if (reverse && length > fuzzyKeyBytes.length) {
563
564 for (int i = fuzzyKeyBytes.length; i < result.length; i++) {
565 result[i] = (byte) 0xFF;
566 }
567 }
568 int toInc = -1;
569 final Order order = Order.orderFor(reverse);
570
571 boolean increased = false;
572 for (int i = 0; i < result.length; i++) {
573 if (i >= fuzzyKeyMeta.length || fuzzyKeyMeta[i] == 0
574 result[i] = row[offset + i];
575 if (!order.isMax(row[offset + i])) {
576
577 toInc = i;
578 }
579 } else if (i < fuzzyKeyMeta.length && fuzzyKeyMeta[i] == -1
580 if (order.lt((row[i + offset] & 0xFF), (fuzzyKeyBytes[i] & 0xFF))) {
581
582
583 increased = true;
584 break;
585 }
586
587 if (order.gt((row[i + offset] & 0xFF), (fuzzyKeyBytes[i] & 0xFF))) {
588
589
590
591 break;
592 }
593 }
594 }
595
596 if (!increased) {
597 if (toInc < 0) {
598 return null;
599 }
600 result[toInc] = order.inc(result[toInc]);
601
602
603
604 for (int i = toInc + 1; i < result.length; i++) {
605 if (i >= fuzzyKeyMeta.length || fuzzyKeyMeta[i] == 0
606 result[i] = order.min();
607 }
608 }
609 }
610
611 return reverse? result: trimTrailingZeroes(result, fuzzyKeyMeta, toInc);
612 }
613
614
615
616
617
618
619
620
621
622
623
624
625
626 private static byte[] trimTrailingZeroes(byte[] result, byte[] fuzzyKeyMeta, int toInc) {
627 int off = fuzzyKeyMeta.length >= result.length? result.length -1:
628 fuzzyKeyMeta.length -1;
629 for( ; off >= 0; off--){
630 if(fuzzyKeyMeta[off] != 0) break;
631 }
632 if (off < toInc) off = toInc;
633 byte[] retValue = new byte[off+1];
634 System.arraycopy(result, 0, retValue, 0, retValue.length);
635 return retValue;
636 }
637
638
639
640
641
642 @Override
643 boolean areSerializedFieldsEqual(Filter o) {
644 if (o == this) return true;
645 if (!(o instanceof FuzzyRowFilter)) return false;
646
647 FuzzyRowFilter other = (FuzzyRowFilter) o;
648 if (this.fuzzyKeysData.size() != other.fuzzyKeysData.size()) return false;
649 for (int i = 0; i < fuzzyKeysData.size(); ++i) {
650 Pair<byte[], byte[]> thisData = this.fuzzyKeysData.get(i);
651 Pair<byte[], byte[]> otherData = other.fuzzyKeysData.get(i);
652 if (!(Bytes.equals(thisData.getFirst(), otherData.getFirst()) && Bytes.equals(
653 thisData.getSecond(), otherData.getSecond()))) {
654 return false;
655 }
656 }
657 return true;
658 }
659
660 @Override
661 public boolean equals(Object obj) {
662 return obj instanceof Filter && areSerializedFieldsEqual((Filter) obj);
663 }
664
665 @Override
666 public int hashCode() {
667 return Objects.hash(this.fuzzyKeysData);
668 }
669 }