View Javadoc

1   /**
2    *
3    * Licensed to the Apache Software Foundation (ASF) under one
4    * or more contributor license agreements.  See the NOTICE file
5    * distributed with this work for additional information
6    * regarding copyright ownership.  The ASF licenses this file
7    * to you under the Apache License, Version 2.0 (the
8    * "License"); you may not use this file except in compliance
9    * with the License.  You may obtain a copy of the License at
10   *
11   *     http://www.apache.org/licenses/LICENSE-2.0
12   *
13   * Unless required by applicable law or agreed to in writing, software
14   * distributed under the License is distributed on an "AS IS" BASIS,
15   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16   * See the License for the specific language governing permissions and
17   * limitations under the License.
18   */
19  
20  package org.apache.hadoop.hbase.regionserver;
21  
22  import java.io.FileNotFoundException;
23  import java.io.IOException;
24  import java.util.ArrayList;
25  import java.util.Collection;
26  import java.util.Collections;
27  import java.util.List;
28  import java.util.concurrent.atomic.AtomicLong;
29  
30  import org.apache.commons.logging.Log;
31  import org.apache.commons.logging.LogFactory;
32  import org.apache.hadoop.hbase.Cell;
33  import org.apache.hadoop.hbase.CellUtil;
34  import org.apache.hadoop.hbase.HConstants;
35  import org.apache.hadoop.hbase.KeyValue;
36  import org.apache.hadoop.hbase.KeyValueUtil;
37  import org.apache.hadoop.hbase.classification.InterfaceAudience;
38  import org.apache.hadoop.hbase.client.Scan;
39  import org.apache.hadoop.hbase.io.TimeRange;
40  import org.apache.hadoop.hbase.io.hfile.HFileScanner;
41  import org.apache.hadoop.hbase.regionserver.StoreFile.Reader;
42  import org.apache.hadoop.hbase.regionserver.querymatcher.ScanQueryMatcher;
43  
44  /**
45   * KeyValueScanner adaptor over the Reader.  It also provides hooks into
46   * bloom filter things.
47   */
48  @InterfaceAudience.LimitedPrivate("Coprocessor")
49  public class StoreFileScanner implements KeyValueScanner {
50    private static final Log LOG = LogFactory.getLog(HStore.class);
51  
52    // the reader it comes from:
53    private final StoreFile.Reader reader;
54    private final HFileScanner hfs;
55    private Cell cur = null;
56    private boolean closed = false;
57  
58    private boolean realSeekDone;
59    private boolean delayedReseek;
60    private Cell delayedSeekKV;
61  
62    private final boolean enforceMVCC;
63    private final boolean hasMVCCInfo;
64    // A flag represents whether could stop skipping KeyValues for MVCC
65    // if have encountered the next row. Only used for reversed scan
66    private boolean stopSkippingKVsIfNextRow = false;
67  
68    private static AtomicLong seekCount;
69  
70    private final boolean canOptimizeForNonNullColumn;
71  
72    private final long readPt;
73  
74    // Order of this scanner relative to other scanners when duplicate key-value is found.
75    // Higher values means scanner has newer data.
76    private final long scannerOrder;
77  
78    /**
79     * Implements a {@link KeyValueScanner} on top of the specified {@link HFileScanner}
80     * @param useMVCC If true, scanner will filter out updates with MVCC larger than {@code readPt}.
81     * @param readPt MVCC value to use to filter out the updates newer than this scanner.
82     * @param hasMVCC Set to true if underlying store file reader has MVCC info.
83     * @param scannerOrder Order of the scanner relative to other scanners. See
84     *          {@link KeyValueScanner#getScannerOrder()}.
85     * @param canOptimizeForNonNullColumn {@code true} if we can make sure there is no null column,
86     *          otherwise {@code false}. This is a hint for optimization.
87     */
88    public StoreFileScanner(StoreFile.Reader reader, HFileScanner hfs, boolean useMVCC,
89        boolean hasMVCC, long readPt, long scannerOrder, boolean canOptimizeForNonNullColumn) {
90      this.readPt = readPt;
91      this.reader = reader;
92      this.hfs = hfs;
93      this.enforceMVCC = useMVCC;
94      this.hasMVCCInfo = hasMVCC;
95      this.scannerOrder = scannerOrder;
96      this.canOptimizeForNonNullColumn = canOptimizeForNonNullColumn;
97    }
98  
99    boolean isPrimaryReplica() {
100     return reader.isPrimaryReplicaReader();
101   }
102 
103   /**
104    * Return an array of scanners corresponding to the given
105    * set of store files.
106    */
107   public static List<StoreFileScanner> getScannersForStoreFiles(
108       Collection<StoreFile> files,
109       boolean cacheBlocks,
110       boolean usePread, long readPt) throws IOException {
111     return getScannersForStoreFiles(files, cacheBlocks,
112                                    usePread, false, false, readPt);
113   }
114 
115   /**
116    * Return an array of scanners corresponding to the given set of store files.
117    */
118   public static List<StoreFileScanner> getScannersForStoreFiles(
119       Collection<StoreFile> files, boolean cacheBlocks, boolean usePread,
120       boolean isCompaction, boolean useDropBehind, long readPt) throws IOException {
121     return getScannersForStoreFiles(files, cacheBlocks, usePread, isCompaction,
122         useDropBehind, null, readPt);
123   }
124 
125   /**
126    * Return an array of scanners corresponding to the given set of store files, And set the
127    * ScanQueryMatcher for each store file scanner for further optimization
128    */
129   public static List<StoreFileScanner> getScannersForStoreFiles(Collection<StoreFile> files,
130       boolean cacheBlocks, boolean usePread, boolean isCompaction, boolean canUseDrop,
131       ScanQueryMatcher matcher, long readPt, boolean isPrimaryReplica) throws IOException {
132     List<StoreFileScanner> scanners = new ArrayList<StoreFileScanner>(files.size());
133     List<StoreFile> sorted_files = new ArrayList<>(files);
134     Collections.sort(sorted_files, StoreFile.Comparators.SEQ_ID);
135     boolean succ = false;
136     try {
137       for (int i = 0; i < sorted_files.size(); i++) {
138         StoreFile.Reader r = sorted_files.get(i).createReader(canUseDrop);
139         r.setReplicaStoreFile(isPrimaryReplica);
140         StoreFileScanner scanner = r.getStoreFileScanner(cacheBlocks, usePread, isCompaction, readPt,
141             i, matcher != null ? !matcher.hasNullColumnInQuery() : false);
142         scanners.add(scanner);
143       }
144       succ = true;
145     } finally {
146       if (!succ) {
147         for (StoreFileScanner scanner : scanners) {
148           scanner.close();
149         }
150       }
151     }
152     return scanners;
153   }
154 
155   public static List<StoreFileScanner> getScannersForStoreFiles(
156     Collection<StoreFile> files, boolean cacheBlocks, boolean usePread,
157     boolean isCompaction, boolean canUseDrop,
158     ScanQueryMatcher matcher, long readPt) throws IOException {
159     return getScannersForStoreFiles(files, cacheBlocks, usePread, isCompaction, canUseDrop,
160       matcher, readPt, true);
161   }
162 
163   @Override
164   public String toString() {
165     return "StoreFileScanner[" + hfs.toString() + ", cur=" + cur + "]";
166   }
167 
168   @Override
169   public Cell peek() {
170     return cur;
171   }
172 
173   @Override
174   public Cell next() throws IOException {
175     Cell retKey = cur;
176 
177     try {
178       // only seek if we aren't at the end. cur == null implies 'end'.
179       if (cur != null) {
180         hfs.next();
181         setCurrentCell(hfs.getKeyValue());
182         if (hasMVCCInfo || this.reader.isBulkLoaded()) {
183           skipKVsNewerThanReadpoint();
184         }
185       }
186     } catch (FileNotFoundException e) {
187       throw e;
188     } catch(IOException e) {
189       throw new IOException("Could not iterate " + this, e);
190     }
191     return retKey;
192   }
193 
194   @Override
195   public boolean seek(Cell key) throws IOException {
196     if (seekCount != null) seekCount.incrementAndGet();
197 
198     try {
199       try {
200         if(!seekAtOrAfter(hfs, key)) {
201           this.cur = null;
202           return false;
203         }
204 
205         setCurrentCell(hfs.getKeyValue());
206 
207         if (!hasMVCCInfo && this.reader.isBulkLoaded()) {
208           return skipKVsNewerThanReadpoint();
209         } else {
210           return !hasMVCCInfo ? true : skipKVsNewerThanReadpoint();
211         }
212       } finally {
213         realSeekDone = true;
214       }
215     } catch (FileNotFoundException e) {
216       throw e;
217     } catch (IOException ioe) {
218       throw new IOException("Could not seek " + this + " to key " + key, ioe);
219     }
220   }
221 
222   @Override
223   public boolean reseek(Cell key) throws IOException {
224     if (seekCount != null) seekCount.incrementAndGet();
225 
226     try {
227       try {
228         if (!reseekAtOrAfter(hfs, key)) {
229           this.cur = null;
230           return false;
231         }
232         setCurrentCell(hfs.getKeyValue());
233 
234         if (!hasMVCCInfo && this.reader.isBulkLoaded()) {
235           return skipKVsNewerThanReadpoint();
236         } else {
237           return !hasMVCCInfo ? true : skipKVsNewerThanReadpoint();
238         }
239       } finally {
240         realSeekDone = true;
241       }
242     } catch (FileNotFoundException e) {
243       throw e;
244     } catch (IOException ioe) {
245       throw new IOException("Could not reseek " + this + " to key " + key,
246           ioe);
247     }
248   }
249 
250   protected void setCurrentCell(Cell newVal) throws IOException {
251     this.cur = newVal;
252     if (this.cur != null && this.reader.isBulkLoaded()) {
253       CellUtil.setSequenceId(cur, this.reader.getSequenceID());
254     }
255   }
256 
257   protected boolean skipKVsNewerThanReadpoint() throws IOException {
258     // We want to ignore all key-values that are newer than our current
259     // readPoint
260     Cell startKV = cur;
261     while(enforceMVCC
262         && cur != null
263         && (cur.getMvccVersion() > readPt)) {
264       boolean hasNext = hfs.next();
265       setCurrentCell(hfs.getKeyValue());
266       if (hasNext && this.stopSkippingKVsIfNextRow
267           && getComparator().compareRows(cur.getRowArray(), cur.getRowOffset(),
268               cur.getRowLength(), startKV.getRowArray(), startKV.getRowOffset(),
269               startKV.getRowLength()) > 0) {
270         return false;
271       }
272     }
273 
274     if (cur == null) {
275       return false;
276     }
277 
278     return true;
279   }
280 
281   @Override
282   public void close() {
283     cur = null;
284     if (closed) return;    
285     if (this.reader != null) {
286       this.reader.decrementRefCount();
287     }
288     closed = true;
289     this.hfs.close();
290   }
291 
292   /**
293    *
294    * @param s
295    * @param k
296    * @return false if not found or if k is after the end.
297    * @throws IOException
298    */
299   public static boolean seekAtOrAfter(HFileScanner s, Cell k)
300   throws IOException {
301     int result = s.seekTo(k);
302     if(result < 0) {
303       if (result == HConstants.INDEX_KEY_MAGIC) {
304         // using faked key
305         return true;
306       }
307       // Passed KV is smaller than first KV in file, work from start of file
308       return s.seekTo();
309     } else if(result > 0) {
310       // Passed KV is larger than current KV in file, if there is a next
311       // it is the "after", if not then this scanner is done.
312       return s.next();
313     }
314     // Seeked to the exact key
315     return true;
316   }
317 
318   static boolean reseekAtOrAfter(HFileScanner s, Cell k)
319   throws IOException {
320     //This function is similar to seekAtOrAfter function
321     int result = s.reseekTo(k);
322     if (result <= 0) {
323       if (result == HConstants.INDEX_KEY_MAGIC) {
324         // using faked key
325         return true;
326       }
327       // If up to now scanner is not seeked yet, this means passed KV is smaller
328       // than first KV in file, and it is the first time we seek on this file.
329       // So we also need to work from the start of file.
330       if (!s.isSeeked()) {
331         return  s.seekTo();
332       }
333       return true;
334     }
335     // passed KV is larger than current KV in file, if there is a next
336     // it is after, if not then this scanner is done.
337     return s.next();
338   }
339 
340   /**
341    * @see KeyValueScanner#getScannerOrder()
342    */
343   @Override
344   public long getScannerOrder() {
345     return scannerOrder;
346   }
347 
348   /**
349    * Pretend we have done a seek but don't do it yet, if possible. The hope is
350    * that we find requested columns in more recent files and won't have to seek
351    * in older files. Creates a fake key/value with the given row/column and the
352    * highest (most recent) possible timestamp we might get from this file. When
353    * users of such "lazy scanner" need to know the next KV precisely (e.g. when
354    * this scanner is at the top of the heap), they run {@link #enforceSeek()}.
355    * <p>
356    * Note that this function does guarantee that the current KV of this scanner
357    * will be advanced to at least the given KV. Because of this, it does have
358    * to do a real seek in cases when the seek timestamp is older than the
359    * highest timestamp of the file, e.g. when we are trying to seek to the next
360    * row/column and use OLDEST_TIMESTAMP in the seek key.
361    */
362   @Override
363   public boolean requestSeek(Cell kv, boolean forward, boolean useBloom)
364       throws IOException {
365     if (kv.getFamilyLength() == 0) {
366       useBloom = false;
367     }
368 
369     boolean haveToSeek = true;
370     if (useBloom) {
371       // check ROWCOL Bloom filter first.
372       if (reader.getBloomFilterType() == BloomType.ROWCOL) {
373         haveToSeek = reader.passesGeneralBloomFilter(kv.getRowArray(),
374             kv.getRowOffset(), kv.getRowLength(), kv.getQualifierArray(),
375             kv.getQualifierOffset(), kv.getQualifierLength());
376       } else if (canOptimizeForNonNullColumn
377           && ((CellUtil.isDeleteFamily(kv) || CellUtil.isDeleteFamilyVersion(kv)))) {
378         // if there is no such delete family kv in the store file,
379         // then no need to seek.
380         haveToSeek = reader.passesDeleteFamilyBloomFilter(kv.getRowArray(), kv.getRowOffset(),
381           kv.getRowLength());
382       }
383     }
384 
385     delayedReseek = forward;
386     delayedSeekKV = kv;
387 
388     if (haveToSeek) {
389       // This row/column might be in this store file (or we did not use the
390       // Bloom filter), so we still need to seek.
391       realSeekDone = false;
392       long maxTimestampInFile = reader.getMaxTimestamp();
393       long seekTimestamp = kv.getTimestamp();
394       if (seekTimestamp > maxTimestampInFile) {
395         // Create a fake key that is not greater than the real next key.
396         // (Lower timestamps correspond to higher KVs.)
397         // To understand this better, consider that we are asked to seek to
398         // a higher timestamp than the max timestamp in this file. We know that
399         // the next point when we have to consider this file again is when we
400         // pass the max timestamp of this file (with the same row/column).
401         setCurrentCell(KeyValueUtil.createFirstOnRowColTS(kv, maxTimestampInFile));
402       } else {
403         // This will be the case e.g. when we need to seek to the next
404         // row/column, and we don't know exactly what they are, so we set the
405         // seek key's timestamp to OLDEST_TIMESTAMP to skip the rest of this
406         // row/column.
407         enforceSeek();
408       }
409       return cur != null;
410     }
411 
412     // Multi-column Bloom filter optimization.
413     // Create a fake key/value, so that this scanner only bubbles up to the top
414     // of the KeyValueHeap in StoreScanner after we scanned this row/column in
415     // all other store files. The query matcher will then just skip this fake
416     // key/value and the store scanner will progress to the next column. This
417     // is obviously not a "real real" seek, but unlike the fake KV earlier in
418     // this method, we want this to be propagated to ScanQueryMatcher.
419     setCurrentCell(KeyValueUtil.createLastOnRowCol(kv));
420 
421     realSeekDone = true;
422     return true;
423   }
424 
425   Reader getReader() {
426     return reader;
427   }
428 
429   KeyValue.KVComparator getComparator() {
430     return reader.getComparator();
431   }
432 
433   @Override
434   public boolean realSeekDone() {
435     return realSeekDone;
436   }
437 
438   @Override
439   public void enforceSeek() throws IOException {
440     if (realSeekDone)
441       return;
442 
443     if (delayedReseek) {
444       reseek(delayedSeekKV);
445     } else {
446       seek(delayedSeekKV);
447     }
448   }
449 
450   @Override
451   public boolean isFileScanner() {
452     return true;
453   }
454 
455   // Test methods
456 
457   static final long getSeekCount() {
458     return seekCount.get();
459   }
460   static final void instrument() {
461     seekCount = new AtomicLong();
462   }
463 
464   @Override
465   public boolean shouldUseScanner(Scan scan, Store store, long oldestUnexpiredTS) {
466     // if the file has no entries, no need to validate or create a scanner.
467     byte[] cf = store.getFamily().getName();
468     TimeRange timeRange = scan.getColumnFamilyTimeRange().get(cf);
469     if (timeRange == null) {
470       timeRange = scan.getTimeRange();
471     }
472     return reader.passesTimerangeFilter(timeRange, oldestUnexpiredTS) && reader
473         .passesKeyRangeFilter(scan) && reader.passesBloomFilter(scan, scan.getFamilyMap().get(cf));
474   }
475 
476   @Override
477   @SuppressWarnings("deprecation")
478   public boolean seekToPreviousRow(Cell originalKey) throws IOException {
479     try {
480       try {
481         boolean keepSeeking = false;
482         Cell key = originalKey;
483         do {
484           KeyValue seekKey = KeyValueUtil.createFirstOnRow(key.getRowArray(), key.getRowOffset(),
485               key.getRowLength());
486           if (seekCount != null) seekCount.incrementAndGet();
487           if (!hfs.seekBefore(seekKey.getBuffer(), seekKey.getKeyOffset(),
488               seekKey.getKeyLength())) {
489             this.cur = null;
490             return false;
491           }
492           KeyValue firstKeyOfPreviousRow = KeyValueUtil.createFirstOnRow(hfs.getKeyValue()
493               .getRowArray(), hfs.getKeyValue().getRowOffset(), hfs.getKeyValue().getRowLength());
494 
495           if (seekCount != null) seekCount.incrementAndGet();
496           if (!seekAtOrAfter(hfs, firstKeyOfPreviousRow)) {
497             close();
498             return false;
499           }
500 
501           setCurrentCell(hfs.getKeyValue());
502           this.stopSkippingKVsIfNextRow = true;
503           boolean resultOfSkipKVs;
504           try {
505             resultOfSkipKVs = skipKVsNewerThanReadpoint();
506           } finally {
507             this.stopSkippingKVsIfNextRow = false;
508           }
509           if (!resultOfSkipKVs
510               || getComparator().compareRows(cur, firstKeyOfPreviousRow) > 0) {
511             keepSeeking = true;
512             key = firstKeyOfPreviousRow;
513             continue;
514           } else {
515             keepSeeking = false;
516           }
517         } while (keepSeeking);
518         return true;
519       } finally {
520         realSeekDone = true;
521       }
522     } catch (FileNotFoundException e) {
523       throw e;
524     } catch (IOException ioe) {
525       throw new IOException("Could not seekToPreviousRow " + this + " to key "
526           + originalKey, ioe);
527     }
528   }
529 
530   @Override
531   public boolean seekToLastRow() throws IOException {
532     byte[] lastRow = reader.getLastRowKey();
533     if (lastRow == null) {
534       return false;
535     }
536     KeyValue seekKey = KeyValueUtil.createFirstOnRow(lastRow);
537     if (seek(seekKey)) {
538       return true;
539     } else {
540       return seekToPreviousRow(seekKey);
541     }
542   }
543 
544   @Override
545   public boolean backwardSeek(Cell key) throws IOException {
546     seek(key);
547     if (cur == null
548         || getComparator().compareRows(cur.getRowArray(), cur.getRowOffset(),
549             cur.getRowLength(), key.getRowArray(), key.getRowOffset(),
550             key.getRowLength()) > 0) {
551       return seekToPreviousRow(key);
552     }
553     return true;
554   }
555 
556   @Override
557   public Cell getNextIndexedKey() {
558     return hfs.getNextIndexedKey();
559   }
560 }