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.io.InterruptedIOException;
24  import java.util.ArrayList;
25  import java.util.List;
26  import java.util.NavigableSet;
27  import java.util.concurrent.CountDownLatch;
28  import java.util.concurrent.locks.ReentrantLock;
29  
30  import org.apache.commons.logging.Log;
31  import org.apache.commons.logging.LogFactory;
32  import org.apache.hadoop.hbase.Cell;
33  import org.apache.hadoop.hbase.CellUtil;
34  import org.apache.hadoop.hbase.DoNotRetryIOException;
35  import org.apache.hadoop.hbase.HConstants;
36  import org.apache.hadoop.hbase.KeyValue;
37  import org.apache.hadoop.hbase.KeyValue.KVComparator;
38  import org.apache.hadoop.hbase.KeyValueUtil;
39  import org.apache.hadoop.hbase.classification.InterfaceAudience;
40  import org.apache.hadoop.hbase.client.IsolationLevel;
41  import org.apache.hadoop.hbase.client.Scan;
42  import org.apache.hadoop.hbase.executor.ExecutorService;
43  import org.apache.hadoop.hbase.filter.Filter;
44  import org.apache.hadoop.hbase.regionserver.ScannerContext.LimitScope;
45  import org.apache.hadoop.hbase.regionserver.ScannerContext.NextState;
46  import org.apache.hadoop.hbase.regionserver.handler.ParallelSeekHandler;
47  import org.apache.hadoop.hbase.util.Bytes;
48  import org.apache.hadoop.hbase.util.EnvironmentEdgeManager;
49  
50  import com.google.common.annotations.VisibleForTesting;
51  import org.apache.hadoop.hbase.util.CollectionUtils;
52  
53  /**
54   * Scanner scans both the memstore and the Store. Coalesce KeyValue stream
55   * into List<KeyValue> for a single row.
56   */
57  @InterfaceAudience.Private
58  public class StoreScanner extends NonReversedNonLazyKeyValueScanner
59      implements KeyValueScanner, InternalScanner, ChangedReadersObserver {
60    private static final Log LOG = LogFactory.getLog(StoreScanner.class);
61    // In unit tests, the store could be null
62    protected final Store store;
63    protected ScanQueryMatcher matcher;
64    protected KeyValueHeap heap;
65    protected boolean cacheBlocks;
66  
67    protected long countPerRow = 0;
68    protected int storeLimit = -1;
69    protected int storeOffset = 0;
70  
71    // Used to indicate that the scanner has closed (see HBASE-1107)
72    // Doesnt need to be volatile because it's always accessed via synchronized methods
73    protected boolean closing = false;
74    protected final boolean get;
75    protected final boolean explicitColumnQuery;
76    protected final boolean useRowColBloom;
77    /**
78     * A flag that enables StoreFileScanner parallel-seeking
79     */
80    protected boolean parallelSeekEnabled = false;
81    protected ExecutorService executor;
82    protected final Scan scan;
83    protected final NavigableSet<byte[]> columns;
84    protected final long oldestUnexpiredTS;
85    protected final long now;
86    protected final int minVersions;
87    protected final long maxRowSize;
88    protected final long cellsPerHeartbeatCheck;
89  
90    /**
91     * If we close the memstore scanners before sending data to client, the chunk may be reclaimed
92     * by other updates and the data will be corrupt.
93     */
94    private final List<KeyValueScanner> scannersForDelayedClose = new ArrayList<>();
95    /**
96     * The number of KVs seen by the scanner. Includes explicitly skipped KVs, but not
97     * KVs skipped via seeking to next row/column. TODO: estimate them?
98     */
99    private long kvsScanned = 0;
100   private Cell prevCell = null;
101 
102   /** We don't ever expect to change this, the constant is just for clarity. */
103   static final boolean LAZY_SEEK_ENABLED_BY_DEFAULT = true;
104   public static final String STORESCANNER_PARALLEL_SEEK_ENABLE =
105       "hbase.storescanner.parallel.seek.enable";
106 
107   /** Used during unit testing to ensure that lazy seek does save seek ops */
108   protected static boolean lazySeekEnabledGlobally =
109       LAZY_SEEK_ENABLED_BY_DEFAULT;
110 
111   /**
112    * The number of cells scanned in between timeout checks. Specifying a larger value means that
113    * timeout checks will occur less frequently. Specifying a small value will lead to more frequent
114    * timeout checks.
115    */
116   public static final String HBASE_CELLS_SCANNED_PER_HEARTBEAT_CHECK =
117       "hbase.cells.scanned.per.heartbeat.check";
118 
119   /**
120    * Default value of {@link #HBASE_CELLS_SCANNED_PER_HEARTBEAT_CHECK}.
121    */
122   public static final long DEFAULT_HBASE_CELLS_SCANNED_PER_HEARTBEAT_CHECK = 10000;
123 
124   // if heap == null and lastTop != null, you need to reseek given the key below
125   protected Cell lastTop = null;
126 
127   // A flag whether use pread for scan
128   private boolean scanUsePread = false;
129   // Indicates whether there was flush during the course of the scan
130   private volatile boolean flushed = false;
131 
132   // generally we get one file from a flush
133   private final List<KeyValueScanner> flushedstoreFileScanners =
134       new ArrayList<KeyValueScanner>(1);
135   // generally we get one memstroe scanner from a flush
136   private final List<KeyValueScanner> memStoreScannersAfterFlush = new ArrayList<>(1);
137   // The current list of scanners
138   private final List<KeyValueScanner> currentScanners = new ArrayList<KeyValueScanner>();
139   // flush update lock
140   private ReentrantLock flushLock = new ReentrantLock();
141 
142   private final long readPt;
143   private boolean topChanged = false;
144   // used by the injection framework to test race between StoreScanner construction and compaction
145   enum StoreScannerCompactionRace {
146     BEFORE_SEEK,
147     AFTER_SEEK,
148     COMPACT_COMPLETE
149   }
150 
151   /** An internal constructor. */
152   protected StoreScanner(Store store, Scan scan, final ScanInfo scanInfo,
153       final NavigableSet<byte[]> columns, long readPt, boolean cacheBlocks) {
154     this.readPt = readPt;
155     this.store = store;
156     this.cacheBlocks = cacheBlocks;
157     get = scan.isGetScan();
158     int numCol = columns == null ? 0 : columns.size();
159     explicitColumnQuery = numCol > 0;
160     this.scan = scan;
161     this.columns = columns;
162     this.now = EnvironmentEdgeManager.currentTime();
163     this.oldestUnexpiredTS = now - scanInfo.getTtl();
164     this.minVersions = scanInfo.getMinVersions();
165 
166      // We look up row-column Bloom filters for multi-column queries as part of
167      // the seek operation. However, we also look the row-column Bloom filter
168      // for multi-row (non-"get") scans because this is not done in
169      // StoreFile.passesBloomFilter(Scan, SortedSet<byte[]>).
170      this.useRowColBloom = numCol > 1 || (!get && numCol == 1);
171 
172      this.maxRowSize = scanInfo.getTableMaxRowSize();
173      this.scanUsePread = scan.isSmall()? true: scanInfo.isUsePread();
174      this.cellsPerHeartbeatCheck = scanInfo.getCellsPerTimeoutCheck();
175      // Parallel seeking is on if the config allows and more there is more than one store file.
176      if (this.store != null && this.store.getStorefilesCount() > 1) {
177        RegionServerServices rsService = ((HStore)store).getHRegion().getRegionServerServices();
178        if (rsService != null && scanInfo.isParallelSeekEnabled()) {
179          this.parallelSeekEnabled = true;
180          this.executor = rsService.getExecutorService();
181        }
182      }
183   }
184 
185   protected void addCurrentScanners(List<? extends KeyValueScanner> scanners) {
186     this.currentScanners.addAll(scanners);
187   }
188   /**
189    * Opens a scanner across memstore, snapshot, and all StoreFiles. Assumes we
190    * are not in a compaction.
191    *
192    * @param store who we scan
193    * @param scan the spec
194    * @param columns which columns we are scanning
195    * @throws IOException
196    */
197   public StoreScanner(Store store, ScanInfo scanInfo, Scan scan, final NavigableSet<byte[]> columns,
198       long readPt)
199   throws IOException {
200     this(store, scan, scanInfo, columns, readPt, scan.getCacheBlocks());
201     if (columns != null && scan.isRaw()) {
202       throw new DoNotRetryIOException("Cannot specify any column for a raw scan");
203     }
204     matcher = new ScanQueryMatcher(scan, scanInfo, columns,
205         ScanType.USER_SCAN, Long.MAX_VALUE, HConstants.LATEST_TIMESTAMP,
206         oldestUnexpiredTS, now, store.getCoprocessorHost());
207 
208     this.store.addChangedReaderObserver(this);
209 
210     try {
211       // Pass columns to try to filter out unnecessary StoreFiles.
212       List<KeyValueScanner> scanners = getScannersNoCompaction();
213 
214       // Seek all scanners to the start of the Row (or if the exact matching row
215       // key does not exist, then to the start of the next matching Row).
216       // Always check bloom filter to optimize the top row seek for delete
217       // family marker.
218       seekScanners(scanners, matcher.getStartKey(), explicitColumnQuery && lazySeekEnabledGlobally,
219         parallelSeekEnabled);
220 
221       // set storeLimit
222       this.storeLimit = scan.getMaxResultsPerColumnFamily();
223 
224       // set rowOffset
225       this.storeOffset = scan.getRowOffsetPerColumnFamily();
226       addCurrentScanners(scanners);
227       // Combine all seeked scanners with a heap
228       resetKVHeap(scanners, store.getComparator());
229     } catch (IOException e) {
230       // remove us from the HStore#changedReaderObservers here or we'll have no chance to
231       // and might cause memory leak
232       this.store.deleteChangedReaderObserver(this);
233       throw e;
234     }
235   }
236 
237   /**
238    * Used for compactions.<p>
239    *
240    * Opens a scanner across specified StoreFiles.
241    * @param store who we scan
242    * @param scan the spec
243    * @param scanners ancillary scanners
244    * @param smallestReadPoint the readPoint that we should use for tracking
245    *          versions
246    */
247   public StoreScanner(Store store, ScanInfo scanInfo, Scan scan,
248       List<? extends KeyValueScanner> scanners, ScanType scanType,
249       long smallestReadPoint, long earliestPutTs) throws IOException {
250     this(store, scanInfo, scan, scanners, scanType, smallestReadPoint, earliestPutTs, null, null);
251   }
252 
253   /**
254    * Used for compactions that drop deletes from a limited range of rows.<p>
255    *
256    * Opens a scanner across specified StoreFiles.
257    * @param store who we scan
258    * @param scan the spec
259    * @param scanners ancillary scanners
260    * @param smallestReadPoint the readPoint that we should use for tracking versions
261    * @param dropDeletesFromRow The inclusive left bound of the range; can be EMPTY_START_ROW.
262    * @param dropDeletesToRow The exclusive right bound of the range; can be EMPTY_END_ROW.
263    */
264   public StoreScanner(Store store, ScanInfo scanInfo, Scan scan,
265       List<? extends KeyValueScanner> scanners, long smallestReadPoint, long earliestPutTs,
266       byte[] dropDeletesFromRow, byte[] dropDeletesToRow) throws IOException {
267     this(store, scanInfo, scan, scanners, ScanType.COMPACT_RETAIN_DELETES, smallestReadPoint,
268         earliestPutTs, dropDeletesFromRow, dropDeletesToRow);
269   }
270 
271   private StoreScanner(Store store, ScanInfo scanInfo, Scan scan,
272       List<? extends KeyValueScanner> scanners, ScanType scanType, long smallestReadPoint,
273       long earliestPutTs, byte[] dropDeletesFromRow, byte[] dropDeletesToRow) throws IOException {
274     this(store, scan, scanInfo, null,
275       ((HStore)store).getHRegion().getReadpoint(IsolationLevel.READ_COMMITTED), false);
276     if (dropDeletesFromRow == null) {
277       matcher = new ScanQueryMatcher(scan, scanInfo, null, scanType, smallestReadPoint,
278           earliestPutTs, oldestUnexpiredTS, now, store.getCoprocessorHost());
279     } else {
280       matcher = new ScanQueryMatcher(scan, scanInfo, null, smallestReadPoint, earliestPutTs,
281           oldestUnexpiredTS, now, dropDeletesFromRow, dropDeletesToRow, store.getCoprocessorHost());
282     }
283 
284     // Filter the list of scanners using Bloom filters, time range, TTL, etc.
285     scanners = selectScannersFrom(scanners);
286 
287     // Seek all scanners to the initial key
288     seekScanners(scanners, matcher.getStartKey(), false, parallelSeekEnabled);
289     addCurrentScanners(scanners);
290     // Combine all seeked scanners with a heap
291     resetKVHeap(scanners, store.getComparator());
292   }
293 
294   @VisibleForTesting
295   StoreScanner(final Scan scan, ScanInfo scanInfo,
296       ScanType scanType, final NavigableSet<byte[]> columns,
297       final List<KeyValueScanner> scanners) throws IOException {
298     this(scan, scanInfo, scanType, columns, scanners,
299         HConstants.LATEST_TIMESTAMP,
300         // 0 is passed as readpoint because the test bypasses Store
301         0);
302   }
303 
304   @VisibleForTesting
305   StoreScanner(final Scan scan, ScanInfo scanInfo,
306     ScanType scanType, final NavigableSet<byte[]> columns,
307     final List<KeyValueScanner> scanners, long earliestPutTs)
308         throws IOException {
309     this(scan, scanInfo, scanType, columns, scanners, earliestPutTs,
310       // 0 is passed as readpoint because the test bypasses Store
311       0);
312   }
313 
314   private StoreScanner(final Scan scan, ScanInfo scanInfo,
315       ScanType scanType, final NavigableSet<byte[]> columns,
316       final List<KeyValueScanner> scanners, long earliestPutTs, long readPt)
317   throws IOException {
318     this(null, scan, scanInfo, columns, readPt, scan.getCacheBlocks());
319     this.matcher = new ScanQueryMatcher(scan, scanInfo, columns, scanType,
320         Long.MAX_VALUE, earliestPutTs, oldestUnexpiredTS, now, null);
321 
322     // In unit tests, the store could be null
323     if (this.store != null) {
324       this.store.addChangedReaderObserver(this);
325     }
326     // Seek all scanners to the initial key
327     seekScanners(scanners, matcher.getStartKey(), false, parallelSeekEnabled);
328     addCurrentScanners(scanners);
329     resetKVHeap(scanners, scanInfo.getComparator());
330   }
331 
332   /**
333    * Get a filtered list of scanners. Assumes we are not in a compaction.
334    * @return list of scanners to seek
335    */
336   protected List<KeyValueScanner> getScannersNoCompaction() throws IOException {
337     final boolean isCompaction = false;
338     boolean usePread = get || scanUsePread;
339     return selectScannersFrom(store.getScanners(cacheBlocks, get, usePread,
340         isCompaction, matcher, scan.getStartRow(), scan.getStopRow(), this.readPt));
341   }
342 
343   /**
344    * Seek the specified scanners with the given key
345    * @param scanners
346    * @param seekKey
347    * @param isLazy true if using lazy seek
348    * @param isParallelSeek true if using parallel seek
349    * @throws IOException
350    */
351   protected void seekScanners(List<? extends KeyValueScanner> scanners,
352       Cell seekKey, boolean isLazy, boolean isParallelSeek)
353       throws IOException {
354     // Seek all scanners to the start of the Row (or if the exact matching row
355     // key does not exist, then to the start of the next matching Row).
356     // Always check bloom filter to optimize the top row seek for delete
357     // family marker.
358     if (isLazy) {
359       for (KeyValueScanner scanner : scanners) {
360         scanner.requestSeek(seekKey, false, true);
361       }
362     } else {
363       if (!isParallelSeek) {
364         long totalScannersSoughtBytes = 0;
365         for (KeyValueScanner scanner : scanners) {
366           if (totalScannersSoughtBytes >= maxRowSize) {
367             throw new RowTooBigException("Max row size allowed: " + maxRowSize
368               + ", but row is bigger than that");
369           }
370           scanner.seek(seekKey);
371           Cell c = scanner.peek();
372           if (c != null) {
373             totalScannersSoughtBytes += CellUtil.estimatedSerializedSizeOf(c);
374           }
375         }
376       } else {
377         parallelSeek(scanners, seekKey);
378       }
379     }
380   }
381 
382   protected void resetKVHeap(List<? extends KeyValueScanner> scanners,
383       KVComparator comparator) throws IOException {
384     // Combine all seeked scanners with a heap
385     heap = new KeyValueHeap(scanners, comparator);
386   }
387 
388   /**
389    * Filters the given list of scanners using Bloom filter, time range, and
390    * TTL.
391    */
392   protected List<KeyValueScanner> selectScannersFrom(
393       final List<? extends KeyValueScanner> allScanners) {
394     boolean memOnly;
395     boolean filesOnly;
396     if (scan instanceof InternalScan) {
397       InternalScan iscan = (InternalScan)scan;
398       memOnly = iscan.isCheckOnlyMemStore();
399       filesOnly = iscan.isCheckOnlyStoreFiles();
400     } else {
401       memOnly = false;
402       filesOnly = false;
403     }
404 
405     List<KeyValueScanner> scanners =
406         new ArrayList<KeyValueScanner>(allScanners.size());
407 
408     // We can only exclude store files based on TTL if minVersions is set to 0.
409     // Otherwise, we might have to return KVs that have technically expired.
410     long expiredTimestampCutoff = minVersions == 0 ? oldestUnexpiredTS: Long.MIN_VALUE;
411 
412     // include only those scan files which pass all filters
413     for (KeyValueScanner kvs : allScanners) {
414       boolean isFile = kvs.isFileScanner();
415       if ((!isFile && filesOnly) || (isFile && memOnly)) {
416         continue;
417       }
418 
419       if (kvs.shouldUseScanner(scan, store, expiredTimestampCutoff)) {
420         scanners.add(kvs);
421       } else {
422         kvs.close();
423       }
424     }
425     return scanners;
426   }
427 
428   @Override
429   public Cell peek() {
430     if (this.heap == null) {
431       return this.lastTop;
432     }
433     return this.heap.peek();
434   }
435 
436   @Override
437   public KeyValue next() {
438     // throw runtime exception perhaps?
439     throw new RuntimeException("Never call StoreScanner.next()");
440   }
441 
442   @Override
443   public void close() {
444     if (this.closing) {
445       return;
446     }
447     // Lets remove from observers as early as possible
448     // Under test, we dont have a this.store
449     if (this.store != null) {
450       this.store.deleteChangedReaderObserver(this);
451     }
452     // There is a race condition between close() and updateReaders(), during region flush. So,
453     // even though its just close, we will still acquire the flush lock, as a
454     // ConcurrentModificationException will abort the regionserver.
455     flushLock.lock();
456     try {
457       this.closing = true;
458       clearAndClose(scannersForDelayedClose);
459       clearAndClose(memStoreScannersAfterFlush);
460       // clear them at any case. In case scanner.next() was never called
461       // and there were some lease expiry we need to close all the scanners
462       // on the flushed files which are open
463       clearAndClose(flushedstoreFileScanners);
464     } finally {
465       flushLock.unlock();
466     }
467     if (this.heap != null)
468       this.heap.close();
469     this.heap = null; // CLOSED!
470     this.lastTop = null; // If both are null, we are closed.
471   }
472 
473   @Override
474   public boolean seek(Cell key) throws IOException {
475     boolean flushed = checkFlushed();
476     // reset matcher state, in case that underlying store changed
477     checkReseek(flushed);
478     return this.heap.seek(key);
479   }
480 
481   @Override
482   public boolean next(List<Cell> outResult) throws IOException {
483     return next(outResult, NoLimitScannerContext.getInstance());
484   }
485 
486   /**
487    * Get the next row of values from this Store.
488    * @param outResult
489    * @param scannerContext
490    * @return true if there are more rows, false if scanner is done
491    */
492   @Override
493   public boolean next(List<Cell> outResult, ScannerContext scannerContext) throws IOException {
494     if (scannerContext == null) {
495       throw new IllegalArgumentException("Scanner context cannot be null");
496     }
497     boolean flushed = checkFlushed();
498     if (checkReseek(flushed)) {
499       return scannerContext.setScannerState(NextState.MORE_VALUES).hasMoreValues();
500     }
501 
502     // if the heap was left null, then the scanners had previously run out anyways, close and
503     // return.
504     if (this.heap == null) {
505       close();
506       return scannerContext.setScannerState(NextState.NO_MORE_VALUES).hasMoreValues();
507     }
508 
509     Cell cell = this.heap.peek();
510     if (cell == null) {
511       close();
512       return scannerContext.setScannerState(NextState.NO_MORE_VALUES).hasMoreValues();
513     }
514 
515     // only call setRow if the row changes; avoids confusing the query matcher
516     // if scanning intra-row
517     byte[] row = cell.getRowArray();
518     int offset = cell.getRowOffset();
519     short length = cell.getRowLength();
520 
521     // If no limits exists in the scope LimitScope.Between_Cells then we are sure we are changing
522     // rows. Else it is possible we are still traversing the same row so we must perform the row
523     // comparison.
524     if (!scannerContext.hasAnyLimit(LimitScope.BETWEEN_CELLS) || matcher.row == null) {
525       this.countPerRow = 0;
526       matcher.setRow(row, offset, length);
527     }
528 
529     // Clear progress away unless invoker has indicated it should be kept.
530     if (!scannerContext.getKeepProgress()) scannerContext.clearProgress();
531 
532     // Only do a sanity-check if store and comparator are available.
533     KeyValue.KVComparator comparator =
534         store != null ? store.getComparator() : null;
535 
536     int count = 0;
537     long totalBytesRead = 0;
538 
539     LOOP: do {
540       // Update and check the time limit based on the configured value of cellsPerTimeoutCheck
541       if ((kvsScanned % cellsPerHeartbeatCheck == 0)) {
542         scannerContext.updateTimeProgress();
543         if (scannerContext.checkTimeLimit(LimitScope.BETWEEN_CELLS)) {
544           return scannerContext.setScannerState(NextState.TIME_LIMIT_REACHED).hasMoreValues();
545         }
546       }
547 
548       if (prevCell != cell) ++kvsScanned; // Do object compare - we set prevKV from the same heap.
549       checkScanOrder(prevCell, cell, comparator);
550       prevCell = cell;
551       topChanged = false;
552       ScanQueryMatcher.MatchCode qcode = matcher.match(cell);
553       switch (qcode) {
554         case INCLUDE:
555         case INCLUDE_AND_SEEK_NEXT_ROW:
556         case INCLUDE_AND_SEEK_NEXT_COL:
557 
558           Filter f = matcher.getFilter();
559           if (f != null) {
560             // TODO convert Scan Query Matcher to be Cell instead of KV based ?
561             cell = f.transformCell(cell);
562           }
563 
564           this.countPerRow++;
565           if (storeLimit > -1 &&
566               this.countPerRow > (storeLimit + storeOffset)) {
567             // do what SEEK_NEXT_ROW does.
568             if (!matcher.moreRowsMayExistAfter(cell)) {
569               return scannerContext.setScannerState(NextState.NO_MORE_VALUES).hasMoreValues();
570             }
571             // Setting the matcher.row = null, will mean that after the subsequent seekToNextRow()
572             // the heap.peek() will any way be in the next row. So the SQM.match(cell) need do
573             // another compareRow to say the current row is DONE
574             matcher.row = null;
575             seekToNextRow(cell);
576             break LOOP;
577           }
578 
579           // add to results only if we have skipped #storeOffset kvs
580           // also update metric accordingly
581           if (this.countPerRow > storeOffset) {
582             outResult.add(cell);
583 
584             // Update local tracking information
585             count++;
586             totalBytesRead += CellUtil.estimatedSerializedSizeOf(cell);
587 
588             // Update the progress of the scanner context
589             scannerContext.incrementSizeProgress(CellUtil.estimatedHeapSizeOfWithoutTags(cell));
590             scannerContext.incrementBatchProgress(1);
591 
592             if (totalBytesRead > maxRowSize) {
593               throw new RowTooBigException("Max row size allowed: " + maxRowSize
594                   + ", but the row is bigger than that.");
595             }
596           }
597 
598           if (qcode == ScanQueryMatcher.MatchCode.INCLUDE_AND_SEEK_NEXT_ROW) {
599             if (!matcher.moreRowsMayExistAfter(cell)) {
600               return scannerContext.setScannerState(NextState.NO_MORE_VALUES).hasMoreValues();
601             }
602             // Setting the matcher.row = null, will mean that after the subsequent seekToNextRow()
603             // the heap.peek() will any way be in the next row. So the SQM.match(cell) need do
604             // another compareRow to say the current row is DONE
605             matcher.row = null;
606             seekOrSkipToNextRow(cell);
607           } else if (qcode == ScanQueryMatcher.MatchCode.INCLUDE_AND_SEEK_NEXT_COL) {
608             seekOrSkipToNextColumn(cell);
609           } else {
610             this.heap.next();
611           }
612 
613           if (scannerContext.checkBatchLimit(LimitScope.BETWEEN_CELLS)) {
614             break LOOP;
615           }
616           if (scannerContext.checkSizeLimit(LimitScope.BETWEEN_CELLS)) {
617             break LOOP;
618           }
619           continue;
620 
621         case DONE:
622           // Optimization for Gets! If DONE, no more to get on this row, early exit!
623           if (this.scan.isGetScan()) {
624             // Then no more to this row... exit.
625             close();// Do all cleanup except heap.close()
626             return scannerContext.setScannerState(NextState.NO_MORE_VALUES).hasMoreValues();
627           }
628           // We are sure that this row is done and we are in the next row.
629           // So subsequent StoresScanner.next() call need not do another compare
630           // and set the matcher.row
631           matcher.row = null;
632           return scannerContext.setScannerState(NextState.MORE_VALUES).hasMoreValues();
633 
634         case DONE_SCAN:
635           close();
636           return scannerContext.setScannerState(NextState.NO_MORE_VALUES).hasMoreValues();
637 
638         case SEEK_NEXT_ROW:
639           // This is just a relatively simple end of scan fix, to short-cut end
640           // us if there is an endKey in the scan.
641           if (!matcher.moreRowsMayExistAfter(cell)) {
642             return scannerContext.setScannerState(NextState.NO_MORE_VALUES).hasMoreValues();
643           }
644           // Setting the matcher.row = null, will mean that after the subsequent seekToNextRow()
645           // the heap.peek() will any way be in the next row. So the SQM.match(cell) need do
646           // another compareRow to say the current row is DONE
647           matcher.row = null;
648           seekOrSkipToNextRow(cell);
649           NextState stateAfterSeekNextRow = needToReturn(outResult);
650           if (stateAfterSeekNextRow != null) {
651             return scannerContext.setScannerState(stateAfterSeekNextRow).hasMoreValues();
652           }
653           break;
654 
655         case SEEK_NEXT_COL:
656           seekOrSkipToNextColumn(cell);
657           NextState stateAfterSeekNextColumn = needToReturn(outResult);
658           if (stateAfterSeekNextColumn != null) {
659             return scannerContext.setScannerState(stateAfterSeekNextColumn).hasMoreValues();
660           }
661           break;
662 
663         case SKIP:
664           this.heap.next();
665           break;
666 
667         case SEEK_NEXT_USING_HINT:
668           // TODO convert resee to Cell?
669           Cell nextKV = matcher.getNextKeyHint(cell);
670           if (nextKV != null) {
671             seekAsDirection(nextKV);
672             NextState stateAfterSeekByHint = needToReturn(outResult);
673             if (stateAfterSeekByHint != null) {
674               return scannerContext.setScannerState(stateAfterSeekByHint).hasMoreValues();
675             }
676           } else {
677             heap.next();
678           }
679           break;
680 
681         default:
682           throw new RuntimeException("UNEXPECTED");
683       }
684     } while((cell = this.heap.peek()) != null);
685 
686     if (count > 0) {
687       return scannerContext.setScannerState(NextState.MORE_VALUES).hasMoreValues();
688     }
689 
690     // No more keys
691     close();
692     return scannerContext.setScannerState(NextState.NO_MORE_VALUES).hasMoreValues();
693   }
694 
695   /**
696    * If the top cell won't be flushed into disk, the new top cell may be
697    * changed after #reopenAfterFlush. Because the older top cell only exist
698    * in the memstore scanner but the memstore scanner is replaced by hfile
699    * scanner after #reopenAfterFlush. If the row of top cell is changed,
700    * we should return the current cells. Otherwise, we may return
701    * the cells across different rows.
702    * @param outResult the cells which are visible for user scan
703    * @return null is the top cell doesn't change. Otherwise, the NextState
704    *         to return
705    */
706   private NextState needToReturn(List<Cell> outResult) {
707     if (!outResult.isEmpty() && topChanged) {
708       return heap.peek() == null ? NextState.NO_MORE_VALUES : NextState.MORE_VALUES;
709     }
710     return null;
711   }
712 
713   @Override
714   public long getReadPoint() {
715     return readPt;
716   }
717 
718   private static void clearAndClose(List<KeyValueScanner> scanners) {
719     for (KeyValueScanner s : scanners) {
720       s.close();
721     }
722     scanners.clear();
723   }
724 
725   // Implementation of ChangedReadersObserver
726   @Override
727   public void updateReaders(List<StoreFile> sfs, List<KeyValueScanner> memStoreScanners) throws IOException {
728     if (CollectionUtils.isEmpty(sfs) && CollectionUtils.isEmpty(memStoreScanners)) {
729       return;
730     }
731     flushLock.lock();
732     try {
733       if (this.closing) {
734         // Lets close scanners created by caller, since close() won't notice this.
735         // memStoreScanners is immutable, so lets create a new list.
736         if (!CollectionUtils.isEmpty(memStoreScanners)) {
737           clearAndClose(new ArrayList<>(memStoreScanners));
738         }
739         return;
740       }
741       flushed = true;
742       final boolean isCompaction = false;
743       boolean usePread = get || scanUsePread;
744       // SEE HBASE-19468 where the flushed files are getting compacted even before a scanner
745       // calls next(). So its better we create scanners here rather than next() call. Ensure
746       // these scanners are properly closed() whether or not the scan is completed successfully
747       // Eagerly creating scanners so that we have the ref counting ticking on the newly created
748       // store files. In case of stream scanners this eager creation does not induce performance
749       // penalty because in scans (that uses stream scanners) the next() call is bound to happen.
750       List<KeyValueScanner> scanners = store.getScanners(sfs, cacheBlocks, get, usePread,
751         isCompaction, matcher, scan.getStartRow(), scan.getStopRow(), this.readPt, false);
752       flushedstoreFileScanners.addAll(scanners);
753       if (!CollectionUtils.isEmpty(memStoreScanners)) {
754         clearAndClose(memStoreScannersAfterFlush);
755         memStoreScannersAfterFlush.addAll(memStoreScanners);
756       }
757     } finally {
758       flushLock.unlock();
759     }
760   }
761 
762   // Implementation of ChangedReadersObserver
763   protected void nullifyCurrentHeap() throws IOException {
764     if (this.closing) return;
765 
766     // All public synchronized API calls will call 'checkReseek' which will cause
767     // the scanner stack to reseek if this.heap==null && this.lastTop != null.
768     // But if two calls to updateReaders() happen without a 'next' or 'peek' then we
769     // will end up calling this.peek() which would cause a reseek in the middle of a updateReaders
770     // which is NOT what we want, not to mention could cause an NPE. So we early out here.
771     if (this.heap == null) return;
772 
773     // this could be null.
774     this.lastTop = this.heap.peek();
775 
776     //DebugPrint.println("SS updateReaders, topKey = " + lastTop);
777 
778     // close scanners to old obsolete Store files
779     this.heap.close(); // bubble thru and close all scanners.
780     this.heap = null; // the re-seeks could be slow (access HDFS) free up memory ASAP
781 
782     // Let the next() call handle re-creating and seeking
783   }
784 
785   private void seekOrSkipToNextRow(Cell cell) throws IOException {
786     // If it is a Get Scan, then we know that we are done with this row; there are no more
787     // rows beyond the current one: don't try to optimize.
788     if (!get) {
789       if (trySkipToNextRow(cell)) {
790         return;
791       }
792     }
793     seekToNextRow(cell);
794   }
795 
796   private void seekOrSkipToNextColumn(Cell cell) throws IOException {
797     if (!trySkipToNextColumn(cell)) {
798       seekAsDirection(matcher.getKeyForNextColumn(cell));
799     }
800   }
801 
802   /**
803    * See if we should actually SEEK or rather just SKIP to the next Cell (see HBASE-13109).
804    * ScanQueryMatcher may issue SEEK hints, such as seek to next column, next row, or seek to an
805    * arbitrary seek key. This method decides whether a seek is the most efficient _actual_ way to
806    * get us to the requested cell (SEEKs are more expensive than SKIP, SKIP, SKIP inside the
807    * current, loaded block). It does this by looking at the next indexed key of the current HFile.
808    * This key is then compared with the _SEEK_ key, where a SEEK key is an artificial 'last possible
809    * key on the row' (only in here, we avoid actually creating a SEEK key; in the compare we work
810    * with the current Cell but compare as though it were a seek key; see down in
811    * matcher.compareKeyForNextRow, etc). If the compare gets us onto the next block we *_SEEK,
812    * otherwise we just SKIP to the next requested cell.
813    * <p>
814    * Other notes:
815    * <ul>
816    * <li>Rows can straddle block boundaries</li>
817    * <li>Versions of columns can straddle block boundaries (i.e. column C1 at T1 might be in a
818    * different block than column C1 at T2)</li>
819    * <li>We want to SKIP if the chance is high that we'll find the desired Cell after a few
820    * SKIPs...</li>
821    * <li>We want to SEEK when the chance is high that we'll be able to seek past many Cells,
822    * especially if we know we need to go to the next block.</li>
823    * </ul>
824    * <p>
825    * A good proxy (best effort) to determine whether SKIP is better than SEEK is whether we'll
826    * likely end up seeking to the next block (or past the next block) to get our next column.
827    * Example:
828    *
829    * <pre>
830    * |    BLOCK 1              |     BLOCK 2                   |
831    * |  r1/c1, r1/c2, r1/c3    |    r1/c4, r1/c5, r2/c1        |
832    *                                   ^         ^
833    *                                   |         |
834    *                           Next Index Key   SEEK_NEXT_ROW (before r2/c1)
835    *
836    *
837    * |    BLOCK 1                       |     BLOCK 2                      |
838    * |  r1/c1/t5, r1/c1/t4, r1/c1/t3    |    r1/c1/t2, r1/c1/T1, r1/c2/T3  |
839    *                                            ^              ^
840    *                                            |              |
841    *                                    Next Index Key        SEEK_NEXT_COL
842    * </pre>
843    *
844    * Now imagine we want columns c1 and c3 (see first diagram above), the 'Next Index Key' of r1/c4
845    * is > r1/c3 so we should seek to get to the c1 on the next row, r2. In second case, say we only
846    * want one version of c1, after we have it, a SEEK_COL will be issued to get to c2. Looking at
847    * the 'Next Index Key', it would land us in the next block, so we should SEEK. In other scenarios
848    * where the SEEK will not land us in the next block, it is very likely better to issues a series
849    * of SKIPs.
850    * @param cell current cell
851    * @return true means skip to next row, false means not
852    */
853   @VisibleForTesting
854   protected boolean trySkipToNextRow(Cell cell) throws IOException {
855     Cell nextCell = null;
856     // used to guard against a changed next indexed key by doing a identity comparison
857     // when the identity changes we need to compare the bytes again
858     Cell previousIndexedKey = null;
859     do {
860       Cell nextIndexedKey = getNextIndexedKey();
861       if (nextIndexedKey != null && nextIndexedKey != KeyValueScanner.NO_NEXT_INDEXED_KEY
862           && (nextIndexedKey == previousIndexedKey
863               || matcher.compareKeyForNextRow(nextIndexedKey, cell) >= 0)) {
864         this.heap.next();
865         ++kvsScanned;
866         previousIndexedKey = nextIndexedKey;
867       } else {
868         return false;
869       }
870       nextCell = this.heap.peek();
871     } while (nextCell != null && CellUtil.matchingRow(cell, nextCell));
872     return true;
873   }
874 
875   /**
876    * See {@link org.apache.hadoop.hbase.regionserver.StoreScanner#trySkipToNextRow(Cell)}
877    * @param cell current cell
878    * @return true means skip to next column, false means not
879    */
880   @VisibleForTesting
881   protected boolean trySkipToNextColumn(Cell cell) throws IOException {
882     Cell nextCell = null;
883     // used to guard against a changed next indexed key by doing a identity comparison
884     // when the identity changes we need to compare the bytes again
885     Cell previousIndexedKey = null;
886     do {
887       Cell nextIndexedKey = getNextIndexedKey();
888       if (nextIndexedKey != null && nextIndexedKey != KeyValueScanner.NO_NEXT_INDEXED_KEY
889           && (nextIndexedKey == previousIndexedKey
890               || matcher.compareKeyForNextColumn(nextIndexedKey, cell) >= 0)) {
891         this.heap.next();
892         ++kvsScanned;
893         previousIndexedKey = nextIndexedKey;
894       } else {
895         return false;
896       }
897       nextCell = this.heap.peek();
898     } while (nextCell != null && CellUtil.matchingRow(cell, nextCell)
899         && CellUtil.matchingColumn(cell, nextCell));
900     // We need this check because it may happen that the new scanner that we get
901     // during heap.next() is requiring reseek due of fake KV previously generated for
902     // ROWCOL bloom filter optimization. See HBASE-19863 for more details
903     if (nextCell != null && matcher.compareKeyForNextColumn(nextCell, cell) < 0) {
904       return false;
905     }
906     return true;
907   }
908 
909   /**
910    * @param flushed indicates if there was a flush
911    * @return true if top of heap has changed (and KeyValueHeap has to try the
912    *         next KV)
913    * @throws IOException
914    */
915   protected boolean checkReseek(boolean flushed) throws IOException {
916     if (flushed && this.lastTop != null) {
917       resetScannerStack(this.lastTop);
918       if (this.heap.peek() == null
919           || store.getComparator().compareRows(this.lastTop, this.heap.peek()) != 0) {
920         LOG.info("Storescanner.peek() is changed where before = "
921             + this.lastTop.toString() + ",and after = " + this.heap.peek());
922         this.lastTop = null;
923         topChanged = true;
924         return true;
925       }
926       this.lastTop = null; // gone!
927     }
928     // else dont need to reseek
929     topChanged = false;
930     return false;
931   }
932 
933   protected void resetScannerStack(Cell lastTopKey) throws IOException {
934     /* When we have the scan object, should we not pass it to getScanners()
935      * to get a limited set of scanners? We did so in the constructor and we
936      * could have done it now by storing the scan object from the constructor
937      */
938 
939     final boolean isCompaction = false;
940     boolean usePread = get || scanUsePread;
941     List<KeyValueScanner> scanners = null;
942     flushLock.lock();
943     try {
944       List<KeyValueScanner> allScanners =
945           new ArrayList<>(flushedstoreFileScanners.size() + memStoreScannersAfterFlush.size());
946       allScanners.addAll(flushedstoreFileScanners);
947       allScanners.addAll(memStoreScannersAfterFlush);
948       scanners = selectScannersFrom(allScanners);
949       // Clear the current set of flushed store files so that they don't get added again
950       flushedstoreFileScanners.clear();
951       memStoreScannersAfterFlush.clear();
952     } finally {
953       flushLock.unlock();
954     }
955 
956     // Seek the new scanners to the last key
957     seekScanners(scanners, lastTopKey, false, parallelSeekEnabled);
958     // remove the older memstore scanner
959     for (int i = 0; i < currentScanners.size(); i++) {
960       if (!currentScanners.get(i).isFileScanner()) {
961         scannersForDelayedClose.add(currentScanners.remove(i));
962         break;
963       }
964     }
965     // add the newly created scanners on the flushed files and the current active memstore scanner
966     addCurrentScanners(scanners);
967     // Combine all seeked scanners with a heap
968     resetKVHeap(this.currentScanners, store.getComparator());
969     // Reset the state of the Query Matcher and set to top row.
970     // Only reset and call setRow if the row changes; avoids confusing the
971     // query matcher if scanning intra-row.
972     Cell kv = heap.peek();
973     if (kv == null) {
974       kv = lastTopKey;
975     }
976     byte[] row = kv.getRowArray();
977     int offset = kv.getRowOffset();
978     short length = kv.getRowLength();
979     if ((matcher.row == null) || !Bytes.equals(row, offset, length, matcher.row,
980         matcher.rowOffset, matcher.rowLength)) {
981       this.countPerRow = 0;
982       matcher.reset();
983       matcher.setRow(row, offset, length);
984     }
985   }
986 
987   /**
988    * Check whether scan as expected order
989    * @param prevKV
990    * @param kv
991    * @param comparator
992    * @throws IOException
993    */
994   protected void checkScanOrder(Cell prevKV, Cell kv,
995       KeyValue.KVComparator comparator) throws IOException {
996     // Check that the heap gives us KVs in an increasing order.
997     assert prevKV == null || comparator == null
998         || comparator.compare(prevKV, kv) <= 0 : "Key " + prevKV
999         + " followed by a " + "smaller key " + kv + " in cf " + store;
1000   }
1001 
1002   protected boolean seekToNextRow(Cell kv) throws IOException {
1003     return reseek(KeyValueUtil.createLastOnRow(kv));
1004   }
1005 
1006   /**
1007    * Do a reseek in a normal StoreScanner(scan forward)
1008    * @param kv
1009    * @return true if scanner has values left, false if end of scanner
1010    * @throws IOException
1011    */
1012   protected boolean seekAsDirection(Cell kv)
1013       throws IOException {
1014     return reseek(kv);
1015   }
1016 
1017   @Override
1018   public boolean reseek(Cell kv) throws IOException {
1019     boolean flushed = checkFlushed();
1020     // Heap will not be null, if this is called from next() which.
1021     // If called from RegionScanner.reseek(...) make sure the scanner
1022     // stack is reset if needed.
1023     checkReseek(flushed);
1024     if (explicitColumnQuery && lazySeekEnabledGlobally) {
1025       return heap.requestSeek(kv, true, useRowColBloom);
1026     }
1027     return heap.reseek(kv);
1028   }
1029 
1030   protected boolean checkFlushed() {
1031     // check the var without any lock. Suppose even if we see the old
1032     // value here still it is ok to continue because we will not be resetting
1033     // the heap but will continue with the referenced memstore's snapshot. For compactions
1034     // any way we don't need the updateReaders at all to happen as we still continue with
1035     // the older files
1036     if (flushed) {
1037       // If there is a flush and the current scan is notified on the flush ensure that the
1038       // scan's heap gets reset and we do a seek on the newly flushed file.
1039       if(!this.closing) {
1040         this.lastTop = this.peek();
1041       } else {
1042         return false;
1043       }
1044       // reset the flag
1045       flushed = false;
1046       return true;
1047     }
1048     return false;
1049   }
1050 
1051   @Override
1052   public long getSequenceID() {
1053     return 0;
1054   }
1055 
1056   /**
1057    * Seek storefiles in parallel to optimize IO latency as much as possible
1058    * @param scanners the list {@link KeyValueScanner}s to be read from
1059    * @param kv the KeyValue on which the operation is being requested
1060    * @throws IOException
1061    */
1062   private void parallelSeek(final List<? extends KeyValueScanner>
1063       scanners, final Cell kv) throws IOException {
1064     if (scanners.isEmpty()) return;
1065     int storeFileScannerCount = scanners.size();
1066     CountDownLatch latch = new CountDownLatch(storeFileScannerCount);
1067     List<ParallelSeekHandler> handlers =
1068         new ArrayList<ParallelSeekHandler>(storeFileScannerCount);
1069     for (KeyValueScanner scanner : scanners) {
1070       if (scanner instanceof StoreFileScanner) {
1071         ParallelSeekHandler seekHandler = new ParallelSeekHandler(scanner, kv,
1072           this.readPt, latch);
1073         executor.submit(seekHandler);
1074         handlers.add(seekHandler);
1075       } else {
1076         scanner.seek(kv);
1077         latch.countDown();
1078       }
1079     }
1080 
1081     try {
1082       latch.await();
1083     } catch (InterruptedException ie) {
1084       throw (InterruptedIOException)new InterruptedIOException().initCause(ie);
1085     }
1086 
1087     for (ParallelSeekHandler handler : handlers) {
1088       if (handler.getErr() != null) {
1089         throw new IOException(handler.getErr());
1090       }
1091     }
1092   }
1093 
1094   /**
1095    * Used in testing.
1096    * @return all scanners in no particular order
1097    */
1098   List<KeyValueScanner> getAllScannersForTesting() {
1099     List<KeyValueScanner> allScanners = new ArrayList<KeyValueScanner>();
1100     KeyValueScanner current = heap.getCurrentForTesting();
1101     if (current != null)
1102       allScanners.add(current);
1103     for (KeyValueScanner scanner : heap.getHeap())
1104       allScanners.add(scanner);
1105     return allScanners;
1106   }
1107 
1108   static void enableLazySeekGlobally(boolean enable) {
1109     lazySeekEnabledGlobally = enable;
1110   }
1111 
1112   /**
1113    * @return The estimated number of KVs seen by this scanner (includes some skipped KVs).
1114    */
1115   public long getEstimatedNumberOfKvsScanned() {
1116     return this.kvsScanned;
1117   }
1118 
1119   @Override
1120   public Cell getNextIndexedKey() {
1121     return this.heap.getNextIndexedKey();
1122   }
1123 }