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