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