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 = Math.min(scan.getMaxVersions(), scanInfo.getMaxVersions());
162     // Single branch to deal with two types of reads (columns vs all in family)
163     if (columns == null || columns.size() == 0) {
164       // there is always a null column in the wildcard column query.
165       hasNullColumn = true;
166 
167       // use a specialized scan for wildcard column tracker.
168       this.columns = new ScanWildcardColumnTracker(
169           scanInfo.getMinVersions(), maxVersions, oldestUnexpiredTS);
170     } else {
171       // whether there is null column in the explicit column query
172       hasNullColumn = (columns.first().length == 0);
173 
174       // We can share the ExplicitColumnTracker, diff is we reset
175       // between rows, not between storefiles.
176       this.columns = new ExplicitColumnTracker(columns,
177           scanInfo.getMinVersions(), maxVersions, oldestUnexpiredTS);
178     }
179   }
180 
181   /*
182    * Constructor for tests
183    */
184   ScanQueryMatcher(Scan scan, Store.ScanInfo scanInfo,
185       NavigableSet<byte[]> columns, long oldestUnexpiredTS) {
186     this(scan, scanInfo, columns, ScanType.USER_SCAN,
187           Long.MAX_VALUE, /* max Readpoint to track versions */
188         HConstants.LATEST_TIMESTAMP, oldestUnexpiredTS);
189   }
190 
191   /**
192    *
193    * @return  whether there is an null column in the query
194    */
195   public boolean hasNullColumnInQuery() {
196     return hasNullColumn;
197   }
198 
199   /**
200    * Determines if the caller should do one of several things:
201    * - seek/skip to the next row (MatchCode.SEEK_NEXT_ROW)
202    * - seek/skip to the next column (MatchCode.SEEK_NEXT_COL)
203    * - include the current KeyValue (MatchCode.INCLUDE)
204    * - ignore the current KeyValue (MatchCode.SKIP)
205    * - got to the next row (MatchCode.DONE)
206    *
207    * @param kv KeyValue to check
208    * @return The match code instance.
209    * @throws IOException in case there is an internal consistency problem
210    *      caused by a data corruption.
211    */
212   public MatchCode match(KeyValue kv) throws IOException {
213     if (filter != null && filter.filterAllRemaining()) {
214       return MatchCode.DONE_SCAN;
215     }
216 
217     byte [] bytes = kv.getBuffer();
218     int offset = kv.getOffset();
219     int initialOffset = offset;
220 
221     int keyLength = Bytes.toInt(bytes, offset, Bytes.SIZEOF_INT);
222     offset += KeyValue.ROW_OFFSET;
223 
224     short rowLength = Bytes.toShort(bytes, offset, Bytes.SIZEOF_SHORT);
225     offset += Bytes.SIZEOF_SHORT;
226 
227     int ret = this.rowComparator.compareRows(row, this.rowOffset, this.rowLength,
228         bytes, offset, rowLength);
229     if (ret <= -1) {
230       return MatchCode.DONE;
231     } else if (ret >= 1) {
232       // could optimize this, if necessary?
233       // Could also be called SEEK_TO_CURRENT_ROW, but this
234       // should be rare/never happens.
235       return MatchCode.SEEK_NEXT_ROW;
236     }
237 
238     // optimize case.
239     if (this.stickyNextRow)
240         return MatchCode.SEEK_NEXT_ROW;
241 
242     if (this.columns.done()) {
243       stickyNextRow = true;
244       return MatchCode.SEEK_NEXT_ROW;
245     }
246 
247     //Passing rowLength
248     offset += rowLength;
249 
250     //Skipping family
251     byte familyLength = bytes [offset];
252     offset += familyLength + 1;
253 
254     int qualLength = keyLength + KeyValue.ROW_OFFSET -
255       (offset - initialOffset) - KeyValue.TIMESTAMP_TYPE_SIZE;
256 
257     long timestamp = kv.getTimestamp();
258     // check for early out based on timestamp alone
259     if (columns.isDone(timestamp)) {
260         return columns.getNextRowOrNextColumn(bytes, offset, qualLength);
261     }
262 
263     /*
264      * The delete logic is pretty complicated now.
265      * This is corroborated by the following:
266      * 1. The store might be instructed to keep deleted rows around.
267      * 2. A scan can optionally see past a delete marker now.
268      * 3. If deleted rows are kept, we have to find out when we can
269      *    remove the delete markers.
270      * 4. Family delete markers are always first (regardless of their TS)
271      * 5. Delete markers should not be counted as version
272      * 6. Delete markers affect puts of the *same* TS
273      * 7. Delete marker need to be version counted together with puts
274      *    they affect
275      */
276     byte type = kv.getType();
277     if (kv.isDelete()) {
278       if (!keepDeletedCells) {
279         // first ignore delete markers if the scanner can do so, and the
280         // range does not include the marker
281         //
282         // during flushes and compactions also ignore delete markers newer
283         // than the readpoint of any open scanner, this prevents deleted
284         // rows that could still be seen by a scanner from being collected
285         boolean includeDeleteMarker = seePastDeleteMarkers ?
286             tr.withinTimeRange(timestamp) :
287             tr.withinOrAfterTimeRange(timestamp);
288         if (includeDeleteMarker
289             && kv.getMemstoreTS() <= maxReadPointToTrackVersions) {
290           this.deletes.add(bytes, offset, qualLength, timestamp, type);
291         }
292         // Can't early out now, because DelFam come before any other keys
293       }
294       if (retainDeletesInOutput
295           || (!isUserScan && (EnvironmentEdgeManager.currentTimeMillis() - timestamp) <= timeToPurgeDeletes)
296           || kv.getMemstoreTS() > maxReadPointToTrackVersions) {
297         // always include or it is not time yet to check whether it is OK
298         // to purge deltes or not
299         return MatchCode.INCLUDE;
300       } else if (keepDeletedCells) {
301         if (timestamp < earliestPutTs) {
302           // keeping delete rows, but there are no puts older than
303           // this delete in the store files.
304           return columns.getNextRowOrNextColumn(bytes, offset, qualLength);
305         }
306         // else: fall through and do version counting on the
307         // delete markers
308       } else {
309         return MatchCode.SKIP;
310       }
311       // note the following next else if...
312       // delete marker are not subject to other delete markers
313     } else if (!this.deletes.isEmpty()) {
314       DeleteResult deleteResult = deletes.isDeleted(bytes, offset, qualLength,
315           timestamp);
316       switch (deleteResult) {
317         case FAMILY_DELETED:
318         case COLUMN_DELETED:
319           return columns.getNextRowOrNextColumn(bytes, offset, qualLength);
320         case VERSION_DELETED:
321           return MatchCode.SKIP;
322         case NOT_DELETED:
323           break;
324         default:
325           throw new RuntimeException("UNEXPECTED");
326         }
327     }
328 
329     int timestampComparison = tr.compare(timestamp);
330     if (timestampComparison >= 1) {
331       return MatchCode.SKIP;
332     } else if (timestampComparison <= -1) {
333       return columns.getNextRowOrNextColumn(bytes, offset, qualLength);
334     }
335 
336     /**
337      * Filters should be checked before checking column trackers. If we do
338      * otherwise, as was previously being done, ColumnTracker may increment its
339      * counter for even that KV which may be discarded later on by Filter. This
340      * would lead to incorrect results in certain cases.
341      */
342     ReturnCode filterResponse = ReturnCode.SKIP;
343     if (filter != null) {
344       filterResponse = filter.filterKeyValue(kv);
345       if (filterResponse == ReturnCode.SKIP) {
346         return MatchCode.SKIP;
347       } else if (filterResponse == ReturnCode.NEXT_COL) {
348         return columns.getNextRowOrNextColumn(bytes, offset, qualLength);
349       } else if (filterResponse == ReturnCode.NEXT_ROW) {
350         stickyNextRow = true;
351         return MatchCode.SEEK_NEXT_ROW;
352       } else if (filterResponse == ReturnCode.SEEK_NEXT_USING_HINT) {
353         return MatchCode.SEEK_NEXT_USING_HINT;
354       }
355     }
356 
357     MatchCode colChecker = columns.checkColumn(bytes, offset, qualLength,
358         timestamp, type, kv.getMemstoreTS() > maxReadPointToTrackVersions);
359     /*
360      * According to current implementation, colChecker can only be
361      * SEEK_NEXT_COL, SEEK_NEXT_ROW, SKIP or INCLUDE. Therefore, always return
362      * the MatchCode. If it is SEEK_NEXT_ROW, also set stickyNextRow.
363      */
364     if (colChecker == MatchCode.SEEK_NEXT_ROW) {
365       stickyNextRow = true;
366     } else if (filter != null && colChecker == MatchCode.INCLUDE &&
367                filterResponse == ReturnCode.INCLUDE_AND_NEXT_COL) {
368       return MatchCode.INCLUDE_AND_SEEK_NEXT_COL;
369     }
370     return colChecker;
371 
372   }
373 
374   public boolean moreRowsMayExistAfter(KeyValue kv) {
375     if (!Bytes.equals(stopRow , HConstants.EMPTY_END_ROW) &&
376         rowComparator.compareRows(kv.getBuffer(),kv.getRowOffset(),
377             kv.getRowLength(), stopRow, 0, stopRow.length) >= 0) {
378       // KV >= STOPROW
379       // then NO there is nothing left.
380       return false;
381     } else {
382       return true;
383     }
384   }
385 
386   /**
387    * Set current row
388    * @param row
389    */
390   public void setRow(byte [] row, int offset, short length) {
391     this.row = row;
392     this.rowOffset = offset;
393     this.rowLength = length;
394     reset();
395   }
396 
397   public void reset() {
398     this.deletes.reset();
399     this.columns.reset();
400 
401     stickyNextRow = false;
402   }
403 
404   /**
405    *
406    * @return the start key
407    */
408   public KeyValue getStartKey() {
409     return this.startKey;
410   }
411 
412   /**
413    *
414    * @return the Filter
415    */
416   Filter getFilter() {
417     return this.filter;
418   }
419 
420   public KeyValue getNextKeyHint(KeyValue kv) {
421     if (filter == null) {
422       return null;
423     } else {
424       return filter.getNextKeyHint(kv);
425     }
426   }
427 
428   public KeyValue getKeyForNextColumn(KeyValue kv) {
429     ColumnCount nextColumn = columns.getColumnHint();
430     if (nextColumn == null) {
431       return KeyValue.createLastOnRow(
432           kv.getBuffer(), kv.getRowOffset(), kv.getRowLength(),
433           kv.getBuffer(), kv.getFamilyOffset(), kv.getFamilyLength(),
434           kv.getBuffer(), kv.getQualifierOffset(), kv.getQualifierLength());
435     } else {
436       return KeyValue.createFirstOnRow(
437           kv.getBuffer(), kv.getRowOffset(), kv.getRowLength(),
438           kv.getBuffer(), kv.getFamilyOffset(), kv.getFamilyLength(),
439           nextColumn.getBuffer(), nextColumn.getOffset(), nextColumn.getLength());
440     }
441   }
442 
443   public KeyValue getKeyForNextRow(KeyValue kv) {
444     return KeyValue.createLastOnRow(
445         kv.getBuffer(), kv.getRowOffset(), kv.getRowLength(),
446         null, 0, 0,
447         null, 0, 0);
448   }
449 
450   /**
451    * {@link #match} return codes.  These instruct the scanner moving through
452    * memstores and StoreFiles what to do with the current KeyValue.
453    * <p>
454    * Additionally, this contains "early-out" language to tell the scanner to
455    * move on to the next File (memstore or Storefile), or to return immediately.
456    */
457   public static enum MatchCode {
458     /**
459      * Include KeyValue in the returned result
460      */
461     INCLUDE,
462 
463     /**
464      * Do not include KeyValue in the returned result
465      */
466     SKIP,
467 
468     /**
469      * Do not include, jump to next StoreFile or memstore (in time order)
470      */
471     NEXT,
472 
473     /**
474      * Do not include, return current result
475      */
476     DONE,
477 
478     /**
479      * These codes are used by the ScanQueryMatcher
480      */
481 
482     /**
483      * Done with the row, seek there.
484      */
485     SEEK_NEXT_ROW,
486     /**
487      * Done with column, seek to next.
488      */
489     SEEK_NEXT_COL,
490 
491     /**
492      * Done with scan, thanks to the row filter.
493      */
494     DONE_SCAN,
495 
496     /*
497      * Seek to next key which is given as hint.
498      */
499     SEEK_NEXT_USING_HINT,
500 
501     /**
502      * Include KeyValue and done with column, seek to next.
503      */
504     INCLUDE_AND_SEEK_NEXT_COL,
505 
506     /**
507      * Include KeyValue and done with row, seek to next.
508      */
509     INCLUDE_AND_SEEK_NEXT_ROW,
510   }
511 }