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.IOException;
23  import java.util.ArrayList;
24  import java.util.Collection;
25  import java.util.List;
26  import java.util.SortedSet;
27  import java.util.concurrent.atomic.AtomicLong;
28  
29  import org.apache.commons.logging.Log;
30  import org.apache.commons.logging.LogFactory;
31  import org.apache.hadoop.classification.InterfaceAudience;
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.client.Scan;
38  import org.apache.hadoop.hbase.io.hfile.HFileScanner;
39  import org.apache.hadoop.hbase.regionserver.StoreFile.Reader;
40  
41  /**
42   * KeyValueScanner adaptor over the Reader.  It also provides hooks into
43   * bloom filter things.
44   */
45  @InterfaceAudience.LimitedPrivate("Coprocessor")
46  public class StoreFileScanner implements KeyValueScanner {
47    static final Log LOG = LogFactory.getLog(HStore.class);
48  
49    // the reader it comes from:
50    private final StoreFile.Reader reader;
51    private final HFileScanner hfs;
52    private Cell cur = null;
53  
54    private boolean realSeekDone;
55    private boolean delayedReseek;
56    private Cell delayedSeekKV;
57  
58    private boolean enforceMVCC = false;
59    private boolean hasMVCCInfo = false;
60    // A flag represents whether could stop skipping KeyValues for MVCC
61    // if have encountered the next row. Only used for reversed scan
62    private boolean stopSkippingKVsIfNextRow = false;
63  
64    private static AtomicLong seekCount;
65  
66    private ScanQueryMatcher matcher;
67    
68    private long readPt;
69  
70    /**
71     * Implements a {@link KeyValueScanner} on top of the specified {@link HFileScanner}
72     * @param hfs HFile scanner
73     */
74    public StoreFileScanner(StoreFile.Reader reader, HFileScanner hfs, boolean useMVCC,
75        boolean hasMVCC, long readPt) {
76      this.readPt = readPt;
77      this.reader = reader;
78      this.hfs = hfs;
79      this.enforceMVCC = useMVCC;
80      this.hasMVCCInfo = hasMVCC;
81    }
82  
83    /**
84     * Return an array of scanners corresponding to the given
85     * set of store files.
86     */
87    public static List<StoreFileScanner> getScannersForStoreFiles(
88        Collection<StoreFile> files,
89        boolean cacheBlocks,
90        boolean usePread, long readPt) throws IOException {
91      return getScannersForStoreFiles(files, cacheBlocks,
92                                     usePread, false, readPt);
93    }
94  
95    /**
96     * Return an array of scanners corresponding to the given set of store files.
97     */
98    public static List<StoreFileScanner> getScannersForStoreFiles(
99        Collection<StoreFile> files, boolean cacheBlocks, boolean usePread,
100       boolean isCompaction, long readPt) throws IOException {
101     return getScannersForStoreFiles(files, cacheBlocks, usePread, isCompaction,
102         null, readPt);
103   }
104 
105   /**
106    * Return an array of scanners corresponding to the given set of store files,
107    * And set the ScanQueryMatcher for each store file scanner for further
108    * optimization
109    */
110   public static List<StoreFileScanner> getScannersForStoreFiles(
111       Collection<StoreFile> files, boolean cacheBlocks, boolean usePread,
112       boolean isCompaction, ScanQueryMatcher matcher, long readPt) throws IOException {
113     List<StoreFileScanner> scanners = new ArrayList<StoreFileScanner>(
114         files.size());
115     for (StoreFile file : files) {
116       StoreFile.Reader r = file.createReader();
117       StoreFileScanner scanner = r.getStoreFileScanner(cacheBlocks, usePread,
118           isCompaction, readPt);
119       scanner.setScanQueryMatcher(matcher);
120       scanners.add(scanner);
121     }
122     return scanners;
123   }
124 
125   public String toString() {
126     return "StoreFileScanner[" + hfs.toString() + ", cur=" + cur + "]";
127   }
128 
129   public Cell peek() {
130     return cur;
131   }
132 
133   public Cell next() throws IOException {
134     Cell retKey = cur;
135 
136     try {
137       // only seek if we aren't at the end. cur == null implies 'end'.
138       if (cur != null) {
139         hfs.next();
140         cur = hfs.getKeyValue();
141         if (hasMVCCInfo)
142           skipKVsNewerThanReadpoint();
143       }
144     } catch(IOException e) {
145       throw new IOException("Could not iterate " + this, e);
146     }
147     return retKey;
148   }
149 
150   public boolean seek(Cell key) throws IOException {
151     if (seekCount != null) seekCount.incrementAndGet();
152 
153     try {
154       try {
155         if(!seekAtOrAfter(hfs, key)) {
156           close();
157           return false;
158         }
159 
160         cur = hfs.getKeyValue();
161 
162         return !hasMVCCInfo ? true : skipKVsNewerThanReadpoint();
163       } finally {
164         realSeekDone = true;
165       }
166     } catch (IOException ioe) {
167       throw new IOException("Could not seek " + this + " to key " + key, ioe);
168     }
169   }
170 
171   public boolean reseek(Cell key) throws IOException {
172     if (seekCount != null) seekCount.incrementAndGet();
173 
174     try {
175       try {
176         if (!reseekAtOrAfter(hfs, key)) {
177           close();
178           return false;
179         }
180         cur = hfs.getKeyValue();
181 
182         return !hasMVCCInfo ? true : skipKVsNewerThanReadpoint();
183       } finally {
184         realSeekDone = true;
185       }
186     } catch (IOException ioe) {
187       throw new IOException("Could not reseek " + this + " to key " + key,
188           ioe);
189     }
190   }
191 
192   protected boolean skipKVsNewerThanReadpoint() throws IOException {
193     // We want to ignore all key-values that are newer than our current
194     // readPoint
195     Cell startKV = cur;
196     while(enforceMVCC
197         && cur != null
198         && (cur.getMvccVersion() > readPt)) {
199       hfs.next();
200       cur = hfs.getKeyValue();
201       if (this.stopSkippingKVsIfNextRow
202           && getComparator().compareRows(cur.getRowArray(), cur.getRowOffset(),
203               cur.getRowLength(), startKV.getRowArray(), startKV.getRowOffset(),
204               startKV.getRowLength()) > 0) {
205         return false;
206       }
207     }
208 
209     if (cur == null) {
210       close();
211       return false;
212     }
213 
214     return true;
215   }
216 
217   public void close() {
218     // Nothing to close on HFileScanner?
219     cur = null;
220   }
221 
222   /**
223    *
224    * @param s
225    * @param k
226    * @return false if not found or if k is after the end.
227    * @throws IOException
228    */
229   public static boolean seekAtOrAfter(HFileScanner s, Cell k)
230   throws IOException {
231     int result = s.seekTo(k);
232     if(result < 0) {
233       if (result == HConstants.INDEX_KEY_MAGIC) {
234         // using faked key
235         return true;
236       }
237       // Passed KV is smaller than first KV in file, work from start of file
238       return s.seekTo();
239     } else if(result > 0) {
240       // Passed KV is larger than current KV in file, if there is a next
241       // it is the "after", if not then this scanner is done.
242       return s.next();
243     }
244     // Seeked to the exact key
245     return true;
246   }
247 
248   static boolean reseekAtOrAfter(HFileScanner s, Cell k)
249   throws IOException {
250     //This function is similar to seekAtOrAfter function
251     int result = s.reseekTo(k);
252     if (result <= 0) {
253       if (result == HConstants.INDEX_KEY_MAGIC) {
254         // using faked key
255         return true;
256       }
257       // If up to now scanner is not seeked yet, this means passed KV is smaller
258       // than first KV in file, and it is the first time we seek on this file.
259       // So we also need to work from the start of file.
260       if (!s.isSeeked()) {
261         return  s.seekTo();
262       }
263       return true;
264     }
265     // passed KV is larger than current KV in file, if there is a next
266     // it is after, if not then this scanner is done.
267     return s.next();
268   }
269 
270   @Override
271   public long getSequenceID() {
272     return reader.getSequenceID();
273   }
274 
275   /**
276    * Pretend we have done a seek but don't do it yet, if possible. The hope is
277    * that we find requested columns in more recent files and won't have to seek
278    * in older files. Creates a fake key/value with the given row/column and the
279    * highest (most recent) possible timestamp we might get from this file. When
280    * users of such "lazy scanner" need to know the next KV precisely (e.g. when
281    * this scanner is at the top of the heap), they run {@link #enforceSeek()}.
282    * <p>
283    * Note that this function does guarantee that the current KV of this scanner
284    * will be advanced to at least the given KV. Because of this, it does have
285    * to do a real seek in cases when the seek timestamp is older than the
286    * highest timestamp of the file, e.g. when we are trying to seek to the next
287    * row/column and use OLDEST_TIMESTAMP in the seek key.
288    */
289   @Override
290   public boolean requestSeek(Cell kv, boolean forward, boolean useBloom)
291       throws IOException {
292     if (kv.getFamilyLength() == 0) {
293       useBloom = false;
294     }
295 
296     boolean haveToSeek = true;
297     if (useBloom) {
298       // check ROWCOL Bloom filter first.
299       if (reader.getBloomFilterType() == BloomType.ROWCOL) {
300         haveToSeek = reader.passesGeneralBloomFilter(kv.getRowArray(),
301             kv.getRowOffset(), kv.getRowLength(), kv.getQualifierArray(),
302             kv.getQualifierOffset(), kv.getQualifierLength());
303       } else if (this.matcher != null && !matcher.hasNullColumnInQuery() &&
304           ((CellUtil.isDeleteFamily(kv) || CellUtil.isDeleteFamilyVersion(kv)))) {
305         // if there is no such delete family kv in the store file,
306         // then no need to seek.
307         haveToSeek = reader.passesDeleteFamilyBloomFilter(kv.getRowArray(),
308             kv.getRowOffset(), kv.getRowLength());
309       }
310     }
311 
312     delayedReseek = forward;
313     delayedSeekKV = kv;
314 
315     if (haveToSeek) {
316       // This row/column might be in this store file (or we did not use the
317       // Bloom filter), so we still need to seek.
318       realSeekDone = false;
319       long maxTimestampInFile = reader.getMaxTimestamp();
320       long seekTimestamp = kv.getTimestamp();
321       if (seekTimestamp > maxTimestampInFile) {
322         // Create a fake key that is not greater than the real next key.
323         // (Lower timestamps correspond to higher KVs.)
324         // To understand this better, consider that we are asked to seek to
325         // a higher timestamp than the max timestamp in this file. We know that
326         // the next point when we have to consider this file again is when we
327         // pass the max timestamp of this file (with the same row/column).
328         cur = KeyValueUtil.createFirstOnRowColTS(kv, maxTimestampInFile);
329       } else {
330         // This will be the case e.g. when we need to seek to the next
331         // row/column, and we don't know exactly what they are, so we set the
332         // seek key's timestamp to OLDEST_TIMESTAMP to skip the rest of this
333         // row/column.
334         enforceSeek();
335       }
336       return cur != null;
337     }
338 
339     // Multi-column Bloom filter optimization.
340     // Create a fake key/value, so that this scanner only bubbles up to the top
341     // of the KeyValueHeap in StoreScanner after we scanned this row/column in
342     // all other store files. The query matcher will then just skip this fake
343     // key/value and the store scanner will progress to the next column. This
344     // is obviously not a "real real" seek, but unlike the fake KV earlier in
345     // this method, we want this to be propagated to ScanQueryMatcher.
346     cur = KeyValueUtil.createLastOnRowCol(kv);
347 
348     realSeekDone = true;
349     return true;
350   }
351 
352   Reader getReaderForTesting() {
353     return reader;
354   }
355 
356   KeyValue.KVComparator getComparator() {
357     return reader.getComparator();
358   }
359 
360   @Override
361   public boolean realSeekDone() {
362     return realSeekDone;
363   }
364 
365   @Override
366   public void enforceSeek() throws IOException {
367     if (realSeekDone)
368       return;
369 
370     if (delayedReseek) {
371       reseek(delayedSeekKV);
372     } else {
373       seek(delayedSeekKV);
374     }
375   }
376 
377   public void setScanQueryMatcher(ScanQueryMatcher matcher) {
378     this.matcher = matcher;
379   }
380 
381   @Override
382   public boolean isFileScanner() {
383     return true;
384   }
385 
386   // Test methods
387 
388   static final long getSeekCount() {
389     return seekCount.get();
390   }
391   static final void instrument() {
392     seekCount = new AtomicLong();
393   }
394 
395   @Override
396   public boolean shouldUseScanner(Scan scan, SortedSet<byte[]> columns, long oldestUnexpiredTS) {
397     return reader.passesTimerangeFilter(scan, oldestUnexpiredTS)
398         && reader.passesKeyRangeFilter(scan) && reader.passesBloomFilter(scan, columns);
399   }
400 
401   @Override
402   @SuppressWarnings("deprecation")
403   public boolean seekToPreviousRow(Cell key) throws IOException {
404     try {
405       try {
406         KeyValue seekKey = KeyValueUtil.createFirstOnRow(key.getRowArray(), key.getRowOffset(),
407             key.getRowLength());
408         if (seekCount != null) seekCount.incrementAndGet();
409         if (!hfs.seekBefore(seekKey.getBuffer(), seekKey.getKeyOffset(),
410             seekKey.getKeyLength())) {
411           close();
412           return false;
413         }
414         KeyValue firstKeyOfPreviousRow = KeyValueUtil.createFirstOnRow(hfs.getKeyValue()
415             .getRowArray(), hfs.getKeyValue().getRowOffset(), hfs.getKeyValue().getRowLength());
416 
417         if (seekCount != null) seekCount.incrementAndGet();
418         if (!seekAtOrAfter(hfs, firstKeyOfPreviousRow)) {
419           close();
420           return false;
421         }
422 
423         cur = hfs.getKeyValue();
424         this.stopSkippingKVsIfNextRow = true;
425         boolean resultOfSkipKVs;
426         try {
427           resultOfSkipKVs = skipKVsNewerThanReadpoint();
428         } finally {
429           this.stopSkippingKVsIfNextRow = false;
430         }
431         if (!resultOfSkipKVs
432             || getComparator().compareRows(cur, firstKeyOfPreviousRow) > 0) {
433           return seekToPreviousRow(firstKeyOfPreviousRow);
434         }
435 
436         return true;
437       } finally {
438         realSeekDone = true;
439       }
440     } catch (IOException ioe) {
441       throw new IOException("Could not seekToPreviousRow " + this + " to key "
442           + key, ioe);
443     }
444   }
445 
446   @Override
447   public boolean seekToLastRow() throws IOException {
448     byte[] lastRow = reader.getLastRowKey();
449     if (lastRow == null) {
450       return false;
451     }
452     KeyValue seekKey = KeyValueUtil.createFirstOnRow(lastRow);
453     if (seek(seekKey)) {
454       return true;
455     } else {
456       return seekToPreviousRow(seekKey);
457     }
458   }
459 
460   @Override
461   public boolean backwardSeek(Cell key) throws IOException {
462     seek(key);
463     if (cur == null
464         || getComparator().compareRows(cur.getRowArray(), cur.getRowOffset(),
465             cur.getRowLength(), key.getRowArray(), key.getRowOffset(),
466             key.getRowLength()) > 0) {
467       return seekToPreviousRow(key);
468     }
469     return true;
470   }
471 }