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