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.net.InetSocketAddress; 024import java.util.ArrayList; 025import java.util.Collection; 026import java.util.Collections; 027import java.util.HashMap; 028import java.util.HashSet; 029import java.util.Iterator; 030import java.util.List; 031import java.util.Map; 032import java.util.NavigableSet; 033import java.util.Optional; 034import java.util.OptionalDouble; 035import java.util.OptionalLong; 036import java.util.Set; 037import java.util.concurrent.Callable; 038import java.util.concurrent.CompletionService; 039import java.util.concurrent.ConcurrentHashMap; 040import java.util.concurrent.ExecutionException; 041import java.util.concurrent.ExecutorCompletionService; 042import java.util.concurrent.Future; 043import java.util.concurrent.ThreadPoolExecutor; 044import java.util.concurrent.atomic.AtomicBoolean; 045import java.util.concurrent.atomic.AtomicLong; 046import java.util.concurrent.locks.ReentrantLock; 047import java.util.concurrent.locks.ReentrantReadWriteLock; 048import java.util.function.Predicate; 049import java.util.function.ToLongFunction; 050import java.util.stream.Collectors; 051import java.util.stream.LongStream; 052 053import org.apache.hadoop.conf.Configuration; 054import org.apache.hadoop.fs.FileSystem; 055import org.apache.hadoop.fs.Path; 056import org.apache.hadoop.hbase.Cell; 057import org.apache.hadoop.hbase.CellComparator; 058import org.apache.hadoop.hbase.CellUtil; 059import org.apache.hadoop.hbase.CompoundConfiguration; 060import org.apache.hadoop.hbase.HConstants; 061import org.apache.hadoop.hbase.MemoryCompactionPolicy; 062import org.apache.hadoop.hbase.TableName; 063import org.apache.hadoop.hbase.backup.FailedArchiveException; 064import org.apache.hadoop.hbase.client.ColumnFamilyDescriptor; 065import org.apache.hadoop.hbase.client.RegionInfo; 066import org.apache.hadoop.hbase.client.Scan; 067import org.apache.hadoop.hbase.conf.ConfigurationManager; 068import org.apache.hadoop.hbase.conf.PropagatingConfigurationObserver; 069import org.apache.hadoop.hbase.io.HeapSize; 070import org.apache.hadoop.hbase.io.compress.Compression; 071import org.apache.hadoop.hbase.io.crypto.Encryption; 072import org.apache.hadoop.hbase.io.hfile.CacheConfig; 073import org.apache.hadoop.hbase.io.hfile.HFile; 074import org.apache.hadoop.hbase.io.hfile.HFileContext; 075import org.apache.hadoop.hbase.io.hfile.HFileContextBuilder; 076import org.apache.hadoop.hbase.io.hfile.HFileDataBlockEncoder; 077import org.apache.hadoop.hbase.io.hfile.HFileDataBlockEncoderImpl; 078import org.apache.hadoop.hbase.io.hfile.HFileScanner; 079import org.apache.hadoop.hbase.io.hfile.InvalidHFileException; 080import org.apache.hadoop.hbase.log.HBaseMarkers; 081import org.apache.hadoop.hbase.monitoring.MonitoredTask; 082import org.apache.hadoop.hbase.regionserver.compactions.CompactionContext; 083import org.apache.hadoop.hbase.regionserver.compactions.CompactionLifeCycleTracker; 084import org.apache.hadoop.hbase.regionserver.compactions.CompactionProgress; 085import org.apache.hadoop.hbase.regionserver.compactions.CompactionRequestImpl; 086import org.apache.hadoop.hbase.regionserver.compactions.DefaultCompactor; 087import org.apache.hadoop.hbase.regionserver.compactions.OffPeakHours; 088import org.apache.hadoop.hbase.regionserver.querymatcher.ScanQueryMatcher; 089import org.apache.hadoop.hbase.regionserver.throttle.ThroughputController; 090import org.apache.hadoop.hbase.regionserver.wal.WALUtil; 091import org.apache.hadoop.hbase.security.EncryptionUtil; 092import org.apache.hadoop.hbase.security.User; 093import org.apache.hadoop.hbase.util.Bytes; 094import org.apache.hadoop.hbase.util.ChecksumType; 095import org.apache.hadoop.hbase.util.ClassSize; 096import org.apache.hadoop.hbase.util.EnvironmentEdgeManager; 097import org.apache.hadoop.hbase.util.Pair; 098import org.apache.hadoop.hbase.util.ReflectionUtils; 099import org.apache.hadoop.util.StringUtils; 100import org.apache.hadoop.util.StringUtils.TraditionalBinaryPrefix; 101import org.apache.yetus.audience.InterfaceAudience; 102import org.slf4j.Logger; 103import org.slf4j.LoggerFactory; 104import org.apache.hbase.thirdparty.com.google.common.annotations.VisibleForTesting; 105import org.apache.hbase.thirdparty.com.google.common.base.Preconditions; 106import org.apache.hbase.thirdparty.com.google.common.collect.ImmutableCollection; 107import org.apache.hbase.thirdparty.com.google.common.collect.ImmutableList; 108import org.apache.hbase.thirdparty.com.google.common.collect.Lists; 109import org.apache.hbase.thirdparty.com.google.common.collect.Sets; 110import org.apache.hbase.thirdparty.org.apache.commons.collections4.CollectionUtils; 111import org.apache.hbase.thirdparty.org.apache.commons.collections4.IterableUtils; 112import org.apache.hadoop.hbase.shaded.protobuf.ProtobufUtil; 113import org.apache.hadoop.hbase.shaded.protobuf.generated.WALProtos.CompactionDescriptor; 114 115/** 116 * A Store holds a column family in a Region. Its a memstore and a set of zero 117 * or more StoreFiles, which stretch backwards over time. 118 * 119 * <p>There's no reason to consider append-logging at this level; all logging 120 * and locking is handled at the HRegion level. Store just provides 121 * services to manage sets of StoreFiles. One of the most important of those 122 * services is compaction services where files are aggregated once they pass 123 * a configurable threshold. 124 * 125 * <p>Locking and transactions are handled at a higher level. This API should 126 * not be called directly but by an HRegion manager. 127 */ 128@InterfaceAudience.Private 129public class HStore implements Store, HeapSize, StoreConfigInformation, PropagatingConfigurationObserver { 130 public static final String MEMSTORE_CLASS_NAME = "hbase.regionserver.memstore.class"; 131 public static final String COMPACTCHECKER_INTERVAL_MULTIPLIER_KEY = 132 "hbase.server.compactchecker.interval.multiplier"; 133 public static final String BLOCKING_STOREFILES_KEY = "hbase.hstore.blockingStoreFiles"; 134 public static final String BLOCK_STORAGE_POLICY_KEY = "hbase.hstore.block.storage.policy"; 135 // keep in accordance with HDFS default storage policy 136 public static final String DEFAULT_BLOCK_STORAGE_POLICY = "HOT"; 137 public static final int DEFAULT_COMPACTCHECKER_INTERVAL_MULTIPLIER = 1000; 138 public static final int DEFAULT_BLOCKING_STOREFILE_COUNT = 16; 139 140 private static final Logger LOG = LoggerFactory.getLogger(HStore.class); 141 142 protected final MemStore memstore; 143 // This stores directory in the filesystem. 144 protected final HRegion region; 145 private final ColumnFamilyDescriptor family; 146 private final HRegionFileSystem fs; 147 protected Configuration conf; 148 protected CacheConfig cacheConf; 149 private long lastCompactSize = 0; 150 volatile boolean forceMajor = false; 151 /* how many bytes to write between status checks */ 152 static int closeCheckInterval = 0; 153 private AtomicLong storeSize = new AtomicLong(); 154 private AtomicLong totalUncompressedBytes = new AtomicLong(); 155 156 /** 157 * RWLock for store operations. 158 * Locked in shared mode when the list of component stores is looked at: 159 * - all reads/writes to table data 160 * - checking for split 161 * Locked in exclusive mode when the list of component stores is modified: 162 * - closing 163 * - completing a compaction 164 */ 165 final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(); 166 /** 167 * Lock specific to archiving compacted store files. This avoids races around 168 * the combination of retrieving the list of compacted files and moving them to 169 * the archive directory. Since this is usually a background process (other than 170 * on close), we don't want to handle this with the store write lock, which would 171 * block readers and degrade performance. 172 * 173 * Locked by: 174 * - CompactedHFilesDispatchHandler via closeAndArchiveCompactedFiles() 175 * - close() 176 */ 177 final ReentrantLock archiveLock = new ReentrantLock(); 178 179 private final boolean verifyBulkLoads; 180 181 private ScanInfo scanInfo; 182 183 // All access must be synchronized. 184 // TODO: ideally, this should be part of storeFileManager, as we keep passing this to it. 185 private final List<HStoreFile> filesCompacting = Lists.newArrayList(); 186 187 // All access must be synchronized. 188 private final Set<ChangedReadersObserver> changedReaderObservers = 189 Collections.newSetFromMap(new ConcurrentHashMap<ChangedReadersObserver, Boolean>()); 190 191 protected final int blocksize; 192 private HFileDataBlockEncoder dataBlockEncoder; 193 194 /** Checksum configuration */ 195 protected ChecksumType checksumType; 196 protected int bytesPerChecksum; 197 198 // Comparing KeyValues 199 protected final CellComparator comparator; 200 201 final StoreEngine<?, ?, ?, ?> storeEngine; 202 203 private static final AtomicBoolean offPeakCompactionTracker = new AtomicBoolean(); 204 private volatile OffPeakHours offPeakHours; 205 206 private static final int DEFAULT_FLUSH_RETRIES_NUMBER = 10; 207 private int flushRetriesNumber; 208 private int pauseTime; 209 210 private long blockingFileCount; 211 private int compactionCheckMultiplier; 212 protected Encryption.Context cryptoContext = Encryption.Context.NONE; 213 214 private AtomicLong flushedCellsCount = new AtomicLong(); 215 private AtomicLong compactedCellsCount = new AtomicLong(); 216 private AtomicLong majorCompactedCellsCount = new AtomicLong(); 217 private AtomicLong flushedCellsSize = new AtomicLong(); 218 private AtomicLong flushedOutputFileSize = new AtomicLong(); 219 private AtomicLong compactedCellsSize = new AtomicLong(); 220 private AtomicLong majorCompactedCellsSize = new AtomicLong(); 221 222 /** 223 * Constructor 224 * @param region 225 * @param family HColumnDescriptor for this column 226 * @param confParam configuration object 227 * failed. Can be null. 228 * @throws IOException 229 */ 230 protected HStore(final HRegion region, final ColumnFamilyDescriptor family, 231 final Configuration confParam) throws IOException { 232 233 this.fs = region.getRegionFileSystem(); 234 235 // Assemble the store's home directory and Ensure it exists. 236 fs.createStoreDir(family.getNameAsString()); 237 this.region = region; 238 this.family = family; 239 // 'conf' renamed to 'confParam' b/c we use this.conf in the constructor 240 // CompoundConfiguration will look for keys in reverse order of addition, so we'd 241 // add global config first, then table and cf overrides, then cf metadata. 242 this.conf = new CompoundConfiguration() 243 .add(confParam) 244 .addBytesMap(region.getTableDescriptor().getValues()) 245 .addStringMap(family.getConfiguration()) 246 .addBytesMap(family.getValues()); 247 this.blocksize = family.getBlocksize(); 248 249 // set block storage policy for store directory 250 String policyName = family.getStoragePolicy(); 251 if (null == policyName) { 252 policyName = this.conf.get(BLOCK_STORAGE_POLICY_KEY, DEFAULT_BLOCK_STORAGE_POLICY); 253 } 254 this.fs.setStoragePolicy(family.getNameAsString(), policyName.trim()); 255 256 this.dataBlockEncoder = new HFileDataBlockEncoderImpl(family.getDataBlockEncoding()); 257 258 this.comparator = region.getCellComparator(); 259 // used by ScanQueryMatcher 260 long timeToPurgeDeletes = 261 Math.max(conf.getLong("hbase.hstore.time.to.purge.deletes", 0), 0); 262 LOG.trace("Time to purge deletes set to {}ms in store {}", timeToPurgeDeletes, this); 263 // Get TTL 264 long ttl = determineTTLFromFamily(family); 265 // Why not just pass a HColumnDescriptor in here altogether? Even if have 266 // to clone it? 267 scanInfo = new ScanInfo(conf, family, ttl, timeToPurgeDeletes, this.comparator); 268 this.memstore = getMemstore(); 269 this.offPeakHours = OffPeakHours.getInstance(conf); 270 271 // Setting up cache configuration for this family 272 createCacheConf(family); 273 274 this.verifyBulkLoads = conf.getBoolean("hbase.hstore.bulkload.verify", false); 275 276 this.blockingFileCount = 277 conf.getInt(BLOCKING_STOREFILES_KEY, DEFAULT_BLOCKING_STOREFILE_COUNT); 278 this.compactionCheckMultiplier = conf.getInt( 279 COMPACTCHECKER_INTERVAL_MULTIPLIER_KEY, DEFAULT_COMPACTCHECKER_INTERVAL_MULTIPLIER); 280 if (this.compactionCheckMultiplier <= 0) { 281 LOG.error("Compaction check period multiplier must be positive, setting default: {}", 282 DEFAULT_COMPACTCHECKER_INTERVAL_MULTIPLIER); 283 this.compactionCheckMultiplier = DEFAULT_COMPACTCHECKER_INTERVAL_MULTIPLIER; 284 } 285 286 if (HStore.closeCheckInterval == 0) { 287 HStore.closeCheckInterval = conf.getInt( 288 "hbase.hstore.close.check.interval", 10*1000*1000 /* 10 MB */); 289 } 290 291 this.storeEngine = createStoreEngine(this, this.conf, this.comparator); 292 this.storeEngine.getStoreFileManager().loadFiles(loadStoreFiles()); 293 294 // Initialize checksum type from name. The names are CRC32, CRC32C, etc. 295 this.checksumType = getChecksumType(conf); 296 // Initialize bytes per checksum 297 this.bytesPerChecksum = getBytesPerChecksum(conf); 298 flushRetriesNumber = conf.getInt( 299 "hbase.hstore.flush.retries.number", DEFAULT_FLUSH_RETRIES_NUMBER); 300 pauseTime = conf.getInt(HConstants.HBASE_SERVER_PAUSE, HConstants.DEFAULT_HBASE_SERVER_PAUSE); 301 if (flushRetriesNumber <= 0) { 302 throw new IllegalArgumentException( 303 "hbase.hstore.flush.retries.number must be > 0, not " 304 + flushRetriesNumber); 305 } 306 cryptoContext = EncryptionUtil.createEncryptionContext(conf, family); 307 308 LOG.info("Store={}, memstore type={}, storagePolicy={}, verifyBulkLoads={}", 309 getColumnFamilyName(), this.memstore.getClass().getSimpleName(), policyName, 310 this.verifyBulkLoads); 311 } 312 313 /** 314 * @return MemStore Instance to use in this store. 315 */ 316 private MemStore getMemstore() { 317 MemStore ms = null; 318 // Check if in-memory-compaction configured. Note MemoryCompactionPolicy is an enum! 319 MemoryCompactionPolicy inMemoryCompaction = null; 320 if (this.getTableName().isSystemTable()) { 321 inMemoryCompaction = MemoryCompactionPolicy.valueOf( 322 conf.get("hbase.systemtables.compacting.memstore.type", "NONE")); 323 } else { 324 inMemoryCompaction = family.getInMemoryCompaction(); 325 } 326 if (inMemoryCompaction == null) { 327 inMemoryCompaction = 328 MemoryCompactionPolicy.valueOf(conf.get(CompactingMemStore.COMPACTING_MEMSTORE_TYPE_KEY, 329 CompactingMemStore.COMPACTING_MEMSTORE_TYPE_DEFAULT)); 330 } 331 switch (inMemoryCompaction) { 332 case NONE: 333 ms = ReflectionUtils.newInstance(DefaultMemStore.class, 334 new Object[]{conf, this.comparator}); 335 break; 336 default: 337 Class<? extends CompactingMemStore> clz = conf.getClass(MEMSTORE_CLASS_NAME, 338 CompactingMemStore.class, CompactingMemStore.class); 339 ms = ReflectionUtils.newInstance(clz, new Object[]{conf, this.comparator, this, 340 this.getHRegion().getRegionServicesForStores(), inMemoryCompaction}); 341 } 342 return ms; 343 } 344 345 /** 346 * Creates the cache config. 347 * @param family The current column family. 348 */ 349 protected void createCacheConf(final ColumnFamilyDescriptor family) { 350 this.cacheConf = new CacheConfig(conf, family); 351 } 352 353 /** 354 * Creates the store engine configured for the given Store. 355 * @param store The store. An unfortunate dependency needed due to it 356 * being passed to coprocessors via the compactor. 357 * @param conf Store configuration. 358 * @param kvComparator KVComparator for storeFileManager. 359 * @return StoreEngine to use. 360 */ 361 protected StoreEngine<?, ?, ?, ?> createStoreEngine(HStore store, Configuration conf, 362 CellComparator kvComparator) throws IOException { 363 return StoreEngine.create(store, conf, comparator); 364 } 365 366 /** 367 * @param family 368 * @return TTL in seconds of the specified family 369 */ 370 public static long determineTTLFromFamily(final ColumnFamilyDescriptor family) { 371 // HCD.getTimeToLive returns ttl in seconds. Convert to milliseconds. 372 long ttl = family.getTimeToLive(); 373 if (ttl == HConstants.FOREVER) { 374 // Default is unlimited ttl. 375 ttl = Long.MAX_VALUE; 376 } else if (ttl == -1) { 377 ttl = Long.MAX_VALUE; 378 } else { 379 // Second -> ms adjust for user data 380 ttl *= 1000; 381 } 382 return ttl; 383 } 384 385 @Override 386 public String getColumnFamilyName() { 387 return this.family.getNameAsString(); 388 } 389 390 @Override 391 public TableName getTableName() { 392 return this.getRegionInfo().getTable(); 393 } 394 395 @Override 396 public FileSystem getFileSystem() { 397 return this.fs.getFileSystem(); 398 } 399 400 public HRegionFileSystem getRegionFileSystem() { 401 return this.fs; 402 } 403 404 /* Implementation of StoreConfigInformation */ 405 @Override 406 public long getStoreFileTtl() { 407 // TTL only applies if there's no MIN_VERSIONs setting on the column. 408 return (this.scanInfo.getMinVersions() == 0) ? this.scanInfo.getTtl() : Long.MAX_VALUE; 409 } 410 411 @Override 412 public long getMemStoreFlushSize() { 413 // TODO: Why is this in here? The flushsize of the region rather than the store? St.Ack 414 return this.region.memstoreFlushSize; 415 } 416 417 @Override 418 public MemStoreSize getFlushableSize() { 419 return this.memstore.getFlushableSize(); 420 } 421 422 @Override 423 public MemStoreSize getSnapshotSize() { 424 return this.memstore.getSnapshotSize(); 425 } 426 427 @Override 428 public long getCompactionCheckMultiplier() { 429 return this.compactionCheckMultiplier; 430 } 431 432 @Override 433 public long getBlockingFileCount() { 434 return blockingFileCount; 435 } 436 /* End implementation of StoreConfigInformation */ 437 438 /** 439 * Returns the configured bytesPerChecksum value. 440 * @param conf The configuration 441 * @return The bytesPerChecksum that is set in the configuration 442 */ 443 public static int getBytesPerChecksum(Configuration conf) { 444 return conf.getInt(HConstants.BYTES_PER_CHECKSUM, 445 HFile.DEFAULT_BYTES_PER_CHECKSUM); 446 } 447 448 /** 449 * Returns the configured checksum algorithm. 450 * @param conf The configuration 451 * @return The checksum algorithm that is set in the configuration 452 */ 453 public static ChecksumType getChecksumType(Configuration conf) { 454 String checksumName = conf.get(HConstants.CHECKSUM_TYPE_NAME); 455 if (checksumName == null) { 456 return ChecksumType.getDefaultChecksumType(); 457 } else { 458 return ChecksumType.nameToType(checksumName); 459 } 460 } 461 462 /** 463 * @return how many bytes to write between status checks 464 */ 465 public static int getCloseCheckInterval() { 466 return closeCheckInterval; 467 } 468 469 @Override 470 public ColumnFamilyDescriptor getColumnFamilyDescriptor() { 471 return this.family; 472 } 473 474 @Override 475 public OptionalLong getMaxSequenceId() { 476 return StoreUtils.getMaxSequenceIdInList(this.getStorefiles()); 477 } 478 479 @Override 480 public OptionalLong getMaxMemStoreTS() { 481 return StoreUtils.getMaxMemStoreTSInList(this.getStorefiles()); 482 } 483 484 /** 485 * @param tabledir {@link Path} to where the table is being stored 486 * @param hri {@link RegionInfo} for the region. 487 * @param family {@link ColumnFamilyDescriptor} describing the column family 488 * @return Path to family/Store home directory. 489 */ 490 @Deprecated 491 public static Path getStoreHomedir(final Path tabledir, 492 final RegionInfo hri, final byte[] family) { 493 return getStoreHomedir(tabledir, hri.getEncodedName(), family); 494 } 495 496 /** 497 * @param tabledir {@link Path} to where the table is being stored 498 * @param encodedName Encoded region name. 499 * @param family {@link ColumnFamilyDescriptor} describing the column family 500 * @return Path to family/Store home directory. 501 */ 502 @Deprecated 503 public static Path getStoreHomedir(final Path tabledir, 504 final String encodedName, final byte[] family) { 505 return new Path(tabledir, new Path(encodedName, Bytes.toString(family))); 506 } 507 508 /** 509 * @return the data block encoder 510 */ 511 public HFileDataBlockEncoder getDataBlockEncoder() { 512 return dataBlockEncoder; 513 } 514 515 /** 516 * Should be used only in tests. 517 * @param blockEncoder the block delta encoder to use 518 */ 519 void setDataBlockEncoderInTest(HFileDataBlockEncoder blockEncoder) { 520 this.dataBlockEncoder = blockEncoder; 521 } 522 523 /** 524 * Creates an unsorted list of StoreFile loaded in parallel 525 * from the given directory. 526 * @throws IOException 527 */ 528 private List<HStoreFile> loadStoreFiles() throws IOException { 529 Collection<StoreFileInfo> files = fs.getStoreFiles(getColumnFamilyName()); 530 return openStoreFiles(files); 531 } 532 533 private List<HStoreFile> openStoreFiles(Collection<StoreFileInfo> files) throws IOException { 534 if (CollectionUtils.isEmpty(files)) { 535 return Collections.emptyList(); 536 } 537 // initialize the thread pool for opening store files in parallel.. 538 ThreadPoolExecutor storeFileOpenerThreadPool = 539 this.region.getStoreFileOpenAndCloseThreadPool("StoreFileOpenerThread-" + 540 this.getColumnFamilyName()); 541 CompletionService<HStoreFile> completionService = new ExecutorCompletionService<>(storeFileOpenerThreadPool); 542 543 int totalValidStoreFile = 0; 544 for (StoreFileInfo storeFileInfo : files) { 545 // open each store file in parallel 546 completionService.submit(() -> this.createStoreFileAndReader(storeFileInfo)); 547 totalValidStoreFile++; 548 } 549 550 ArrayList<HStoreFile> results = new ArrayList<>(files.size()); 551 IOException ioe = null; 552 try { 553 for (int i = 0; i < totalValidStoreFile; i++) { 554 try { 555 HStoreFile storeFile = completionService.take().get(); 556 if (storeFile != null) { 557 long length = storeFile.getReader().length(); 558 this.storeSize.addAndGet(length); 559 this.totalUncompressedBytes 560 .addAndGet(storeFile.getReader().getTotalUncompressedBytes()); 561 LOG.debug("loaded {}", storeFile); 562 results.add(storeFile); 563 } 564 } catch (InterruptedException e) { 565 if (ioe == null) ioe = new InterruptedIOException(e.getMessage()); 566 } catch (ExecutionException e) { 567 if (ioe == null) ioe = new IOException(e.getCause()); 568 } 569 } 570 } finally { 571 storeFileOpenerThreadPool.shutdownNow(); 572 } 573 if (ioe != null) { 574 // close StoreFile readers 575 boolean evictOnClose = 576 cacheConf != null? cacheConf.shouldEvictOnClose(): true; 577 for (HStoreFile file : results) { 578 try { 579 if (file != null) { 580 file.closeStoreFile(evictOnClose); 581 } 582 } catch (IOException e) { 583 LOG.warn("Could not close store file", e); 584 } 585 } 586 throw ioe; 587 } 588 589 return results; 590 } 591 592 @Override 593 public void refreshStoreFiles() throws IOException { 594 Collection<StoreFileInfo> newFiles = fs.getStoreFiles(getColumnFamilyName()); 595 refreshStoreFilesInternal(newFiles); 596 } 597 598 /** 599 * Replaces the store files that the store has with the given files. Mainly used by secondary 600 * region replicas to keep up to date with the primary region files. 601 * @throws IOException 602 */ 603 public void refreshStoreFiles(Collection<String> newFiles) throws IOException { 604 List<StoreFileInfo> storeFiles = new ArrayList<>(newFiles.size()); 605 for (String file : newFiles) { 606 storeFiles.add(fs.getStoreFileInfo(getColumnFamilyName(), file)); 607 } 608 refreshStoreFilesInternal(storeFiles); 609 } 610 611 /** 612 * Checks the underlying store files, and opens the files that have not 613 * been opened, and removes the store file readers for store files no longer 614 * available. Mainly used by secondary region replicas to keep up to date with 615 * the primary region files. 616 * @throws IOException 617 */ 618 private void refreshStoreFilesInternal(Collection<StoreFileInfo> newFiles) throws IOException { 619 StoreFileManager sfm = storeEngine.getStoreFileManager(); 620 Collection<HStoreFile> currentFiles = sfm.getStorefiles(); 621 Collection<HStoreFile> compactedFiles = sfm.getCompactedfiles(); 622 if (currentFiles == null) currentFiles = Collections.emptySet(); 623 if (newFiles == null) newFiles = Collections.emptySet(); 624 if (compactedFiles == null) compactedFiles = Collections.emptySet(); 625 626 HashMap<StoreFileInfo, HStoreFile> currentFilesSet = new HashMap<>(currentFiles.size()); 627 for (HStoreFile sf : currentFiles) { 628 currentFilesSet.put(sf.getFileInfo(), sf); 629 } 630 HashMap<StoreFileInfo, HStoreFile> compactedFilesSet = new HashMap<>(compactedFiles.size()); 631 for (HStoreFile sf : compactedFiles) { 632 compactedFilesSet.put(sf.getFileInfo(), sf); 633 } 634 635 Set<StoreFileInfo> newFilesSet = new HashSet<StoreFileInfo>(newFiles); 636 // Exclude the files that have already been compacted 637 newFilesSet = Sets.difference(newFilesSet, compactedFilesSet.keySet()); 638 Set<StoreFileInfo> toBeAddedFiles = Sets.difference(newFilesSet, currentFilesSet.keySet()); 639 Set<StoreFileInfo> toBeRemovedFiles = Sets.difference(currentFilesSet.keySet(), newFilesSet); 640 641 if (toBeAddedFiles.isEmpty() && toBeRemovedFiles.isEmpty()) { 642 return; 643 } 644 645 LOG.info("Refreshing store files for region " + this.getRegionInfo().getRegionNameAsString() 646 + " files to add: " + toBeAddedFiles + " files to remove: " + toBeRemovedFiles); 647 648 Set<HStoreFile> toBeRemovedStoreFiles = new HashSet<>(toBeRemovedFiles.size()); 649 for (StoreFileInfo sfi : toBeRemovedFiles) { 650 toBeRemovedStoreFiles.add(currentFilesSet.get(sfi)); 651 } 652 653 // try to open the files 654 List<HStoreFile> openedFiles = openStoreFiles(toBeAddedFiles); 655 656 // propogate the file changes to the underlying store file manager 657 replaceStoreFiles(toBeRemovedStoreFiles, openedFiles); //won't throw an exception 658 659 // Advance the memstore read point to be at least the new store files seqIds so that 660 // readers might pick it up. This assumes that the store is not getting any writes (otherwise 661 // in-flight transactions might be made visible) 662 if (!toBeAddedFiles.isEmpty()) { 663 // we must have the max sequence id here as we do have several store files 664 region.getMVCC().advanceTo(this.getMaxSequenceId().getAsLong()); 665 } 666 667 completeCompaction(toBeRemovedStoreFiles); 668 } 669 670 @VisibleForTesting 671 protected HStoreFile createStoreFileAndReader(final Path p) throws IOException { 672 StoreFileInfo info = new StoreFileInfo(conf, this.getFileSystem(), p); 673 return createStoreFileAndReader(info); 674 } 675 676 private HStoreFile createStoreFileAndReader(StoreFileInfo info) throws IOException { 677 info.setRegionCoprocessorHost(this.region.getCoprocessorHost()); 678 HStoreFile storeFile = new HStoreFile(this.getFileSystem(), info, this.conf, this.cacheConf, 679 this.family.getBloomFilterType(), isPrimaryReplicaStore()); 680 storeFile.initReader(); 681 return storeFile; 682 } 683 684 /** 685 * This message intends to inform the MemStore that next coming updates 686 * are going to be part of the replaying edits from WAL 687 */ 688 public void startReplayingFromWAL(){ 689 this.memstore.startReplayingFromWAL(); 690 } 691 692 /** 693 * This message intends to inform the MemStore that the replaying edits from WAL 694 * are done 695 */ 696 public void stopReplayingFromWAL(){ 697 this.memstore.stopReplayingFromWAL(); 698 } 699 700 /** 701 * Adds a value to the memstore 702 */ 703 public void add(final Cell cell, MemStoreSizing memstoreSizing) { 704 lock.readLock().lock(); 705 try { 706 this.memstore.add(cell, memstoreSizing); 707 } finally { 708 lock.readLock().unlock(); 709 } 710 } 711 712 /** 713 * Adds the specified value to the memstore 714 */ 715 public void add(final Iterable<Cell> cells, MemStoreSizing memstoreSizing) { 716 lock.readLock().lock(); 717 try { 718 memstore.add(cells, memstoreSizing); 719 } finally { 720 lock.readLock().unlock(); 721 } 722 } 723 724 @Override 725 public long timeOfOldestEdit() { 726 return memstore.timeOfOldestEdit(); 727 } 728 729 /** 730 * @return All store files. 731 */ 732 @Override 733 public Collection<HStoreFile> getStorefiles() { 734 return this.storeEngine.getStoreFileManager().getStorefiles(); 735 } 736 737 @Override 738 public Collection<HStoreFile> getCompactedFiles() { 739 return this.storeEngine.getStoreFileManager().getCompactedfiles(); 740 } 741 742 /** 743 * This throws a WrongRegionException if the HFile does not fit in this region, or an 744 * InvalidHFileException if the HFile is not valid. 745 */ 746 public void assertBulkLoadHFileOk(Path srcPath) throws IOException { 747 HFile.Reader reader = null; 748 try { 749 LOG.info("Validating hfile at " + srcPath + " for inclusion in " 750 + "store " + this + " region " + this.getRegionInfo().getRegionNameAsString()); 751 reader = HFile.createReader(srcPath.getFileSystem(conf), srcPath, cacheConf, 752 isPrimaryReplicaStore(), conf); 753 reader.loadFileInfo(); 754 755 Optional<byte[]> firstKey = reader.getFirstRowKey(); 756 Preconditions.checkState(firstKey.isPresent(), "First key can not be null"); 757 Optional<Cell> lk = reader.getLastKey(); 758 Preconditions.checkState(lk.isPresent(), "Last key can not be null"); 759 byte[] lastKey = CellUtil.cloneRow(lk.get()); 760 761 if (LOG.isDebugEnabled()) { 762 LOG.debug("HFile bounds: first=" + Bytes.toStringBinary(firstKey.get()) + 763 " last=" + Bytes.toStringBinary(lastKey)); 764 LOG.debug("Region bounds: first=" + 765 Bytes.toStringBinary(getRegionInfo().getStartKey()) + 766 " last=" + Bytes.toStringBinary(getRegionInfo().getEndKey())); 767 } 768 769 if (!this.getRegionInfo().containsRange(firstKey.get(), lastKey)) { 770 throw new WrongRegionException( 771 "Bulk load file " + srcPath.toString() + " does not fit inside region " 772 + this.getRegionInfo().getRegionNameAsString()); 773 } 774 775 if(reader.length() > conf.getLong(HConstants.HREGION_MAX_FILESIZE, 776 HConstants.DEFAULT_MAX_FILE_SIZE)) { 777 LOG.warn("Trying to bulk load hfile " + srcPath + " with size: " + 778 reader.length() + " bytes can be problematic as it may lead to oversplitting."); 779 } 780 781 if (verifyBulkLoads) { 782 long verificationStartTime = EnvironmentEdgeManager.currentTime(); 783 LOG.info("Full verification started for bulk load hfile: {}", srcPath); 784 Cell prevCell = null; 785 HFileScanner scanner = reader.getScanner(false, false, false); 786 scanner.seekTo(); 787 do { 788 Cell cell = scanner.getCell(); 789 if (prevCell != null) { 790 if (comparator.compareRows(prevCell, cell) > 0) { 791 throw new InvalidHFileException("Previous row is greater than" 792 + " current row: path=" + srcPath + " previous=" 793 + CellUtil.getCellKeyAsString(prevCell) + " current=" 794 + CellUtil.getCellKeyAsString(cell)); 795 } 796 if (CellComparator.getInstance().compareFamilies(prevCell, cell) != 0) { 797 throw new InvalidHFileException("Previous key had different" 798 + " family compared to current key: path=" + srcPath 799 + " previous=" 800 + Bytes.toStringBinary(prevCell.getFamilyArray(), prevCell.getFamilyOffset(), 801 prevCell.getFamilyLength()) 802 + " current=" 803 + Bytes.toStringBinary(cell.getFamilyArray(), cell.getFamilyOffset(), 804 cell.getFamilyLength())); 805 } 806 } 807 prevCell = cell; 808 } while (scanner.next()); 809 LOG.info("Full verification complete for bulk load hfile: " + srcPath.toString() 810 + " took " + (EnvironmentEdgeManager.currentTime() - verificationStartTime) 811 + " ms"); 812 } 813 } finally { 814 if (reader != null) reader.close(); 815 } 816 } 817 818 /** 819 * This method should only be called from Region. It is assumed that the ranges of values in the 820 * HFile fit within the stores assigned region. (assertBulkLoadHFileOk checks this) 821 * 822 * @param srcPathStr 823 * @param seqNum sequence Id associated with the HFile 824 */ 825 public Pair<Path, Path> preBulkLoadHFile(String srcPathStr, long seqNum) throws IOException { 826 Path srcPath = new Path(srcPathStr); 827 return fs.bulkLoadStoreFile(getColumnFamilyName(), srcPath, seqNum); 828 } 829 830 public Path bulkLoadHFile(byte[] family, String srcPathStr, Path dstPath) throws IOException { 831 Path srcPath = new Path(srcPathStr); 832 try { 833 fs.commitStoreFile(srcPath, dstPath); 834 } finally { 835 if (this.getCoprocessorHost() != null) { 836 this.getCoprocessorHost().postCommitStoreFile(family, srcPath, dstPath); 837 } 838 } 839 840 LOG.info("Loaded HFile " + srcPath + " into store '" + getColumnFamilyName() + "' as " 841 + dstPath + " - updating store file list."); 842 843 HStoreFile sf = createStoreFileAndReader(dstPath); 844 bulkLoadHFile(sf); 845 846 LOG.info("Successfully loaded store file {} into store {} (new location: {})", 847 srcPath, this, dstPath); 848 849 return dstPath; 850 } 851 852 public void bulkLoadHFile(StoreFileInfo fileInfo) throws IOException { 853 HStoreFile sf = createStoreFileAndReader(fileInfo); 854 bulkLoadHFile(sf); 855 } 856 857 private void bulkLoadHFile(HStoreFile sf) throws IOException { 858 StoreFileReader r = sf.getReader(); 859 this.storeSize.addAndGet(r.length()); 860 this.totalUncompressedBytes.addAndGet(r.getTotalUncompressedBytes()); 861 862 // Append the new storefile into the list 863 this.lock.writeLock().lock(); 864 try { 865 this.storeEngine.getStoreFileManager().insertNewFiles(Lists.newArrayList(sf)); 866 } finally { 867 // We need the lock, as long as we are updating the storeFiles 868 // or changing the memstore. Let us release it before calling 869 // notifyChangeReadersObservers. See HBASE-4485 for a possible 870 // deadlock scenario that could have happened if continue to hold 871 // the lock. 872 this.lock.writeLock().unlock(); 873 } 874 LOG.info("Loaded HFile " + sf.getFileInfo() + " into store '" + getColumnFamilyName()); 875 if (LOG.isTraceEnabled()) { 876 String traceMessage = "BULK LOAD time,size,store size,store files [" 877 + EnvironmentEdgeManager.currentTime() + "," + r.length() + "," + storeSize 878 + "," + storeEngine.getStoreFileManager().getStorefileCount() + "]"; 879 LOG.trace(traceMessage); 880 } 881 } 882 883 /** 884 * Close all the readers We don't need to worry about subsequent requests because the Region holds 885 * a write lock that will prevent any more reads or writes. 886 * @return the {@link StoreFile StoreFiles} that were previously being used. 887 * @throws IOException on failure 888 */ 889 public ImmutableCollection<HStoreFile> close() throws IOException { 890 this.archiveLock.lock(); 891 this.lock.writeLock().lock(); 892 try { 893 // Clear so metrics doesn't find them. 894 ImmutableCollection<HStoreFile> result = storeEngine.getStoreFileManager().clearFiles(); 895 Collection<HStoreFile> compactedfiles = 896 storeEngine.getStoreFileManager().clearCompactedFiles(); 897 // clear the compacted files 898 if (CollectionUtils.isNotEmpty(compactedfiles)) { 899 removeCompactedfiles(compactedfiles); 900 } 901 if (!result.isEmpty()) { 902 // initialize the thread pool for closing store files in parallel. 903 ThreadPoolExecutor storeFileCloserThreadPool = this.region 904 .getStoreFileOpenAndCloseThreadPool("StoreFileCloserThread-" 905 + this.getColumnFamilyName()); 906 907 // close each store file in parallel 908 CompletionService<Void> completionService = 909 new ExecutorCompletionService<>(storeFileCloserThreadPool); 910 for (HStoreFile f : result) { 911 completionService.submit(new Callable<Void>() { 912 @Override 913 public Void call() throws IOException { 914 boolean evictOnClose = 915 cacheConf != null? cacheConf.shouldEvictOnClose(): true; 916 f.closeStoreFile(evictOnClose); 917 return null; 918 } 919 }); 920 } 921 922 IOException ioe = null; 923 try { 924 for (int i = 0; i < result.size(); i++) { 925 try { 926 Future<Void> future = completionService.take(); 927 future.get(); 928 } catch (InterruptedException e) { 929 if (ioe == null) { 930 ioe = new InterruptedIOException(); 931 ioe.initCause(e); 932 } 933 } catch (ExecutionException e) { 934 if (ioe == null) ioe = new IOException(e.getCause()); 935 } 936 } 937 } finally { 938 storeFileCloserThreadPool.shutdownNow(); 939 } 940 if (ioe != null) throw ioe; 941 } 942 LOG.trace("Closed {}", this); 943 return result; 944 } finally { 945 this.lock.writeLock().unlock(); 946 this.archiveLock.unlock(); 947 } 948 } 949 950 /** 951 * Snapshot this stores memstore. Call before running 952 * {@link #flushCache(long, MemStoreSnapshot, MonitoredTask, ThroughputController, 953 * FlushLifeCycleTracker)} 954 * so it has some work to do. 955 */ 956 void snapshot() { 957 this.lock.writeLock().lock(); 958 try { 959 this.memstore.snapshot(); 960 } finally { 961 this.lock.writeLock().unlock(); 962 } 963 } 964 965 /** 966 * Write out current snapshot. Presumes {@link #snapshot()} has been called previously. 967 * @param logCacheFlushId flush sequence number 968 * @param snapshot 969 * @param status 970 * @param throughputController 971 * @return The path name of the tmp file to which the store was flushed 972 * @throws IOException if exception occurs during process 973 */ 974 protected List<Path> flushCache(final long logCacheFlushId, MemStoreSnapshot snapshot, 975 MonitoredTask status, ThroughputController throughputController, 976 FlushLifeCycleTracker tracker) throws IOException { 977 // If an exception happens flushing, we let it out without clearing 978 // the memstore snapshot. The old snapshot will be returned when we say 979 // 'snapshot', the next time flush comes around. 980 // Retry after catching exception when flushing, otherwise server will abort 981 // itself 982 StoreFlusher flusher = storeEngine.getStoreFlusher(); 983 IOException lastException = null; 984 for (int i = 0; i < flushRetriesNumber; i++) { 985 try { 986 List<Path> pathNames = 987 flusher.flushSnapshot(snapshot, logCacheFlushId, status, throughputController, tracker); 988 Path lastPathName = null; 989 try { 990 for (Path pathName : pathNames) { 991 lastPathName = pathName; 992 validateStoreFile(pathName); 993 } 994 return pathNames; 995 } catch (Exception e) { 996 LOG.warn("Failed validating store file {}, retrying num={}", lastPathName, i, e); 997 if (e instanceof IOException) { 998 lastException = (IOException) e; 999 } else { 1000 lastException = new IOException(e); 1001 } 1002 } 1003 } catch (IOException e) { 1004 LOG.warn("Failed flushing store file, retrying num={}", i, e); 1005 lastException = e; 1006 } 1007 if (lastException != null && i < (flushRetriesNumber - 1)) { 1008 try { 1009 Thread.sleep(pauseTime); 1010 } catch (InterruptedException e) { 1011 IOException iie = new InterruptedIOException(); 1012 iie.initCause(e); 1013 throw iie; 1014 } 1015 } 1016 } 1017 throw lastException; 1018 } 1019 1020 /** 1021 * @param path The pathname of the tmp file into which the store was flushed 1022 * @param logCacheFlushId 1023 * @param status 1024 * @return store file created. 1025 * @throws IOException 1026 */ 1027 private HStoreFile commitFile(Path path, long logCacheFlushId, MonitoredTask status) 1028 throws IOException { 1029 // Write-out finished successfully, move into the right spot 1030 Path dstPath = fs.commitStoreFile(getColumnFamilyName(), path); 1031 1032 status.setStatus("Flushing " + this + ": reopening flushed file"); 1033 HStoreFile sf = createStoreFileAndReader(dstPath); 1034 1035 StoreFileReader r = sf.getReader(); 1036 this.storeSize.addAndGet(r.length()); 1037 this.totalUncompressedBytes.addAndGet(r.getTotalUncompressedBytes()); 1038 1039 if (LOG.isInfoEnabled()) { 1040 LOG.info("Added " + sf + ", entries=" + r.getEntries() + 1041 ", sequenceid=" + logCacheFlushId + 1042 ", filesize=" + TraditionalBinaryPrefix.long2String(r.length(), "", 1)); 1043 } 1044 return sf; 1045 } 1046 1047 /** 1048 * @param maxKeyCount 1049 * @param compression Compression algorithm to use 1050 * @param isCompaction whether we are creating a new file in a compaction 1051 * @param includeMVCCReadpoint - whether to include MVCC or not 1052 * @param includesTag - includesTag or not 1053 * @return Writer for a new StoreFile in the tmp dir. 1054 */ 1055 // TODO : allow the Writer factory to create Writers of ShipperListener type only in case of 1056 // compaction 1057 public StoreFileWriter createWriterInTmp(long maxKeyCount, Compression.Algorithm compression, 1058 boolean isCompaction, boolean includeMVCCReadpoint, boolean includesTag, 1059 boolean shouldDropBehind) throws IOException { 1060 final CacheConfig writerCacheConf; 1061 if (isCompaction) { 1062 // Don't cache data on write on compactions. 1063 writerCacheConf = new CacheConfig(cacheConf); 1064 writerCacheConf.setCacheDataOnWrite(false); 1065 } else { 1066 writerCacheConf = cacheConf; 1067 } 1068 InetSocketAddress[] favoredNodes = null; 1069 if (region.getRegionServerServices() != null) { 1070 favoredNodes = region.getRegionServerServices().getFavoredNodesForRegion( 1071 region.getRegionInfo().getEncodedName()); 1072 } 1073 HFileContext hFileContext = createFileContext(compression, includeMVCCReadpoint, includesTag, 1074 cryptoContext); 1075 Path familyTempDir = new Path(fs.getTempDir(), family.getNameAsString()); 1076 StoreFileWriter.Builder builder = new StoreFileWriter.Builder(conf, writerCacheConf, 1077 this.getFileSystem()) 1078 .withOutputDir(familyTempDir) 1079 .withComparator(comparator) 1080 .withBloomType(family.getBloomFilterType()) 1081 .withMaxKeyCount(maxKeyCount) 1082 .withFavoredNodes(favoredNodes) 1083 .withFileContext(hFileContext) 1084 .withShouldDropCacheBehind(shouldDropBehind); 1085 return builder.build(); 1086 } 1087 1088 private HFileContext createFileContext(Compression.Algorithm compression, 1089 boolean includeMVCCReadpoint, boolean includesTag, Encryption.Context cryptoContext) { 1090 if (compression == null) { 1091 compression = HFile.DEFAULT_COMPRESSION_ALGORITHM; 1092 } 1093 HFileContext hFileContext = new HFileContextBuilder() 1094 .withIncludesMvcc(includeMVCCReadpoint) 1095 .withIncludesTags(includesTag) 1096 .withCompression(compression) 1097 .withCompressTags(family.isCompressTags()) 1098 .withChecksumType(checksumType) 1099 .withBytesPerCheckSum(bytesPerChecksum) 1100 .withBlockSize(blocksize) 1101 .withHBaseCheckSum(true) 1102 .withDataBlockEncoding(family.getDataBlockEncoding()) 1103 .withEncryptionContext(cryptoContext) 1104 .withCreateTime(EnvironmentEdgeManager.currentTime()) 1105 .build(); 1106 return hFileContext; 1107 } 1108 1109 1110 private long getTotalSize(Collection<HStoreFile> sfs) { 1111 return sfs.stream().mapToLong(sf -> sf.getReader().length()).sum(); 1112 } 1113 1114 /** 1115 * Change storeFiles adding into place the Reader produced by this new flush. 1116 * @param sfs Store files 1117 * @param snapshotId 1118 * @throws IOException 1119 * @return Whether compaction is required. 1120 */ 1121 private boolean updateStorefiles(List<HStoreFile> sfs, long snapshotId) throws IOException { 1122 this.lock.writeLock().lock(); 1123 try { 1124 this.storeEngine.getStoreFileManager().insertNewFiles(sfs); 1125 if (snapshotId > 0) { 1126 this.memstore.clearSnapshot(snapshotId); 1127 } 1128 } finally { 1129 // We need the lock, as long as we are updating the storeFiles 1130 // or changing the memstore. Let us release it before calling 1131 // notifyChangeReadersObservers. See HBASE-4485 for a possible 1132 // deadlock scenario that could have happened if continue to hold 1133 // the lock. 1134 this.lock.writeLock().unlock(); 1135 } 1136 // notify to be called here - only in case of flushes 1137 notifyChangedReadersObservers(sfs); 1138 if (LOG.isTraceEnabled()) { 1139 long totalSize = getTotalSize(sfs); 1140 String traceMessage = "FLUSH time,count,size,store size,store files [" 1141 + EnvironmentEdgeManager.currentTime() + "," + sfs.size() + "," + totalSize 1142 + "," + storeSize + "," + storeEngine.getStoreFileManager().getStorefileCount() + "]"; 1143 LOG.trace(traceMessage); 1144 } 1145 return needsCompaction(); 1146 } 1147 1148 /** 1149 * Notify all observers that set of Readers has changed. 1150 * @throws IOException 1151 */ 1152 private void notifyChangedReadersObservers(List<HStoreFile> sfs) throws IOException { 1153 for (ChangedReadersObserver o : this.changedReaderObservers) { 1154 List<KeyValueScanner> memStoreScanners; 1155 this.lock.readLock().lock(); 1156 try { 1157 memStoreScanners = this.memstore.getScanners(o.getReadPoint()); 1158 } finally { 1159 this.lock.readLock().unlock(); 1160 } 1161 o.updateReaders(sfs, memStoreScanners); 1162 } 1163 } 1164 1165 /** 1166 * Get all scanners with no filtering based on TTL (that happens further down the line). 1167 * @param cacheBlocks cache the blocks or not 1168 * @param usePread true to use pread, false if not 1169 * @param isCompaction true if the scanner is created for compaction 1170 * @param matcher the scan query matcher 1171 * @param startRow the start row 1172 * @param stopRow the stop row 1173 * @param readPt the read point of the current scan 1174 * @return all scanners for this store 1175 */ 1176 public List<KeyValueScanner> getScanners(boolean cacheBlocks, boolean isGet, boolean usePread, 1177 boolean isCompaction, ScanQueryMatcher matcher, byte[] startRow, byte[] stopRow, long readPt) 1178 throws IOException { 1179 return getScanners(cacheBlocks, usePread, isCompaction, matcher, startRow, true, stopRow, false, 1180 readPt); 1181 } 1182 1183 /** 1184 * Get all scanners with no filtering based on TTL (that happens further down the line). 1185 * @param cacheBlocks cache the blocks or not 1186 * @param usePread true to use pread, false if not 1187 * @param isCompaction true if the scanner is created for compaction 1188 * @param matcher the scan query matcher 1189 * @param startRow the start row 1190 * @param includeStartRow true to include start row, false if not 1191 * @param stopRow the stop row 1192 * @param includeStopRow true to include stop row, false if not 1193 * @param readPt the read point of the current scan 1194 * @return all scanners for this store 1195 */ 1196 public List<KeyValueScanner> getScanners(boolean cacheBlocks, boolean usePread, 1197 boolean isCompaction, ScanQueryMatcher matcher, byte[] startRow, boolean includeStartRow, 1198 byte[] stopRow, boolean includeStopRow, long readPt) throws IOException { 1199 Collection<HStoreFile> storeFilesToScan; 1200 List<KeyValueScanner> memStoreScanners; 1201 this.lock.readLock().lock(); 1202 try { 1203 storeFilesToScan = this.storeEngine.getStoreFileManager().getFilesForScan(startRow, 1204 includeStartRow, stopRow, includeStopRow); 1205 memStoreScanners = this.memstore.getScanners(readPt); 1206 } finally { 1207 this.lock.readLock().unlock(); 1208 } 1209 1210 // First the store file scanners 1211 1212 // TODO this used to get the store files in descending order, 1213 // but now we get them in ascending order, which I think is 1214 // actually more correct, since memstore get put at the end. 1215 List<StoreFileScanner> sfScanners = StoreFileScanner.getScannersForStoreFiles(storeFilesToScan, 1216 cacheBlocks, usePread, isCompaction, false, matcher, readPt); 1217 List<KeyValueScanner> scanners = new ArrayList<>(sfScanners.size() + 1); 1218 scanners.addAll(sfScanners); 1219 // Then the memstore scanners 1220 scanners.addAll(memStoreScanners); 1221 return scanners; 1222 } 1223 1224 /** 1225 * Create scanners on the given files and if needed on the memstore with no filtering based on TTL 1226 * (that happens further down the line). 1227 * @param files the list of files on which the scanners has to be created 1228 * @param cacheBlocks cache the blocks or not 1229 * @param usePread true to use pread, false if not 1230 * @param isCompaction true if the scanner is created for compaction 1231 * @param matcher the scan query matcher 1232 * @param startRow the start row 1233 * @param stopRow the stop row 1234 * @param readPt the read point of the current scan 1235 * @param includeMemstoreScanner true if memstore has to be included 1236 * @return scanners on the given files and on the memstore if specified 1237 */ 1238 public List<KeyValueScanner> getScanners(List<HStoreFile> files, boolean cacheBlocks, 1239 boolean isGet, boolean usePread, boolean isCompaction, ScanQueryMatcher matcher, 1240 byte[] startRow, byte[] stopRow, long readPt, boolean includeMemstoreScanner) 1241 throws IOException { 1242 return getScanners(files, cacheBlocks, usePread, isCompaction, matcher, startRow, true, stopRow, 1243 false, readPt, includeMemstoreScanner); 1244 } 1245 1246 /** 1247 * Create scanners on the given files and if needed on the memstore with no filtering based on TTL 1248 * (that happens further down the line). 1249 * @param files the list of files on which the scanners has to be created 1250 * @param cacheBlocks ache the blocks or not 1251 * @param usePread true to use pread, false if not 1252 * @param isCompaction true if the scanner is created for compaction 1253 * @param matcher the scan query matcher 1254 * @param startRow the start row 1255 * @param includeStartRow true to include start row, false if not 1256 * @param stopRow the stop row 1257 * @param includeStopRow true to include stop row, false if not 1258 * @param readPt the read point of the current scan 1259 * @param includeMemstoreScanner true if memstore has to be included 1260 * @return scanners on the given files and on the memstore if specified 1261 */ 1262 public List<KeyValueScanner> getScanners(List<HStoreFile> files, boolean cacheBlocks, 1263 boolean usePread, boolean isCompaction, ScanQueryMatcher matcher, byte[] startRow, 1264 boolean includeStartRow, byte[] stopRow, boolean includeStopRow, long readPt, 1265 boolean includeMemstoreScanner) throws IOException { 1266 List<KeyValueScanner> memStoreScanners = null; 1267 if (includeMemstoreScanner) { 1268 this.lock.readLock().lock(); 1269 try { 1270 memStoreScanners = this.memstore.getScanners(readPt); 1271 } finally { 1272 this.lock.readLock().unlock(); 1273 } 1274 } 1275 List<StoreFileScanner> sfScanners = StoreFileScanner.getScannersForStoreFiles(files, 1276 cacheBlocks, usePread, isCompaction, false, matcher, readPt); 1277 List<KeyValueScanner> scanners = new ArrayList<>(sfScanners.size() + 1); 1278 scanners.addAll(sfScanners); 1279 // Then the memstore scanners 1280 if (memStoreScanners != null) { 1281 scanners.addAll(memStoreScanners); 1282 } 1283 return scanners; 1284 } 1285 1286 /** 1287 * @param o Observer who wants to know about changes in set of Readers 1288 */ 1289 public void addChangedReaderObserver(ChangedReadersObserver o) { 1290 this.changedReaderObservers.add(o); 1291 } 1292 1293 /** 1294 * @param o Observer no longer interested in changes in set of Readers. 1295 */ 1296 public void deleteChangedReaderObserver(ChangedReadersObserver o) { 1297 // We don't check if observer present; it may not be (legitimately) 1298 this.changedReaderObservers.remove(o); 1299 } 1300 1301 ////////////////////////////////////////////////////////////////////////////// 1302 // Compaction 1303 ////////////////////////////////////////////////////////////////////////////// 1304 1305 /** 1306 * Compact the StoreFiles. This method may take some time, so the calling 1307 * thread must be able to block for long periods. 1308 * 1309 * <p>During this time, the Store can work as usual, getting values from 1310 * StoreFiles and writing new StoreFiles from the memstore. 1311 * 1312 * Existing StoreFiles are not destroyed until the new compacted StoreFile is 1313 * completely written-out to disk. 1314 * 1315 * <p>The compactLock prevents multiple simultaneous compactions. 1316 * The structureLock prevents us from interfering with other write operations. 1317 * 1318 * <p>We don't want to hold the structureLock for the whole time, as a compact() 1319 * can be lengthy and we want to allow cache-flushes during this period. 1320 * 1321 * <p> Compaction event should be idempotent, since there is no IO Fencing for 1322 * the region directory in hdfs. A region server might still try to complete the 1323 * compaction after it lost the region. That is why the following events are carefully 1324 * ordered for a compaction: 1325 * 1. Compaction writes new files under region/.tmp directory (compaction output) 1326 * 2. Compaction atomically moves the temporary file under region directory 1327 * 3. Compaction appends a WAL edit containing the compaction input and output files. 1328 * Forces sync on WAL. 1329 * 4. Compaction deletes the input files from the region directory. 1330 * 1331 * Failure conditions are handled like this: 1332 * - If RS fails before 2, compaction wont complete. Even if RS lives on and finishes 1333 * the compaction later, it will only write the new data file to the region directory. 1334 * Since we already have this data, this will be idempotent but we will have a redundant 1335 * copy of the data. 1336 * - If RS fails between 2 and 3, the region will have a redundant copy of the data. The 1337 * RS that failed won't be able to finish snyc() for WAL because of lease recovery in WAL. 1338 * - If RS fails after 3, the region region server who opens the region will pick up the 1339 * the compaction marker from the WAL and replay it by removing the compaction input files. 1340 * Failed RS can also attempt to delete those files, but the operation will be idempotent 1341 * 1342 * See HBASE-2231 for details. 1343 * 1344 * @param compaction compaction details obtained from requestCompaction() 1345 * @throws IOException 1346 * @return Storefile we compacted into or null if we failed or opted out early. 1347 */ 1348 public List<HStoreFile> compact(CompactionContext compaction, 1349 ThroughputController throughputController, User user) throws IOException { 1350 assert compaction != null; 1351 List<HStoreFile> sfs = null; 1352 CompactionRequestImpl cr = compaction.getRequest(); 1353 try { 1354 // Do all sanity checking in here if we have a valid CompactionRequestImpl 1355 // because we need to clean up after it on the way out in a finally 1356 // block below 1357 long compactionStartTime = EnvironmentEdgeManager.currentTime(); 1358 assert compaction.hasSelection(); 1359 Collection<HStoreFile> filesToCompact = cr.getFiles(); 1360 assert !filesToCompact.isEmpty(); 1361 synchronized (filesCompacting) { 1362 // sanity check: we're compacting files that this store knows about 1363 // TODO: change this to LOG.error() after more debugging 1364 Preconditions.checkArgument(filesCompacting.containsAll(filesToCompact)); 1365 } 1366 1367 // Ready to go. Have list of files to compact. 1368 LOG.info("Starting compaction of " + filesToCompact + 1369 " into tmpdir=" + fs.getTempDir() + ", totalSize=" + 1370 TraditionalBinaryPrefix.long2String(cr.getSize(), "", 1)); 1371 1372 return doCompaction(cr, filesToCompact, user, compactionStartTime, 1373 compaction.compact(throughputController, user)); 1374 } finally { 1375 finishCompactionRequest(cr); 1376 } 1377 } 1378 1379 @VisibleForTesting 1380 protected List<HStoreFile> doCompaction(CompactionRequestImpl cr, 1381 Collection<HStoreFile> filesToCompact, User user, long compactionStartTime, 1382 List<Path> newFiles) throws IOException { 1383 // Do the steps necessary to complete the compaction. 1384 List<HStoreFile> sfs = moveCompactedFilesIntoPlace(cr, newFiles, user); 1385 writeCompactionWalRecord(filesToCompact, sfs); 1386 replaceStoreFiles(filesToCompact, sfs); 1387 if (cr.isMajor()) { 1388 majorCompactedCellsCount.addAndGet(getCompactionProgress().getTotalCompactingKVs()); 1389 majorCompactedCellsSize.addAndGet(getCompactionProgress().totalCompactedSize); 1390 } else { 1391 compactedCellsCount.addAndGet(getCompactionProgress().getTotalCompactingKVs()); 1392 compactedCellsSize.addAndGet(getCompactionProgress().totalCompactedSize); 1393 } 1394 long outputBytes = getTotalSize(sfs); 1395 1396 // At this point the store will use new files for all new scanners. 1397 completeCompaction(filesToCompact); // update store size. 1398 1399 long now = EnvironmentEdgeManager.currentTime(); 1400 if (region.getRegionServerServices() != null 1401 && region.getRegionServerServices().getMetrics() != null) { 1402 region.getRegionServerServices().getMetrics().updateCompaction(cr.isMajor(), 1403 now - compactionStartTime, cr.getFiles().size(), newFiles.size(), cr.getSize(), 1404 outputBytes); 1405 } 1406 1407 logCompactionEndMessage(cr, sfs, now, compactionStartTime); 1408 return sfs; 1409 } 1410 1411 private List<HStoreFile> moveCompactedFilesIntoPlace(CompactionRequestImpl cr, List<Path> newFiles, 1412 User user) throws IOException { 1413 List<HStoreFile> sfs = new ArrayList<>(newFiles.size()); 1414 for (Path newFile : newFiles) { 1415 assert newFile != null; 1416 HStoreFile sf = moveFileIntoPlace(newFile); 1417 if (this.getCoprocessorHost() != null) { 1418 getCoprocessorHost().postCompact(this, sf, cr.getTracker(), cr, user); 1419 } 1420 assert sf != null; 1421 sfs.add(sf); 1422 } 1423 return sfs; 1424 } 1425 1426 // Package-visible for tests 1427 HStoreFile moveFileIntoPlace(Path newFile) throws IOException { 1428 validateStoreFile(newFile); 1429 // Move the file into the right spot 1430 Path destPath = fs.commitStoreFile(getColumnFamilyName(), newFile); 1431 return createStoreFileAndReader(destPath); 1432 } 1433 1434 /** 1435 * Writes the compaction WAL record. 1436 * @param filesCompacted Files compacted (input). 1437 * @param newFiles Files from compaction. 1438 */ 1439 private void writeCompactionWalRecord(Collection<HStoreFile> filesCompacted, 1440 Collection<HStoreFile> newFiles) throws IOException { 1441 if (region.getWAL() == null) { 1442 return; 1443 } 1444 List<Path> inputPaths = 1445 filesCompacted.stream().map(HStoreFile::getPath).collect(Collectors.toList()); 1446 List<Path> outputPaths = 1447 newFiles.stream().map(HStoreFile::getPath).collect(Collectors.toList()); 1448 RegionInfo info = this.region.getRegionInfo(); 1449 CompactionDescriptor compactionDescriptor = ProtobufUtil.toCompactionDescriptor(info, 1450 family.getName(), inputPaths, outputPaths, fs.getStoreDir(getColumnFamilyDescriptor().getNameAsString())); 1451 // Fix reaching into Region to get the maxWaitForSeqId. 1452 // Does this method belong in Region altogether given it is making so many references up there? 1453 // Could be Region#writeCompactionMarker(compactionDescriptor); 1454 WALUtil.writeCompactionMarker(this.region.getWAL(), this.region.getReplicationScope(), 1455 this.region.getRegionInfo(), compactionDescriptor, this.region.getMVCC()); 1456 } 1457 1458 @VisibleForTesting 1459 void replaceStoreFiles(Collection<HStoreFile> compactedFiles, Collection<HStoreFile> result) 1460 throws IOException { 1461 this.lock.writeLock().lock(); 1462 try { 1463 this.storeEngine.getStoreFileManager().addCompactionResults(compactedFiles, result); 1464 synchronized (filesCompacting) { 1465 filesCompacting.removeAll(compactedFiles); 1466 } 1467 } finally { 1468 this.lock.writeLock().unlock(); 1469 } 1470 } 1471 1472 /** 1473 * Log a very elaborate compaction completion message. 1474 * @param cr Request. 1475 * @param sfs Resulting files. 1476 * @param compactionStartTime Start time. 1477 */ 1478 private void logCompactionEndMessage( 1479 CompactionRequestImpl cr, List<HStoreFile> sfs, long now, long compactionStartTime) { 1480 StringBuilder message = new StringBuilder( 1481 "Completed" + (cr.isMajor() ? " major" : "") + " compaction of " 1482 + cr.getFiles().size() + (cr.isAllFiles() ? " (all)" : "") + " file(s) in " 1483 + this + " of " + this.getRegionInfo().getShortNameToLog() + " into "); 1484 if (sfs.isEmpty()) { 1485 message.append("none, "); 1486 } else { 1487 for (HStoreFile sf: sfs) { 1488 message.append(sf.getPath().getName()); 1489 message.append("(size="); 1490 message.append(TraditionalBinaryPrefix.long2String(sf.getReader().length(), "", 1)); 1491 message.append("), "); 1492 } 1493 } 1494 message.append("total size for store is ") 1495 .append(StringUtils.TraditionalBinaryPrefix.long2String(storeSize.get(), "", 1)) 1496 .append(". This selection was in queue for ") 1497 .append(StringUtils.formatTimeDiff(compactionStartTime, cr.getSelectionTime())) 1498 .append(", and took ").append(StringUtils.formatTimeDiff(now, compactionStartTime)) 1499 .append(" to execute."); 1500 LOG.info(message.toString()); 1501 if (LOG.isTraceEnabled()) { 1502 int fileCount = storeEngine.getStoreFileManager().getStorefileCount(); 1503 long resultSize = getTotalSize(sfs); 1504 String traceMessage = "COMPACTION start,end,size out,files in,files out,store size," 1505 + "store files [" + compactionStartTime + "," + now + "," + resultSize + "," 1506 + cr.getFiles().size() + "," + sfs.size() + "," + storeSize + "," + fileCount + "]"; 1507 LOG.trace(traceMessage); 1508 } 1509 } 1510 1511 /** 1512 * Call to complete a compaction. Its for the case where we find in the WAL a compaction 1513 * that was not finished. We could find one recovering a WAL after a regionserver crash. 1514 * See HBASE-2231. 1515 * @param compaction 1516 */ 1517 public void replayCompactionMarker(CompactionDescriptor compaction, boolean pickCompactionFiles, 1518 boolean removeFiles) throws IOException { 1519 LOG.debug("Completing compaction from the WAL marker"); 1520 List<String> compactionInputs = compaction.getCompactionInputList(); 1521 List<String> compactionOutputs = Lists.newArrayList(compaction.getCompactionOutputList()); 1522 1523 // The Compaction Marker is written after the compaction is completed, 1524 // and the files moved into the region/family folder. 1525 // 1526 // If we crash after the entry is written, we may not have removed the 1527 // input files, but the output file is present. 1528 // (The unremoved input files will be removed by this function) 1529 // 1530 // If we scan the directory and the file is not present, it can mean that: 1531 // - The file was manually removed by the user 1532 // - The file was removed as consequence of subsequent compaction 1533 // so, we can't do anything with the "compaction output list" because those 1534 // files have already been loaded when opening the region (by virtue of 1535 // being in the store's folder) or they may be missing due to a compaction. 1536 1537 String familyName = this.getColumnFamilyName(); 1538 Set<String> inputFiles = new HashSet<>(); 1539 for (String compactionInput : compactionInputs) { 1540 Path inputPath = fs.getStoreFilePath(familyName, compactionInput); 1541 inputFiles.add(inputPath.getName()); 1542 } 1543 1544 //some of the input files might already be deleted 1545 List<HStoreFile> inputStoreFiles = new ArrayList<>(compactionInputs.size()); 1546 for (HStoreFile sf : this.getStorefiles()) { 1547 if (inputFiles.contains(sf.getPath().getName())) { 1548 inputStoreFiles.add(sf); 1549 } 1550 } 1551 1552 // check whether we need to pick up the new files 1553 List<HStoreFile> outputStoreFiles = new ArrayList<>(compactionOutputs.size()); 1554 1555 if (pickCompactionFiles) { 1556 for (HStoreFile sf : this.getStorefiles()) { 1557 compactionOutputs.remove(sf.getPath().getName()); 1558 } 1559 for (String compactionOutput : compactionOutputs) { 1560 StoreFileInfo storeFileInfo = fs.getStoreFileInfo(getColumnFamilyName(), compactionOutput); 1561 HStoreFile storeFile = createStoreFileAndReader(storeFileInfo); 1562 outputStoreFiles.add(storeFile); 1563 } 1564 } 1565 1566 if (!inputStoreFiles.isEmpty() || !outputStoreFiles.isEmpty()) { 1567 LOG.info("Replaying compaction marker, replacing input files: " + 1568 inputStoreFiles + " with output files : " + outputStoreFiles); 1569 this.replaceStoreFiles(inputStoreFiles, outputStoreFiles); 1570 this.completeCompaction(inputStoreFiles); 1571 } 1572 } 1573 1574 /** 1575 * This method tries to compact N recent files for testing. 1576 * Note that because compacting "recent" files only makes sense for some policies, 1577 * e.g. the default one, it assumes default policy is used. It doesn't use policy, 1578 * but instead makes a compaction candidate list by itself. 1579 * @param N Number of files. 1580 */ 1581 @VisibleForTesting 1582 public void compactRecentForTestingAssumingDefaultPolicy(int N) throws IOException { 1583 List<HStoreFile> filesToCompact; 1584 boolean isMajor; 1585 1586 this.lock.readLock().lock(); 1587 try { 1588 synchronized (filesCompacting) { 1589 filesToCompact = Lists.newArrayList(storeEngine.getStoreFileManager().getStorefiles()); 1590 if (!filesCompacting.isEmpty()) { 1591 // exclude all files older than the newest file we're currently 1592 // compacting. this allows us to preserve contiguity (HBASE-2856) 1593 HStoreFile last = filesCompacting.get(filesCompacting.size() - 1); 1594 int idx = filesToCompact.indexOf(last); 1595 Preconditions.checkArgument(idx != -1); 1596 filesToCompact.subList(0, idx + 1).clear(); 1597 } 1598 int count = filesToCompact.size(); 1599 if (N > count) { 1600 throw new RuntimeException("Not enough files"); 1601 } 1602 1603 filesToCompact = filesToCompact.subList(count - N, count); 1604 isMajor = (filesToCompact.size() == storeEngine.getStoreFileManager().getStorefileCount()); 1605 filesCompacting.addAll(filesToCompact); 1606 Collections.sort(filesCompacting, storeEngine.getStoreFileManager() 1607 .getStoreFileComparator()); 1608 } 1609 } finally { 1610 this.lock.readLock().unlock(); 1611 } 1612 1613 try { 1614 // Ready to go. Have list of files to compact. 1615 List<Path> newFiles = ((DefaultCompactor)this.storeEngine.getCompactor()) 1616 .compactForTesting(filesToCompact, isMajor); 1617 for (Path newFile: newFiles) { 1618 // Move the compaction into place. 1619 HStoreFile sf = moveFileIntoPlace(newFile); 1620 if (this.getCoprocessorHost() != null) { 1621 this.getCoprocessorHost().postCompact(this, sf, null, null, null); 1622 } 1623 replaceStoreFiles(filesToCompact, Collections.singletonList(sf)); 1624 completeCompaction(filesToCompact); 1625 } 1626 } finally { 1627 synchronized (filesCompacting) { 1628 filesCompacting.removeAll(filesToCompact); 1629 } 1630 } 1631 } 1632 1633 @Override 1634 public boolean hasReferences() { 1635 return StoreUtils.hasReferences(this.storeEngine.getStoreFileManager().getStorefiles()); 1636 } 1637 1638 /** 1639 * getter for CompactionProgress object 1640 * @return CompactionProgress object; can be null 1641 */ 1642 public CompactionProgress getCompactionProgress() { 1643 return this.storeEngine.getCompactor().getProgress(); 1644 } 1645 1646 @Override 1647 public boolean shouldPerformMajorCompaction() throws IOException { 1648 for (HStoreFile sf : this.storeEngine.getStoreFileManager().getStorefiles()) { 1649 // TODO: what are these reader checks all over the place? 1650 if (sf.getReader() == null) { 1651 LOG.debug("StoreFile {} has null Reader", sf); 1652 return false; 1653 } 1654 } 1655 return storeEngine.getCompactionPolicy().shouldPerformMajorCompaction( 1656 this.storeEngine.getStoreFileManager().getStorefiles()); 1657 } 1658 1659 public Optional<CompactionContext> requestCompaction() throws IOException { 1660 return requestCompaction(NO_PRIORITY, CompactionLifeCycleTracker.DUMMY, null); 1661 } 1662 1663 public Optional<CompactionContext> requestCompaction(int priority, 1664 CompactionLifeCycleTracker tracker, User user) throws IOException { 1665 // don't even select for compaction if writes are disabled 1666 if (!this.areWritesEnabled()) { 1667 return Optional.empty(); 1668 } 1669 // Before we do compaction, try to get rid of unneeded files to simplify things. 1670 removeUnneededFiles(); 1671 1672 final CompactionContext compaction = storeEngine.createCompaction(); 1673 CompactionRequestImpl request = null; 1674 this.lock.readLock().lock(); 1675 try { 1676 synchronized (filesCompacting) { 1677 // First, see if coprocessor would want to override selection. 1678 if (this.getCoprocessorHost() != null) { 1679 final List<HStoreFile> candidatesForCoproc = compaction.preSelect(this.filesCompacting); 1680 boolean override = getCoprocessorHost().preCompactSelection(this, 1681 candidatesForCoproc, tracker, user); 1682 if (override) { 1683 // Coprocessor is overriding normal file selection. 1684 compaction.forceSelect(new CompactionRequestImpl(candidatesForCoproc)); 1685 } 1686 } 1687 1688 // Normal case - coprocessor is not overriding file selection. 1689 if (!compaction.hasSelection()) { 1690 boolean isUserCompaction = priority == Store.PRIORITY_USER; 1691 boolean mayUseOffPeak = offPeakHours.isOffPeakHour() && 1692 offPeakCompactionTracker.compareAndSet(false, true); 1693 try { 1694 compaction.select(this.filesCompacting, isUserCompaction, 1695 mayUseOffPeak, forceMajor && filesCompacting.isEmpty()); 1696 } catch (IOException e) { 1697 if (mayUseOffPeak) { 1698 offPeakCompactionTracker.set(false); 1699 } 1700 throw e; 1701 } 1702 assert compaction.hasSelection(); 1703 if (mayUseOffPeak && !compaction.getRequest().isOffPeak()) { 1704 // Compaction policy doesn't want to take advantage of off-peak. 1705 offPeakCompactionTracker.set(false); 1706 } 1707 } 1708 if (this.getCoprocessorHost() != null) { 1709 this.getCoprocessorHost().postCompactSelection( 1710 this, ImmutableList.copyOf(compaction.getRequest().getFiles()), tracker, 1711 compaction.getRequest(), user); 1712 } 1713 // Finally, we have the resulting files list. Check if we have any files at all. 1714 request = compaction.getRequest(); 1715 Collection<HStoreFile> selectedFiles = request.getFiles(); 1716 if (selectedFiles.isEmpty()) { 1717 return Optional.empty(); 1718 } 1719 1720 addToCompactingFiles(selectedFiles); 1721 1722 // If we're enqueuing a major, clear the force flag. 1723 this.forceMajor = this.forceMajor && !request.isMajor(); 1724 1725 // Set common request properties. 1726 // Set priority, either override value supplied by caller or from store. 1727 request.setPriority((priority != Store.NO_PRIORITY) ? priority : getCompactPriority()); 1728 request.setDescription(getRegionInfo().getRegionNameAsString(), getColumnFamilyName()); 1729 request.setTracker(tracker); 1730 } 1731 } finally { 1732 this.lock.readLock().unlock(); 1733 } 1734 1735 if (LOG.isDebugEnabled()) { 1736 LOG.debug(getRegionInfo().getEncodedName() + " - " + getColumnFamilyName() 1737 + ": Initiating " + (request.isMajor() ? "major" : "minor") + " compaction" 1738 + (request.isAllFiles() ? " (all files)" : "")); 1739 } 1740 this.region.reportCompactionRequestStart(request.isMajor()); 1741 return Optional.of(compaction); 1742 } 1743 1744 /** Adds the files to compacting files. filesCompacting must be locked. */ 1745 private void addToCompactingFiles(Collection<HStoreFile> filesToAdd) { 1746 if (CollectionUtils.isEmpty(filesToAdd)) { 1747 return; 1748 } 1749 // Check that we do not try to compact the same StoreFile twice. 1750 if (!Collections.disjoint(filesCompacting, filesToAdd)) { 1751 Preconditions.checkArgument(false, "%s overlaps with %s", filesToAdd, filesCompacting); 1752 } 1753 filesCompacting.addAll(filesToAdd); 1754 Collections.sort(filesCompacting, storeEngine.getStoreFileManager().getStoreFileComparator()); 1755 } 1756 1757 private void removeUnneededFiles() throws IOException { 1758 if (!conf.getBoolean("hbase.store.delete.expired.storefile", true)) return; 1759 if (getColumnFamilyDescriptor().getMinVersions() > 0) { 1760 LOG.debug("Skipping expired store file removal due to min version being {}", 1761 getColumnFamilyDescriptor().getMinVersions()); 1762 return; 1763 } 1764 this.lock.readLock().lock(); 1765 Collection<HStoreFile> delSfs = null; 1766 try { 1767 synchronized (filesCompacting) { 1768 long cfTtl = getStoreFileTtl(); 1769 if (cfTtl != Long.MAX_VALUE) { 1770 delSfs = storeEngine.getStoreFileManager().getUnneededFiles( 1771 EnvironmentEdgeManager.currentTime() - cfTtl, filesCompacting); 1772 addToCompactingFiles(delSfs); 1773 } 1774 } 1775 } finally { 1776 this.lock.readLock().unlock(); 1777 } 1778 1779 if (CollectionUtils.isEmpty(delSfs)) { 1780 return; 1781 } 1782 1783 Collection<HStoreFile> newFiles = Collections.emptyList(); // No new files. 1784 writeCompactionWalRecord(delSfs, newFiles); 1785 replaceStoreFiles(delSfs, newFiles); 1786 completeCompaction(delSfs); 1787 LOG.info("Completed removal of " + delSfs.size() + " unnecessary (expired) file(s) in " 1788 + this + " of " + this.getRegionInfo().getRegionNameAsString() 1789 + "; total size for store is " 1790 + TraditionalBinaryPrefix.long2String(storeSize.get(), "", 1)); 1791 } 1792 1793 public void cancelRequestedCompaction(CompactionContext compaction) { 1794 finishCompactionRequest(compaction.getRequest()); 1795 } 1796 1797 private void finishCompactionRequest(CompactionRequestImpl cr) { 1798 this.region.reportCompactionRequestEnd(cr.isMajor(), cr.getFiles().size(), cr.getSize()); 1799 if (cr.isOffPeak()) { 1800 offPeakCompactionTracker.set(false); 1801 cr.setOffPeak(false); 1802 } 1803 synchronized (filesCompacting) { 1804 filesCompacting.removeAll(cr.getFiles()); 1805 } 1806 } 1807 1808 /** 1809 * Validates a store file by opening and closing it. In HFileV2 this should not be an expensive 1810 * operation. 1811 * @param path the path to the store file 1812 */ 1813 private void validateStoreFile(Path path) throws IOException { 1814 HStoreFile storeFile = null; 1815 try { 1816 storeFile = createStoreFileAndReader(path); 1817 } catch (IOException e) { 1818 LOG.error("Failed to open store file : {}, keeping it in tmp location", path, e); 1819 throw e; 1820 } finally { 1821 if (storeFile != null) { 1822 storeFile.closeStoreFile(false); 1823 } 1824 } 1825 } 1826 1827 /** 1828 * <p>It works by processing a compaction that's been written to disk. 1829 * 1830 * <p>It is usually invoked at the end of a compaction, but might also be 1831 * invoked at HStore startup, if the prior execution died midway through. 1832 * 1833 * <p>Moving the compacted TreeMap into place means: 1834 * <pre> 1835 * 1) Unload all replaced StoreFile, close and collect list to delete. 1836 * 2) Compute new store size 1837 * </pre> 1838 * 1839 * @param compactedFiles list of files that were compacted 1840 */ 1841 @VisibleForTesting 1842 protected void completeCompaction(Collection<HStoreFile> compactedFiles) 1843 throws IOException { 1844 this.storeSize.set(0L); 1845 this.totalUncompressedBytes.set(0L); 1846 for (HStoreFile hsf : this.storeEngine.getStoreFileManager().getStorefiles()) { 1847 StoreFileReader r = hsf.getReader(); 1848 if (r == null) { 1849 LOG.warn("StoreFile {} has a null Reader", hsf); 1850 continue; 1851 } 1852 this.storeSize.addAndGet(r.length()); 1853 this.totalUncompressedBytes.addAndGet(r.getTotalUncompressedBytes()); 1854 } 1855 } 1856 1857 /* 1858 * @param wantedVersions How many versions were asked for. 1859 * @return wantedVersions or this families' {@link HConstants#VERSIONS}. 1860 */ 1861 int versionsToReturn(final int wantedVersions) { 1862 if (wantedVersions <= 0) { 1863 throw new IllegalArgumentException("Number of versions must be > 0"); 1864 } 1865 // Make sure we do not return more than maximum versions for this store. 1866 int maxVersions = this.family.getMaxVersions(); 1867 return wantedVersions > maxVersions ? maxVersions: wantedVersions; 1868 } 1869 1870 @Override 1871 public boolean canSplit() { 1872 this.lock.readLock().lock(); 1873 try { 1874 // Not split-able if we find a reference store file present in the store. 1875 boolean result = !hasReferences(); 1876 if (!result) { 1877 LOG.trace("Not splittable; has references: {}", this); 1878 } 1879 return result; 1880 } finally { 1881 this.lock.readLock().unlock(); 1882 } 1883 } 1884 1885 /** 1886 * Determines if Store should be split. 1887 */ 1888 public Optional<byte[]> getSplitPoint() { 1889 this.lock.readLock().lock(); 1890 try { 1891 // Should already be enforced by the split policy! 1892 assert !this.getRegionInfo().isMetaRegion(); 1893 // Not split-able if we find a reference store file present in the store. 1894 if (hasReferences()) { 1895 LOG.trace("Not splittable; has references: {}", this); 1896 return Optional.empty(); 1897 } 1898 return this.storeEngine.getStoreFileManager().getSplitPoint(); 1899 } catch(IOException e) { 1900 LOG.warn("Failed getting store size for {}", this, e); 1901 } finally { 1902 this.lock.readLock().unlock(); 1903 } 1904 return Optional.empty(); 1905 } 1906 1907 @Override 1908 public long getLastCompactSize() { 1909 return this.lastCompactSize; 1910 } 1911 1912 @Override 1913 public long getSize() { 1914 return storeSize.get(); 1915 } 1916 1917 public void triggerMajorCompaction() { 1918 this.forceMajor = true; 1919 } 1920 1921 ////////////////////////////////////////////////////////////////////////////// 1922 // File administration 1923 ////////////////////////////////////////////////////////////////////////////// 1924 1925 /** 1926 * Return a scanner for both the memstore and the HStore files. Assumes we are not in a 1927 * compaction. 1928 * @param scan Scan to apply when scanning the stores 1929 * @param targetCols columns to scan 1930 * @return a scanner over the current key values 1931 * @throws IOException on failure 1932 */ 1933 public KeyValueScanner getScanner(Scan scan, final NavigableSet<byte[]> targetCols, long readPt) 1934 throws IOException { 1935 lock.readLock().lock(); 1936 try { 1937 ScanInfo scanInfo; 1938 if (this.getCoprocessorHost() != null) { 1939 scanInfo = this.getCoprocessorHost().preStoreScannerOpen(this); 1940 } else { 1941 scanInfo = getScanInfo(); 1942 } 1943 return createScanner(scan, scanInfo, targetCols, readPt); 1944 } finally { 1945 lock.readLock().unlock(); 1946 } 1947 } 1948 1949 // HMobStore will override this method to return its own implementation. 1950 protected KeyValueScanner createScanner(Scan scan, ScanInfo scanInfo, 1951 NavigableSet<byte[]> targetCols, long readPt) throws IOException { 1952 return scan.isReversed() ? new ReversedStoreScanner(this, scanInfo, scan, targetCols, readPt) 1953 : new StoreScanner(this, scanInfo, scan, targetCols, readPt); 1954 } 1955 1956 /** 1957 * Recreates the scanners on the current list of active store file scanners 1958 * @param currentFileScanners the current set of active store file scanners 1959 * @param cacheBlocks cache the blocks or not 1960 * @param usePread use pread or not 1961 * @param isCompaction is the scanner for compaction 1962 * @param matcher the scan query matcher 1963 * @param startRow the scan's start row 1964 * @param includeStartRow should the scan include the start row 1965 * @param stopRow the scan's stop row 1966 * @param includeStopRow should the scan include the stop row 1967 * @param readPt the read point of the current scane 1968 * @param includeMemstoreScanner whether the current scanner should include memstorescanner 1969 * @return list of scanners recreated on the current Scanners 1970 * @throws IOException 1971 */ 1972 public List<KeyValueScanner> recreateScanners(List<KeyValueScanner> currentFileScanners, 1973 boolean cacheBlocks, boolean usePread, boolean isCompaction, ScanQueryMatcher matcher, 1974 byte[] startRow, boolean includeStartRow, byte[] stopRow, boolean includeStopRow, long readPt, 1975 boolean includeMemstoreScanner) throws IOException { 1976 this.lock.readLock().lock(); 1977 try { 1978 Map<String, HStoreFile> name2File = 1979 new HashMap<>(getStorefilesCount() + getCompactedFilesCount()); 1980 for (HStoreFile file : getStorefiles()) { 1981 name2File.put(file.getFileInfo().getActiveFileName(), file); 1982 } 1983 Collection<HStoreFile> compactedFiles = getCompactedFiles(); 1984 for (HStoreFile file : IterableUtils.emptyIfNull(compactedFiles)) { 1985 name2File.put(file.getFileInfo().getActiveFileName(), file); 1986 } 1987 List<HStoreFile> filesToReopen = new ArrayList<>(); 1988 for (KeyValueScanner kvs : currentFileScanners) { 1989 assert kvs.isFileScanner(); 1990 if (kvs.peek() == null) { 1991 continue; 1992 } 1993 filesToReopen.add(name2File.get(kvs.getFilePath().getName())); 1994 } 1995 if (filesToReopen.isEmpty()) { 1996 return null; 1997 } 1998 return getScanners(filesToReopen, cacheBlocks, false, false, matcher, startRow, 1999 includeStartRow, stopRow, includeStopRow, readPt, false); 2000 } finally { 2001 this.lock.readLock().unlock(); 2002 } 2003 } 2004 2005 @Override 2006 public String toString() { 2007 return this.getColumnFamilyName(); 2008 } 2009 2010 @Override 2011 public int getStorefilesCount() { 2012 return this.storeEngine.getStoreFileManager().getStorefileCount(); 2013 } 2014 2015 @Override 2016 public int getCompactedFilesCount() { 2017 return this.storeEngine.getStoreFileManager().getCompactedFilesCount(); 2018 } 2019 2020 private LongStream getStoreFileAgeStream() { 2021 return this.storeEngine.getStoreFileManager().getStorefiles().stream().filter(sf -> { 2022 if (sf.getReader() == null) { 2023 LOG.warn("StoreFile {} has a null Reader", sf); 2024 return false; 2025 } else { 2026 return true; 2027 } 2028 }).filter(HStoreFile::isHFile).mapToLong(sf -> sf.getFileInfo().getCreatedTimestamp()) 2029 .map(t -> EnvironmentEdgeManager.currentTime() - t); 2030 } 2031 2032 @Override 2033 public OptionalLong getMaxStoreFileAge() { 2034 return getStoreFileAgeStream().max(); 2035 } 2036 2037 @Override 2038 public OptionalLong getMinStoreFileAge() { 2039 return getStoreFileAgeStream().min(); 2040 } 2041 2042 @Override 2043 public OptionalDouble getAvgStoreFileAge() { 2044 return getStoreFileAgeStream().average(); 2045 } 2046 2047 @Override 2048 public long getNumReferenceFiles() { 2049 return this.storeEngine.getStoreFileManager().getStorefiles().stream() 2050 .filter(HStoreFile::isReference).count(); 2051 } 2052 2053 @Override 2054 public long getNumHFiles() { 2055 return this.storeEngine.getStoreFileManager().getStorefiles().stream() 2056 .filter(HStoreFile::isHFile).count(); 2057 } 2058 2059 @Override 2060 public long getStoreSizeUncompressed() { 2061 return this.totalUncompressedBytes.get(); 2062 } 2063 2064 @Override 2065 public long getStorefilesSize() { 2066 // Include all StoreFiles 2067 return getStorefilesSize(storeFile -> true); 2068 } 2069 2070 @Override 2071 public long getHFilesSize() { 2072 // Include only StoreFiles which are HFiles 2073 return getStorefilesSize(storeFile -> storeFile.isHFile()); 2074 } 2075 2076 private long getStorefilesSize(Predicate<HStoreFile> predicate) { 2077 return this.storeEngine.getStoreFileManager().getStorefiles().stream().filter(sf -> { 2078 if (sf.getReader() == null) { 2079 LOG.warn("StoreFile {} has a null Reader", sf); 2080 return false; 2081 } else { 2082 return true; 2083 } 2084 }).filter(predicate).mapToLong(sf -> sf.getReader().length()).sum(); 2085 } 2086 2087 private long getStoreFileFieldSize(ToLongFunction<StoreFileReader> f) { 2088 return this.storeEngine.getStoreFileManager().getStorefiles().stream().filter(sf -> { 2089 if (sf.getReader() == null) { 2090 LOG.warn("StoreFile {} has a null Reader", sf); 2091 return false; 2092 } else { 2093 return true; 2094 } 2095 }).map(HStoreFile::getReader).mapToLong(f).sum(); 2096 } 2097 2098 @Override 2099 public long getStorefilesRootLevelIndexSize() { 2100 return getStoreFileFieldSize(StoreFileReader::indexSize); 2101 } 2102 2103 @Override 2104 public long getTotalStaticIndexSize() { 2105 return getStoreFileFieldSize(StoreFileReader::getUncompressedDataIndexSize); 2106 } 2107 2108 @Override 2109 public long getTotalStaticBloomSize() { 2110 return getStoreFileFieldSize(StoreFileReader::getTotalBloomSize); 2111 } 2112 2113 @Override 2114 public MemStoreSize getMemStoreSize() { 2115 return this.memstore.size(); 2116 } 2117 2118 @Override 2119 public int getCompactPriority() { 2120 int priority = this.storeEngine.getStoreFileManager().getStoreCompactionPriority(); 2121 if (priority == PRIORITY_USER) { 2122 LOG.warn("Compaction priority is USER despite there being no user compaction"); 2123 } 2124 return priority; 2125 } 2126 2127 public boolean throttleCompaction(long compactionSize) { 2128 return storeEngine.getCompactionPolicy().throttleCompaction(compactionSize); 2129 } 2130 2131 public HRegion getHRegion() { 2132 return this.region; 2133 } 2134 2135 public RegionCoprocessorHost getCoprocessorHost() { 2136 return this.region.getCoprocessorHost(); 2137 } 2138 2139 @Override 2140 public RegionInfo getRegionInfo() { 2141 return this.fs.getRegionInfo(); 2142 } 2143 2144 @Override 2145 public boolean areWritesEnabled() { 2146 return this.region.areWritesEnabled(); 2147 } 2148 2149 @Override 2150 public long getSmallestReadPoint() { 2151 return this.region.getSmallestReadPoint(); 2152 } 2153 2154 /** 2155 * Adds or replaces the specified KeyValues. 2156 * <p> 2157 * For each KeyValue specified, if a cell with the same row, family, and qualifier exists in 2158 * MemStore, it will be replaced. Otherwise, it will just be inserted to MemStore. 2159 * <p> 2160 * This operation is atomic on each KeyValue (row/family/qualifier) but not necessarily atomic 2161 * across all of them. 2162 * @param readpoint readpoint below which we can safely remove duplicate KVs 2163 * @throws IOException 2164 */ 2165 public void upsert(Iterable<Cell> cells, long readpoint, MemStoreSizing memstoreSizing) 2166 throws IOException { 2167 this.lock.readLock().lock(); 2168 try { 2169 this.memstore.upsert(cells, readpoint, memstoreSizing); 2170 } finally { 2171 this.lock.readLock().unlock(); 2172 } 2173 } 2174 2175 public StoreFlushContext createFlushContext(long cacheFlushId, FlushLifeCycleTracker tracker) { 2176 return new StoreFlusherImpl(cacheFlushId, tracker); 2177 } 2178 2179 private final class StoreFlusherImpl implements StoreFlushContext { 2180 2181 private final FlushLifeCycleTracker tracker; 2182 private final long cacheFlushSeqNum; 2183 private MemStoreSnapshot snapshot; 2184 private List<Path> tempFiles; 2185 private List<Path> committedFiles; 2186 private long cacheFlushCount; 2187 private long cacheFlushSize; 2188 private long outputFileSize; 2189 2190 private StoreFlusherImpl(long cacheFlushSeqNum, FlushLifeCycleTracker tracker) { 2191 this.cacheFlushSeqNum = cacheFlushSeqNum; 2192 this.tracker = tracker; 2193 } 2194 2195 /** 2196 * This is not thread safe. The caller should have a lock on the region or the store. 2197 * If necessary, the lock can be added with the patch provided in HBASE-10087 2198 */ 2199 @Override 2200 public MemStoreSize prepare() { 2201 // passing the current sequence number of the wal - to allow bookkeeping in the memstore 2202 this.snapshot = memstore.snapshot(); 2203 this.cacheFlushCount = snapshot.getCellsCount(); 2204 this.cacheFlushSize = snapshot.getDataSize(); 2205 committedFiles = new ArrayList<>(1); 2206 return snapshot.getMemStoreSize(); 2207 } 2208 2209 @Override 2210 public void flushCache(MonitoredTask status) throws IOException { 2211 RegionServerServices rsService = region.getRegionServerServices(); 2212 ThroughputController throughputController = 2213 rsService == null ? null : rsService.getFlushThroughputController(); 2214 tempFiles = 2215 HStore.this.flushCache(cacheFlushSeqNum, snapshot, status, throughputController, tracker); 2216 } 2217 2218 @Override 2219 public boolean commit(MonitoredTask status) throws IOException { 2220 if (CollectionUtils.isEmpty(this.tempFiles)) { 2221 return false; 2222 } 2223 List<HStoreFile> storeFiles = new ArrayList<>(this.tempFiles.size()); 2224 for (Path storeFilePath : tempFiles) { 2225 try { 2226 HStoreFile sf = HStore.this.commitFile(storeFilePath, cacheFlushSeqNum, status); 2227 outputFileSize += sf.getReader().length(); 2228 storeFiles.add(sf); 2229 } catch (IOException ex) { 2230 LOG.error("Failed to commit store file {}", storeFilePath, ex); 2231 // Try to delete the files we have committed before. 2232 for (HStoreFile sf : storeFiles) { 2233 Path pathToDelete = sf.getPath(); 2234 try { 2235 sf.deleteStoreFile(); 2236 } catch (IOException deleteEx) { 2237 LOG.error(HBaseMarkers.FATAL, "Failed to delete store file we committed, " 2238 + "halting {}", pathToDelete, ex); 2239 Runtime.getRuntime().halt(1); 2240 } 2241 } 2242 throw new IOException("Failed to commit the flush", ex); 2243 } 2244 } 2245 2246 for (HStoreFile sf : storeFiles) { 2247 if (HStore.this.getCoprocessorHost() != null) { 2248 HStore.this.getCoprocessorHost().postFlush(HStore.this, sf, tracker); 2249 } 2250 committedFiles.add(sf.getPath()); 2251 } 2252 2253 HStore.this.flushedCellsCount.addAndGet(cacheFlushCount); 2254 HStore.this.flushedCellsSize.addAndGet(cacheFlushSize); 2255 HStore.this.flushedOutputFileSize.addAndGet(outputFileSize); 2256 2257 // Add new file to store files. Clear snapshot too while we have the Store write lock. 2258 return HStore.this.updateStorefiles(storeFiles, snapshot.getId()); 2259 } 2260 2261 @Override 2262 public long getOutputFileSize() { 2263 return outputFileSize; 2264 } 2265 2266 @Override 2267 public List<Path> getCommittedFiles() { 2268 return committedFiles; 2269 } 2270 2271 /** 2272 * Similar to commit, but called in secondary region replicas for replaying the 2273 * flush cache from primary region. Adds the new files to the store, and drops the 2274 * snapshot depending on dropMemstoreSnapshot argument. 2275 * @param fileNames names of the flushed files 2276 * @param dropMemstoreSnapshot whether to drop the prepared memstore snapshot 2277 * @throws IOException 2278 */ 2279 @Override 2280 public void replayFlush(List<String> fileNames, boolean dropMemstoreSnapshot) 2281 throws IOException { 2282 List<HStoreFile> storeFiles = new ArrayList<>(fileNames.size()); 2283 for (String file : fileNames) { 2284 // open the file as a store file (hfile link, etc) 2285 StoreFileInfo storeFileInfo = fs.getStoreFileInfo(getColumnFamilyName(), file); 2286 HStoreFile storeFile = createStoreFileAndReader(storeFileInfo); 2287 storeFiles.add(storeFile); 2288 HStore.this.storeSize.addAndGet(storeFile.getReader().length()); 2289 HStore.this.totalUncompressedBytes 2290 .addAndGet(storeFile.getReader().getTotalUncompressedBytes()); 2291 if (LOG.isInfoEnabled()) { 2292 LOG.info("Region: " + HStore.this.getRegionInfo().getEncodedName() + 2293 " added " + storeFile + ", entries=" + storeFile.getReader().getEntries() + 2294 ", sequenceid=" + +storeFile.getReader().getSequenceID() + ", filesize=" 2295 + TraditionalBinaryPrefix.long2String(storeFile.getReader().length(), "", 1)); 2296 } 2297 } 2298 2299 long snapshotId = -1; // -1 means do not drop 2300 if (dropMemstoreSnapshot && snapshot != null) { 2301 snapshotId = snapshot.getId(); 2302 snapshot.close(); 2303 } 2304 HStore.this.updateStorefiles(storeFiles, snapshotId); 2305 } 2306 2307 /** 2308 * Abort the snapshot preparation. Drops the snapshot if any. 2309 * @throws IOException 2310 */ 2311 @Override 2312 public void abort() throws IOException { 2313 if (snapshot != null) { 2314 HStore.this.updateStorefiles(Collections.emptyList(), snapshot.getId()); 2315 } 2316 } 2317 } 2318 2319 @Override 2320 public boolean needsCompaction() { 2321 List<HStoreFile> filesCompactingClone = null; 2322 synchronized (filesCompacting) { 2323 filesCompactingClone = Lists.newArrayList(filesCompacting); 2324 } 2325 return this.storeEngine.needsCompaction(filesCompactingClone); 2326 } 2327 2328 /** 2329 * Used for tests. 2330 * @return cache configuration for this Store. 2331 */ 2332 @VisibleForTesting 2333 public CacheConfig getCacheConfig() { 2334 return this.cacheConf; 2335 } 2336 2337 public static final long FIXED_OVERHEAD = 2338 ClassSize.align(ClassSize.OBJECT + (26 * ClassSize.REFERENCE) + (2 * Bytes.SIZEOF_LONG) 2339 + (5 * Bytes.SIZEOF_INT) + (2 * Bytes.SIZEOF_BOOLEAN)); 2340 2341 public static final long DEEP_OVERHEAD = ClassSize.align(FIXED_OVERHEAD 2342 + ClassSize.OBJECT + ClassSize.REENTRANT_LOCK 2343 + ClassSize.CONCURRENT_SKIPLISTMAP 2344 + ClassSize.CONCURRENT_SKIPLISTMAP_ENTRY + ClassSize.OBJECT 2345 + ScanInfo.FIXED_OVERHEAD); 2346 2347 @Override 2348 public long heapSize() { 2349 MemStoreSize memstoreSize = this.memstore.size(); 2350 return DEEP_OVERHEAD + memstoreSize.getHeapSize(); 2351 } 2352 2353 @Override 2354 public CellComparator getComparator() { 2355 return comparator; 2356 } 2357 2358 public ScanInfo getScanInfo() { 2359 return scanInfo; 2360 } 2361 2362 /** 2363 * Set scan info, used by test 2364 * @param scanInfo new scan info to use for test 2365 */ 2366 void setScanInfo(ScanInfo scanInfo) { 2367 this.scanInfo = scanInfo; 2368 } 2369 2370 @Override 2371 public boolean hasTooManyStoreFiles() { 2372 return getStorefilesCount() > this.blockingFileCount; 2373 } 2374 2375 @Override 2376 public long getFlushedCellsCount() { 2377 return flushedCellsCount.get(); 2378 } 2379 2380 @Override 2381 public long getFlushedCellsSize() { 2382 return flushedCellsSize.get(); 2383 } 2384 2385 @Override 2386 public long getFlushedOutputFileSize() { 2387 return flushedOutputFileSize.get(); 2388 } 2389 2390 @Override 2391 public long getCompactedCellsCount() { 2392 return compactedCellsCount.get(); 2393 } 2394 2395 @Override 2396 public long getCompactedCellsSize() { 2397 return compactedCellsSize.get(); 2398 } 2399 2400 @Override 2401 public long getMajorCompactedCellsCount() { 2402 return majorCompactedCellsCount.get(); 2403 } 2404 2405 @Override 2406 public long getMajorCompactedCellsSize() { 2407 return majorCompactedCellsSize.get(); 2408 } 2409 2410 /** 2411 * Returns the StoreEngine that is backing this concrete implementation of Store. 2412 * @return Returns the {@link StoreEngine} object used internally inside this HStore object. 2413 */ 2414 @VisibleForTesting 2415 public StoreEngine<?, ?, ?, ?> getStoreEngine() { 2416 return this.storeEngine; 2417 } 2418 2419 protected OffPeakHours getOffPeakHours() { 2420 return this.offPeakHours; 2421 } 2422 2423 /** 2424 * {@inheritDoc} 2425 */ 2426 @Override 2427 public void onConfigurationChange(Configuration conf) { 2428 this.conf = new CompoundConfiguration() 2429 .add(conf) 2430 .addBytesMap(family.getValues()); 2431 this.storeEngine.compactionPolicy.setConf(conf); 2432 this.offPeakHours = OffPeakHours.getInstance(conf); 2433 } 2434 2435 /** 2436 * {@inheritDoc} 2437 */ 2438 @Override 2439 public void registerChildren(ConfigurationManager manager) { 2440 // No children to register 2441 } 2442 2443 /** 2444 * {@inheritDoc} 2445 */ 2446 @Override 2447 public void deregisterChildren(ConfigurationManager manager) { 2448 // No children to deregister 2449 } 2450 2451 @Override 2452 public double getCompactionPressure() { 2453 return storeEngine.getStoreFileManager().getCompactionPressure(); 2454 } 2455 2456 @Override 2457 public boolean isPrimaryReplicaStore() { 2458 return getRegionInfo().getReplicaId() == RegionInfo.DEFAULT_REPLICA_ID; 2459 } 2460 2461 /** 2462 * Sets the store up for a region level snapshot operation. 2463 * @see #postSnapshotOperation() 2464 */ 2465 public void preSnapshotOperation() { 2466 archiveLock.lock(); 2467 } 2468 2469 /** 2470 * Perform tasks needed after the completion of snapshot operation. 2471 * @see #preSnapshotOperation() 2472 */ 2473 public void postSnapshotOperation() { 2474 archiveLock.unlock(); 2475 } 2476 2477 /** 2478 * Closes and archives the compacted files under this store 2479 */ 2480 public synchronized void closeAndArchiveCompactedFiles() throws IOException { 2481 // ensure other threads do not attempt to archive the same files on close() 2482 archiveLock.lock(); 2483 try { 2484 lock.readLock().lock(); 2485 Collection<HStoreFile> copyCompactedfiles = null; 2486 try { 2487 Collection<HStoreFile> compactedfiles = 2488 this.getStoreEngine().getStoreFileManager().getCompactedfiles(); 2489 if (CollectionUtils.isNotEmpty(compactedfiles)) { 2490 // Do a copy under read lock 2491 copyCompactedfiles = new ArrayList<>(compactedfiles); 2492 } else { 2493 LOG.trace("No compacted files to archive"); 2494 } 2495 } finally { 2496 lock.readLock().unlock(); 2497 } 2498 if (CollectionUtils.isNotEmpty(copyCompactedfiles)) { 2499 removeCompactedfiles(copyCompactedfiles); 2500 } 2501 } finally { 2502 archiveLock.unlock(); 2503 } 2504 } 2505 2506 /** 2507 * Archives and removes the compacted files 2508 * @param compactedfiles The compacted files in this store that are not active in reads 2509 * @throws IOException 2510 */ 2511 private void removeCompactedfiles(Collection<HStoreFile> compactedfiles) 2512 throws IOException { 2513 final List<HStoreFile> filesToRemove = new ArrayList<>(compactedfiles.size()); 2514 for (final HStoreFile file : compactedfiles) { 2515 synchronized (file) { 2516 try { 2517 StoreFileReader r = file.getReader(); 2518 if (r == null) { 2519 LOG.debug("The file {} was closed but still not archived", file); 2520 filesToRemove.add(file); 2521 continue; 2522 } 2523 if (file.isCompactedAway() && !file.isReferencedInReads()) { 2524 // Even if deleting fails we need not bother as any new scanners won't be 2525 // able to use the compacted file as the status is already compactedAway 2526 LOG.trace("Closing and archiving the file {}", file); 2527 r.close(true); 2528 // Just close and return 2529 filesToRemove.add(file); 2530 } 2531 } catch (Exception e) { 2532 LOG.error("Exception while trying to close the compacted store file {}", 2533 file.getPath(), e); 2534 } 2535 } 2536 } 2537 if (this.isPrimaryReplicaStore()) { 2538 // Only the primary region is allowed to move the file to archive. 2539 // The secondary region does not move the files to archive. Any active reads from 2540 // the secondary region will still work because the file as such has active readers on it. 2541 if (!filesToRemove.isEmpty()) { 2542 LOG.debug("Moving the files {} to archive", filesToRemove); 2543 // Only if this is successful it has to be removed 2544 try { 2545 this.fs.removeStoreFiles(this.getColumnFamilyDescriptor().getNameAsString(), filesToRemove); 2546 } catch (FailedArchiveException fae) { 2547 // Even if archiving some files failed, we still need to clear out any of the 2548 // files which were successfully archived. Otherwise we will receive a 2549 // FileNotFoundException when we attempt to re-archive them in the next go around. 2550 Collection<Path> failedFiles = fae.getFailedFiles(); 2551 Iterator<HStoreFile> iter = filesToRemove.iterator(); 2552 while (iter.hasNext()) { 2553 if (failedFiles.contains(iter.next().getPath())) { 2554 iter.remove(); 2555 } 2556 } 2557 if (!filesToRemove.isEmpty()) { 2558 clearCompactedfiles(filesToRemove); 2559 } 2560 throw fae; 2561 } 2562 } 2563 } 2564 if (!filesToRemove.isEmpty()) { 2565 // Clear the compactedfiles from the store file manager 2566 clearCompactedfiles(filesToRemove); 2567 } 2568 } 2569 2570 public Long preFlushSeqIDEstimation() { 2571 return memstore.preFlushSeqIDEstimation(); 2572 } 2573 2574 @Override 2575 public boolean isSloppyMemStore() { 2576 return this.memstore.isSloppy(); 2577 } 2578 2579 private void clearCompactedfiles(List<HStoreFile> filesToRemove) throws IOException { 2580 LOG.trace("Clearing the compacted file {} from this store", filesToRemove); 2581 try { 2582 lock.writeLock().lock(); 2583 this.getStoreEngine().getStoreFileManager().removeCompactedFiles(filesToRemove); 2584 } finally { 2585 lock.writeLock().unlock(); 2586 } 2587 } 2588}