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 */ 019 020package org.apache.hadoop.hbase.regionserver; 021 022import java.io.FileNotFoundException; 023import java.io.IOException; 024import java.util.ArrayList; 025import java.util.Collection; 026import java.util.Collections; 027import java.util.List; 028import java.util.Optional; 029import java.util.PriorityQueue; 030import java.util.concurrent.atomic.LongAdder; 031 032import org.apache.hadoop.fs.Path; 033import org.apache.hadoop.hbase.Cell; 034import org.apache.hadoop.hbase.CellComparator; 035import org.apache.hadoop.hbase.HBaseInterfaceAudience; 036import org.apache.hadoop.hbase.HConstants; 037import org.apache.hadoop.hbase.PrivateCellUtil; 038import org.apache.yetus.audience.InterfaceAudience; 039import org.apache.yetus.audience.InterfaceStability; 040import org.apache.hadoop.hbase.client.Scan; 041import org.apache.hadoop.hbase.io.TimeRange; 042import org.apache.hadoop.hbase.io.hfile.HFileScanner; 043import org.apache.hadoop.hbase.regionserver.querymatcher.ScanQueryMatcher; 044 045/** 046 * KeyValueScanner adaptor over the Reader. It also provides hooks into 047 * bloom filter things. 048 */ 049@InterfaceAudience.LimitedPrivate(HBaseInterfaceAudience.PHOENIX) 050@InterfaceStability.Evolving 051public class StoreFileScanner implements KeyValueScanner { 052 // the reader it comes from: 053 private final StoreFileReader reader; 054 private final HFileScanner hfs; 055 private Cell cur = null; 056 private boolean closed = false; 057 058 private boolean realSeekDone; 059 private boolean delayedReseek; 060 private Cell delayedSeekKV; 061 062 private final boolean enforceMVCC; 063 private final boolean hasMVCCInfo; 064 // A flag represents whether could stop skipping KeyValues for MVCC 065 // if have encountered the next row. Only used for reversed scan 066 private boolean stopSkippingKVsIfNextRow = false; 067 068 private static LongAdder seekCount; 069 070 private final boolean canOptimizeForNonNullColumn; 071 072 private final long readPt; 073 074 // Order of this scanner relative to other scanners when duplicate key-value is found. 075 // Higher values means scanner has newer data. 076 private final long scannerOrder; 077 078 /** 079 * Implements a {@link KeyValueScanner} on top of the specified {@link HFileScanner} 080 * @param useMVCC If true, scanner will filter out updates with MVCC larger than {@code readPt}. 081 * @param readPt MVCC value to use to filter out the updates newer than this scanner. 082 * @param hasMVCC Set to true if underlying store file reader has MVCC info. 083 * @param scannerOrder Order of the scanner relative to other scanners. See 084 * {@link KeyValueScanner#getScannerOrder()}. 085 * @param canOptimizeForNonNullColumn {@code true} if we can make sure there is no null column, 086 * otherwise {@code false}. This is a hint for optimization. 087 */ 088 public StoreFileScanner(StoreFileReader reader, HFileScanner hfs, boolean useMVCC, 089 boolean hasMVCC, long readPt, long scannerOrder, boolean canOptimizeForNonNullColumn) { 090 this.readPt = readPt; 091 this.reader = reader; 092 this.hfs = hfs; 093 this.enforceMVCC = useMVCC; 094 this.hasMVCCInfo = hasMVCC; 095 this.scannerOrder = scannerOrder; 096 this.canOptimizeForNonNullColumn = canOptimizeForNonNullColumn; 097 } 098 099 boolean isPrimaryReplica() { 100 return reader.isPrimaryReplicaReader(); 101 } 102 103 /** 104 * Return an array of scanners corresponding to the given set of store files. 105 */ 106 public static List<StoreFileScanner> getScannersForStoreFiles(Collection<HStoreFile> files, 107 boolean cacheBlocks, boolean usePread, long readPt) throws IOException { 108 return getScannersForStoreFiles(files, cacheBlocks, usePread, false, false, readPt); 109 } 110 111 /** 112 * Return an array of scanners corresponding to the given set of store files. 113 */ 114 public static List<StoreFileScanner> getScannersForStoreFiles(Collection<HStoreFile> files, 115 boolean cacheBlocks, boolean usePread, boolean isCompaction, boolean useDropBehind, 116 long readPt) throws IOException { 117 return getScannersForStoreFiles(files, cacheBlocks, usePread, isCompaction, useDropBehind, null, 118 readPt); 119 } 120 121 /** 122 * Return an array of scanners corresponding to the given set of store files, And set the 123 * ScanQueryMatcher for each store file scanner for further optimization 124 */ 125 public static List<StoreFileScanner> getScannersForStoreFiles(Collection<HStoreFile> files, 126 boolean cacheBlocks, boolean usePread, boolean isCompaction, boolean canUseDrop, 127 ScanQueryMatcher matcher, long readPt) throws IOException { 128 if (files.isEmpty()) { 129 return Collections.emptyList(); 130 } 131 List<StoreFileScanner> scanners = new ArrayList<>(files.size()); 132 boolean canOptimizeForNonNullColumn = matcher != null ? !matcher.hasNullColumnInQuery() : false; 133 PriorityQueue<HStoreFile> sortedFiles = 134 new PriorityQueue<>(files.size(), StoreFileComparators.SEQ_ID); 135 for (HStoreFile file : files) { 136 // The sort function needs metadata so we need to open reader first before sorting the list. 137 file.initReader(); 138 sortedFiles.add(file); 139 } 140 boolean succ = false; 141 try { 142 for (int i = 0, n = files.size(); i < n; i++) { 143 HStoreFile sf = sortedFiles.remove(); 144 StoreFileScanner scanner; 145 if (usePread) { 146 scanner = sf.getPreadScanner(cacheBlocks, readPt, i, canOptimizeForNonNullColumn); 147 } else { 148 scanner = sf.getStreamScanner(canUseDrop, cacheBlocks, isCompaction, readPt, i, 149 canOptimizeForNonNullColumn); 150 } 151 scanners.add(scanner); 152 } 153 succ = true; 154 } finally { 155 if (!succ) { 156 for (StoreFileScanner scanner : scanners) { 157 scanner.close(); 158 } 159 } 160 } 161 return scanners; 162 } 163 164 /** 165 * Get scanners for compaction. We will create a separated reader for each store file to avoid 166 * contention with normal read request. 167 */ 168 public static List<StoreFileScanner> getScannersForCompaction(Collection<HStoreFile> files, 169 boolean canUseDropBehind, long readPt) throws IOException { 170 List<StoreFileScanner> scanners = new ArrayList<>(files.size()); 171 List<HStoreFile> sortedFiles = new ArrayList<>(files); 172 Collections.sort(sortedFiles, StoreFileComparators.SEQ_ID); 173 boolean succ = false; 174 try { 175 for (int i = 0, n = sortedFiles.size(); i < n; i++) { 176 scanners.add( 177 sortedFiles.get(i).getStreamScanner(canUseDropBehind, false, true, readPt, i, false)); 178 } 179 succ = true; 180 } finally { 181 if (!succ) { 182 for (StoreFileScanner scanner : scanners) { 183 scanner.close(); 184 } 185 } 186 } 187 return scanners; 188 } 189 190 @Override 191 public String toString() { 192 return "StoreFileScanner[" + hfs.toString() + ", cur=" + cur + "]"; 193 } 194 195 @Override 196 public Cell peek() { 197 return cur; 198 } 199 200 @Override 201 public Cell next() throws IOException { 202 Cell retKey = cur; 203 204 try { 205 // only seek if we aren't at the end. cur == null implies 'end'. 206 if (cur != null) { 207 hfs.next(); 208 setCurrentCell(hfs.getCell()); 209 if (hasMVCCInfo || this.reader.isBulkLoaded()) { 210 skipKVsNewerThanReadpoint(); 211 } 212 } 213 } catch (FileNotFoundException e) { 214 throw e; 215 } catch(IOException e) { 216 throw new IOException("Could not iterate " + this, e); 217 } 218 return retKey; 219 } 220 221 @Override 222 public boolean seek(Cell key) throws IOException { 223 if (seekCount != null) seekCount.increment(); 224 225 try { 226 try { 227 if(!seekAtOrAfter(hfs, key)) { 228 this.cur = null; 229 return false; 230 } 231 232 setCurrentCell(hfs.getCell()); 233 234 if (!hasMVCCInfo && this.reader.isBulkLoaded()) { 235 return skipKVsNewerThanReadpoint(); 236 } else { 237 return !hasMVCCInfo ? true : skipKVsNewerThanReadpoint(); 238 } 239 } finally { 240 realSeekDone = true; 241 } 242 } catch (FileNotFoundException e) { 243 throw e; 244 } catch (IOException ioe) { 245 throw new IOException("Could not seek " + this + " to key " + key, ioe); 246 } 247 } 248 249 @Override 250 public boolean reseek(Cell key) throws IOException { 251 if (seekCount != null) seekCount.increment(); 252 253 try { 254 try { 255 if (!reseekAtOrAfter(hfs, key)) { 256 this.cur = null; 257 return false; 258 } 259 setCurrentCell(hfs.getCell()); 260 261 if (!hasMVCCInfo && this.reader.isBulkLoaded()) { 262 return skipKVsNewerThanReadpoint(); 263 } else { 264 return !hasMVCCInfo ? true : skipKVsNewerThanReadpoint(); 265 } 266 } finally { 267 realSeekDone = true; 268 } 269 } catch (FileNotFoundException e) { 270 throw e; 271 } catch (IOException ioe) { 272 throw new IOException("Could not reseek " + this + " to key " + key, 273 ioe); 274 } 275 } 276 277 protected void setCurrentCell(Cell newVal) throws IOException { 278 this.cur = newVal; 279 if (this.cur != null && this.reader.isBulkLoaded() && !this.reader.isSkipResetSeqId()) { 280 PrivateCellUtil.setSequenceId(cur, this.reader.getSequenceID()); 281 } 282 } 283 284 protected boolean skipKVsNewerThanReadpoint() throws IOException { 285 // We want to ignore all key-values that are newer than our current 286 // readPoint 287 Cell startKV = cur; 288 while(enforceMVCC 289 && cur != null 290 && (cur.getSequenceId() > readPt)) { 291 boolean hasNext = hfs.next(); 292 setCurrentCell(hfs.getCell()); 293 if (hasNext && this.stopSkippingKVsIfNextRow 294 && getComparator().compareRows(cur, startKV) > 0) { 295 return false; 296 } 297 } 298 299 if (cur == null) { 300 return false; 301 } 302 303 return true; 304 } 305 306 @Override 307 public void close() { 308 if (closed) return; 309 cur = null; 310 this.hfs.close(); 311 if (this.reader != null) { 312 this.reader.readCompleted(); 313 } 314 closed = true; 315 } 316 317 /** 318 * 319 * @param s 320 * @param k 321 * @return false if not found or if k is after the end. 322 * @throws IOException 323 */ 324 public static boolean seekAtOrAfter(HFileScanner s, Cell k) 325 throws IOException { 326 int result = s.seekTo(k); 327 if(result < 0) { 328 if (result == HConstants.INDEX_KEY_MAGIC) { 329 // using faked key 330 return true; 331 } 332 // Passed KV is smaller than first KV in file, work from start of file 333 return s.seekTo(); 334 } else if(result > 0) { 335 // Passed KV is larger than current KV in file, if there is a next 336 // it is the "after", if not then this scanner is done. 337 return s.next(); 338 } 339 // Seeked to the exact key 340 return true; 341 } 342 343 static boolean reseekAtOrAfter(HFileScanner s, Cell k) 344 throws IOException { 345 //This function is similar to seekAtOrAfter function 346 int result = s.reseekTo(k); 347 if (result <= 0) { 348 if (result == HConstants.INDEX_KEY_MAGIC) { 349 // using faked key 350 return true; 351 } 352 // If up to now scanner is not seeked yet, this means passed KV is smaller 353 // than first KV in file, and it is the first time we seek on this file. 354 // So we also need to work from the start of file. 355 if (!s.isSeeked()) { 356 return s.seekTo(); 357 } 358 return true; 359 } 360 // passed KV is larger than current KV in file, if there is a next 361 // it is after, if not then this scanner is done. 362 return s.next(); 363 } 364 365 /** 366 * @see KeyValueScanner#getScannerOrder() 367 */ 368 @Override 369 public long getScannerOrder() { 370 return scannerOrder; 371 } 372 373 /** 374 * Pretend we have done a seek but don't do it yet, if possible. The hope is 375 * that we find requested columns in more recent files and won't have to seek 376 * in older files. Creates a fake key/value with the given row/column and the 377 * highest (most recent) possible timestamp we might get from this file. When 378 * users of such "lazy scanner" need to know the next KV precisely (e.g. when 379 * this scanner is at the top of the heap), they run {@link #enforceSeek()}. 380 * <p> 381 * Note that this function does guarantee that the current KV of this scanner 382 * will be advanced to at least the given KV. Because of this, it does have 383 * to do a real seek in cases when the seek timestamp is older than the 384 * highest timestamp of the file, e.g. when we are trying to seek to the next 385 * row/column and use OLDEST_TIMESTAMP in the seek key. 386 */ 387 @Override 388 public boolean requestSeek(Cell kv, boolean forward, boolean useBloom) 389 throws IOException { 390 if (kv.getFamilyLength() == 0) { 391 useBloom = false; 392 } 393 394 boolean haveToSeek = true; 395 if (useBloom) { 396 // check ROWCOL Bloom filter first. 397 if (reader.getBloomFilterType() == BloomType.ROWCOL) { 398 haveToSeek = reader.passesGeneralRowColBloomFilter(kv); 399 } else if (canOptimizeForNonNullColumn 400 && ((PrivateCellUtil.isDeleteFamily(kv) 401 || PrivateCellUtil.isDeleteFamilyVersion(kv)))) { 402 // if there is no such delete family kv in the store file, 403 // then no need to seek. 404 haveToSeek = reader.passesDeleteFamilyBloomFilter(kv.getRowArray(), kv.getRowOffset(), 405 kv.getRowLength()); 406 } 407 } 408 409 delayedReseek = forward; 410 delayedSeekKV = kv; 411 412 if (haveToSeek) { 413 // This row/column might be in this store file (or we did not use the 414 // Bloom filter), so we still need to seek. 415 realSeekDone = false; 416 long maxTimestampInFile = reader.getMaxTimestamp(); 417 long seekTimestamp = kv.getTimestamp(); 418 if (seekTimestamp > maxTimestampInFile) { 419 // Create a fake key that is not greater than the real next key. 420 // (Lower timestamps correspond to higher KVs.) 421 // To understand this better, consider that we are asked to seek to 422 // a higher timestamp than the max timestamp in this file. We know that 423 // the next point when we have to consider this file again is when we 424 // pass the max timestamp of this file (with the same row/column). 425 setCurrentCell(PrivateCellUtil.createFirstOnRowColTS(kv, maxTimestampInFile)); 426 } else { 427 // This will be the case e.g. when we need to seek to the next 428 // row/column, and we don't know exactly what they are, so we set the 429 // seek key's timestamp to OLDEST_TIMESTAMP to skip the rest of this 430 // row/column. 431 enforceSeek(); 432 } 433 return cur != null; 434 } 435 436 // Multi-column Bloom filter optimization. 437 // Create a fake key/value, so that this scanner only bubbles up to the top 438 // of the KeyValueHeap in StoreScanner after we scanned this row/column in 439 // all other store files. The query matcher will then just skip this fake 440 // key/value and the store scanner will progress to the next column. This 441 // is obviously not a "real real" seek, but unlike the fake KV earlier in 442 // this method, we want this to be propagated to ScanQueryMatcher. 443 setCurrentCell(PrivateCellUtil.createLastOnRowCol(kv)); 444 445 realSeekDone = true; 446 return true; 447 } 448 449 StoreFileReader getReader() { 450 return reader; 451 } 452 453 CellComparator getComparator() { 454 return reader.getComparator(); 455 } 456 457 @Override 458 public boolean realSeekDone() { 459 return realSeekDone; 460 } 461 462 @Override 463 public void enforceSeek() throws IOException { 464 if (realSeekDone) 465 return; 466 467 if (delayedReseek) { 468 reseek(delayedSeekKV); 469 } else { 470 seek(delayedSeekKV); 471 } 472 } 473 474 @Override 475 public boolean isFileScanner() { 476 return true; 477 } 478 479 @Override 480 public Path getFilePath() { 481 return reader.getHFileReader().getPath(); 482 } 483 484 // Test methods 485 static final long getSeekCount() { 486 return seekCount.sum(); 487 } 488 489 static final void instrument() { 490 seekCount = new LongAdder(); 491 } 492 493 @Override 494 public boolean shouldUseScanner(Scan scan, HStore store, long oldestUnexpiredTS) { 495 // if the file has no entries, no need to validate or create a scanner. 496 byte[] cf = store.getColumnFamilyDescriptor().getName(); 497 TimeRange timeRange = scan.getColumnFamilyTimeRange().get(cf); 498 if (timeRange == null) { 499 timeRange = scan.getTimeRange(); 500 } 501 return reader.passesTimerangeFilter(timeRange, oldestUnexpiredTS) && reader 502 .passesKeyRangeFilter(scan) && reader.passesBloomFilter(scan, scan.getFamilyMap().get(cf)); 503 } 504 505 @Override 506 public boolean seekToPreviousRow(Cell originalKey) throws IOException { 507 try { 508 try { 509 boolean keepSeeking = false; 510 Cell key = originalKey; 511 do { 512 Cell seekKey = PrivateCellUtil.createFirstOnRow(key); 513 if (seekCount != null) seekCount.increment(); 514 if (!hfs.seekBefore(seekKey)) { 515 this.cur = null; 516 return false; 517 } 518 Cell curCell = hfs.getCell(); 519 Cell firstKeyOfPreviousRow = PrivateCellUtil.createFirstOnRow(curCell); 520 521 if (seekCount != null) seekCount.increment(); 522 if (!seekAtOrAfter(hfs, firstKeyOfPreviousRow)) { 523 this.cur = null; 524 return false; 525 } 526 527 setCurrentCell(hfs.getCell()); 528 this.stopSkippingKVsIfNextRow = true; 529 boolean resultOfSkipKVs; 530 try { 531 resultOfSkipKVs = skipKVsNewerThanReadpoint(); 532 } finally { 533 this.stopSkippingKVsIfNextRow = false; 534 } 535 if (!resultOfSkipKVs 536 || getComparator().compareRows(cur, firstKeyOfPreviousRow) > 0) { 537 keepSeeking = true; 538 key = firstKeyOfPreviousRow; 539 continue; 540 } else { 541 keepSeeking = false; 542 } 543 } while (keepSeeking); 544 return true; 545 } finally { 546 realSeekDone = true; 547 } 548 } catch (FileNotFoundException e) { 549 throw e; 550 } catch (IOException ioe) { 551 throw new IOException("Could not seekToPreviousRow " + this + " to key " 552 + originalKey, ioe); 553 } 554 } 555 556 @Override 557 public boolean seekToLastRow() throws IOException { 558 Optional<byte[]> lastRow = reader.getLastRowKey(); 559 if (!lastRow.isPresent()) { 560 return false; 561 } 562 Cell seekKey = PrivateCellUtil.createFirstOnRow(lastRow.get()); 563 if (seek(seekKey)) { 564 return true; 565 } else { 566 return seekToPreviousRow(seekKey); 567 } 568 } 569 570 @Override 571 public boolean backwardSeek(Cell key) throws IOException { 572 seek(key); 573 if (cur == null 574 || getComparator().compareRows(cur, key) > 0) { 575 return seekToPreviousRow(key); 576 } 577 return true; 578 } 579 580 @Override 581 public Cell getNextIndexedKey() { 582 return hfs.getNextIndexedKey(); 583 } 584 585 @Override 586 public void shipped() throws IOException { 587 this.hfs.shipped(); 588 } 589}