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