View Javadoc

1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *     http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing, software
13   * distributed under the License is distributed on an "AS IS" BASIS,
14   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15   * See the License for the specific language governing permissions and
16   * limitations under the License.
17   */
18  package org.apache.hadoop.hbase.filter;
19  
20  import java.io.IOException;
21  import java.util.ArrayList;
22  import java.util.Collections;
23  import java.util.List;
24  
25  import org.apache.hadoop.hbase.Cell;
26  import org.apache.hadoop.hbase.HConstants;
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.util.ByteStringer;
33  import org.apache.hadoop.hbase.util.Bytes;
34  
35  import com.google.protobuf.InvalidProtocolBufferException;
36  
37  /**
38   * Filter to support scan multiple row key ranges. It can construct the row key ranges from the
39   * passed list which can be accessed by each region server.
40   *
41   * HBase is quite efficient when scanning only one small row key range. If user needs to specify
42   * multiple row key ranges in one scan, the typical solutions are: 1. through FilterList which is a
43   * list of row key Filters, 2. using the SQL layer over HBase to join with two table, such as hive,
44   * phoenix etc. However, both solutions are inefficient. Both of them can't utilize the range info
45   * to perform fast forwarding during scan which is quite time consuming. If the number of ranges
46   * are quite big (e.g. millions), join is a proper solution though it is slow. However, there are
47   * cases that user wants to specify a small number of ranges to scan (e.g. <1000 ranges). Both
48   * solutions can't provide satisfactory performance in such case. MultiRowRangeFilter is to support
49   * such usec ase (scan multiple row key ranges), which can construct the row key ranges from user
50   * specified list and perform fast-forwarding during scan. Thus, the scan will be quite efficient.
51   */
52  @InterfaceAudience.Public
53  @InterfaceStability.Evolving
54  public class MultiRowRangeFilter extends FilterBase {
55  
56    private List<RowRange> rangeList;
57  
58    private static final int ROW_BEFORE_FIRST_RANGE = -1;
59    private boolean EXCLUSIVE = false;
60    private boolean done = false;
61    private boolean initialized = false;
62    private int index;
63    private RowRange range;
64    private ReturnCode currentReturnCode;
65  
66    /**
67     * @param list A list of <code>RowRange</code>
68     * @throws java.io.IOException
69     *           throw an exception if the range list is not in an natural order or any
70     *           <code>RowRange</code> is invalid
71     */
72    public MultiRowRangeFilter(List<RowRange> list) throws IOException {
73      this.rangeList = sortAndMerge(list);
74    }
75  
76    @Override
77    public boolean filterAllRemaining() {
78      return done;
79    }
80  
81    public List<RowRange> getRowRanges() {
82      return this.rangeList;
83    }
84  
85    @Override
86    public boolean filterRowKey(byte[] buffer, int offset, int length) {
87      // If it is the first time of running, calculate the current range index for
88      // the row key. If index is out of bound which happens when the start row
89      // user sets is after the largest stop row of the ranges, stop the scan.
90      // If row key is after the current range, find the next range and update index.
91      if (!initialized || !range.contains(buffer, offset, length)) {
92        byte[] rowkey = new byte[length];
93        System.arraycopy(buffer, offset, rowkey, 0, length);
94        index = getNextRangeIndex(rowkey);
95        if (index >= rangeList.size()) {
96          done = true;
97          currentReturnCode = ReturnCode.NEXT_ROW;
98          return false;
99        }
100       if(index != ROW_BEFORE_FIRST_RANGE) {
101         range = rangeList.get(index);
102       } else {
103         range = rangeList.get(0);
104       }
105       if(EXCLUSIVE) {
106         EXCLUSIVE = false;
107         currentReturnCode = ReturnCode.NEXT_ROW;
108         return false;
109       }
110       if (!initialized) {
111         if(index != ROW_BEFORE_FIRST_RANGE) {
112           currentReturnCode = ReturnCode.INCLUDE;
113         } else {
114           currentReturnCode = ReturnCode.SEEK_NEXT_USING_HINT;
115         }
116         initialized = true;
117       } else {
118         currentReturnCode = ReturnCode.SEEK_NEXT_USING_HINT;
119       }
120     } else {
121       currentReturnCode = ReturnCode.INCLUDE;
122     }
123     return false;
124   }
125 
126   @Override
127   public ReturnCode filterKeyValue(Cell ignored) {
128     return currentReturnCode;
129   }
130 
131   @Override
132   public Cell getNextCellHint(Cell currentKV) {
133     // skip to the next range's start row
134     return KeyValueUtil.createFirstOnRow(range.startRow);
135   }
136 
137   /**
138    * @return The filter serialized using pb
139    */
140   public byte[] toByteArray() {
141     FilterProtos.MultiRowRangeFilter.Builder builder = FilterProtos.MultiRowRangeFilter
142         .newBuilder();
143     for (RowRange range : rangeList) {
144       if (range != null) {
145         FilterProtos.RowRange.Builder rangebuilder = FilterProtos.RowRange.newBuilder();
146         if (range.startRow != null)
147           rangebuilder.setStartRow(ByteStringer.wrap(range.startRow));
148         rangebuilder.setStartRowInclusive(range.startRowInclusive);
149         if (range.stopRow != null)
150           rangebuilder.setStopRow(ByteStringer.wrap(range.stopRow));
151         rangebuilder.setStopRowInclusive(range.stopRowInclusive);
152         range.isScan = Bytes.equals(range.startRow, range.stopRow) ? 1 : 0;
153         builder.addRowRangeList(rangebuilder.build());
154       }
155     }
156     return builder.build().toByteArray();
157   }
158 
159   /**
160    * @param pbBytes A pb serialized instance
161    * @return An instance of MultiRowRangeFilter
162    * @throws org.apache.hadoop.hbase.exceptions.DeserializationException
163    */
164   public static MultiRowRangeFilter parseFrom(final byte[] pbBytes)
165       throws DeserializationException {
166     FilterProtos.MultiRowRangeFilter proto;
167     try {
168       proto = FilterProtos.MultiRowRangeFilter.parseFrom(pbBytes);
169     } catch (InvalidProtocolBufferException e) {
170       throw new DeserializationException(e);
171     }
172     int length = proto.getRowRangeListCount();
173     List<FilterProtos.RowRange> rangeProtos = proto.getRowRangeListList();
174     List<RowRange> rangeList = new ArrayList<RowRange>(length);
175     for (FilterProtos.RowRange rangeProto : rangeProtos) {
176       RowRange range = new RowRange(rangeProto.hasStartRow() ? rangeProto.getStartRow()
177           .toByteArray() : null, rangeProto.getStartRowInclusive(), rangeProto.hasStopRow() ?
178               rangeProto.getStopRow().toByteArray() : null, rangeProto.getStopRowInclusive());
179       rangeList.add(range);
180     }
181     try {
182       return new MultiRowRangeFilter(rangeList);
183     } catch (IOException e) {
184       throw new DeserializationException("Fail to instantiate the MultiRowRangeFilter", e);
185     }
186   }
187 
188   /**
189    * @param o the filter to compare
190    * @return true if and only if the fields of the filter that are serialized are equal to the
191    *         corresponding fields in other. Used for testing.
192    */
193   boolean areSerializedFieldsEqual(Filter o) {
194     if (o == this)
195       return true;
196     if (!(o instanceof MultiRowRangeFilter))
197       return false;
198 
199     MultiRowRangeFilter other = (MultiRowRangeFilter) o;
200     if (this.rangeList.size() != other.rangeList.size())
201       return false;
202     for (int i = 0; i < rangeList.size(); ++i) {
203       RowRange thisRange = this.rangeList.get(i);
204       RowRange otherRange = other.rangeList.get(i);
205       if (!(Bytes.equals(thisRange.startRow, otherRange.startRow) && Bytes.equals(
206           thisRange.stopRow, otherRange.stopRow) && (thisRange.startRowInclusive ==
207           otherRange.startRowInclusive) && (thisRange.stopRowInclusive ==
208           otherRange.stopRowInclusive))) {
209         return false;
210       }
211     }
212     return true;
213   }
214 
215   /**
216    * calculate the position where the row key in the ranges list.
217    *
218    * @param rowKey the row key to calculate
219    * @return index the position of the row key
220    */
221   private int getNextRangeIndex(byte[] rowKey) {
222     RowRange temp = new RowRange(rowKey, true, null, true);
223     int index = Collections.binarySearch(rangeList, temp);
224     if (index < 0) {
225       int insertionPosition = -index - 1;
226       // check if the row key in the range before the insertion position
227       if (insertionPosition != 0 && rangeList.get(insertionPosition - 1).contains(rowKey)) {
228         return insertionPosition - 1;
229       }
230       // check if the row key is before the first range
231       if (insertionPosition == 0 && !rangeList.get(insertionPosition).contains(rowKey)) {
232         return ROW_BEFORE_FIRST_RANGE;
233       }
234       return insertionPosition;
235     }
236     // the row key equals one of the start keys, and the the range exclude the start key
237     if(rangeList.get(index).startRowInclusive == false) {
238       EXCLUSIVE = true;
239     }
240     return index;
241   }
242 
243   /**
244    * sort the ranges and if the ranges with overlap, then merge them.
245    *
246    * @param ranges the list of ranges to sort and merge.
247    * @return the ranges after sort and merge.
248    */
249   public static List<RowRange> sortAndMerge(List<RowRange> ranges) {
250     if (ranges.size() == 0) {
251       throw new IllegalArgumentException("No ranges found.");
252     }
253     List<RowRange> invalidRanges = new ArrayList<RowRange>();
254     List<RowRange> newRanges = new ArrayList<RowRange>(ranges.size());
255     Collections.sort(ranges);
256     if(ranges.get(0).isValid()) {
257       if (ranges.size() == 1) {
258         newRanges.add(ranges.get(0));
259       }
260     } else {
261       invalidRanges.add(ranges.get(0));
262     }
263 
264     byte[] lastStartRow = ranges.get(0).startRow;
265     boolean lastStartRowInclusive = ranges.get(0).startRowInclusive;
266     byte[] lastStopRow = ranges.get(0).stopRow;
267     boolean lastStopRowInclusive = ranges.get(0).stopRowInclusive;
268     int i = 1;
269     for (; i < ranges.size(); i++) {
270       RowRange range = ranges.get(i);
271       if (!range.isValid()) {
272         invalidRanges.add(range);
273       }
274       if(Bytes.equals(lastStopRow, HConstants.EMPTY_BYTE_ARRAY)) {
275         newRanges.add(new RowRange(lastStartRow, lastStartRowInclusive, lastStopRow,
276             lastStopRowInclusive));
277         break;
278       }
279       // with overlap in the ranges
280       if ((Bytes.compareTo(lastStopRow, range.startRow) > 0) ||
281           (Bytes.compareTo(lastStopRow, range.startRow) == 0 && !(lastStopRowInclusive == false &&
282           range.isStartRowInclusive() == false))) {
283         if(Bytes.equals(range.stopRow, HConstants.EMPTY_BYTE_ARRAY)) {
284           newRanges.add(new RowRange(lastStartRow, lastStartRowInclusive, range.stopRow,
285               range.stopRowInclusive));
286           break;
287         }
288         // if first range contains second range, ignore the second range
289         if (Bytes.compareTo(lastStopRow, range.stopRow) >= 0) {
290           if((Bytes.compareTo(lastStopRow, range.stopRow) == 0)) {
291             if(lastStopRowInclusive == true || range.stopRowInclusive == true) {
292               lastStopRowInclusive = true;
293             }
294           }
295           if ((i + 1) == ranges.size()) {
296             newRanges.add(new RowRange(lastStartRow, lastStartRowInclusive, lastStopRow,
297                 lastStopRowInclusive));
298           }
299         } else {
300           lastStopRow = range.stopRow;
301           lastStopRowInclusive = range.stopRowInclusive;
302           if ((i + 1) < ranges.size()) {
303             i++;
304             range = ranges.get(i);
305             if (!range.isValid()) {
306               invalidRanges.add(range);
307             }
308           } else {
309             newRanges.add(new RowRange(lastStartRow, lastStartRowInclusive, lastStopRow,
310                 lastStopRowInclusive));
311             break;
312           }
313           while ((Bytes.compareTo(lastStopRow, range.startRow) > 0) ||
314               (Bytes.compareTo(lastStopRow, range.startRow) == 0 &&
315               (lastStopRowInclusive == true || range.startRowInclusive==true))) {
316             if(Bytes.equals(range.stopRow, HConstants.EMPTY_BYTE_ARRAY)) {
317               break;
318             }
319             // if this first range contain second range, ignore the second range
320             if (Bytes.compareTo(lastStopRow, range.stopRow) >= 0) {
321               if(lastStopRowInclusive == true || range.stopRowInclusive == true) {
322                 lastStopRowInclusive = true;
323               }
324               i++;
325               if (i < ranges.size()) {
326                 range = ranges.get(i);
327                 if (!range.isValid()) {
328                   invalidRanges.add(range);
329                 }
330               } else {
331                 break;
332               }
333             } else {
334               lastStopRow = range.stopRow;
335               lastStopRowInclusive = range.stopRowInclusive;
336               i++;
337               if (i < ranges.size()) {
338                 range = ranges.get(i);
339                 if (!range.isValid()) {
340                   invalidRanges.add(range);
341                 }
342               } else {
343                 break;
344               }
345             }
346           }
347           if(Bytes.equals(range.stopRow, HConstants.EMPTY_BYTE_ARRAY)) {
348             if((Bytes.compareTo(lastStopRow, range.startRow) < 0) ||
349                 (Bytes.compareTo(lastStopRow, range.startRow) == 0 &&
350                 lastStopRowInclusive == false && range.startRowInclusive == false)) {
351               newRanges.add(new RowRange(lastStartRow, lastStartRowInclusive, lastStopRow,
352                   lastStopRowInclusive));
353               newRanges.add(range);
354             } else {
355               newRanges.add(new RowRange(lastStartRow, lastStartRowInclusive, range.stopRow,
356                   range.stopRowInclusive));
357               break;
358             }
359           }
360           newRanges.add(new RowRange(lastStartRow, lastStartRowInclusive, lastStopRow,
361               lastStopRowInclusive));
362           if ((i + 1) == ranges.size()) {
363             newRanges.add(range);
364           }
365           lastStartRow = range.startRow;
366           lastStartRowInclusive = range.startRowInclusive;
367           lastStopRow = range.stopRow;
368           lastStopRowInclusive = range.stopRowInclusive;
369         }
370       } else {
371         newRanges.add(new RowRange(lastStartRow, lastStartRowInclusive, lastStopRow,
372             lastStopRowInclusive));
373         if ((i + 1) == ranges.size()) {
374           newRanges.add(range);
375         }
376         lastStartRow = range.startRow;
377         lastStartRowInclusive = range.startRowInclusive;
378         lastStopRow = range.stopRow;
379         lastStopRowInclusive = range.stopRowInclusive;
380       }
381     }
382     // check the remaining ranges
383     for(int j=i; j < ranges.size(); j++) {
384       if(!ranges.get(j).isValid()) {
385         invalidRanges.add(ranges.get(j));
386       }
387     }
388     // if invalid range exists, throw the exception
389     if (invalidRanges.size() != 0) {
390       throwExceptionForInvalidRanges(invalidRanges, true);
391     }
392     // If no valid ranges found, throw the exception
393     if(newRanges.size() == 0) {
394       throw new IllegalArgumentException("No valid ranges found.");
395     }
396     return newRanges;
397   }
398 
399   private static void throwExceptionForInvalidRanges(List<RowRange> invalidRanges,
400       boolean details) {
401     StringBuilder sb = new StringBuilder();
402     sb.append(invalidRanges.size()).append(" invaild ranges.\n");
403     if (details) {
404       for (RowRange range : invalidRanges) {
405         sb.append(
406             "Invalid range: start row => " + Bytes.toString(range.startRow) + ", stop row => "
407                 + Bytes.toString(range.stopRow)).append('\n');
408       }
409     }
410     throw new IllegalArgumentException(sb.toString());
411   }
412 
413   @InterfaceAudience.Public
414   @InterfaceStability.Evolving
415   public static class RowRange implements Comparable<RowRange> {
416     private byte[] startRow;
417     private boolean startRowInclusive = true;
418     private byte[] stopRow;
419     private boolean stopRowInclusive = false;
420     private int isScan = 0;
421 
422     public RowRange() {
423     }
424     /**
425      * If the startRow is empty or null, set it to HConstants.EMPTY_BYTE_ARRAY, means begin at the
426      * start row of the table. If the stopRow is empty or null, set it to
427      * HConstants.EMPTY_BYTE_ARRAY, means end of the last row of table.
428      */
429     public RowRange(String startRow, boolean startRowInclusive, String stopRow,
430         boolean stopRowInclusive) {
431       this((startRow == null || startRow.isEmpty()) ? HConstants.EMPTY_BYTE_ARRAY :
432         Bytes.toBytes(startRow), startRowInclusive,
433         (stopRow == null || stopRow.isEmpty()) ? HConstants.EMPTY_BYTE_ARRAY :
434         Bytes.toBytes(stopRow), stopRowInclusive);
435     }
436 
437     public RowRange(byte[] startRow,  boolean startRowInclusive, byte[] stopRow,
438         boolean stopRowInclusive) {
439       this.startRow = (startRow == null) ? HConstants.EMPTY_BYTE_ARRAY : startRow;
440       this.startRowInclusive = startRowInclusive;
441       this.stopRow = (stopRow == null) ? HConstants.EMPTY_BYTE_ARRAY :stopRow;
442       this.stopRowInclusive = stopRowInclusive;
443       isScan = Bytes.equals(startRow, stopRow) ? 1 : 0;
444     }
445 
446     public byte[] getStartRow() {
447       return startRow;
448     }
449 
450     public byte[] getStopRow() {
451       return stopRow;
452     }
453 
454     /**
455      * @return if start row is inclusive.
456      */
457     public boolean isStartRowInclusive() {
458       return startRowInclusive;
459     }
460 
461     /**
462      * @return if stop row is inclusive.
463      */
464     public boolean isStopRowInclusive() {
465       return stopRowInclusive;
466     }
467 
468     public boolean contains(byte[] row) {
469       return contains(row, 0, row.length);
470     }
471 
472     public boolean contains(byte[] buffer, int offset, int length) {
473       if(startRowInclusive) {
474         if(stopRowInclusive) {
475           return Bytes.compareTo(buffer, offset, length, startRow, 0, startRow.length) >= 0
476               && (Bytes.equals(stopRow, HConstants.EMPTY_BYTE_ARRAY) ||
477                   Bytes.compareTo(buffer, offset, length, stopRow, 0, stopRow.length) <= isScan);
478         } else {
479           return Bytes.compareTo(buffer, offset, length, startRow, 0, startRow.length) >= 0
480               && (Bytes.equals(stopRow, HConstants.EMPTY_BYTE_ARRAY) ||
481                   Bytes.compareTo(buffer, offset, length, stopRow, 0, stopRow.length) < isScan);
482         }
483       } else {
484         if(stopRowInclusive) {
485           return Bytes.compareTo(buffer, offset, length, startRow, 0, startRow.length) > 0
486               && (Bytes.equals(stopRow, HConstants.EMPTY_BYTE_ARRAY) ||
487                   Bytes.compareTo(buffer, offset, length, stopRow, 0, stopRow.length) <= isScan);
488         } else {
489           return Bytes.compareTo(buffer, offset, length, startRow, 0, startRow.length) > 0
490               && (Bytes.equals(stopRow, HConstants.EMPTY_BYTE_ARRAY) ||
491                   Bytes.compareTo(buffer, offset, length, stopRow, 0, stopRow.length) < isScan);
492         }
493       }
494     }
495 
496     @Override
497     public int compareTo(RowRange other) {
498       return Bytes.compareTo(this.startRow, other.startRow);
499     }
500 
501     public boolean isValid() {
502       return Bytes.equals(startRow, HConstants.EMPTY_BYTE_ARRAY)
503           || Bytes.equals(stopRow, HConstants.EMPTY_BYTE_ARRAY)
504           || Bytes.compareTo(startRow, stopRow) < 0
505           || (Bytes.compareTo(startRow, stopRow) == 0 && stopRowInclusive == true);
506     }
507   }
508 }