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