001/** 002 * 003 * Licensed to the Apache Software Foundation (ASF) under one 004 * or more contributor license agreements. See the NOTICE file 005 * distributed with this work for additional information 006 * regarding copyright ownership. The ASF licenses this file 007 * to you under the Apache License, Version 2.0 (the 008 * "License"); you may not use this file except in compliance 009 * with the License. You may obtain a copy of the License at 010 * 011 * http://www.apache.org/licenses/LICENSE-2.0 012 * 013 * Unless required by applicable law or agreed to in writing, software 014 * distributed under the License is distributed on an "AS IS" BASIS, 015 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 016 * See the License for the specific language governing permissions and 017 * limitations under the License. 018 */ 019package org.apache.hadoop.hbase.regionserver; 020 021import java.io.IOException; 022import java.io.InterruptedIOException; 023import java.util.ArrayList; 024import java.util.List; 025import java.util.NavigableSet; 026import java.util.OptionalInt; 027import java.util.concurrent.CountDownLatch; 028import java.util.concurrent.locks.ReentrantLock; 029 030import org.apache.hadoop.hbase.Cell; 031import org.apache.hadoop.hbase.CellComparator; 032import org.apache.hadoop.hbase.CellUtil; 033import org.apache.hadoop.hbase.DoNotRetryIOException; 034import org.apache.hadoop.hbase.HConstants; 035import org.apache.hadoop.hbase.PrivateCellUtil; 036import org.apache.hadoop.hbase.KeyValue; 037import org.apache.hadoop.hbase.KeyValueUtil; 038import org.apache.hadoop.hbase.client.IsolationLevel; 039import org.apache.hadoop.hbase.client.Scan; 040import org.apache.hadoop.hbase.executor.ExecutorService; 041import org.apache.hadoop.hbase.filter.Filter; 042import org.apache.hadoop.hbase.regionserver.ScannerContext.LimitScope; 043import org.apache.hadoop.hbase.regionserver.ScannerContext.NextState; 044import org.apache.hadoop.hbase.regionserver.handler.ParallelSeekHandler; 045import org.apache.hadoop.hbase.regionserver.querymatcher.CompactionScanQueryMatcher; 046import org.apache.hadoop.hbase.regionserver.querymatcher.ScanQueryMatcher; 047import org.apache.hadoop.hbase.regionserver.querymatcher.UserScanQueryMatcher; 048import org.apache.hadoop.hbase.util.CollectionUtils; 049import org.apache.hadoop.hbase.util.EnvironmentEdgeManager; 050import org.apache.yetus.audience.InterfaceAudience; 051import org.slf4j.Logger; 052import org.slf4j.LoggerFactory; 053import org.apache.hbase.thirdparty.com.google.common.annotations.VisibleForTesting; 054import org.apache.hbase.thirdparty.com.google.common.base.Preconditions; 055 056/** 057 * Scanner scans both the memstore and the Store. Coalesce KeyValue stream into List<KeyValue> 058 * for a single row. 059 * <p> 060 * The implementation is not thread safe. So there will be no race between next and close. The only 061 * exception is updateReaders, it will be called in the memstore flush thread to indicate that there 062 * is a flush. 063 */ 064@InterfaceAudience.Private 065public class StoreScanner extends NonReversedNonLazyKeyValueScanner 066 implements KeyValueScanner, InternalScanner, ChangedReadersObserver { 067 private static final Logger LOG = LoggerFactory.getLogger(StoreScanner.class); 068 // In unit tests, the store could be null 069 protected final HStore store; 070 private final CellComparator comparator; 071 private ScanQueryMatcher matcher; 072 protected KeyValueHeap heap; 073 private boolean cacheBlocks; 074 075 private long countPerRow = 0; 076 private int storeLimit = -1; 077 private int storeOffset = 0; 078 079 // Used to indicate that the scanner has closed (see HBASE-1107) 080 // Do not need to be volatile because it's always accessed via synchronized methods 081 private boolean closing = false; 082 private final boolean get; 083 private final boolean explicitColumnQuery; 084 private final boolean useRowColBloom; 085 /** 086 * A flag that enables StoreFileScanner parallel-seeking 087 */ 088 private boolean parallelSeekEnabled = false; 089 private ExecutorService executor; 090 private final Scan scan; 091 private final long oldestUnexpiredTS; 092 private final long now; 093 private final int minVersions; 094 private final long maxRowSize; 095 private final long cellsPerHeartbeatCheck; 096 097 // 1) Collects all the KVHeap that are eagerly getting closed during the 098 // course of a scan 099 // 2) Collects the unused memstore scanners. If we close the memstore scanners 100 // before sending data to client, the chunk may be reclaimed by other 101 // updates and the data will be corrupt. 102 private final List<KeyValueScanner> scannersForDelayedClose = new ArrayList<>(); 103 104 /** 105 * The number of KVs seen by the scanner. Includes explicitly skipped KVs, but not 106 * KVs skipped via seeking to next row/column. TODO: estimate them? 107 */ 108 private long kvsScanned = 0; 109 private Cell prevCell = null; 110 111 private final long preadMaxBytes; 112 private long bytesRead; 113 114 /** We don't ever expect to change this, the constant is just for clarity. */ 115 static final boolean LAZY_SEEK_ENABLED_BY_DEFAULT = true; 116 public static final String STORESCANNER_PARALLEL_SEEK_ENABLE = 117 "hbase.storescanner.parallel.seek.enable"; 118 119 /** Used during unit testing to ensure that lazy seek does save seek ops */ 120 private static boolean lazySeekEnabledGlobally = LAZY_SEEK_ENABLED_BY_DEFAULT; 121 122 /** 123 * The number of cells scanned in between timeout checks. Specifying a larger value means that 124 * timeout checks will occur less frequently. Specifying a small value will lead to more frequent 125 * timeout checks. 126 */ 127 public static final String HBASE_CELLS_SCANNED_PER_HEARTBEAT_CHECK = 128 "hbase.cells.scanned.per.heartbeat.check"; 129 130 /** 131 * Default value of {@link #HBASE_CELLS_SCANNED_PER_HEARTBEAT_CHECK}. 132 */ 133 public static final long DEFAULT_HBASE_CELLS_SCANNED_PER_HEARTBEAT_CHECK = 10000; 134 135 /** 136 * If the read type if Scan.ReadType.DEFAULT, we will start with pread, and if the kvs we scanned 137 * reaches this limit, we will reopen the scanner with stream. The default value is 4 times of 138 * block size for this store. 139 */ 140 public static final String STORESCANNER_PREAD_MAX_BYTES = "hbase.storescanner.pread.max.bytes"; 141 142 private final Scan.ReadType readType; 143 144 // A flag whether use pread for scan 145 // it maybe changed if we use Scan.ReadType.DEFAULT and we have read lots of data. 146 private boolean scanUsePread; 147 // Indicates whether there was flush during the course of the scan 148 private volatile boolean flushed = false; 149 // generally we get one file from a flush 150 private final List<KeyValueScanner> flushedstoreFileScanners = new ArrayList<>(1); 151 // Since CompactingMemstore is now default, we get three memstore scanners from a flush 152 private final List<KeyValueScanner> memStoreScannersAfterFlush = new ArrayList<>(3); 153 // The current list of scanners 154 @VisibleForTesting 155 final List<KeyValueScanner> currentScanners = new ArrayList<>(); 156 // flush update lock 157 private final ReentrantLock flushLock = new ReentrantLock(); 158 159 protected final long readPt; 160 private boolean topChanged = false; 161 162 /** An internal constructor. */ 163 private StoreScanner(HStore store, Scan scan, ScanInfo scanInfo, 164 int numColumns, long readPt, boolean cacheBlocks, ScanType scanType) { 165 this.readPt = readPt; 166 this.store = store; 167 this.cacheBlocks = cacheBlocks; 168 this.comparator = Preconditions.checkNotNull(scanInfo.getComparator()); 169 get = scan.isGetScan(); 170 explicitColumnQuery = numColumns > 0; 171 this.scan = scan; 172 this.now = EnvironmentEdgeManager.currentTime(); 173 this.oldestUnexpiredTS = scan.isRaw() ? 0L : now - scanInfo.getTtl(); 174 this.minVersions = scanInfo.getMinVersions(); 175 176 // We look up row-column Bloom filters for multi-column queries as part of 177 // the seek operation. However, we also look the row-column Bloom filter 178 // for multi-row (non-"get") scans because this is not done in 179 // StoreFile.passesBloomFilter(Scan, SortedSet<byte[]>). 180 this.useRowColBloom = numColumns > 1 || (!get && numColumns == 1); 181 this.maxRowSize = scanInfo.getTableMaxRowSize(); 182 if (get) { 183 this.readType = Scan.ReadType.PREAD; 184 this.scanUsePread = true; 185 } else if(scanType != ScanType.USER_SCAN) { 186 // For compaction scanners never use Pread as already we have stream based scanners on the 187 // store files to be compacted 188 this.readType = Scan.ReadType.STREAM; 189 this.scanUsePread = false; 190 } else { 191 if (scan.getReadType() == Scan.ReadType.DEFAULT) { 192 this.readType = scanInfo.isUsePread() ? Scan.ReadType.PREAD : Scan.ReadType.DEFAULT; 193 } else { 194 this.readType = scan.getReadType(); 195 } 196 // Always start with pread unless user specific stream. Will change to stream later if 197 // readType is default if the scan keeps running for a long time. 198 this.scanUsePread = this.readType != Scan.ReadType.STREAM; 199 } 200 this.preadMaxBytes = scanInfo.getPreadMaxBytes(); 201 this.cellsPerHeartbeatCheck = scanInfo.getCellsPerTimeoutCheck(); 202 // Parallel seeking is on if the config allows and more there is more than one store file. 203 if (store != null && store.getStorefilesCount() > 1) { 204 RegionServerServices rsService = store.getHRegion().getRegionServerServices(); 205 if (rsService != null && scanInfo.isParallelSeekEnabled()) { 206 this.parallelSeekEnabled = true; 207 this.executor = rsService.getExecutorService(); 208 } 209 } 210 } 211 212 private void addCurrentScanners(List<? extends KeyValueScanner> scanners) { 213 this.currentScanners.addAll(scanners); 214 } 215 216 /** 217 * Opens a scanner across memstore, snapshot, and all StoreFiles. Assumes we 218 * are not in a compaction. 219 * 220 * @param store who we scan 221 * @param scan the spec 222 * @param columns which columns we are scanning 223 * @throws IOException 224 */ 225 public StoreScanner(HStore store, ScanInfo scanInfo, Scan scan, NavigableSet<byte[]> columns, 226 long readPt) throws IOException { 227 this(store, scan, scanInfo, columns != null ? columns.size() : 0, readPt, 228 scan.getCacheBlocks(), ScanType.USER_SCAN); 229 if (columns != null && scan.isRaw()) { 230 throw new DoNotRetryIOException("Cannot specify any column for a raw scan"); 231 } 232 matcher = UserScanQueryMatcher.create(scan, scanInfo, columns, oldestUnexpiredTS, now, 233 store.getCoprocessorHost()); 234 235 store.addChangedReaderObserver(this); 236 237 try { 238 // Pass columns to try to filter out unnecessary StoreFiles. 239 List<KeyValueScanner> scanners = selectScannersFrom(store, 240 store.getScanners(cacheBlocks, scanUsePread, false, matcher, scan.getStartRow(), 241 scan.includeStartRow(), scan.getStopRow(), scan.includeStopRow(), this.readPt)); 242 243 // Seek all scanners to the start of the Row (or if the exact matching row 244 // key does not exist, then to the start of the next matching Row). 245 // Always check bloom filter to optimize the top row seek for delete 246 // family marker. 247 seekScanners(scanners, matcher.getStartKey(), explicitColumnQuery && lazySeekEnabledGlobally, 248 parallelSeekEnabled); 249 250 // set storeLimit 251 this.storeLimit = scan.getMaxResultsPerColumnFamily(); 252 253 // set rowOffset 254 this.storeOffset = scan.getRowOffsetPerColumnFamily(); 255 addCurrentScanners(scanners); 256 // Combine all seeked scanners with a heap 257 resetKVHeap(scanners, comparator); 258 } catch (IOException e) { 259 // remove us from the HStore#changedReaderObservers here or we'll have no chance to 260 // and might cause memory leak 261 store.deleteChangedReaderObserver(this); 262 throw e; 263 } 264 } 265 266 // a dummy scan instance for compaction. 267 private static final Scan SCAN_FOR_COMPACTION = new Scan(); 268 269 /** 270 * Used for store file compaction and memstore compaction. 271 * <p> 272 * Opens a scanner across specified StoreFiles/MemStoreSegments. 273 * @param store who we scan 274 * @param scanners ancillary scanners 275 * @param smallestReadPoint the readPoint that we should use for tracking versions 276 */ 277 public StoreScanner(HStore store, ScanInfo scanInfo, List<? extends KeyValueScanner> scanners, 278 ScanType scanType, long smallestReadPoint, long earliestPutTs) throws IOException { 279 this(store, scanInfo, scanners, scanType, smallestReadPoint, earliestPutTs, null, null); 280 } 281 282 /** 283 * Used for compactions that drop deletes from a limited range of rows. 284 * <p> 285 * Opens a scanner across specified StoreFiles. 286 * @param store who we scan 287 * @param scanners ancillary scanners 288 * @param smallestReadPoint the readPoint that we should use for tracking versions 289 * @param dropDeletesFromRow The inclusive left bound of the range; can be EMPTY_START_ROW. 290 * @param dropDeletesToRow The exclusive right bound of the range; can be EMPTY_END_ROW. 291 */ 292 public StoreScanner(HStore store, ScanInfo scanInfo, List<? extends KeyValueScanner> scanners, 293 long smallestReadPoint, long earliestPutTs, byte[] dropDeletesFromRow, 294 byte[] dropDeletesToRow) throws IOException { 295 this(store, scanInfo, scanners, ScanType.COMPACT_RETAIN_DELETES, smallestReadPoint, 296 earliestPutTs, dropDeletesFromRow, dropDeletesToRow); 297 } 298 299 private StoreScanner(HStore store, ScanInfo scanInfo, List<? extends KeyValueScanner> scanners, 300 ScanType scanType, long smallestReadPoint, long earliestPutTs, byte[] dropDeletesFromRow, 301 byte[] dropDeletesToRow) throws IOException { 302 this(store, SCAN_FOR_COMPACTION, scanInfo, 0, 303 store.getHRegion().getReadPoint(IsolationLevel.READ_COMMITTED), false, scanType); 304 assert scanType != ScanType.USER_SCAN; 305 matcher = 306 CompactionScanQueryMatcher.create(scanInfo, scanType, smallestReadPoint, earliestPutTs, 307 oldestUnexpiredTS, now, dropDeletesFromRow, dropDeletesToRow, store.getCoprocessorHost()); 308 309 // Filter the list of scanners using Bloom filters, time range, TTL, etc. 310 scanners = selectScannersFrom(store, scanners); 311 312 // Seek all scanners to the initial key 313 seekScanners(scanners, matcher.getStartKey(), false, parallelSeekEnabled); 314 addCurrentScanners(scanners); 315 // Combine all seeked scanners with a heap 316 resetKVHeap(scanners, comparator); 317 } 318 319 private void seekAllScanner(ScanInfo scanInfo, List<? extends KeyValueScanner> scanners) 320 throws IOException { 321 // Seek all scanners to the initial key 322 seekScanners(scanners, matcher.getStartKey(), false, parallelSeekEnabled); 323 addCurrentScanners(scanners); 324 resetKVHeap(scanners, comparator); 325 } 326 327 // For mob compaction only as we do not have a Store instance when doing mob compaction. 328 public StoreScanner(ScanInfo scanInfo, ScanType scanType, 329 List<? extends KeyValueScanner> scanners) throws IOException { 330 this(null, SCAN_FOR_COMPACTION, scanInfo, 0, Long.MAX_VALUE, false, scanType); 331 assert scanType != ScanType.USER_SCAN; 332 this.matcher = CompactionScanQueryMatcher.create(scanInfo, scanType, Long.MAX_VALUE, 0L, 333 oldestUnexpiredTS, now, null, null, null); 334 seekAllScanner(scanInfo, scanners); 335 } 336 337 // Used to instantiate a scanner for user scan in test 338 @VisibleForTesting 339 StoreScanner(Scan scan, ScanInfo scanInfo, NavigableSet<byte[]> columns, 340 List<? extends KeyValueScanner> scanners) throws IOException { 341 // 0 is passed as readpoint because the test bypasses Store 342 this(null, scan, scanInfo, columns != null ? columns.size() : 0, 0L, 343 scan.getCacheBlocks(), ScanType.USER_SCAN); 344 this.matcher = 345 UserScanQueryMatcher.create(scan, scanInfo, columns, oldestUnexpiredTS, now, null); 346 seekAllScanner(scanInfo, scanners); 347 } 348 349 // Used to instantiate a scanner for compaction in test 350 @VisibleForTesting 351 StoreScanner(ScanInfo scanInfo, OptionalInt maxVersions, ScanType scanType, 352 List<? extends KeyValueScanner> scanners) throws IOException { 353 // 0 is passed as readpoint because the test bypasses Store 354 this(null, maxVersions.isPresent() ? new Scan().readVersions(maxVersions.getAsInt()) 355 : SCAN_FOR_COMPACTION, scanInfo, 0, 0L, false, scanType); 356 this.matcher = CompactionScanQueryMatcher.create(scanInfo, scanType, Long.MAX_VALUE, 357 HConstants.OLDEST_TIMESTAMP, oldestUnexpiredTS, now, null, null, null); 358 seekAllScanner(scanInfo, scanners); 359 } 360 361 @VisibleForTesting 362 boolean isScanUsePread() { 363 return this.scanUsePread; 364 } 365 /** 366 * Seek the specified scanners with the given key 367 * @param scanners 368 * @param seekKey 369 * @param isLazy true if using lazy seek 370 * @param isParallelSeek true if using parallel seek 371 * @throws IOException 372 */ 373 protected void seekScanners(List<? extends KeyValueScanner> scanners, 374 Cell seekKey, boolean isLazy, boolean isParallelSeek) 375 throws IOException { 376 // Seek all scanners to the start of the Row (or if the exact matching row 377 // key does not exist, then to the start of the next matching Row). 378 // Always check bloom filter to optimize the top row seek for delete 379 // family marker. 380 if (isLazy) { 381 for (KeyValueScanner scanner : scanners) { 382 scanner.requestSeek(seekKey, false, true); 383 } 384 } else { 385 if (!isParallelSeek) { 386 long totalScannersSoughtBytes = 0; 387 for (KeyValueScanner scanner : scanners) { 388 if (matcher.isUserScan() && totalScannersSoughtBytes >= maxRowSize) { 389 throw new RowTooBigException("Max row size allowed: " + maxRowSize 390 + ", but row is bigger than that"); 391 } 392 scanner.seek(seekKey); 393 Cell c = scanner.peek(); 394 if (c != null) { 395 totalScannersSoughtBytes += PrivateCellUtil.estimatedSerializedSizeOf(c); 396 } 397 } 398 } else { 399 parallelSeek(scanners, seekKey); 400 } 401 } 402 } 403 404 @VisibleForTesting 405 protected void resetKVHeap(List<? extends KeyValueScanner> scanners, 406 CellComparator comparator) throws IOException { 407 // Combine all seeked scanners with a heap 408 heap = newKVHeap(scanners, comparator); 409 } 410 411 protected KeyValueHeap newKVHeap(List<? extends KeyValueScanner> scanners, 412 CellComparator comparator) throws IOException { 413 return new KeyValueHeap(scanners, comparator); 414 } 415 416 /** 417 * Filters the given list of scanners using Bloom filter, time range, and TTL. 418 * <p> 419 * Will be overridden by testcase so declared as protected. 420 */ 421 @VisibleForTesting 422 protected List<KeyValueScanner> selectScannersFrom(HStore store, 423 List<? extends KeyValueScanner> allScanners) { 424 boolean memOnly; 425 boolean filesOnly; 426 if (scan instanceof InternalScan) { 427 InternalScan iscan = (InternalScan) scan; 428 memOnly = iscan.isCheckOnlyMemStore(); 429 filesOnly = iscan.isCheckOnlyStoreFiles(); 430 } else { 431 memOnly = false; 432 filesOnly = false; 433 } 434 435 List<KeyValueScanner> scanners = new ArrayList<>(allScanners.size()); 436 437 // We can only exclude store files based on TTL if minVersions is set to 0. 438 // Otherwise, we might have to return KVs that have technically expired. 439 long expiredTimestampCutoff = minVersions == 0 ? oldestUnexpiredTS : Long.MIN_VALUE; 440 441 // include only those scan files which pass all filters 442 for (KeyValueScanner kvs : allScanners) { 443 boolean isFile = kvs.isFileScanner(); 444 if ((!isFile && filesOnly) || (isFile && memOnly)) { 445 continue; 446 } 447 448 if (kvs.shouldUseScanner(scan, store, expiredTimestampCutoff)) { 449 scanners.add(kvs); 450 } else { 451 kvs.close(); 452 } 453 } 454 return scanners; 455 } 456 457 @Override 458 public Cell peek() { 459 return heap != null ? heap.peek() : null; 460 } 461 462 @Override 463 public KeyValue next() { 464 // throw runtime exception perhaps? 465 throw new RuntimeException("Never call StoreScanner.next()"); 466 } 467 468 @Override 469 public void close() { 470 close(true); 471 } 472 473 private void close(boolean withDelayedScannersClose) { 474 if (this.closing) { 475 return; 476 } 477 if (withDelayedScannersClose) { 478 this.closing = true; 479 } 480 // For mob compaction, we do not have a store. 481 if (this.store != null) { 482 this.store.deleteChangedReaderObserver(this); 483 } 484 if (withDelayedScannersClose) { 485 clearAndClose(scannersForDelayedClose); 486 clearAndClose(memStoreScannersAfterFlush); 487 clearAndClose(flushedstoreFileScanners); 488 if (this.heap != null) { 489 this.heap.close(); 490 this.currentScanners.clear(); 491 this.heap = null; // CLOSED! 492 } 493 } else { 494 if (this.heap != null) { 495 this.scannersForDelayedClose.add(this.heap); 496 this.currentScanners.clear(); 497 this.heap = null; 498 } 499 } 500 } 501 502 @Override 503 public boolean seek(Cell key) throws IOException { 504 if (checkFlushed()) { 505 reopenAfterFlush(); 506 } 507 return this.heap.seek(key); 508 } 509 510 /** 511 * Get the next row of values from this Store. 512 * @param outResult 513 * @param scannerContext 514 * @return true if there are more rows, false if scanner is done 515 */ 516 @Override 517 public boolean next(List<Cell> outResult, ScannerContext scannerContext) throws IOException { 518 if (scannerContext == null) { 519 throw new IllegalArgumentException("Scanner context cannot be null"); 520 } 521 if (checkFlushed() && reopenAfterFlush()) { 522 return scannerContext.setScannerState(NextState.MORE_VALUES).hasMoreValues(); 523 } 524 525 // if the heap was left null, then the scanners had previously run out anyways, close and 526 // return. 527 if (this.heap == null) { 528 // By this time partial close should happened because already heap is null 529 close(false);// Do all cleanup except heap.close() 530 return scannerContext.setScannerState(NextState.NO_MORE_VALUES).hasMoreValues(); 531 } 532 533 Cell cell = this.heap.peek(); 534 if (cell == null) { 535 close(false);// Do all cleanup except heap.close() 536 return scannerContext.setScannerState(NextState.NO_MORE_VALUES).hasMoreValues(); 537 } 538 539 // only call setRow if the row changes; avoids confusing the query matcher 540 // if scanning intra-row 541 542 // If no limits exists in the scope LimitScope.Between_Cells then we are sure we are changing 543 // rows. Else it is possible we are still traversing the same row so we must perform the row 544 // comparison. 545 if (!scannerContext.hasAnyLimit(LimitScope.BETWEEN_CELLS) || matcher.currentRow() == null) { 546 this.countPerRow = 0; 547 matcher.setToNewRow(cell); 548 } 549 550 // Clear progress away unless invoker has indicated it should be kept. 551 if (!scannerContext.getKeepProgress()) { 552 scannerContext.clearProgress(); 553 } 554 555 int count = 0; 556 long totalBytesRead = 0; 557 558 LOOP: do { 559 // Update and check the time limit based on the configured value of cellsPerTimeoutCheck 560 if ((kvsScanned % cellsPerHeartbeatCheck == 0)) { 561 if (scannerContext.checkTimeLimit(LimitScope.BETWEEN_CELLS)) { 562 return scannerContext.setScannerState(NextState.TIME_LIMIT_REACHED).hasMoreValues(); 563 } 564 } 565 // Do object compare - we set prevKV from the same heap. 566 if (prevCell != cell) { 567 ++kvsScanned; 568 } 569 checkScanOrder(prevCell, cell, comparator); 570 int cellSize = PrivateCellUtil.estimatedSerializedSizeOf(cell); 571 bytesRead += cellSize; 572 prevCell = cell; 573 scannerContext.setLastPeekedCell(cell); 574 topChanged = false; 575 ScanQueryMatcher.MatchCode qcode = matcher.match(cell); 576 switch (qcode) { 577 case INCLUDE: 578 case INCLUDE_AND_SEEK_NEXT_ROW: 579 case INCLUDE_AND_SEEK_NEXT_COL: 580 581 Filter f = matcher.getFilter(); 582 if (f != null) { 583 cell = f.transformCell(cell); 584 } 585 586 this.countPerRow++; 587 if (storeLimit > -1 && this.countPerRow > (storeLimit + storeOffset)) { 588 // do what SEEK_NEXT_ROW does. 589 if (!matcher.moreRowsMayExistAfter(cell)) { 590 close(false);// Do all cleanup except heap.close() 591 return scannerContext.setScannerState(NextState.NO_MORE_VALUES).hasMoreValues(); 592 } 593 matcher.clearCurrentRow(); 594 seekToNextRow(cell); 595 break LOOP; 596 } 597 598 // add to results only if we have skipped #storeOffset kvs 599 // also update metric accordingly 600 if (this.countPerRow > storeOffset) { 601 outResult.add(cell); 602 603 // Update local tracking information 604 count++; 605 totalBytesRead += cellSize; 606 607 // Update the progress of the scanner context 608 scannerContext.incrementSizeProgress(cellSize, 609 PrivateCellUtil.estimatedSizeOfCell(cell)); 610 scannerContext.incrementBatchProgress(1); 611 612 if (matcher.isUserScan() && totalBytesRead > maxRowSize) { 613 throw new RowTooBigException( 614 "Max row size allowed: " + maxRowSize + ", but the row is bigger than that."); 615 } 616 } 617 618 if (qcode == ScanQueryMatcher.MatchCode.INCLUDE_AND_SEEK_NEXT_ROW) { 619 if (!matcher.moreRowsMayExistAfter(cell)) { 620 close(false);// Do all cleanup except heap.close() 621 return scannerContext.setScannerState(NextState.NO_MORE_VALUES).hasMoreValues(); 622 } 623 matcher.clearCurrentRow(); 624 seekOrSkipToNextRow(cell); 625 } else if (qcode == ScanQueryMatcher.MatchCode.INCLUDE_AND_SEEK_NEXT_COL) { 626 seekOrSkipToNextColumn(cell); 627 } else { 628 this.heap.next(); 629 } 630 631 if (scannerContext.checkBatchLimit(LimitScope.BETWEEN_CELLS)) { 632 break LOOP; 633 } 634 if (scannerContext.checkSizeLimit(LimitScope.BETWEEN_CELLS)) { 635 break LOOP; 636 } 637 continue; 638 639 case DONE: 640 // Optimization for Gets! If DONE, no more to get on this row, early exit! 641 if (get) { 642 // Then no more to this row... exit. 643 close(false);// Do all cleanup except heap.close() 644 return scannerContext.setScannerState(NextState.NO_MORE_VALUES).hasMoreValues(); 645 } 646 matcher.clearCurrentRow(); 647 return scannerContext.setScannerState(NextState.MORE_VALUES).hasMoreValues(); 648 649 case DONE_SCAN: 650 close(false);// Do all cleanup except heap.close() 651 return scannerContext.setScannerState(NextState.NO_MORE_VALUES).hasMoreValues(); 652 653 case SEEK_NEXT_ROW: 654 // This is just a relatively simple end of scan fix, to short-cut end 655 // us if there is an endKey in the scan. 656 if (!matcher.moreRowsMayExistAfter(cell)) { 657 close(false);// Do all cleanup except heap.close() 658 return scannerContext.setScannerState(NextState.NO_MORE_VALUES).hasMoreValues(); 659 } 660 matcher.clearCurrentRow(); 661 seekOrSkipToNextRow(cell); 662 NextState stateAfterSeekNextRow = needToReturn(outResult); 663 if (stateAfterSeekNextRow != null) { 664 return scannerContext.setScannerState(stateAfterSeekNextRow).hasMoreValues(); 665 } 666 break; 667 668 case SEEK_NEXT_COL: 669 seekOrSkipToNextColumn(cell); 670 NextState stateAfterSeekNextColumn = needToReturn(outResult); 671 if (stateAfterSeekNextColumn != null) { 672 return scannerContext.setScannerState(stateAfterSeekNextColumn).hasMoreValues(); 673 } 674 break; 675 676 case SKIP: 677 this.heap.next(); 678 break; 679 680 case SEEK_NEXT_USING_HINT: 681 Cell nextKV = matcher.getNextKeyHint(cell); 682 if (nextKV != null && comparator.compare(nextKV, cell) > 0) { 683 seekAsDirection(nextKV); 684 NextState stateAfterSeekByHint = needToReturn(outResult); 685 if (stateAfterSeekByHint != null) { 686 return scannerContext.setScannerState(stateAfterSeekByHint).hasMoreValues(); 687 } 688 } else { 689 heap.next(); 690 } 691 break; 692 693 default: 694 throw new RuntimeException("UNEXPECTED"); 695 } 696 } while ((cell = this.heap.peek()) != null); 697 698 if (count > 0) { 699 return scannerContext.setScannerState(NextState.MORE_VALUES).hasMoreValues(); 700 } 701 702 // No more keys 703 close(false);// Do all cleanup except heap.close() 704 return scannerContext.setScannerState(NextState.NO_MORE_VALUES).hasMoreValues(); 705 } 706 707 /** 708 * If the top cell won't be flushed into disk, the new top cell may be 709 * changed after #reopenAfterFlush. Because the older top cell only exist 710 * in the memstore scanner but the memstore scanner is replaced by hfile 711 * scanner after #reopenAfterFlush. If the row of top cell is changed, 712 * we should return the current cells. Otherwise, we may return 713 * the cells across different rows. 714 * @param outResult the cells which are visible for user scan 715 * @return null is the top cell doesn't change. Otherwise, the NextState 716 * to return 717 */ 718 private NextState needToReturn(List<Cell> outResult) { 719 if (!outResult.isEmpty() && topChanged) { 720 return heap.peek() == null ? NextState.NO_MORE_VALUES : NextState.MORE_VALUES; 721 } 722 return null; 723 } 724 725 private void seekOrSkipToNextRow(Cell cell) throws IOException { 726 // If it is a Get Scan, then we know that we are done with this row; there are no more 727 // rows beyond the current one: don't try to optimize. 728 if (!get) { 729 if (trySkipToNextRow(cell)) { 730 return; 731 } 732 } 733 seekToNextRow(cell); 734 } 735 736 private void seekOrSkipToNextColumn(Cell cell) throws IOException { 737 if (!trySkipToNextColumn(cell)) { 738 seekAsDirection(matcher.getKeyForNextColumn(cell)); 739 } 740 } 741 742 /** 743 * See if we should actually SEEK or rather just SKIP to the next Cell (see HBASE-13109). 744 * ScanQueryMatcher may issue SEEK hints, such as seek to next column, next row, 745 * or seek to an arbitrary seek key. This method decides whether a seek is the most efficient 746 * _actual_ way to get us to the requested cell (SEEKs are more expensive than SKIP, SKIP, 747 * SKIP inside the current, loaded block). 748 * It does this by looking at the next indexed key of the current HFile. This key 749 * is then compared with the _SEEK_ key, where a SEEK key is an artificial 'last possible key 750 * on the row' (only in here, we avoid actually creating a SEEK key; in the compare we work with 751 * the current Cell but compare as though it were a seek key; see down in 752 * matcher.compareKeyForNextRow, etc). If the compare gets us onto the 753 * next block we *_SEEK, otherwise we just SKIP to the next requested cell. 754 * 755 * <p>Other notes: 756 * <ul> 757 * <li>Rows can straddle block boundaries</li> 758 * <li>Versions of columns can straddle block boundaries (i.e. column C1 at T1 might be in a 759 * different block than column C1 at T2)</li> 760 * <li>We want to SKIP if the chance is high that we'll find the desired Cell after a 761 * few SKIPs...</li> 762 * <li>We want to SEEK when the chance is high that we'll be able to seek 763 * past many Cells, especially if we know we need to go to the next block.</li> 764 * </ul> 765 * <p>A good proxy (best effort) to determine whether SKIP is better than SEEK is whether 766 * we'll likely end up seeking to the next block (or past the next block) to get our next column. 767 * Example: 768 * <pre> 769 * | BLOCK 1 | BLOCK 2 | 770 * | r1/c1, r1/c2, r1/c3 | r1/c4, r1/c5, r2/c1 | 771 * ^ ^ 772 * | | 773 * Next Index Key SEEK_NEXT_ROW (before r2/c1) 774 * 775 * 776 * | BLOCK 1 | BLOCK 2 | 777 * | r1/c1/t5, r1/c1/t4, r1/c1/t3 | r1/c1/t2, r1/c1/T1, r1/c2/T3 | 778 * ^ ^ 779 * | | 780 * Next Index Key SEEK_NEXT_COL 781 * </pre> 782 * Now imagine we want columns c1 and c3 (see first diagram above), the 'Next Index Key' of r1/c4 783 * is > r1/c3 so we should seek to get to the c1 on the next row, r2. In second case, say we only 784 * want one version of c1, after we have it, a SEEK_COL will be issued to get to c2. Looking at 785 * the 'Next Index Key', it would land us in the next block, so we should SEEK. In other scenarios 786 * where the SEEK will not land us in the next block, it is very likely better to issues a series 787 * of SKIPs. 788 * @param cell current cell 789 * @return true means skip to next row, false means not 790 */ 791 @VisibleForTesting 792 protected boolean trySkipToNextRow(Cell cell) throws IOException { 793 Cell nextCell = null; 794 // used to guard against a changed next indexed key by doing a identity comparison 795 // when the identity changes we need to compare the bytes again 796 Cell previousIndexedKey = null; 797 do { 798 Cell nextIndexedKey = getNextIndexedKey(); 799 if (nextIndexedKey != null && nextIndexedKey != KeyValueScanner.NO_NEXT_INDEXED_KEY && 800 (nextIndexedKey == previousIndexedKey || 801 matcher.compareKeyForNextRow(nextIndexedKey, cell) >= 0)) { 802 this.heap.next(); 803 ++kvsScanned; 804 previousIndexedKey = nextIndexedKey; 805 } else { 806 return false; 807 } 808 } while ((nextCell = this.heap.peek()) != null && CellUtil.matchingRows(cell, nextCell)); 809 return true; 810 } 811 812 /** 813 * See {@link org.apache.hadoop.hbase.regionserver.StoreScanner#trySkipToNextRow(Cell)} 814 * @param cell current cell 815 * @return true means skip to next column, false means not 816 */ 817 @VisibleForTesting 818 protected boolean trySkipToNextColumn(Cell cell) throws IOException { 819 Cell nextCell = null; 820 // used to guard against a changed next indexed key by doing a identity comparison 821 // when the identity changes we need to compare the bytes again 822 Cell previousIndexedKey = null; 823 do { 824 Cell nextIndexedKey = getNextIndexedKey(); 825 if (nextIndexedKey != null && nextIndexedKey != KeyValueScanner.NO_NEXT_INDEXED_KEY && 826 (nextIndexedKey == previousIndexedKey || 827 matcher.compareKeyForNextColumn(nextIndexedKey, cell) >= 0)) { 828 this.heap.next(); 829 ++kvsScanned; 830 previousIndexedKey = nextIndexedKey; 831 } else { 832 return false; 833 } 834 } while ((nextCell = this.heap.peek()) != null && CellUtil.matchingRowColumn(cell, nextCell)); 835 // We need this check because it may happen that the new scanner that we get 836 // during heap.next() is requiring reseek due of fake KV previously generated for 837 // ROWCOL bloom filter optimization. See HBASE-19863 for more details 838 if (nextCell != null && matcher.compareKeyForNextColumn(nextCell, cell) < 0) { 839 return false; 840 } 841 return true; 842 } 843 844 @Override 845 public long getReadPoint() { 846 return this.readPt; 847 } 848 849 private static void clearAndClose(List<KeyValueScanner> scanners) { 850 for (KeyValueScanner s : scanners) { 851 s.close(); 852 } 853 scanners.clear(); 854 } 855 856 // Implementation of ChangedReadersObserver 857 @Override 858 public void updateReaders(List<HStoreFile> sfs, List<KeyValueScanner> memStoreScanners) 859 throws IOException { 860 if (CollectionUtils.isEmpty(sfs) && CollectionUtils.isEmpty(memStoreScanners)) { 861 return; 862 } 863 flushLock.lock(); 864 try { 865 flushed = true; 866 final boolean isCompaction = false; 867 boolean usePread = get || scanUsePread; 868 // SEE HBASE-19468 where the flushed files are getting compacted even before a scanner 869 // calls next(). So its better we create scanners here rather than next() call. Ensure 870 // these scanners are properly closed() whether or not the scan is completed successfully 871 // Eagerly creating scanners so that we have the ref counting ticking on the newly created 872 // store files. In case of stream scanners this eager creation does not induce performance 873 // penalty because in scans (that uses stream scanners) the next() call is bound to happen. 874 List<KeyValueScanner> scanners = store.getScanners(sfs, cacheBlocks, get, usePread, 875 isCompaction, matcher, scan.getStartRow(), scan.getStopRow(), this.readPt, false); 876 flushedstoreFileScanners.addAll(scanners); 877 if (!CollectionUtils.isEmpty(memStoreScanners)) { 878 clearAndClose(memStoreScannersAfterFlush); 879 memStoreScannersAfterFlush.addAll(memStoreScanners); 880 } 881 } finally { 882 flushLock.unlock(); 883 } 884 // Let the next() call handle re-creating and seeking 885 } 886 887 /** 888 * @return if top of heap has changed (and KeyValueHeap has to try the next KV) 889 */ 890 protected final boolean reopenAfterFlush() throws IOException { 891 // here we can make sure that we have a Store instance so no null check on store. 892 Cell lastTop = heap.peek(); 893 // When we have the scan object, should we not pass it to getScanners() to get a limited set of 894 // scanners? We did so in the constructor and we could have done it now by storing the scan 895 // object from the constructor 896 List<KeyValueScanner> scanners; 897 flushLock.lock(); 898 try { 899 List<KeyValueScanner> allScanners = 900 new ArrayList<>(flushedstoreFileScanners.size() + memStoreScannersAfterFlush.size()); 901 allScanners.addAll(flushedstoreFileScanners); 902 allScanners.addAll(memStoreScannersAfterFlush); 903 scanners = selectScannersFrom(store, allScanners); 904 // Clear the current set of flushed store files scanners so that they don't get added again 905 flushedstoreFileScanners.clear(); 906 memStoreScannersAfterFlush.clear(); 907 } finally { 908 flushLock.unlock(); 909 } 910 911 // Seek the new scanners to the last key 912 seekScanners(scanners, lastTop, false, parallelSeekEnabled); 913 // remove the older memstore scanner 914 for (int i = currentScanners.size() - 1; i >=0; i--) { 915 if (!currentScanners.get(i).isFileScanner()) { 916 scannersForDelayedClose.add(currentScanners.remove(i)); 917 } else { 918 // we add the memstore scanner to the end of currentScanners 919 break; 920 } 921 } 922 // add the newly created scanners on the flushed files and the current active memstore scanner 923 addCurrentScanners(scanners); 924 // Combine all seeked scanners with a heap 925 resetKVHeap(this.currentScanners, store.getComparator()); 926 resetQueryMatcher(lastTop); 927 if (heap.peek() == null || store.getComparator().compareRows(lastTop, this.heap.peek()) != 0) { 928 LOG.info("Storescanner.peek() is changed where before = " + lastTop.toString() + 929 ",and after = " + heap.peek()); 930 topChanged = true; 931 } else { 932 topChanged = false; 933 } 934 return topChanged; 935 } 936 937 private void resetQueryMatcher(Cell lastTopKey) { 938 // Reset the state of the Query Matcher and set to top row. 939 // Only reset and call setRow if the row changes; avoids confusing the 940 // query matcher if scanning intra-row. 941 Cell cell = heap.peek(); 942 if (cell == null) { 943 cell = lastTopKey; 944 } 945 if ((matcher.currentRow() == null) || !CellUtil.matchingRows(cell, matcher.currentRow())) { 946 this.countPerRow = 0; 947 // The setToNewRow will call reset internally 948 matcher.setToNewRow(cell); 949 } 950 } 951 952 /** 953 * Check whether scan as expected order 954 * @param prevKV 955 * @param kv 956 * @param comparator 957 * @throws IOException 958 */ 959 protected void checkScanOrder(Cell prevKV, Cell kv, 960 CellComparator comparator) throws IOException { 961 // Check that the heap gives us KVs in an increasing order. 962 assert prevKV == null || comparator == null 963 || comparator.compare(prevKV, kv) <= 0 : "Key " + prevKV 964 + " followed by a " + "smaller key " + kv + " in cf " + store; 965 } 966 967 protected boolean seekToNextRow(Cell c) throws IOException { 968 return reseek(PrivateCellUtil.createLastOnRow(c)); 969 } 970 971 /** 972 * Do a reseek in a normal StoreScanner(scan forward) 973 * @param kv 974 * @return true if scanner has values left, false if end of scanner 975 * @throws IOException 976 */ 977 protected boolean seekAsDirection(Cell kv) 978 throws IOException { 979 return reseek(kv); 980 } 981 982 @Override 983 public boolean reseek(Cell kv) throws IOException { 984 if (checkFlushed()) { 985 reopenAfterFlush(); 986 } 987 if (explicitColumnQuery && lazySeekEnabledGlobally) { 988 return heap.requestSeek(kv, true, useRowColBloom); 989 } 990 return heap.reseek(kv); 991 } 992 993 @VisibleForTesting 994 void trySwitchToStreamRead() { 995 if (readType != Scan.ReadType.DEFAULT || !scanUsePread || closing || 996 heap.peek() == null || bytesRead < preadMaxBytes) { 997 return; 998 } 999 LOG.debug("Switch to stream read (scanned={} bytes) of {}", bytesRead, 1000 this.store.getColumnFamilyName()); 1001 scanUsePread = false; 1002 Cell lastTop = heap.peek(); 1003 List<KeyValueScanner> memstoreScanners = new ArrayList<>(); 1004 List<KeyValueScanner> scannersToClose = new ArrayList<>(); 1005 for (KeyValueScanner kvs : currentScanners) { 1006 if (!kvs.isFileScanner()) { 1007 // collect memstorescanners here 1008 memstoreScanners.add(kvs); 1009 } else { 1010 scannersToClose.add(kvs); 1011 } 1012 } 1013 List<KeyValueScanner> fileScanners = null; 1014 List<KeyValueScanner> newCurrentScanners; 1015 KeyValueHeap newHeap; 1016 try { 1017 // We must have a store instance here so no null check 1018 // recreate the scanners on the current file scanners 1019 fileScanners = store.recreateScanners(scannersToClose, cacheBlocks, false, false, 1020 matcher, scan.getStartRow(), scan.includeStartRow(), scan.getStopRow(), 1021 scan.includeStopRow(), readPt, false); 1022 if (fileScanners == null) { 1023 return; 1024 } 1025 seekScanners(fileScanners, lastTop, false, parallelSeekEnabled); 1026 newCurrentScanners = new ArrayList<>(fileScanners.size() + memstoreScanners.size()); 1027 newCurrentScanners.addAll(fileScanners); 1028 newCurrentScanners.addAll(memstoreScanners); 1029 newHeap = newKVHeap(newCurrentScanners, comparator); 1030 } catch (Exception e) { 1031 LOG.warn("failed to switch to stream read", e); 1032 if (fileScanners != null) { 1033 fileScanners.forEach(KeyValueScanner::close); 1034 } 1035 return; 1036 } 1037 currentScanners.clear(); 1038 addCurrentScanners(newCurrentScanners); 1039 this.heap = newHeap; 1040 resetQueryMatcher(lastTop); 1041 scannersToClose.forEach(KeyValueScanner::close); 1042 } 1043 1044 protected final boolean checkFlushed() { 1045 // check the var without any lock. Suppose even if we see the old 1046 // value here still it is ok to continue because we will not be resetting 1047 // the heap but will continue with the referenced memstore's snapshot. For compactions 1048 // any way we don't need the updateReaders at all to happen as we still continue with 1049 // the older files 1050 if (flushed) { 1051 // If there is a flush and the current scan is notified on the flush ensure that the 1052 // scan's heap gets reset and we do a seek on the newly flushed file. 1053 if (this.closing) { 1054 return false; 1055 } 1056 // reset the flag 1057 flushed = false; 1058 return true; 1059 } 1060 return false; 1061 } 1062 1063 /** 1064 * @see KeyValueScanner#getScannerOrder() 1065 */ 1066 @Override 1067 public long getScannerOrder() { 1068 return 0; 1069 } 1070 1071 /** 1072 * Seek storefiles in parallel to optimize IO latency as much as possible 1073 * @param scanners the list {@link KeyValueScanner}s to be read from 1074 * @param kv the KeyValue on which the operation is being requested 1075 * @throws IOException 1076 */ 1077 private void parallelSeek(final List<? extends KeyValueScanner> 1078 scanners, final Cell kv) throws IOException { 1079 if (scanners.isEmpty()) return; 1080 int storeFileScannerCount = scanners.size(); 1081 CountDownLatch latch = new CountDownLatch(storeFileScannerCount); 1082 List<ParallelSeekHandler> handlers = new ArrayList<>(storeFileScannerCount); 1083 for (KeyValueScanner scanner : scanners) { 1084 if (scanner instanceof StoreFileScanner) { 1085 ParallelSeekHandler seekHandler = new ParallelSeekHandler(scanner, kv, 1086 this.readPt, latch); 1087 executor.submit(seekHandler); 1088 handlers.add(seekHandler); 1089 } else { 1090 scanner.seek(kv); 1091 latch.countDown(); 1092 } 1093 } 1094 1095 try { 1096 latch.await(); 1097 } catch (InterruptedException ie) { 1098 throw (InterruptedIOException)new InterruptedIOException().initCause(ie); 1099 } 1100 1101 for (ParallelSeekHandler handler : handlers) { 1102 if (handler.getErr() != null) { 1103 throw new IOException(handler.getErr()); 1104 } 1105 } 1106 } 1107 1108 /** 1109 * Used in testing. 1110 * @return all scanners in no particular order 1111 */ 1112 @VisibleForTesting 1113 List<KeyValueScanner> getAllScannersForTesting() { 1114 List<KeyValueScanner> allScanners = new ArrayList<>(); 1115 KeyValueScanner current = heap.getCurrentForTesting(); 1116 if (current != null) 1117 allScanners.add(current); 1118 for (KeyValueScanner scanner : heap.getHeap()) 1119 allScanners.add(scanner); 1120 return allScanners; 1121 } 1122 1123 static void enableLazySeekGlobally(boolean enable) { 1124 lazySeekEnabledGlobally = enable; 1125 } 1126 1127 /** 1128 * @return The estimated number of KVs seen by this scanner (includes some skipped KVs). 1129 */ 1130 public long getEstimatedNumberOfKvsScanned() { 1131 return this.kvsScanned; 1132 } 1133 1134 @Override 1135 public Cell getNextIndexedKey() { 1136 return this.heap.getNextIndexedKey(); 1137 } 1138 1139 @Override 1140 public void shipped() throws IOException { 1141 if (prevCell != null) { 1142 // Do the copy here so that in case the prevCell ref is pointing to the previous 1143 // blocks we can safely release those blocks. 1144 // This applies to blocks that are got from Bucket cache, L1 cache and the blocks 1145 // fetched from HDFS. Copying this would ensure that we let go the references to these 1146 // blocks so that they can be GCed safely(in case of bucket cache) 1147 prevCell = KeyValueUtil.toNewKeyCell(this.prevCell); 1148 } 1149 matcher.beforeShipped(); 1150 // There wont be further fetch of Cells from these scanners. Just close. 1151 clearAndClose(scannersForDelayedClose); 1152 if (this.heap != null) { 1153 this.heap.shipped(); 1154 // When switching from pread to stream, we will open a new scanner for each store file, but 1155 // the old scanner may still track the HFileBlocks we have scanned but not sent back to client 1156 // yet. If we close the scanner immediately then the HFileBlocks may be messed up by others 1157 // before we serialize and send it back to client. The HFileBlocks will be released in shipped 1158 // method, so we here will also open new scanners and close old scanners in shipped method. 1159 // See HBASE-18055 for more details. 1160 trySwitchToStreamRead(); 1161 } 1162 } 1163} 1164