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