View Javadoc

1   /**
2    * Copyright 2010 The Apache Software Foundation
3    *
4    * Licensed to the Apache Software Foundation (ASF) under one
5    * or more contributor license agreements.  See the NOTICE file
6    * distributed with this work for additional information
7    * regarding copyright ownership.  The ASF licenses this file
8    * to you under the Apache License, Version 2.0 (the
9    * "License"); you may not use this file except in compliance
10   * with the License.  You may obtain a copy of the License at
11   *
12   *     http://www.apache.org/licenses/LICENSE-2.0
13   *
14   * Unless required by applicable law or agreed to in writing, software
15   * distributed under the License is distributed on an "AS IS" BASIS,
16   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17   * See the License for the specific language governing permissions and
18   * limitations under the License.
19   */
20  
21  package org.apache.hadoop.hbase.regionserver;
22  
23  import java.io.IOException;
24  import java.util.NavigableSet;
25  
26  import org.apache.hadoop.hbase.HConstants;
27  import org.apache.hadoop.hbase.KeyValue;
28  import org.apache.hadoop.hbase.client.Scan;
29  import org.apache.hadoop.hbase.filter.Filter;
30  import org.apache.hadoop.hbase.filter.Filter.ReturnCode;
31  import org.apache.hadoop.hbase.io.TimeRange;
32  import org.apache.hadoop.hbase.regionserver.DeleteTracker.DeleteResult;
33  import org.apache.hadoop.hbase.util.Bytes;
34  import org.apache.hadoop.hbase.util.EnvironmentEdgeManager;
35  
36  /**
37   * A query matcher that is specifically designed for the scan case.
38   */
39  public class ScanQueryMatcher {
40    // Optimization so we can skip lots of compares when we decide to skip
41    // to the next row.
42    private boolean stickyNextRow;
43    private final byte[] stopRow;
44  
45    private final TimeRange tr;
46  
47    private final Filter filter;
48  
49    /** Keeps track of deletes */
50    private final DeleteTracker deletes;
51  
52    /*
53     * The following three booleans define how we deal with deletes.
54     * There are three different aspects:
55     * 1. Whether to keep delete markers. This is used in compactions.
56     *    Minor compactions always keep delete markers.
57     * 2. Whether to keep deleted rows. This is also used in compactions,
58     *    if the store is set to keep deleted rows. This implies keeping
59     *    the delete markers as well.
60     *    In this case deleted rows are subject to the normal max version
61     *    and TTL/min version rules just like "normal" rows.
62     * 3. Whether a scan can do time travel queries even before deleted
63     *    marker to reach deleted rows.
64     */
65    /** whether to retain delete markers */
66    private final boolean retainDeletesInOutput;
67    /** whether to return deleted rows */
68    private final boolean keepDeletedCells;
69    /** whether time range queries can see rows "behind" a delete */
70    private final boolean seePastDeleteMarkers;
71  
72  
73    /** Keeps track of columns and versions */
74    private final ColumnTracker columns;
75  
76    /** Key to seek to in memstore and StoreFiles */
77    private final KeyValue startKey;
78  
79    /** Row comparator for the region this query is for */
80    private final KeyValue.KeyComparator rowComparator;
81  
82    /* row is not private for tests */
83    /** Row the query is on */
84    byte [] row;
85    int rowOffset;
86    short rowLength;
87    
88    /**
89     * Oldest put in any of the involved store files
90     * Used to decide whether it is ok to delete
91     * family delete marker of this store keeps
92     * deleted KVs.
93     */
94    private final long earliestPutTs;
95  
96    /** readPoint over which the KVs are unconditionally included */
97    protected long maxReadPointToTrackVersions;
98  
99    /**
100    * This variable shows whether there is an null column in the query. There
101    * always exists a null column in the wildcard column query.
102    * There maybe exists a null column in the explicit column query based on the
103    * first column.
104    * */
105   private boolean hasNullColumn = true;
106 
107   // By default, when hbase.hstore.time.to.purge.deletes is 0ms, a delete
108   // marker is always removed during a major compaction. If set to non-zero
109   // value then major compaction will try to keep a delete marker around for
110   // the given number of milliseconds. We want to keep the delete markers
111   // around a bit longer because old puts might appear out-of-order. For
112   // example, during log replication between two clusters.
113   //
114   // If the delete marker has lived longer than its column-family's TTL then
115   // the delete marker will be removed even if time.to.purge.deletes has not
116   // passed. This is because all the Puts that this delete marker can influence
117   // would have also expired. (Removing of delete markers on col family TTL will
118   // not happen if min-versions is set to non-zero)
119   //
120   // But, if time.to.purge.deletes has not expired then a delete
121   // marker will not be removed just because there are no Puts that it is
122   // currently influencing. This is because Puts, that this delete can
123   // influence.  may appear out of order.
124   private final long timeToPurgeDeletes;
125   
126   private final boolean isUserScan;
127 
128   /**
129    * Construct a QueryMatcher for a scan
130    * @param scan
131    * @param scanInfo The store's immutable scan info
132    * @param columns
133    * @param scanType Type of the scan
134    * @param earliestPutTs Earliest put seen in any of the store files.
135    * @param oldestUnexpiredTS the oldest timestamp we are interested in,
136    *  based on TTL
137    */
138   public ScanQueryMatcher(Scan scan, Store.ScanInfo scanInfo,
139       NavigableSet<byte[]> columns, ScanType scanType,
140       long readPointToUse, long earliestPutTs, long oldestUnexpiredTS) {
141     this.tr = scan.getTimeRange();
142     this.rowComparator = scanInfo.getComparator().getRawComparator();
143     this.deletes =  new ScanDeleteTracker();
144     this.stopRow = scan.getStopRow();
145     this.startKey = KeyValue.createFirstDeleteFamilyOnRow(scan.getStartRow(),
146         scanInfo.getFamily());
147     this.filter = scan.getFilter();
148     this.earliestPutTs = earliestPutTs;
149     this.maxReadPointToTrackVersions = readPointToUse;
150     this.timeToPurgeDeletes = scanInfo.getTimeToPurgeDeletes();
151 
152     /* how to deal with deletes */
153     this.isUserScan = scanType == ScanType.USER_SCAN;
154     // keep deleted cells: if compaction or raw scan
155     this.keepDeletedCells = (scanInfo.getKeepDeletedCells() && !isUserScan) || scan.isRaw();
156     // retain deletes: if minor compaction or raw scan
157     this.retainDeletesInOutput = scanType == ScanType.MINOR_COMPACT || scan.isRaw();
158     // seePastDeleteMarker: user initiated scans
159     this.seePastDeleteMarkers = scanInfo.getKeepDeletedCells() && isUserScan;
160 
161     int maxVersions =
162         scan.isRaw() ? scan.getMaxVersions() : Math.min(scan.getMaxVersions(),
163           scanInfo.getMaxVersions());
164 
165     // Single branch to deal with two types of reads (columns vs all in family)
166     if (columns == null || columns.size() == 0) {
167       // there is always a null column in the wildcard column query.
168       hasNullColumn = true;
169 
170       // use a specialized scan for wildcard column tracker.
171       this.columns = new ScanWildcardColumnTracker(
172           scanInfo.getMinVersions(), maxVersions, oldestUnexpiredTS);
173     } else {
174       // whether there is null column in the explicit column query
175       hasNullColumn = (columns.first().length == 0);
176 
177       // We can share the ExplicitColumnTracker, diff is we reset
178       // between rows, not between storefiles.
179       this.columns = new ExplicitColumnTracker(columns,
180           scanInfo.getMinVersions(), maxVersions, oldestUnexpiredTS);
181     }
182   }
183 
184   /*
185    * Constructor for tests
186    */
187   ScanQueryMatcher(Scan scan, Store.ScanInfo scanInfo,
188       NavigableSet<byte[]> columns, long oldestUnexpiredTS) {
189     this(scan, scanInfo, columns, ScanType.USER_SCAN,
190           Long.MAX_VALUE, /* max Readpoint to track versions */
191         HConstants.LATEST_TIMESTAMP, oldestUnexpiredTS);
192   }
193 
194   /**
195    *
196    * @return  whether there is an null column in the query
197    */
198   public boolean hasNullColumnInQuery() {
199     return hasNullColumn;
200   }
201 
202   /**
203    * Determines if the caller should do one of several things:
204    * - seek/skip to the next row (MatchCode.SEEK_NEXT_ROW)
205    * - seek/skip to the next column (MatchCode.SEEK_NEXT_COL)
206    * - include the current KeyValue (MatchCode.INCLUDE)
207    * - ignore the current KeyValue (MatchCode.SKIP)
208    * - got to the next row (MatchCode.DONE)
209    *
210    * @param kv KeyValue to check
211    * @return The match code instance.
212    * @throws IOException in case there is an internal consistency problem
213    *      caused by a data corruption.
214    */
215   public MatchCode match(KeyValue kv) throws IOException {
216     if (filter != null && filter.filterAllRemaining()) {
217       return MatchCode.DONE_SCAN;
218     }
219 
220     byte [] bytes = kv.getBuffer();
221     int offset = kv.getOffset();
222     int initialOffset = offset;
223 
224     int keyLength = Bytes.toInt(bytes, offset, Bytes.SIZEOF_INT);
225     offset += KeyValue.ROW_OFFSET;
226 
227     short rowLength = Bytes.toShort(bytes, offset, Bytes.SIZEOF_SHORT);
228     offset += Bytes.SIZEOF_SHORT;
229 
230     int ret = this.rowComparator.compareRows(row, this.rowOffset, this.rowLength,
231         bytes, offset, rowLength);
232     if (ret <= -1) {
233       return MatchCode.DONE;
234     } else if (ret >= 1) {
235       // could optimize this, if necessary?
236       // Could also be called SEEK_TO_CURRENT_ROW, but this
237       // should be rare/never happens.
238       return MatchCode.SEEK_NEXT_ROW;
239     }
240 
241     // optimize case.
242     if (this.stickyNextRow)
243         return MatchCode.SEEK_NEXT_ROW;
244 
245     if (this.columns.done()) {
246       stickyNextRow = true;
247       return MatchCode.SEEK_NEXT_ROW;
248     }
249 
250     //Passing rowLength
251     offset += rowLength;
252 
253     //Skipping family
254     byte familyLength = bytes [offset];
255     offset += familyLength + 1;
256 
257     int qualLength = keyLength + KeyValue.ROW_OFFSET -
258       (offset - initialOffset) - KeyValue.TIMESTAMP_TYPE_SIZE;
259 
260     long timestamp = kv.getTimestamp();
261     // check for early out based on timestamp alone
262     if (columns.isDone(timestamp)) {
263         return columns.getNextRowOrNextColumn(bytes, offset, qualLength);
264     }
265 
266     /*
267      * The delete logic is pretty complicated now.
268      * This is corroborated by the following:
269      * 1. The store might be instructed to keep deleted rows around.
270      * 2. A scan can optionally see past a delete marker now.
271      * 3. If deleted rows are kept, we have to find out when we can
272      *    remove the delete markers.
273      * 4. Family delete markers are always first (regardless of their TS)
274      * 5. Delete markers should not be counted as version
275      * 6. Delete markers affect puts of the *same* TS
276      * 7. Delete marker need to be version counted together with puts
277      *    they affect
278      */
279     byte type = kv.getType();
280     if (kv.isDelete()) {
281       if (!keepDeletedCells) {
282         // first ignore delete markers if the scanner can do so, and the
283         // range does not include the marker
284         //
285         // during flushes and compactions also ignore delete markers newer
286         // than the readpoint of any open scanner, this prevents deleted
287         // rows that could still be seen by a scanner from being collected
288         boolean includeDeleteMarker = seePastDeleteMarkers ?
289             tr.withinTimeRange(timestamp) :
290             tr.withinOrAfterTimeRange(timestamp);
291         if (includeDeleteMarker
292             && kv.getMemstoreTS() <= maxReadPointToTrackVersions) {
293           this.deletes.add(bytes, offset, qualLength, timestamp, type);
294         }
295         // Can't early out now, because DelFam come before any other keys
296       }
297       if (retainDeletesInOutput
298           || (!isUserScan && (EnvironmentEdgeManager.currentTimeMillis() - timestamp) <= timeToPurgeDeletes)
299           || kv.getMemstoreTS() > maxReadPointToTrackVersions) {
300         // always include or it is not time yet to check whether it is OK
301         // to purge deltes or not
302         if (!isUserScan) {
303           // if this is not a user scan (compaction), we can filter this deletemarker right here
304           // otherwise (i.e. a "raw" scan) we fall through to normal version and timerange checking
305           return MatchCode.INCLUDE;
306         }
307       } else if (keepDeletedCells) {
308         if (timestamp < earliestPutTs) {
309           // keeping delete rows, but there are no puts older than
310           // this delete in the store files.
311           return columns.getNextRowOrNextColumn(bytes, offset, qualLength);
312         }
313         // else: fall through and do version counting on the
314         // delete markers
315       } else {
316         return MatchCode.SKIP;
317       }
318       // note the following next else if...
319       // delete marker are not subject to other delete markers
320     } else if (!this.deletes.isEmpty()) {
321       DeleteResult deleteResult = deletes.isDeleted(bytes, offset, qualLength,
322           timestamp);
323       switch (deleteResult) {
324         case FAMILY_DELETED:
325         case COLUMN_DELETED:
326           return columns.getNextRowOrNextColumn(bytes, offset, qualLength);
327         case VERSION_DELETED:
328           return MatchCode.SKIP;
329         case NOT_DELETED:
330           break;
331         default:
332           throw new RuntimeException("UNEXPECTED");
333         }
334     }
335 
336     int timestampComparison = tr.compare(timestamp);
337     if (timestampComparison >= 1) {
338       return MatchCode.SKIP;
339     } else if (timestampComparison <= -1) {
340       return columns.getNextRowOrNextColumn(bytes, offset, qualLength);
341     }
342 
343     // STEP 1: Check if the column is part of the requested columns
344     MatchCode colChecker = columns.checkColumn(bytes, offset, qualLength, type);
345     if (colChecker == MatchCode.INCLUDE) {
346       ReturnCode filterResponse = ReturnCode.SKIP;
347       // STEP 2: Yes, the column is part of the requested columns. Check if filter is present
348       if (filter != null) {
349         // STEP 3: Filter the key value and return if it filters out
350         filterResponse = filter.filterKeyValue(kv);
351         switch (filterResponse) {
352         case SKIP:
353           return MatchCode.SKIP;
354         case NEXT_COL:
355           return columns.getNextRowOrNextColumn(bytes, offset, qualLength);
356         case NEXT_ROW:
357           stickyNextRow = true;
358           return MatchCode.SEEK_NEXT_ROW;
359         case SEEK_NEXT_USING_HINT:
360           return MatchCode.SEEK_NEXT_USING_HINT;
361         default:
362           //It means it is either include or include and seek next
363           break;
364         }
365       }
366       /*
367        * STEP 4: Reaching this step means the column is part of the requested columns and either
368        * the filter is null or the filter has returned INCLUDE or INCLUDE_AND_NEXT_COL response.
369        * Now check the number of versions needed. This method call returns SKIP, INCLUDE,
370        * INCLUDE_AND_SEEK_NEXT_ROW, INCLUDE_AND_SEEK_NEXT_COL.
371        *
372        * FilterResponse            ColumnChecker               Desired behavior
373        * INCLUDE                   SKIP                        row has already been included, SKIP.
374        * INCLUDE                   INCLUDE                     INCLUDE
375        * INCLUDE                   INCLUDE_AND_SEEK_NEXT_COL   INCLUDE_AND_SEEK_NEXT_COL
376        * INCLUDE                   INCLUDE_AND_SEEK_NEXT_ROW   INCLUDE_AND_SEEK_NEXT_ROW
377        * INCLUDE_AND_SEEK_NEXT_COL SKIP                        row has already been included, SKIP.
378        * INCLUDE_AND_SEEK_NEXT_COL INCLUDE                     INCLUDE_AND_SEEK_NEXT_COL
379        * INCLUDE_AND_SEEK_NEXT_COL INCLUDE_AND_SEEK_NEXT_COL   INCLUDE_AND_SEEK_NEXT_COL
380        * INCLUDE_AND_SEEK_NEXT_COL INCLUDE_AND_SEEK_NEXT_ROW   INCLUDE_AND_SEEK_NEXT_ROW
381        *
382        * In all the above scenarios, we return the column checker return value except for
383        * FilterResponse (INCLUDE_AND_SEEK_NEXT_COL) and ColumnChecker(INCLUDE)
384        */
385       colChecker =
386           columns.checkVersions(bytes, offset, qualLength, timestamp, type,
387             kv.getMemstoreTS() > maxReadPointToTrackVersions);
388       //Optimize with stickyNextRow
389       stickyNextRow = colChecker == MatchCode.INCLUDE_AND_SEEK_NEXT_ROW ? true : stickyNextRow;
390       return (filterResponse == ReturnCode.INCLUDE_AND_NEXT_COL &&
391           colChecker == MatchCode.INCLUDE) ? MatchCode.INCLUDE_AND_SEEK_NEXT_COL
392           : colChecker;
393     }
394     stickyNextRow = (colChecker == MatchCode.SEEK_NEXT_ROW) ? true
395         : stickyNextRow;
396     return colChecker;
397   }
398 
399   public boolean moreRowsMayExistAfter(KeyValue kv) {
400     if (!Bytes.equals(stopRow , HConstants.EMPTY_END_ROW) &&
401         rowComparator.compareRows(kv.getBuffer(),kv.getRowOffset(),
402             kv.getRowLength(), stopRow, 0, stopRow.length) >= 0) {
403       // KV >= STOPROW
404       // then NO there is nothing left.
405       return false;
406     } else {
407       return true;
408     }
409   }
410 
411   /**
412    * Set current row
413    * @param row
414    */
415   public void setRow(byte [] row, int offset, short length) {
416     this.row = row;
417     this.rowOffset = offset;
418     this.rowLength = length;
419     reset();
420   }
421 
422   public void reset() {
423     this.deletes.reset();
424     this.columns.reset();
425 
426     stickyNextRow = false;
427   }
428 
429   /**
430    *
431    * @return the start key
432    */
433   public KeyValue getStartKey() {
434     return this.startKey;
435   }
436 
437   /**
438    *
439    * @return the Filter
440    */
441   Filter getFilter() {
442     return this.filter;
443   }
444 
445   public KeyValue getNextKeyHint(KeyValue kv) {
446     if (filter == null) {
447       return null;
448     } else {
449       return filter.getNextKeyHint(kv);
450     }
451   }
452 
453   public KeyValue getKeyForNextColumn(KeyValue kv) {
454     ColumnCount nextColumn = columns.getColumnHint();
455     if (nextColumn == null) {
456       return KeyValue.createLastOnRow(
457           kv.getBuffer(), kv.getRowOffset(), kv.getRowLength(),
458           kv.getBuffer(), kv.getFamilyOffset(), kv.getFamilyLength(),
459           kv.getBuffer(), kv.getQualifierOffset(), kv.getQualifierLength());
460     } else {
461       return KeyValue.createFirstOnRow(
462           kv.getBuffer(), kv.getRowOffset(), kv.getRowLength(),
463           kv.getBuffer(), kv.getFamilyOffset(), kv.getFamilyLength(),
464           nextColumn.getBuffer(), nextColumn.getOffset(), nextColumn.getLength());
465     }
466   }
467 
468   public KeyValue getKeyForNextRow(KeyValue kv) {
469     return KeyValue.createLastOnRow(
470         kv.getBuffer(), kv.getRowOffset(), kv.getRowLength(),
471         null, 0, 0,
472         null, 0, 0);
473   }
474 
475   // Used only for testing purposes
476   static MatchCode checkColumn(ColumnTracker columnTracker, byte[] bytes, int offset, int length,
477       long ttl, byte type, boolean ignoreCount) throws IOException {
478     MatchCode matchCode = columnTracker.checkColumn(bytes, offset, length, type);
479     if (matchCode == MatchCode.INCLUDE) {
480       return columnTracker.checkVersions(bytes, offset, length, ttl, type, ignoreCount);
481     }
482     return matchCode;
483   }
484 
485   /**
486    * {@link #match} return codes.  These instruct the scanner moving through
487    * memstores and StoreFiles what to do with the current KeyValue.
488    * <p>
489    * Additionally, this contains "early-out" language to tell the scanner to
490    * move on to the next File (memstore or Storefile), or to return immediately.
491    */
492   public static enum MatchCode {
493     /**
494      * Include KeyValue in the returned result
495      */
496     INCLUDE,
497 
498     /**
499      * Do not include KeyValue in the returned result
500      */
501     SKIP,
502 
503     /**
504      * Do not include, jump to next StoreFile or memstore (in time order)
505      */
506     NEXT,
507 
508     /**
509      * Do not include, return current result
510      */
511     DONE,
512 
513     /**
514      * These codes are used by the ScanQueryMatcher
515      */
516 
517     /**
518      * Done with the row, seek there.
519      */
520     SEEK_NEXT_ROW,
521     /**
522      * Done with column, seek to next.
523      */
524     SEEK_NEXT_COL,
525 
526     /**
527      * Done with scan, thanks to the row filter.
528      */
529     DONE_SCAN,
530 
531     /*
532      * Seek to next key which is given as hint.
533      */
534     SEEK_NEXT_USING_HINT,
535 
536     /**
537      * Include KeyValue and done with column, seek to next.
538      */
539     INCLUDE_AND_SEEK_NEXT_COL,
540 
541     /**
542      * Include KeyValue and done with row, seek to next.
543      */
544     INCLUDE_AND_SEEK_NEXT_ROW,
545   }
546 }