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.Comparator;
24  import java.util.List;
25  import java.util.PriorityQueue;
26  
27  import org.apache.hadoop.hbase.classification.InterfaceAudience;
28  import org.apache.hadoop.hbase.Cell;
29  import org.apache.hadoop.hbase.KeyValue;
30  import org.apache.hadoop.hbase.KeyValue.KVComparator;
31  
32  /**
33   * Implements a heap merge across any number of KeyValueScanners.
34   * <p>
35   * Implements KeyValueScanner itself.
36   * <p>
37   * This class is used at the Region level to merge across Stores
38   * and at the Store level to merge across the memstore and StoreFiles.
39   * <p>
40   * In the Region case, we also need InternalScanner.next(List), so this class
41   * also implements InternalScanner.  WARNING: As is, if you try to use this
42   * as an InternalScanner at the Store level, you will get runtime exceptions.
43   */
44  @InterfaceAudience.Private
45  public class KeyValueHeap extends NonReversedNonLazyKeyValueScanner
46      implements KeyValueScanner, InternalScanner {
47    protected PriorityQueue<KeyValueScanner> heap = null;
48  
49    /**
50     * The current sub-scanner, i.e. the one that contains the next key/value
51     * to return to the client. This scanner is NOT included in {@link #heap}
52     * (but we frequently add it back to the heap and pull the new winner out).
53     * We maintain an invariant that the current sub-scanner has already done
54     * a real seek, and that current.peek() is always a real key/value (or null)
55     * except for the fake last-key-on-row-column supplied by the multi-column
56     * Bloom filter optimization, which is OK to propagate to StoreScanner. In
57     * order to ensure that, always use {@link #pollRealKV()} to update current.
58     */
59    protected KeyValueScanner current = null;
60  
61    protected KVScannerComparator comparator;
62    
63    /**
64     * Constructor.  This KeyValueHeap will handle closing of passed in
65     * KeyValueScanners.
66     * @param scanners
67     * @param comparator
68     */
69    public KeyValueHeap(List<? extends KeyValueScanner> scanners,
70        KVComparator comparator) throws IOException {
71      this(scanners, new KVScannerComparator(comparator));
72    }
73  
74    /**
75     * Constructor.
76     * @param scanners
77     * @param comparator
78     * @throws IOException
79     */
80    KeyValueHeap(List<? extends KeyValueScanner> scanners,
81        KVScannerComparator comparator) throws IOException {
82      this.comparator = comparator;
83      if (!scanners.isEmpty()) {
84        this.heap = new PriorityQueue<KeyValueScanner>(scanners.size(),
85            this.comparator);
86        for (KeyValueScanner scanner : scanners) {
87          if (scanner.peek() != null) {
88            this.heap.add(scanner);
89          } else {
90            scanner.close();
91          }
92        }
93        this.current = pollRealKV();
94      }
95    }
96  
97    public KeyValue peek() {
98      if (this.current == null) {
99        return null;
100     }
101     return this.current.peek();
102   }
103 
104   public KeyValue next()  throws IOException {
105     if(this.current == null) {
106       return null;
107     }
108     KeyValue kvReturn = this.current.next();
109     KeyValue kvNext = this.current.peek();
110     if (kvNext == null) {
111       this.current.close();
112       this.current = null;
113       this.current = pollRealKV();
114     } else {
115       KeyValueScanner topScanner = this.heap.peek();
116       // no need to add current back to the heap if it is the only scanner left
117       if (topScanner != null && this.comparator.compare(kvNext, topScanner.peek()) >= 0) {
118         this.heap.add(this.current);
119         this.current = null;
120         this.current = pollRealKV();
121       }
122     }
123     return kvReturn;
124   }
125 
126   /**
127    * Gets the next row of keys from the top-most scanner.
128    * <p>
129    * This method takes care of updating the heap.
130    * <p>
131    * This can ONLY be called when you are using Scanners that implement
132    * InternalScanner as well as KeyValueScanner (a {@link StoreScanner}).
133    * @param result
134    * @param limit
135    * @return true if there are more keys, false if all scanners are done
136    */
137   public boolean next(List<Cell> result, int limit) throws IOException {
138     if (this.current == null) {
139       return false;
140     }
141     InternalScanner currentAsInternal = (InternalScanner)this.current;
142     boolean mayContainMoreRows = currentAsInternal.next(result, limit);
143     KeyValue pee = this.current.peek();
144     /*
145      * By definition, any InternalScanner must return false only when it has no
146      * further rows to be fetched. So, we can close a scanner if it returns
147      * false. All existing implementations seem to be fine with this. It is much
148      * more efficient to close scanners which are not needed than keep them in
149      * the heap. This is also required for certain optimizations.
150      */
151     if (pee == null || !mayContainMoreRows) {
152       this.current.close();
153     } else {
154       this.heap.add(this.current);
155     }
156     this.current = null;
157     this.current = pollRealKV();
158     return (this.current != null);
159   }
160 
161   /**
162    * Gets the next row of keys from the top-most scanner.
163    * <p>
164    * This method takes care of updating the heap.
165    * <p>
166    * This can ONLY be called when you are using Scanners that implement
167    * InternalScanner as well as KeyValueScanner (a {@link StoreScanner}).
168    * @param result
169    * @return true if there are more keys, false if all scanners are done
170    */
171   public boolean next(List<Cell> result) throws IOException {
172     return next(result, -1);
173   }
174 
175   protected static class KVScannerComparator implements Comparator<KeyValueScanner> {
176     protected KVComparator kvComparator;
177     /**
178      * Constructor
179      * @param kvComparator
180      */
181     public KVScannerComparator(KVComparator kvComparator) {
182       this.kvComparator = kvComparator;
183     }
184     public int compare(KeyValueScanner left, KeyValueScanner right) {
185       int comparison = compare(left.peek(), right.peek());
186       if (comparison != 0) {
187         return comparison;
188       } else {
189         // Since both the keys are exactly the same, we break the tie in favor
190         // of the key which came latest.
191         long leftSequenceID = left.getSequenceID();
192         long rightSequenceID = right.getSequenceID();
193         if (leftSequenceID > rightSequenceID) {
194           return -1;
195         } else if (leftSequenceID < rightSequenceID) {
196           return 1;
197         } else {
198           return 0;
199         }
200       }
201     }
202     /**
203      * Compares two KeyValue
204      * @param left
205      * @param right
206      * @return less than 0 if left is smaller, 0 if equal etc..
207      */
208     public int compare(KeyValue left, KeyValue right) {
209       return this.kvComparator.compare(left, right);
210     }
211     /**
212      * @return KVComparator
213      */
214     public KVComparator getComparator() {
215       return this.kvComparator;
216     }
217   }
218 
219   public void close() {
220     if (this.current != null) {
221       this.current.close();
222     }
223     if (this.heap != null) {
224       KeyValueScanner scanner;
225       while ((scanner = this.heap.poll()) != null) {
226         scanner.close();
227       }
228     }
229   }
230 
231   /**
232    * Seeks all scanners at or below the specified seek key.  If we earlied-out
233    * of a row, we may end up skipping values that were never reached yet.
234    * Rather than iterating down, we want to give the opportunity to re-seek.
235    * <p>
236    * As individual scanners may run past their ends, those scanners are
237    * automatically closed and removed from the heap.
238    * <p>
239    * This function (and {@link #reseek(KeyValue)}) does not do multi-column
240    * Bloom filter and lazy-seek optimizations. To enable those, call
241    * {@link #requestSeek(KeyValue, boolean, boolean)}.
242    * @param seekKey KeyValue to seek at or after
243    * @return true if KeyValues exist at or after specified key, false if not
244    * @throws IOException
245    */
246   @Override
247   public boolean seek(KeyValue seekKey) throws IOException {
248     return generalizedSeek(false,    // This is not a lazy seek
249                            seekKey,
250                            false,    // forward (false: this is not a reseek)
251                            false);   // Not using Bloom filters
252   }
253 
254   /**
255    * This function is identical to the {@link #seek(KeyValue)} function except
256    * that scanner.seek(seekKey) is changed to scanner.reseek(seekKey).
257    */
258   @Override
259   public boolean reseek(KeyValue seekKey) throws IOException {
260     return generalizedSeek(false,    // This is not a lazy seek
261                            seekKey,
262                            true,     // forward (true because this is reseek)
263                            false);   // Not using Bloom filters
264   }
265 
266   /**
267    * {@inheritDoc}
268    */
269   @Override
270   public boolean requestSeek(KeyValue key, boolean forward,
271       boolean useBloom) throws IOException {
272     return generalizedSeek(true, key, forward, useBloom);
273   }
274 
275   /**
276    * @param isLazy whether we are trying to seek to exactly the given row/col.
277    *          Enables Bloom filter and most-recent-file-first optimizations for
278    *          multi-column get/scan queries.
279    * @param seekKey key to seek to
280    * @param forward whether to seek forward (also known as reseek)
281    * @param useBloom whether to optimize seeks using Bloom filters
282    */
283   private boolean generalizedSeek(boolean isLazy, KeyValue seekKey,
284       boolean forward, boolean useBloom) throws IOException {
285     if (!isLazy && useBloom) {
286       throw new IllegalArgumentException("Multi-column Bloom filter " +
287           "optimization requires a lazy seek");
288     }
289 
290     if (current == null) {
291       return false;
292     }
293     heap.add(current);
294     current = null;
295 
296     KeyValueScanner scanner;
297     while ((scanner = heap.poll()) != null) {
298       KeyValue topKey = scanner.peek();
299       if (comparator.getComparator().compare(seekKey, topKey) <= 0) {
300         // Top KeyValue is at-or-after Seek KeyValue. We only know that all
301         // scanners are at or after seekKey (because fake keys of
302         // scanners where a lazy-seek operation has been done are not greater
303         // than their real next keys) but we still need to enforce our
304         // invariant that the top scanner has done a real seek. This way
305         // StoreScanner and RegionScanner do not have to worry about fake keys.
306         heap.add(scanner);
307         current = pollRealKV();
308         return current != null;
309       }
310 
311       boolean seekResult;
312       if (isLazy && heap.size() > 0) {
313         // If there is only one scanner left, we don't do lazy seek.
314         seekResult = scanner.requestSeek(seekKey, forward, useBloom);
315       } else {
316         seekResult = NonLazyKeyValueScanner.doRealSeek(
317             scanner, seekKey, forward);
318       }
319 
320       if (!seekResult) {
321         scanner.close();
322       } else {
323         heap.add(scanner);
324       }
325     }
326 
327     // Heap is returning empty, scanner is done
328     return false;
329   }
330 
331   /**
332    * Fetches the top sub-scanner from the priority queue, ensuring that a real
333    * seek has been done on it. Works by fetching the top sub-scanner, and if it
334    * has not done a real seek, making it do so (which will modify its top KV),
335    * putting it back, and repeating this until success. Relies on the fact that
336    * on a lazy seek we set the current key of a StoreFileScanner to a KV that
337    * is not greater than the real next KV to be read from that file, so the
338    * scanner that bubbles up to the top of the heap will have global next KV in
339    * this scanner heap if (1) it has done a real seek and (2) its KV is the top
340    * among all top KVs (some of which are fake) in the scanner heap.
341    */
342   protected KeyValueScanner pollRealKV() throws IOException {
343     KeyValueScanner kvScanner = heap.poll();
344     if (kvScanner == null) {
345       return null;
346     }
347 
348     while (kvScanner != null && !kvScanner.realSeekDone()) {
349       if (kvScanner.peek() != null) {
350         try {
351           kvScanner.enforceSeek();
352         } catch (IOException ioe) {
353           kvScanner.close();
354           throw ioe;
355         }
356         KeyValue curKV = kvScanner.peek();
357         if (curKV != null) {
358           KeyValueScanner nextEarliestScanner = heap.peek();
359           if (nextEarliestScanner == null) {
360             // The heap is empty. Return the only possible scanner.
361             return kvScanner;
362           }
363 
364           // Compare the current scanner to the next scanner. We try to avoid
365           // putting the current one back into the heap if possible.
366           KeyValue nextKV = nextEarliestScanner.peek();
367           if (nextKV == null || comparator.compare(curKV, nextKV) < 0) {
368             // We already have the scanner with the earliest KV, so return it.
369             return kvScanner;
370           }
371 
372           // Otherwise, put the scanner back into the heap and let it compete
373           // against all other scanners (both those that have done a "real
374           // seek" and a "lazy seek").
375           heap.add(kvScanner);
376         } else {
377           // Close the scanner because we did a real seek and found out there
378           // are no more KVs.
379           kvScanner.close();
380         }
381       } else {
382         // Close the scanner because it has already run out of KVs even before
383         // we had to do a real seek on it.
384         kvScanner.close();
385       }
386       kvScanner = heap.poll();
387     }
388 
389     return kvScanner;
390   }
391 
392   /**
393    * @return the current Heap
394    */
395   public PriorityQueue<KeyValueScanner> getHeap() {
396     return this.heap;
397   }
398 
399   @Override
400   public long getSequenceID() {
401     return 0;
402   }
403 
404   KeyValueScanner getCurrentForTesting() {
405     return current;
406   }
407 
408   @Override
409   public byte[] getNextIndexedKey() {
410     // here we return the next index key from the top scanner
411     return current == null ? null : current.getNextIndexedKey();
412   }
413 }