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     // For the optimisation in HBASE-4346, we set the KV's memstoreTS to
215     // 0, if it is older than all the scanners' read points. It is possible
216     // that a newer KV's memstoreTS was reset to 0. But, there is an
217     // older KV which was not reset to 0 (because it was
218     // not old enough during flush). Make sure that we set it correctly now,
219     // so that the comparision order does not change.
220     if (cur.getMvccVersion() <= readPt) {
221       KeyValueUtil.ensureKeyValue(cur).setMvccVersion(0);
222     }
223     return true;
224   }
225 
226   public void close() {
227     // Nothing to close on HFileScanner?
228     cur = null;
229   }
230 
231   /**
232    *
233    * @param s
234    * @param k
235    * @return false if not found or if k is after the end.
236    * @throws IOException
237    */
238   public static boolean seekAtOrAfter(HFileScanner s, Cell k)
239   throws IOException {
240     int result = s.seekTo(k);
241     if(result < 0) {
242       if (result == HConstants.INDEX_KEY_MAGIC) {
243         // using faked key
244         return true;
245       }
246       // Passed KV is smaller than first KV in file, work from start of file
247       return s.seekTo();
248     } else if(result > 0) {
249       // Passed KV is larger than current KV in file, if there is a next
250       // it is the "after", if not then this scanner is done.
251       return s.next();
252     }
253     // Seeked to the exact key
254     return true;
255   }
256 
257   static boolean reseekAtOrAfter(HFileScanner s, Cell k)
258   throws IOException {
259     //This function is similar to seekAtOrAfter function
260     int result = s.reseekTo(k);
261     if (result <= 0) {
262       if (result == HConstants.INDEX_KEY_MAGIC) {
263         // using faked key
264         return true;
265       }
266       // If up to now scanner is not seeked yet, this means passed KV is smaller
267       // than first KV in file, and it is the first time we seek on this file.
268       // So we also need to work from the start of file.
269       if (!s.isSeeked()) {
270         return  s.seekTo();
271       }
272       return true;
273     }
274     // passed KV is larger than current KV in file, if there is a next
275     // it is after, if not then this scanner is done.
276     return s.next();
277   }
278 
279   @Override
280   public long getSequenceID() {
281     return reader.getSequenceID();
282   }
283 
284   /**
285    * Pretend we have done a seek but don't do it yet, if possible. The hope is
286    * that we find requested columns in more recent files and won't have to seek
287    * in older files. Creates a fake key/value with the given row/column and the
288    * highest (most recent) possible timestamp we might get from this file. When
289    * users of such "lazy scanner" need to know the next KV precisely (e.g. when
290    * this scanner is at the top of the heap), they run {@link #enforceSeek()}.
291    * <p>
292    * Note that this function does guarantee that the current KV of this scanner
293    * will be advanced to at least the given KV. Because of this, it does have
294    * to do a real seek in cases when the seek timestamp is older than the
295    * highest timestamp of the file, e.g. when we are trying to seek to the next
296    * row/column and use OLDEST_TIMESTAMP in the seek key.
297    */
298   @Override
299   public boolean requestSeek(Cell kv, boolean forward, boolean useBloom)
300       throws IOException {
301     if (kv.getFamilyLength() == 0) {
302       useBloom = false;
303     }
304 
305     boolean haveToSeek = true;
306     if (useBloom) {
307       // check ROWCOL Bloom filter first.
308       if (reader.getBloomFilterType() == BloomType.ROWCOL) {
309         haveToSeek = reader.passesGeneralBloomFilter(kv.getRowArray(),
310             kv.getRowOffset(), kv.getRowLength(), kv.getQualifierArray(),
311             kv.getQualifierOffset(), kv.getQualifierLength());
312       } else if (this.matcher != null && !matcher.hasNullColumnInQuery() &&
313           ((CellUtil.isDeleteFamily(kv) || CellUtil.isDeleteFamilyVersion(kv)))) {
314         // if there is no such delete family kv in the store file,
315         // then no need to seek.
316         haveToSeek = reader.passesDeleteFamilyBloomFilter(kv.getRowArray(),
317             kv.getRowOffset(), kv.getRowLength());
318       }
319     }
320 
321     delayedReseek = forward;
322     delayedSeekKV = kv;
323 
324     if (haveToSeek) {
325       // This row/column might be in this store file (or we did not use the
326       // Bloom filter), so we still need to seek.
327       realSeekDone = false;
328       long maxTimestampInFile = reader.getMaxTimestamp();
329       long seekTimestamp = kv.getTimestamp();
330       if (seekTimestamp > maxTimestampInFile) {
331         // Create a fake key that is not greater than the real next key.
332         // (Lower timestamps correspond to higher KVs.)
333         // To understand this better, consider that we are asked to seek to
334         // a higher timestamp than the max timestamp in this file. We know that
335         // the next point when we have to consider this file again is when we
336         // pass the max timestamp of this file (with the same row/column).
337         cur = KeyValueUtil.createFirstOnRowColTS(kv, maxTimestampInFile);
338       } else {
339         // This will be the case e.g. when we need to seek to the next
340         // row/column, and we don't know exactly what they are, so we set the
341         // seek key's timestamp to OLDEST_TIMESTAMP to skip the rest of this
342         // row/column.
343         enforceSeek();
344       }
345       return cur != null;
346     }
347 
348     // Multi-column Bloom filter optimization.
349     // Create a fake key/value, so that this scanner only bubbles up to the top
350     // of the KeyValueHeap in StoreScanner after we scanned this row/column in
351     // all other store files. The query matcher will then just skip this fake
352     // key/value and the store scanner will progress to the next column. This
353     // is obviously not a "real real" seek, but unlike the fake KV earlier in
354     // this method, we want this to be propagated to ScanQueryMatcher.
355     cur = KeyValueUtil.createLastOnRowCol(kv);
356 
357     realSeekDone = true;
358     return true;
359   }
360 
361   Reader getReaderForTesting() {
362     return reader;
363   }
364 
365   KeyValue.KVComparator getComparator() {
366     return reader.getComparator();
367   }
368 
369   @Override
370   public boolean realSeekDone() {
371     return realSeekDone;
372   }
373 
374   @Override
375   public void enforceSeek() throws IOException {
376     if (realSeekDone)
377       return;
378 
379     if (delayedReseek) {
380       reseek(delayedSeekKV);
381     } else {
382       seek(delayedSeekKV);
383     }
384   }
385 
386   public void setScanQueryMatcher(ScanQueryMatcher matcher) {
387     this.matcher = matcher;
388   }
389 
390   @Override
391   public boolean isFileScanner() {
392     return true;
393   }
394 
395   // Test methods
396 
397   static final long getSeekCount() {
398     return seekCount.get();
399   }
400   static final void instrument() {
401     seekCount = new AtomicLong();
402   }
403 
404   @Override
405   public boolean shouldUseScanner(Scan scan, SortedSet<byte[]> columns, long oldestUnexpiredTS) {
406     return reader.passesTimerangeFilter(scan, oldestUnexpiredTS)
407         && reader.passesKeyRangeFilter(scan) && reader.passesBloomFilter(scan, columns);
408   }
409 
410   @Override
411   @SuppressWarnings("deprecation")
412   public boolean seekToPreviousRow(Cell key) throws IOException {
413     try {
414       try {
415         KeyValue seekKey = KeyValueUtil.createFirstOnRow(key.getRowArray(), key.getRowOffset(),
416             key.getRowLength());
417         if (seekCount != null) seekCount.incrementAndGet();
418         if (!hfs.seekBefore(seekKey.getBuffer(), seekKey.getKeyOffset(),
419             seekKey.getKeyLength())) {
420           close();
421           return false;
422         }
423         KeyValue firstKeyOfPreviousRow = KeyValueUtil.createFirstOnRow(hfs.getKeyValue()
424             .getRowArray(), hfs.getKeyValue().getRowOffset(), hfs.getKeyValue().getRowLength());
425 
426         if (seekCount != null) seekCount.incrementAndGet();
427         if (!seekAtOrAfter(hfs, firstKeyOfPreviousRow)) {
428           close();
429           return false;
430         }
431 
432         cur = hfs.getKeyValue();
433         this.stopSkippingKVsIfNextRow = true;
434         boolean resultOfSkipKVs;
435         try {
436           resultOfSkipKVs = skipKVsNewerThanReadpoint();
437         } finally {
438           this.stopSkippingKVsIfNextRow = false;
439         }
440         if (!resultOfSkipKVs
441             || getComparator().compareRows(cur, firstKeyOfPreviousRow) > 0) {
442           return seekToPreviousRow(firstKeyOfPreviousRow);
443         }
444 
445         return true;
446       } finally {
447         realSeekDone = true;
448       }
449     } catch (IOException ioe) {
450       throw new IOException("Could not seekToPreviousRow " + this + " to key "
451           + key, ioe);
452     }
453   }
454 
455   @Override
456   public boolean seekToLastRow() throws IOException {
457     byte[] lastRow = reader.getLastRowKey();
458     if (lastRow == null) {
459       return false;
460     }
461     KeyValue seekKey = KeyValueUtil.createFirstOnRow(lastRow);
462     if (seek(seekKey)) {
463       return true;
464     } else {
465       return seekToPreviousRow(seekKey);
466     }
467   }
468 
469   @Override
470   public boolean backwardSeek(Cell key) throws IOException {
471     seek(key);
472     if (cur == null
473         || getComparator().compareRows(cur.getRowArray(), cur.getRowOffset(),
474             cur.getRowLength(), key.getRowArray(), key.getRowOffset(),
475             key.getRowLength()) > 0) {
476       return seekToPreviousRow(key);
477     }
478     return true;
479   }
480 }