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.HashSet;
25  import java.util.List;
26  import java.util.PriorityQueue;
27  import java.util.Set;
28  
29  import org.apache.hadoop.hbase.Cell;
30  import org.apache.hadoop.hbase.CellComparator;
31  import org.apache.hadoop.hbase.classification.InterfaceAudience;
32  import org.apache.hadoop.hbase.regionserver.ScannerContext.NextState;
33  
34  /**
35   * Implements a heap merge across any number of KeyValueScanners.
36   * <p>
37   * Implements KeyValueScanner itself.
38   * <p>
39   * This class is used at the Region level to merge across Stores
40   * and at the Store level to merge across the memstore and StoreFiles.
41   * <p>
42   * In the Region case, we also need InternalScanner.next(List), so this class
43   * also implements InternalScanner.  WARNING: As is, if you try to use this
44   * as an InternalScanner at the Store level, you will get runtime exceptions.
45   */
46  @InterfaceAudience.Private
47  public class KeyValueHeap extends NonReversedNonLazyKeyValueScanner
48      implements KeyValueScanner, InternalScanner {
49    protected PriorityQueue<KeyValueScanner> heap = null;
50    // Holds the scanners when a ever a eager close() happens.  All such eagerly closed
51    // scans are collected and when the final scanner.close() happens will perform the
52    // actual close.
53    protected Set<KeyValueScanner> scannersForDelayedClose = new HashSet<KeyValueScanner>();
54  
55    /**
56     * The current sub-scanner, i.e. the one that contains the next key/value
57     * to return to the client. This scanner is NOT included in {@link #heap}
58     * (but we frequently add it back to the heap and pull the new winner out).
59     * We maintain an invariant that the current sub-scanner has already done
60     * a real seek, and that current.peek() is always a real key/value (or null)
61     * except for the fake last-key-on-row-column supplied by the multi-column
62     * Bloom filter optimization, which is OK to propagate to StoreScanner. In
63     * order to ensure that, always use {@link #pollRealKV()} to update current.
64     */
65    protected KeyValueScanner current = null;
66  
67    protected KVScannerComparator comparator;
68  
69    /**
70     * Constructor.  This KeyValueHeap will handle closing of passed in
71     * KeyValueScanners.
72     * @param scanners
73     * @param comparator
74     */
75    public KeyValueHeap(List<? extends KeyValueScanner> scanners,
76        CellComparator comparator) throws IOException {
77      this(scanners, new KVScannerComparator(comparator));
78    }
79  
80    /**
81     * Constructor.
82     * @param scanners
83     * @param comparator
84     * @throws IOException
85     */
86    KeyValueHeap(List<? extends KeyValueScanner> scanners,
87        KVScannerComparator comparator) throws IOException {
88      this.comparator = comparator;
89      if (!scanners.isEmpty()) {
90        this.heap = new PriorityQueue<KeyValueScanner>(scanners.size(),
91            this.comparator);
92        for (KeyValueScanner scanner : scanners) {
93          if (scanner.peek() != null) {
94            this.heap.add(scanner);
95          } else {
96            this.scannersForDelayedClose.add(scanner);
97          }
98        }
99        this.current = pollRealKV();
100     }
101   }
102 
103   public Cell peek() {
104     if (this.current == null) {
105       return null;
106     }
107     return this.current.peek();
108   }
109 
110   public Cell next()  throws IOException {
111     if(this.current == null) {
112       return null;
113     }
114     Cell kvReturn = this.current.next();
115     Cell kvNext = this.current.peek();
116     if (kvNext == null) {
117       this.scannersForDelayedClose.add(this.current);
118       this.current = null;
119       this.current = pollRealKV();
120     } else {
121       KeyValueScanner topScanner = this.heap.peek();
122       // no need to add current back to the heap if it is the only scanner left
123       if (topScanner != null && this.comparator.compare(kvNext, topScanner.peek()) >= 0) {
124         this.heap.add(this.current);
125         this.current = null;
126         this.current = pollRealKV();
127       }
128     }
129     return kvReturn;
130   }
131 
132   /**
133    * Gets the next row of keys from the top-most scanner.
134    * <p>
135    * This method takes care of updating the heap.
136    * <p>
137    * This can ONLY be called when you are using Scanners that implement InternalScanner as well as
138    * KeyValueScanner (a {@link StoreScanner}).
139    * @param result
140    * @return true if more rows exist after this one, false if scanner is done
141    */
142   @Override
143   public boolean next(List<Cell> result) throws IOException {
144     return next(result, NoLimitScannerContext.getInstance());
145   }
146 
147   @Override
148   public boolean next(List<Cell> result, ScannerContext scannerContext) throws IOException {
149     if (this.current == null) {
150       return scannerContext.setScannerState(NextState.NO_MORE_VALUES).hasMoreValues();
151     }
152     InternalScanner currentAsInternal = (InternalScanner)this.current;
153     boolean moreCells = currentAsInternal.next(result, scannerContext);
154     Cell pee = this.current.peek();
155 
156     /*
157      * By definition, any InternalScanner must return false only when it has no
158      * further rows to be fetched. So, we can close a scanner if it returns
159      * false. All existing implementations seem to be fine with this. It is much
160      * more efficient to close scanners which are not needed than keep them in
161      * the heap. This is also required for certain optimizations.
162      */
163 
164     if (pee == null || !moreCells) {
165       // add the scanner that is to be closed
166       this.scannersForDelayedClose.add(this.current);
167     } else {
168       this.heap.add(this.current);
169     }
170     this.current = null;
171     this.current = pollRealKV();
172     if (this.current == null) {
173       moreCells = scannerContext.setScannerState(NextState.NO_MORE_VALUES).hasMoreValues();
174     }
175     return moreCells;
176   }
177 
178   protected static class KVScannerComparator implements Comparator<KeyValueScanner> {
179     protected CellComparator kvComparator;
180     /**
181      * Constructor
182      * @param kvComparator
183      */
184     public KVScannerComparator(CellComparator kvComparator) {
185       this.kvComparator = kvComparator;
186     }
187     public int compare(KeyValueScanner left, KeyValueScanner right) {
188       int comparison = compare(left.peek(), right.peek());
189       if (comparison != 0) {
190         return comparison;
191       } else {
192         // Since both the keys are exactly the same, we break the tie in favor of higher ordered
193         // scanner since it'll have newer data. Since higher value should come first, we reverse
194         // sort here.
195         return Long.compare(right.getScannerOrder(), left.getScannerOrder());
196       }
197     }
198     /**
199      * Compares two KeyValue
200      * @param left
201      * @param right
202      * @return less than 0 if left is smaller, 0 if equal etc..
203      */
204     public int compare(Cell left, Cell right) {
205       return this.kvComparator.compare(left, right);
206     }
207     /**
208      * @return KVComparator
209      */
210     public CellComparator getComparator() {
211       return this.kvComparator;
212     }
213   }
214
215   public void close() {
216     for (KeyValueScanner scanner : this.scannersForDelayedClose) {
217       scanner.close();
218     }
219     this.scannersForDelayedClose.clear();
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(Cell)}) does not do multi-column
240    * Bloom filter and lazy-seek optimizations. To enable those, call
241    * {@link #requestSeek(Cell, 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(Cell 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(Cell)} function except
256    * that scanner.seek(seekKey) is changed to scanner.reseek(seekKey).
257    */
258   @Override
259   public boolean reseek(Cell 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(Cell 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, Cell 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
294     KeyValueScanner scanner = current;
295     while (scanner != null) {
296       Cell topKey = scanner.peek();
297       if (comparator.getComparator().compare(seekKey, topKey) <= 0) {
298         // Top KeyValue is at-or-after Seek KeyValue. We only know that all
299         // scanners are at or after seekKey (because fake keys of
300         // scanners where a lazy-seek operation has been done are not greater
301         // than their real next keys) but we still need to enforce our
302         // invariant that the top scanner has done a real seek. This way
303         // StoreScanner and RegionScanner do not have to worry about fake keys.
304         heap.add(scanner);
305         current = pollRealKV();
306         return current != null;
307       }
308
309       boolean seekResult;
310       if (isLazy && heap.size() > 0) {
311         // If there is only one scanner left, we don't do lazy seek.
312         seekResult = scanner.requestSeek(seekKey, forward, useBloom);
313       } else {
314         seekResult = NonLazyKeyValueScanner.doRealSeek(
315             scanner, seekKey, forward);
316       }
317
318       if (!seekResult) {
319         this.scannersForDelayedClose.add(scanner);
320       } else {
321         heap.add(scanner);
322       }
323       scanner = heap.poll();
324       if (scanner == null) {
325         current = null;
326       }
327     }
328
329     // Heap is returning empty, scanner is done
330     return false;
331   }
332
333   /**
334    * Fetches the top sub-scanner from the priority queue, ensuring that a real
335    * seek has been done on it. Works by fetching the top sub-scanner, and if it
336    * has not done a real seek, making it do so (which will modify its top KV),
337    * putting it back, and repeating this until success. Relies on the fact that
338    * on a lazy seek we set the current key of a StoreFileScanner to a KV that
339    * is not greater than the real next KV to be read from that file, so the
340    * scanner that bubbles up to the top of the heap will have global next KV in
341    * this scanner heap if (1) it has done a real seek and (2) its KV is the top
342    * among all top KVs (some of which are fake) in the scanner heap.
343    */
344   protected KeyValueScanner pollRealKV() throws IOException {
345     KeyValueScanner kvScanner = heap.poll();
346     if (kvScanner == null) {
347       return null;
348     }
349
350     while (kvScanner != null && !kvScanner.realSeekDone()) {
351       if (kvScanner.peek() != null) {
352         try {
353           kvScanner.enforceSeek();
354         } catch (IOException ioe) {
355           // Add the item to delayed close set in case it is leak from close
356           this.scannersForDelayedClose.add(kvScanner);
357           throw ioe;
358         }
359         Cell curKV = kvScanner.peek();
360         if (curKV != null) {
361           KeyValueScanner nextEarliestScanner = heap.peek();
362           if (nextEarliestScanner == null) {
363             // The heap is empty. Return the only possible scanner.
364             return kvScanner;
365           }
366
367           // Compare the current scanner to the next scanner. We try to avoid
368           // putting the current one back into the heap if possible.
369           Cell nextKV = nextEarliestScanner.peek();
370           if (nextKV == null || comparator.compare(curKV, nextKV) < 0) {
371             // We already have the scanner with the earliest KV, so return it.
372             return kvScanner;
373           }
374
375           // Otherwise, put the scanner back into the heap and let it compete
376           // against all other scanners (both those that have done a "real
377           // seek" and a "lazy seek").
378           heap.add(kvScanner);
379         } else {
380           // Close the scanner because we did a real seek and found out there
381           // are no more KVs.
382           this.scannersForDelayedClose.add(kvScanner);
383         }
384       } else {
385         // Close the scanner because it has already run out of KVs even before
386         // we had to do a real seek on it.
387         this.scannersForDelayedClose.add(kvScanner);
388       }
389       kvScanner = heap.poll();
390     }
391
392     return kvScanner;
393   }
394
395   /**
396    * @return the current Heap
397    */
398   public PriorityQueue<KeyValueScanner> getHeap() {
399     return this.heap;
400   }
401 
402   /**
403    * @see KeyValueScanner#getScannerOrder()
404    */
405   @Override
406   public long getScannerOrder() {
407     return 0;
408   }
409
410   KeyValueScanner getCurrentForTesting() {
411     return current;
412   }
413 
414   @Override
415   public Cell getNextIndexedKey() {
416     // here we return the next index key from the top scanner
417     return current == null ? null : current.getNextIndexedKey();
418   }
419
420   @Override
421   public void shipped() throws IOException {
422     for (KeyValueScanner scanner : this.scannersForDelayedClose) {
423       scanner.close(); // There wont be further fetch of Cells from these scanners. Just close.
424     }
425     this.scannersForDelayedClose.clear();
426     if (this.current != null) {
427       this.current.shipped();
428     }
429     if (this.heap != null) {
430       for (KeyValueScanner scanner : this.heap) {
431         scanner.shipped();
432       }
433     }
434   }
435 }