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