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 = pollRealKV();
113 } else {
114 KeyValueScanner topScanner = this.heap.peek();
115 // no need to add current back to the heap if it is the only scanner left
116 if (topScanner != null && this.comparator.compare(kvNext, topScanner.peek()) >= 0) {
117 this.heap.add(this.current);
118 this.current = pollRealKV();
119 }
120 }
121 return kvReturn;
122 }
123
124 /**
125 * Gets the next row of keys from the top-most scanner.
126 * <p>
127 * This method takes care of updating the heap.
128 * <p>
129 * This can ONLY be called when you are using Scanners that implement
130 * InternalScanner as well as KeyValueScanner (a {@link StoreScanner}).
131 * @param result
132 * @param limit
133 * @return true if there are more keys, false if all scanners are done
134 */
135 public boolean next(List<Cell> result, int limit) throws IOException {
136 if (this.current == null) {
137 return false;
138 }
139 InternalScanner currentAsInternal = (InternalScanner)this.current;
140 boolean mayContainMoreRows = currentAsInternal.next(result, limit);
141 KeyValue pee = this.current.peek();
142 /*
143 * By definition, any InternalScanner must return false only when it has no
144 * further rows to be fetched. So, we can close a scanner if it returns
145 * false. All existing implementations seem to be fine with this. It is much
146 * more efficient to close scanners which are not needed than keep them in
147 * the heap. This is also required for certain optimizations.
148 */
149 if (pee == null || !mayContainMoreRows) {
150 this.current.close();
151 } else {
152 this.heap.add(this.current);
153 }
154 this.current = pollRealKV();
155 return (this.current != null);
156 }
157
158 /**
159 * Gets the next row of keys from the top-most scanner.
160 * <p>
161 * This method takes care of updating the heap.
162 * <p>
163 * This can ONLY be called when you are using Scanners that implement
164 * InternalScanner as well as KeyValueScanner (a {@link StoreScanner}).
165 * @param result
166 * @return true if there are more keys, false if all scanners are done
167 */
168 public boolean next(List<Cell> result) throws IOException {
169 return next(result, -1);
170 }
171
172 protected static class KVScannerComparator implements Comparator<KeyValueScanner> {
173 protected KVComparator kvComparator;
174 /**
175 * Constructor
176 * @param kvComparator
177 */
178 public KVScannerComparator(KVComparator kvComparator) {
179 this.kvComparator = kvComparator;
180 }
181 public int compare(KeyValueScanner left, KeyValueScanner right) {
182 int comparison = compare(left.peek(), right.peek());
183 if (comparison != 0) {
184 return comparison;
185 } else {
186 // Since both the keys are exactly the same, we break the tie in favor
187 // of the key which came latest.
188 long leftSequenceID = left.getSequenceID();
189 long rightSequenceID = right.getSequenceID();
190 if (leftSequenceID > rightSequenceID) {
191 return -1;
192 } else if (leftSequenceID < rightSequenceID) {
193 return 1;
194 } else {
195 return 0;
196 }
197 }
198 }
199 /**
200 * Compares two KeyValue
201 * @param left
202 * @param right
203 * @return less than 0 if left is smaller, 0 if equal etc..
204 */
205 public int compare(KeyValue left, KeyValue right) {
206 return this.kvComparator.compare(left, right);
207 }
208 /**
209 * @return KVComparator
210 */
211 public KVComparator getComparator() {
212 return this.kvComparator;
213 }
214 }
215
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(KeyValue)}) does not do multi-column
237 * Bloom filter and lazy-seek optimizations. To enable those, call
238 * {@link #requestSeek(KeyValue, 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(KeyValue 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(KeyValue)} function except
253 * that scanner.seek(seekKey) is changed to scanner.reseek(seekKey).
254 */
255 @Override
256 public boolean reseek(KeyValue 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(KeyValue 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, KeyValue 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;
294 while ((scanner = heap.poll()) != null) {
295 KeyValue topKey = scanner.peek();
296 if (comparator.getComparator().compare(seekKey, topKey) <= 0) {
297 // Top KeyValue is at-or-after Seek KeyValue. We only know that all
298 // scanners are at or after seekKey (because fake keys of
299 // scanners where a lazy-seek operation has been done are not greater
300 // than their real next keys) but we still need to enforce our
301 // invariant that the top scanner has done a real seek. This way
302 // StoreScanner and RegionScanner do not have to worry about fake keys.
303 heap.add(scanner);
304 current = pollRealKV();
305 return current != null;
306 }
307
308 boolean seekResult;
309 if (isLazy && heap.size() > 0) {
310 // If there is only one scanner left, we don't do lazy seek.
311 seekResult = scanner.requestSeek(seekKey, forward, useBloom);
312 } else {
313 seekResult = NonLazyKeyValueScanner.doRealSeek(
314 scanner, seekKey, forward);
315 }
316
317 if (!seekResult) {
318 scanner.close();
319 } else {
320 heap.add(scanner);
321 }
322 }
323
324 // Heap is returning empty, scanner is done
325 return false;
326 }
327
328 /**
329 * Fetches the top sub-scanner from the priority queue, ensuring that a real
330 * seek has been done on it. Works by fetching the top sub-scanner, and if it
331 * has not done a real seek, making it do so (which will modify its top KV),
332 * putting it back, and repeating this until success. Relies on the fact that
333 * on a lazy seek we set the current key of a StoreFileScanner to a KV that
334 * is not greater than the real next KV to be read from that file, so the
335 * scanner that bubbles up to the top of the heap will have global next KV in
336 * this scanner heap if (1) it has done a real seek and (2) its KV is the top
337 * among all top KVs (some of which are fake) in the scanner heap.
338 */
339 protected KeyValueScanner pollRealKV() throws IOException {
340 KeyValueScanner kvScanner = heap.poll();
341 if (kvScanner == null) {
342 return null;
343 }
344
345 while (kvScanner != null && !kvScanner.realSeekDone()) {
346 if (kvScanner.peek() != null) {
347 kvScanner.enforceSeek();
348 KeyValue curKV = kvScanner.peek();
349 if (curKV != null) {
350 KeyValueScanner nextEarliestScanner = heap.peek();
351 if (nextEarliestScanner == null) {
352 // The heap is empty. Return the only possible scanner.
353 return kvScanner;
354 }
355
356 // Compare the current scanner to the next scanner. We try to avoid
357 // putting the current one back into the heap if possible.
358 KeyValue nextKV = nextEarliestScanner.peek();
359 if (nextKV == null || comparator.compare(curKV, nextKV) < 0) {
360 // We already have the scanner with the earliest KV, so return it.
361 return kvScanner;
362 }
363
364 // Otherwise, put the scanner back into the heap and let it compete
365 // against all other scanners (both those that have done a "real
366 // seek" and a "lazy seek").
367 heap.add(kvScanner);
368 } else {
369 // Close the scanner because we did a real seek and found out there
370 // are no more KVs.
371 kvScanner.close();
372 }
373 } else {
374 // Close the scanner because it has already run out of KVs even before
375 // we had to do a real seek on it.
376 kvScanner.close();
377 }
378 kvScanner = heap.poll();
379 }
380
381 return kvScanner;
382 }
383
384 /**
385 * @return the current Heap
386 */
387 public PriorityQueue<KeyValueScanner> getHeap() {
388 return this.heap;
389 }
390
391 @Override
392 public long getSequenceID() {
393 return 0;
394 }
395
396 KeyValueScanner getCurrentForTesting() {
397 return current;
398 }
399 }