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.io.hfile; 020 021import java.lang.ref.WeakReference; 022import java.util.EnumMap; 023import java.util.Iterator; 024import java.util.List; 025import java.util.Map; 026import java.util.PriorityQueue; 027import java.util.SortedSet; 028import java.util.TreeSet; 029import java.util.concurrent.ConcurrentHashMap; 030import java.util.concurrent.Executors; 031import java.util.concurrent.ScheduledExecutorService; 032import java.util.concurrent.TimeUnit; 033import java.util.concurrent.atomic.AtomicLong; 034import java.util.concurrent.atomic.LongAdder; 035import java.util.concurrent.locks.ReentrantLock; 036 037import org.apache.hadoop.conf.Configuration; 038import org.apache.yetus.audience.InterfaceAudience; 039import org.slf4j.Logger; 040import org.slf4j.LoggerFactory; 041import org.apache.hadoop.hbase.io.HeapSize; 042import org.apache.hadoop.hbase.io.encoding.DataBlockEncoding; 043import org.apache.hadoop.hbase.util.Bytes; 044import org.apache.hadoop.hbase.util.ClassSize; 045import org.apache.hadoop.hbase.util.HasThread; 046import org.apache.hadoop.util.StringUtils; 047 048import org.apache.hbase.thirdparty.com.google.common.annotations.VisibleForTesting; 049import org.apache.hbase.thirdparty.com.google.common.base.MoreObjects; 050import org.apache.hbase.thirdparty.com.google.common.base.Objects; 051import org.apache.hbase.thirdparty.com.google.common.util.concurrent.ThreadFactoryBuilder; 052 053import com.fasterxml.jackson.annotation.JsonIgnore; 054import com.fasterxml.jackson.annotation.JsonIgnoreProperties; 055 056/** 057 * A block cache implementation that is memory-aware using {@link HeapSize}, 058 * memory-bound using an LRU eviction algorithm, and concurrent: backed by a 059 * {@link ConcurrentHashMap} and with a non-blocking eviction thread giving 060 * constant-time {@link #cacheBlock} and {@link #getBlock} operations.<p> 061 * 062 * Contains three levels of block priority to allow for scan-resistance and in-memory families 063 * {@link org.apache.hadoop.hbase.HColumnDescriptor#setInMemory(boolean)} (An in-memory column 064 * family is a column family that should be served from memory if possible): 065 * single-access, multiple-accesses, and in-memory priority. 066 * A block is added with an in-memory priority flag if 067 * {@link org.apache.hadoop.hbase.HColumnDescriptor#isInMemory()}, otherwise a block becomes a 068 * single access priority the first time it is read into this block cache. If a block is 069 * accessed again while in cache, it is marked as a multiple access priority block. This 070 * delineation of blocks is used to prevent scans from thrashing the cache adding a 071 * least-frequently-used element to the eviction algorithm.<p> 072 * 073 * Each priority is given its own chunk of the total cache to ensure 074 * fairness during eviction. Each priority will retain close to its maximum 075 * size, however, if any priority is not using its entire chunk the others 076 * are able to grow beyond their chunk size.<p> 077 * 078 * Instantiated at a minimum with the total size and average block size. 079 * All sizes are in bytes. The block size is not especially important as this 080 * cache is fully dynamic in its sizing of blocks. It is only used for 081 * pre-allocating data structures and in initial heap estimation of the map.<p> 082 * 083 * The detailed constructor defines the sizes for the three priorities (they 084 * should total to the <code>maximum size</code> defined). It also sets the levels that 085 * trigger and control the eviction thread.<p> 086 * 087 * The <code>acceptable size</code> is the cache size level which triggers the eviction 088 * process to start. It evicts enough blocks to get the size below the 089 * minimum size specified.<p> 090 * 091 * Eviction happens in a separate thread and involves a single full-scan 092 * of the map. It determines how many bytes must be freed to reach the minimum 093 * size, and then while scanning determines the fewest least-recently-used 094 * blocks necessary from each of the three priorities (would be 3 times bytes 095 * to free). It then uses the priority chunk sizes to evict fairly according 096 * to the relative sizes and usage. 097 */ 098@InterfaceAudience.Private 099@JsonIgnoreProperties({"encodingCountsForTest"}) 100public class LruBlockCache implements ResizableBlockCache, HeapSize { 101 102 private static final Logger LOG = LoggerFactory.getLogger(LruBlockCache.class); 103 104 /** 105 * Percentage of total size that eviction will evict until; e.g. if set to .8, then we will keep 106 * evicting during an eviction run till the cache size is down to 80% of the total. 107 */ 108 private static final String LRU_MIN_FACTOR_CONFIG_NAME = "hbase.lru.blockcache.min.factor"; 109 110 /** 111 * Acceptable size of cache (no evictions if size < acceptable) 112 */ 113 private static final String LRU_ACCEPTABLE_FACTOR_CONFIG_NAME = 114 "hbase.lru.blockcache.acceptable.factor"; 115 116 /** 117 * Hard capacity limit of cache, will reject any put if size > this * acceptable 118 */ 119 static final String LRU_HARD_CAPACITY_LIMIT_FACTOR_CONFIG_NAME = 120 "hbase.lru.blockcache.hard.capacity.limit.factor"; 121 private static final String LRU_SINGLE_PERCENTAGE_CONFIG_NAME = 122 "hbase.lru.blockcache.single.percentage"; 123 private static final String LRU_MULTI_PERCENTAGE_CONFIG_NAME = 124 "hbase.lru.blockcache.multi.percentage"; 125 private static final String LRU_MEMORY_PERCENTAGE_CONFIG_NAME = 126 "hbase.lru.blockcache.memory.percentage"; 127 128 /** 129 * Configuration key to force data-block always (except in-memory are too much) 130 * cached in memory for in-memory hfile, unlike inMemory, which is a column-family 131 * configuration, inMemoryForceMode is a cluster-wide configuration 132 */ 133 private static final String LRU_IN_MEMORY_FORCE_MODE_CONFIG_NAME = 134 "hbase.lru.rs.inmemoryforcemode"; 135 136 /* Default Configuration Parameters*/ 137 138 /* Backing Concurrent Map Configuration */ 139 static final float DEFAULT_LOAD_FACTOR = 0.75f; 140 static final int DEFAULT_CONCURRENCY_LEVEL = 16; 141 142 /* Eviction thresholds */ 143 private static final float DEFAULT_MIN_FACTOR = 0.95f; 144 static final float DEFAULT_ACCEPTABLE_FACTOR = 0.99f; 145 146 /* Priority buckets */ 147 private static final float DEFAULT_SINGLE_FACTOR = 0.25f; 148 private static final float DEFAULT_MULTI_FACTOR = 0.50f; 149 private static final float DEFAULT_MEMORY_FACTOR = 0.25f; 150 151 private static final float DEFAULT_HARD_CAPACITY_LIMIT_FACTOR = 1.2f; 152 153 private static final boolean DEFAULT_IN_MEMORY_FORCE_MODE = false; 154 155 /* Statistics thread */ 156 private static final int STAT_THREAD_PERIOD = 60 * 5; 157 private static final String LRU_MAX_BLOCK_SIZE = "hbase.lru.max.block.size"; 158 private static final long DEFAULT_MAX_BLOCK_SIZE = 16L * 1024L * 1024L; 159 160 /** Concurrent map (the cache) */ 161 private final Map<BlockCacheKey, LruCachedBlock> map; 162 163 /** Eviction lock (locked when eviction in process) */ 164 private final ReentrantLock evictionLock = new ReentrantLock(true); 165 private final long maxBlockSize; 166 167 /** Volatile boolean to track if we are in an eviction process or not */ 168 private volatile boolean evictionInProgress = false; 169 170 /** Eviction thread */ 171 private final EvictionThread evictionThread; 172 173 /** Statistics thread schedule pool (for heavy debugging, could remove) */ 174 private final ScheduledExecutorService scheduleThreadPool = Executors.newScheduledThreadPool(1, 175 new ThreadFactoryBuilder().setNameFormat("LruBlockCacheStatsExecutor").setDaemon(true).build()); 176 177 /** Current size of cache */ 178 private final AtomicLong size; 179 180 /** Current size of data blocks */ 181 private final LongAdder dataBlockSize; 182 183 /** Current number of cached elements */ 184 private final AtomicLong elements; 185 186 /** Current number of cached data block elements */ 187 private final LongAdder dataBlockElements; 188 189 /** Cache access count (sequential ID) */ 190 private final AtomicLong count; 191 192 /** hard capacity limit */ 193 private float hardCapacityLimitFactor; 194 195 /** Cache statistics */ 196 private final CacheStats stats; 197 198 /** Maximum allowable size of cache (block put if size > max, evict) */ 199 private long maxSize; 200 201 /** Approximate block size */ 202 private long blockSize; 203 204 /** Acceptable size of cache (no evictions if size < acceptable) */ 205 private float acceptableFactor; 206 207 /** Minimum threshold of cache (when evicting, evict until size < min) */ 208 private float minFactor; 209 210 /** Single access bucket size */ 211 private float singleFactor; 212 213 /** Multiple access bucket size */ 214 private float multiFactor; 215 216 /** In-memory bucket size */ 217 private float memoryFactor; 218 219 /** Overhead of the structure itself */ 220 private long overhead; 221 222 /** Whether in-memory hfile's data block has higher priority when evicting */ 223 private boolean forceInMemory; 224 225 /** 226 * Where to send victims (blocks evicted/missing from the cache). This is used only when we use an 227 * external cache as L2. 228 * Note: See org.apache.hadoop.hbase.io.hfile.MemcachedBlockCache 229 */ 230 private BlockCache victimHandler = null; 231 232 /** 233 * Default constructor. Specify maximum size and expected average block 234 * size (approximation is fine). 235 * 236 * <p>All other factors will be calculated based on defaults specified in 237 * this class. 238 * 239 * @param maxSize maximum size of cache, in bytes 240 * @param blockSize approximate size of each block, in bytes 241 */ 242 public LruBlockCache(long maxSize, long blockSize) { 243 this(maxSize, blockSize, true); 244 } 245 246 /** 247 * Constructor used for testing. Allows disabling of the eviction thread. 248 */ 249 public LruBlockCache(long maxSize, long blockSize, boolean evictionThread) { 250 this(maxSize, blockSize, evictionThread, 251 (int) Math.ceil(1.2 * maxSize / blockSize), 252 DEFAULT_LOAD_FACTOR, DEFAULT_CONCURRENCY_LEVEL, 253 DEFAULT_MIN_FACTOR, DEFAULT_ACCEPTABLE_FACTOR, 254 DEFAULT_SINGLE_FACTOR, 255 DEFAULT_MULTI_FACTOR, 256 DEFAULT_MEMORY_FACTOR, 257 DEFAULT_HARD_CAPACITY_LIMIT_FACTOR, 258 false, 259 DEFAULT_MAX_BLOCK_SIZE 260 ); 261 } 262 263 public LruBlockCache(long maxSize, long blockSize, boolean evictionThread, Configuration conf) { 264 this(maxSize, blockSize, evictionThread, 265 (int) Math.ceil(1.2 * maxSize / blockSize), 266 DEFAULT_LOAD_FACTOR, 267 DEFAULT_CONCURRENCY_LEVEL, 268 conf.getFloat(LRU_MIN_FACTOR_CONFIG_NAME, DEFAULT_MIN_FACTOR), 269 conf.getFloat(LRU_ACCEPTABLE_FACTOR_CONFIG_NAME, DEFAULT_ACCEPTABLE_FACTOR), 270 conf.getFloat(LRU_SINGLE_PERCENTAGE_CONFIG_NAME, DEFAULT_SINGLE_FACTOR), 271 conf.getFloat(LRU_MULTI_PERCENTAGE_CONFIG_NAME, DEFAULT_MULTI_FACTOR), 272 conf.getFloat(LRU_MEMORY_PERCENTAGE_CONFIG_NAME, DEFAULT_MEMORY_FACTOR), 273 conf.getFloat(LRU_HARD_CAPACITY_LIMIT_FACTOR_CONFIG_NAME, 274 DEFAULT_HARD_CAPACITY_LIMIT_FACTOR), 275 conf.getBoolean(LRU_IN_MEMORY_FORCE_MODE_CONFIG_NAME, DEFAULT_IN_MEMORY_FORCE_MODE), 276 conf.getLong(LRU_MAX_BLOCK_SIZE, DEFAULT_MAX_BLOCK_SIZE) 277 ); 278 } 279 280 public LruBlockCache(long maxSize, long blockSize, Configuration conf) { 281 this(maxSize, blockSize, true, conf); 282 } 283 284 /** 285 * Configurable constructor. Use this constructor if not using defaults. 286 * 287 * @param maxSize maximum size of this cache, in bytes 288 * @param blockSize expected average size of blocks, in bytes 289 * @param evictionThread whether to run evictions in a bg thread or not 290 * @param mapInitialSize initial size of backing ConcurrentHashMap 291 * @param mapLoadFactor initial load factor of backing ConcurrentHashMap 292 * @param mapConcurrencyLevel initial concurrency factor for backing CHM 293 * @param minFactor percentage of total size that eviction will evict until 294 * @param acceptableFactor percentage of total size that triggers eviction 295 * @param singleFactor percentage of total size for single-access blocks 296 * @param multiFactor percentage of total size for multiple-access blocks 297 * @param memoryFactor percentage of total size for in-memory blocks 298 */ 299 public LruBlockCache(long maxSize, long blockSize, boolean evictionThread, 300 int mapInitialSize, float mapLoadFactor, int mapConcurrencyLevel, 301 float minFactor, float acceptableFactor, float singleFactor, 302 float multiFactor, float memoryFactor, float hardLimitFactor, 303 boolean forceInMemory, long maxBlockSize) { 304 this.maxBlockSize = maxBlockSize; 305 if(singleFactor + multiFactor + memoryFactor != 1 || 306 singleFactor < 0 || multiFactor < 0 || memoryFactor < 0) { 307 throw new IllegalArgumentException("Single, multi, and memory factors " + 308 " should be non-negative and total 1.0"); 309 } 310 if (minFactor >= acceptableFactor) { 311 throw new IllegalArgumentException("minFactor must be smaller than acceptableFactor"); 312 } 313 if (minFactor >= 1.0f || acceptableFactor >= 1.0f) { 314 throw new IllegalArgumentException("all factors must be < 1"); 315 } 316 this.maxSize = maxSize; 317 this.blockSize = blockSize; 318 this.forceInMemory = forceInMemory; 319 map = new ConcurrentHashMap<>(mapInitialSize, mapLoadFactor, mapConcurrencyLevel); 320 this.minFactor = minFactor; 321 this.acceptableFactor = acceptableFactor; 322 this.singleFactor = singleFactor; 323 this.multiFactor = multiFactor; 324 this.memoryFactor = memoryFactor; 325 this.stats = new CacheStats(this.getClass().getSimpleName()); 326 this.count = new AtomicLong(0); 327 this.elements = new AtomicLong(0); 328 this.dataBlockElements = new LongAdder(); 329 this.dataBlockSize = new LongAdder(); 330 this.overhead = calculateOverhead(maxSize, blockSize, mapConcurrencyLevel); 331 this.size = new AtomicLong(this.overhead); 332 this.hardCapacityLimitFactor = hardLimitFactor; 333 if (evictionThread) { 334 this.evictionThread = new EvictionThread(this); 335 this.evictionThread.start(); // FindBugs SC_START_IN_CTOR 336 } else { 337 this.evictionThread = null; 338 } 339 // TODO: Add means of turning this off. Bit obnoxious running thread just to make a log 340 // every five minutes. 341 this.scheduleThreadPool.scheduleAtFixedRate(new StatisticsThread(this), STAT_THREAD_PERIOD, 342 STAT_THREAD_PERIOD, TimeUnit.SECONDS); 343 } 344 345 @Override 346 public void setMaxSize(long maxSize) { 347 this.maxSize = maxSize; 348 if (this.size.get() > acceptableSize() && !evictionInProgress) { 349 runEviction(); 350 } 351 } 352 353 // BlockCache implementation 354 355 /** 356 * Cache the block with the specified name and buffer. 357 * <p> 358 * It is assumed this will NOT be called on an already cached block. In rare cases (HBASE-8547) 359 * this can happen, for which we compare the buffer contents. 360 * 361 * @param cacheKey block's cache key 362 * @param buf block buffer 363 * @param inMemory if block is in-memory 364 */ 365 @Override 366 public void cacheBlock(BlockCacheKey cacheKey, Cacheable buf, boolean inMemory) { 367 if (buf.heapSize() > maxBlockSize) { 368 // If there are a lot of blocks that are too 369 // big this can make the logs way too noisy. 370 // So we log 2% 371 if (stats.failInsert() % 50 == 0) { 372 LOG.warn("Trying to cache too large a block " 373 + cacheKey.getHfileName() + " @ " 374 + cacheKey.getOffset() 375 + " is " + buf.heapSize() 376 + " which is larger than " + maxBlockSize); 377 } 378 return; 379 } 380 381 LruCachedBlock cb = map.get(cacheKey); 382 if (cb != null) { 383 // compare the contents, if they are not equal, we are in big trouble 384 if (BlockCacheUtil.compareCacheBlock(buf, cb.getBuffer()) != 0) { 385 throw new RuntimeException("Cached block contents differ, which should not have happened." 386 + "cacheKey:" + cacheKey); 387 } 388 String msg = "Cached an already cached block: " + cacheKey + " cb:" + cb.getCacheKey(); 389 msg += ". This is harmless and can happen in rare cases (see HBASE-8547)"; 390 LOG.debug(msg); 391 return; 392 } 393 long currentSize = size.get(); 394 long currentAcceptableSize = acceptableSize(); 395 long hardLimitSize = (long) (hardCapacityLimitFactor * currentAcceptableSize); 396 if (currentSize >= hardLimitSize) { 397 stats.failInsert(); 398 if (LOG.isTraceEnabled()) { 399 LOG.trace("LruBlockCache current size " + StringUtils.byteDesc(currentSize) 400 + " has exceeded acceptable size " + StringUtils.byteDesc(currentAcceptableSize) + "." 401 + " The hard limit size is " + StringUtils.byteDesc(hardLimitSize) 402 + ", failed to put cacheKey:" + cacheKey + " into LruBlockCache."); 403 } 404 if (!evictionInProgress) { 405 runEviction(); 406 } 407 return; 408 } 409 cb = new LruCachedBlock(cacheKey, buf, count.incrementAndGet(), inMemory); 410 long newSize = updateSizeMetrics(cb, false); 411 map.put(cacheKey, cb); 412 long val = elements.incrementAndGet(); 413 if (buf.getBlockType().isData()) { 414 dataBlockElements.increment(); 415 } 416 if (LOG.isTraceEnabled()) { 417 long size = map.size(); 418 assertCounterSanity(size, val); 419 } 420 if (newSize > currentAcceptableSize && !evictionInProgress) { 421 runEviction(); 422 } 423 } 424 425 /** 426 * Sanity-checking for parity between actual block cache content and metrics. 427 * Intended only for use with TRACE level logging and -ea JVM. 428 */ 429 private static void assertCounterSanity(long mapSize, long counterVal) { 430 if (counterVal < 0) { 431 LOG.trace("counterVal overflow. Assertions unreliable. counterVal=" + counterVal + 432 ", mapSize=" + mapSize); 433 return; 434 } 435 if (mapSize < Integer.MAX_VALUE) { 436 double pct_diff = Math.abs((((double) counterVal) / ((double) mapSize)) - 1.); 437 if (pct_diff > 0.05) { 438 LOG.trace("delta between reported and actual size > 5%. counterVal=" + counterVal + 439 ", mapSize=" + mapSize); 440 } 441 } 442 } 443 444 /** 445 * Cache the block with the specified name and buffer. 446 * <p> 447 * 448 * @param cacheKey block's cache key 449 * @param buf block buffer 450 */ 451 @Override 452 public void cacheBlock(BlockCacheKey cacheKey, Cacheable buf) { 453 cacheBlock(cacheKey, buf, false); 454 } 455 456 /** 457 * Helper function that updates the local size counter and also updates any 458 * per-cf or per-blocktype metrics it can discern from given 459 * {@link LruCachedBlock} 460 */ 461 private long updateSizeMetrics(LruCachedBlock cb, boolean evict) { 462 long heapsize = cb.heapSize(); 463 BlockType bt = cb.getBuffer().getBlockType(); 464 if (evict) { 465 heapsize *= -1; 466 } 467 if (bt != null && bt.isData()) { 468 dataBlockSize.add(heapsize); 469 } 470 return size.addAndGet(heapsize); 471 } 472 473 /** 474 * Get the buffer of the block with the specified name. 475 * 476 * @param cacheKey block's cache key 477 * @param caching true if the caller caches blocks on cache misses 478 * @param repeat Whether this is a repeat lookup for the same block 479 * (used to avoid double counting cache misses when doing double-check 480 * locking) 481 * @param updateCacheMetrics Whether to update cache metrics or not 482 * 483 * @return buffer of specified cache key, or null if not in cache 484 */ 485 @Override 486 public Cacheable getBlock(BlockCacheKey cacheKey, boolean caching, boolean repeat, 487 boolean updateCacheMetrics) { 488 LruCachedBlock cb = map.get(cacheKey); 489 if (cb == null) { 490 if (!repeat && updateCacheMetrics) { 491 stats.miss(caching, cacheKey.isPrimary(), cacheKey.getBlockType()); 492 } 493 // If there is another block cache then try and read there. 494 // However if this is a retry ( second time in double checked locking ) 495 // And it's already a miss then the l2 will also be a miss. 496 if (victimHandler != null && !repeat) { 497 Cacheable result = victimHandler.getBlock(cacheKey, caching, repeat, updateCacheMetrics); 498 499 // Promote this to L1. 500 if (result != null && caching) { 501 if (result instanceof HFileBlock && ((HFileBlock) result).usesSharedMemory()) { 502 result = ((HFileBlock) result).deepClone(); 503 } 504 cacheBlock(cacheKey, result, /* inMemory = */ false); 505 } 506 return result; 507 } 508 return null; 509 } 510 if (updateCacheMetrics) stats.hit(caching, cacheKey.isPrimary(), cacheKey.getBlockType()); 511 cb.access(count.incrementAndGet()); 512 return cb.getBuffer(); 513 } 514 515 /** 516 * Whether the cache contains block with specified cacheKey 517 * 518 * @return true if contains the block 519 */ 520 public boolean containsBlock(BlockCacheKey cacheKey) { 521 return map.containsKey(cacheKey); 522 } 523 524 @Override 525 public boolean evictBlock(BlockCacheKey cacheKey) { 526 LruCachedBlock cb = map.get(cacheKey); 527 return cb != null && evictBlock(cb, false) > 0; 528 } 529 530 /** 531 * Evicts all blocks for a specific HFile. This is an 532 * expensive operation implemented as a linear-time search through all blocks 533 * in the cache. Ideally this should be a search in a log-access-time map. 534 * 535 * <p> 536 * This is used for evict-on-close to remove all blocks of a specific HFile. 537 * 538 * @return the number of blocks evicted 539 */ 540 @Override 541 public int evictBlocksByHfileName(String hfileName) { 542 int numEvicted = 0; 543 for (BlockCacheKey key : map.keySet()) { 544 if (key.getHfileName().equals(hfileName)) { 545 if (evictBlock(key)) 546 ++numEvicted; 547 } 548 } 549 if (victimHandler != null) { 550 numEvicted += victimHandler.evictBlocksByHfileName(hfileName); 551 } 552 return numEvicted; 553 } 554 555 /** 556 * Evict the block, and it will be cached by the victim handler if exists && 557 * block may be read again later 558 * 559 * @param evictedByEvictionProcess true if the given block is evicted by 560 * EvictionThread 561 * @return the heap size of evicted block 562 */ 563 protected long evictBlock(LruCachedBlock block, boolean evictedByEvictionProcess) { 564 boolean found = map.remove(block.getCacheKey()) != null; 565 if (!found) { 566 return 0; 567 } 568 updateSizeMetrics(block, true); 569 long val = elements.decrementAndGet(); 570 if (LOG.isTraceEnabled()) { 571 long size = map.size(); 572 assertCounterSanity(size, val); 573 } 574 if (block.getBuffer().getBlockType().isData()) { 575 dataBlockElements.decrement(); 576 } 577 if (evictedByEvictionProcess) { 578 // When the eviction of the block happened because of invalidation of HFiles, no need to 579 // update the stats counter. 580 stats.evicted(block.getCachedTime(), block.getCacheKey().isPrimary()); 581 if (victimHandler != null) { 582 victimHandler.cacheBlock(block.getCacheKey(), block.getBuffer()); 583 } 584 } 585 return block.heapSize(); 586 } 587 588 /** 589 * Multi-threaded call to run the eviction process. 590 */ 591 private void runEviction() { 592 if (evictionThread == null) { 593 evict(); 594 } else { 595 evictionThread.evict(); 596 } 597 } 598 599 @VisibleForTesting 600 boolean isEvictionInProgress() { 601 return evictionInProgress; 602 } 603 604 @VisibleForTesting 605 long getOverhead() { 606 return overhead; 607 } 608 609 /** 610 * Eviction method. 611 */ 612 void evict() { 613 614 // Ensure only one eviction at a time 615 if(!evictionLock.tryLock()) return; 616 617 try { 618 evictionInProgress = true; 619 long currentSize = this.size.get(); 620 long bytesToFree = currentSize - minSize(); 621 622 if (LOG.isTraceEnabled()) { 623 LOG.trace("Block cache LRU eviction started; Attempting to free " + 624 StringUtils.byteDesc(bytesToFree) + " of total=" + 625 StringUtils.byteDesc(currentSize)); 626 } 627 628 if (bytesToFree <= 0) return; 629 630 // Instantiate priority buckets 631 BlockBucket bucketSingle = new BlockBucket("single", bytesToFree, blockSize, singleSize()); 632 BlockBucket bucketMulti = new BlockBucket("multi", bytesToFree, blockSize, multiSize()); 633 BlockBucket bucketMemory = new BlockBucket("memory", bytesToFree, blockSize, memorySize()); 634 635 // Scan entire map putting into appropriate buckets 636 for (LruCachedBlock cachedBlock : map.values()) { 637 switch (cachedBlock.getPriority()) { 638 case SINGLE: { 639 bucketSingle.add(cachedBlock); 640 break; 641 } 642 case MULTI: { 643 bucketMulti.add(cachedBlock); 644 break; 645 } 646 case MEMORY: { 647 bucketMemory.add(cachedBlock); 648 break; 649 } 650 } 651 } 652 653 long bytesFreed = 0; 654 if (forceInMemory || memoryFactor > 0.999f) { 655 long s = bucketSingle.totalSize(); 656 long m = bucketMulti.totalSize(); 657 if (bytesToFree > (s + m)) { 658 // this means we need to evict blocks in memory bucket to make room, 659 // so the single and multi buckets will be emptied 660 bytesFreed = bucketSingle.free(s); 661 bytesFreed += bucketMulti.free(m); 662 if (LOG.isTraceEnabled()) { 663 LOG.trace("freed " + StringUtils.byteDesc(bytesFreed) + 664 " from single and multi buckets"); 665 } 666 bytesFreed += bucketMemory.free(bytesToFree - bytesFreed); 667 if (LOG.isTraceEnabled()) { 668 LOG.trace("freed " + StringUtils.byteDesc(bytesFreed) + 669 " total from all three buckets "); 670 } 671 } else { 672 // this means no need to evict block in memory bucket, 673 // and we try best to make the ratio between single-bucket and 674 // multi-bucket is 1:2 675 long bytesRemain = s + m - bytesToFree; 676 if (3 * s <= bytesRemain) { 677 // single-bucket is small enough that no eviction happens for it 678 // hence all eviction goes from multi-bucket 679 bytesFreed = bucketMulti.free(bytesToFree); 680 } else if (3 * m <= 2 * bytesRemain) { 681 // multi-bucket is small enough that no eviction happens for it 682 // hence all eviction goes from single-bucket 683 bytesFreed = bucketSingle.free(bytesToFree); 684 } else { 685 // both buckets need to evict some blocks 686 bytesFreed = bucketSingle.free(s - bytesRemain / 3); 687 if (bytesFreed < bytesToFree) { 688 bytesFreed += bucketMulti.free(bytesToFree - bytesFreed); 689 } 690 } 691 } 692 } else { 693 PriorityQueue<BlockBucket> bucketQueue = new PriorityQueue<>(3); 694 695 bucketQueue.add(bucketSingle); 696 bucketQueue.add(bucketMulti); 697 bucketQueue.add(bucketMemory); 698 699 int remainingBuckets = 3; 700 701 BlockBucket bucket; 702 while ((bucket = bucketQueue.poll()) != null) { 703 long overflow = bucket.overflow(); 704 if (overflow > 0) { 705 long bucketBytesToFree = 706 Math.min(overflow, (bytesToFree - bytesFreed) / remainingBuckets); 707 bytesFreed += bucket.free(bucketBytesToFree); 708 } 709 remainingBuckets--; 710 } 711 } 712 if (LOG.isTraceEnabled()) { 713 long single = bucketSingle.totalSize(); 714 long multi = bucketMulti.totalSize(); 715 long memory = bucketMemory.totalSize(); 716 LOG.trace("Block cache LRU eviction completed; " + 717 "freed=" + StringUtils.byteDesc(bytesFreed) + ", " + 718 "total=" + StringUtils.byteDesc(this.size.get()) + ", " + 719 "single=" + StringUtils.byteDesc(single) + ", " + 720 "multi=" + StringUtils.byteDesc(multi) + ", " + 721 "memory=" + StringUtils.byteDesc(memory)); 722 } 723 } finally { 724 stats.evict(); 725 evictionInProgress = false; 726 evictionLock.unlock(); 727 } 728 } 729 730 @Override 731 public String toString() { 732 return MoreObjects.toStringHelper(this) 733 .add("blockCount", getBlockCount()) 734 .add("currentSize", StringUtils.byteDesc(getCurrentSize())) 735 .add("freeSize", StringUtils.byteDesc(getFreeSize())) 736 .add("maxSize", StringUtils.byteDesc(getMaxSize())) 737 .add("heapSize", StringUtils.byteDesc(heapSize())) 738 .add("minSize", StringUtils.byteDesc(minSize())) 739 .add("minFactor", minFactor) 740 .add("multiSize", StringUtils.byteDesc(multiSize())) 741 .add("multiFactor", multiFactor) 742 .add("singleSize", StringUtils.byteDesc(singleSize())) 743 .add("singleFactor", singleFactor) 744 .toString(); 745 } 746 747 /** 748 * Used to group blocks into priority buckets. There will be a BlockBucket 749 * for each priority (single, multi, memory). Once bucketed, the eviction 750 * algorithm takes the appropriate number of elements out of each according 751 * to configuration parameters and their relatives sizes. 752 */ 753 private class BlockBucket implements Comparable<BlockBucket> { 754 755 private final String name; 756 private LruCachedBlockQueue queue; 757 private long totalSize = 0; 758 private long bucketSize; 759 760 public BlockBucket(String name, long bytesToFree, long blockSize, long bucketSize) { 761 this.name = name; 762 this.bucketSize = bucketSize; 763 queue = new LruCachedBlockQueue(bytesToFree, blockSize); 764 totalSize = 0; 765 } 766 767 public void add(LruCachedBlock block) { 768 totalSize += block.heapSize(); 769 queue.add(block); 770 } 771 772 public long free(long toFree) { 773 if (LOG.isTraceEnabled()) { 774 LOG.trace("freeing " + StringUtils.byteDesc(toFree) + " from " + this); 775 } 776 LruCachedBlock cb; 777 long freedBytes = 0; 778 while ((cb = queue.pollLast()) != null) { 779 freedBytes += evictBlock(cb, true); 780 if (freedBytes >= toFree) { 781 return freedBytes; 782 } 783 } 784 if (LOG.isTraceEnabled()) { 785 LOG.trace("freed " + StringUtils.byteDesc(freedBytes) + " from " + this); 786 } 787 return freedBytes; 788 } 789 790 public long overflow() { 791 return totalSize - bucketSize; 792 } 793 794 public long totalSize() { 795 return totalSize; 796 } 797 798 @Override 799 public int compareTo(BlockBucket that) { 800 return Long.compare(this.overflow(), that.overflow()); 801 } 802 803 @Override 804 public boolean equals(Object that) { 805 if (that == null || !(that instanceof BlockBucket)) { 806 return false; 807 } 808 return compareTo((BlockBucket)that) == 0; 809 } 810 811 @Override 812 public int hashCode() { 813 return Objects.hashCode(name, bucketSize, queue, totalSize); 814 } 815 816 @Override 817 public String toString() { 818 return MoreObjects.toStringHelper(this) 819 .add("name", name) 820 .add("totalSize", StringUtils.byteDesc(totalSize)) 821 .add("bucketSize", StringUtils.byteDesc(bucketSize)) 822 .toString(); 823 } 824 } 825 826 /** 827 * Get the maximum size of this cache. 828 * 829 * @return max size in bytes 830 */ 831 832 @Override 833 public long getMaxSize() { 834 return this.maxSize; 835 } 836 837 @Override 838 public long getCurrentSize() { 839 return this.size.get(); 840 } 841 842 @Override 843 public long getCurrentDataSize() { 844 return this.dataBlockSize.sum(); 845 } 846 847 @Override 848 public long getFreeSize() { 849 return getMaxSize() - getCurrentSize(); 850 } 851 852 @Override 853 public long size() { 854 return getMaxSize(); 855 } 856 857 @Override 858 public long getBlockCount() { 859 return this.elements.get(); 860 } 861 862 @Override 863 public long getDataBlockCount() { 864 return this.dataBlockElements.sum(); 865 } 866 867 EvictionThread getEvictionThread() { 868 return this.evictionThread; 869 } 870 871 /* 872 * Eviction thread. Sits in waiting state until an eviction is triggered 873 * when the cache size grows above the acceptable level.<p> 874 * 875 * Thread is triggered into action by {@link LruBlockCache#runEviction()} 876 */ 877 static class EvictionThread extends HasThread { 878 879 private WeakReference<LruBlockCache> cache; 880 private volatile boolean go = true; 881 // flag set after enter the run method, used for test 882 private boolean enteringRun = false; 883 884 public EvictionThread(LruBlockCache cache) { 885 super(Thread.currentThread().getName() + ".LruBlockCache.EvictionThread"); 886 setDaemon(true); 887 this.cache = new WeakReference<>(cache); 888 } 889 890 @Override 891 public void run() { 892 enteringRun = true; 893 while (this.go) { 894 synchronized (this) { 895 try { 896 this.wait(1000 * 10/*Don't wait for ever*/); 897 } catch (InterruptedException e) { 898 LOG.warn("Interrupted eviction thread ", e); 899 Thread.currentThread().interrupt(); 900 } 901 } 902 LruBlockCache cache = this.cache.get(); 903 if (cache == null) break; 904 cache.evict(); 905 } 906 } 907 908 @edu.umd.cs.findbugs.annotations.SuppressWarnings(value="NN_NAKED_NOTIFY", 909 justification="This is what we want") 910 public void evict() { 911 synchronized (this) { 912 this.notifyAll(); 913 } 914 } 915 916 synchronized void shutdown() { 917 this.go = false; 918 this.notifyAll(); 919 } 920 921 /** 922 * Used for the test. 923 */ 924 boolean isEnteringRun() { 925 return this.enteringRun; 926 } 927 } 928 929 /* 930 * Statistics thread. Periodically prints the cache statistics to the log. 931 */ 932 static class StatisticsThread extends Thread { 933 934 private final LruBlockCache lru; 935 936 public StatisticsThread(LruBlockCache lru) { 937 super("LruBlockCacheStats"); 938 setDaemon(true); 939 this.lru = lru; 940 } 941 942 @Override 943 public void run() { 944 lru.logStats(); 945 } 946 } 947 948 public void logStats() { 949 // Log size 950 long totalSize = heapSize(); 951 long freeSize = maxSize - totalSize; 952 LruBlockCache.LOG.info("totalSize=" + StringUtils.byteDesc(totalSize) + ", " + 953 "freeSize=" + StringUtils.byteDesc(freeSize) + ", " + 954 "max=" + StringUtils.byteDesc(this.maxSize) + ", " + 955 "blockCount=" + getBlockCount() + ", " + 956 "accesses=" + stats.getRequestCount() + ", " + 957 "hits=" + stats.getHitCount() + ", " + 958 "hitRatio=" + (stats.getHitCount() == 0 ? 959 "0" : (StringUtils.formatPercent(stats.getHitRatio(), 2)+ ", ")) + ", " + 960 "cachingAccesses=" + stats.getRequestCachingCount() + ", " + 961 "cachingHits=" + stats.getHitCachingCount() + ", " + 962 "cachingHitsRatio=" + (stats.getHitCachingCount() == 0 ? 963 "0,": (StringUtils.formatPercent(stats.getHitCachingRatio(), 2) + ", ")) + 964 "evictions=" + stats.getEvictionCount() + ", " + 965 "evicted=" + stats.getEvictedCount() + ", " + 966 "evictedPerRun=" + stats.evictedPerEviction()); 967 } 968 969 /** 970 * Get counter statistics for this cache. 971 * 972 * <p>Includes: total accesses, hits, misses, evicted blocks, and runs 973 * of the eviction processes. 974 */ 975 @Override 976 public CacheStats getStats() { 977 return this.stats; 978 } 979 980 public final static long CACHE_FIXED_OVERHEAD = ClassSize.align( 981 (4 * Bytes.SIZEOF_LONG) + (11 * ClassSize.REFERENCE) + 982 (6 * Bytes.SIZEOF_FLOAT) + (2 * Bytes.SIZEOF_BOOLEAN) 983 + ClassSize.OBJECT); 984 985 @Override 986 public long heapSize() { 987 return getCurrentSize(); 988 } 989 990 private static long calculateOverhead(long maxSize, long blockSize, int concurrency) { 991 // FindBugs ICAST_INTEGER_MULTIPLY_CAST_TO_LONG 992 return CACHE_FIXED_OVERHEAD + ClassSize.CONCURRENT_HASHMAP 993 + ((long) Math.ceil(maxSize * 1.2 / blockSize) * ClassSize.CONCURRENT_HASHMAP_ENTRY) 994 + ((long) concurrency * ClassSize.CONCURRENT_HASHMAP_SEGMENT); 995 } 996 997 @Override 998 public Iterator<CachedBlock> iterator() { 999 final Iterator<LruCachedBlock> iterator = map.values().iterator(); 1000 1001 return new Iterator<CachedBlock>() { 1002 private final long now = System.nanoTime(); 1003 1004 @Override 1005 public boolean hasNext() { 1006 return iterator.hasNext(); 1007 } 1008 1009 @Override 1010 public CachedBlock next() { 1011 final LruCachedBlock b = iterator.next(); 1012 return new CachedBlock() { 1013 @Override 1014 public String toString() { 1015 return BlockCacheUtil.toString(this, now); 1016 } 1017 1018 @Override 1019 public BlockPriority getBlockPriority() { 1020 return b.getPriority(); 1021 } 1022 1023 @Override 1024 public BlockType getBlockType() { 1025 return b.getBuffer().getBlockType(); 1026 } 1027 1028 @Override 1029 public long getOffset() { 1030 return b.getCacheKey().getOffset(); 1031 } 1032 1033 @Override 1034 public long getSize() { 1035 return b.getBuffer().heapSize(); 1036 } 1037 1038 @Override 1039 public long getCachedTime() { 1040 return b.getCachedTime(); 1041 } 1042 1043 @Override 1044 public String getFilename() { 1045 return b.getCacheKey().getHfileName(); 1046 } 1047 1048 @Override 1049 public int compareTo(CachedBlock other) { 1050 int diff = this.getFilename().compareTo(other.getFilename()); 1051 if (diff != 0) return diff; 1052 diff = Long.compare(this.getOffset(), other.getOffset()); 1053 if (diff != 0) return diff; 1054 if (other.getCachedTime() < 0 || this.getCachedTime() < 0) { 1055 throw new IllegalStateException(this.getCachedTime() + ", " + other.getCachedTime()); 1056 } 1057 return Long.compare(other.getCachedTime(), this.getCachedTime()); 1058 } 1059 1060 @Override 1061 public int hashCode() { 1062 return b.hashCode(); 1063 } 1064 1065 @Override 1066 public boolean equals(Object obj) { 1067 if (obj instanceof CachedBlock) { 1068 CachedBlock cb = (CachedBlock)obj; 1069 return compareTo(cb) == 0; 1070 } else { 1071 return false; 1072 } 1073 } 1074 }; 1075 } 1076 1077 @Override 1078 public void remove() { 1079 throw new UnsupportedOperationException(); 1080 } 1081 }; 1082 } 1083 1084 // Simple calculators of sizes given factors and maxSize 1085 1086 long acceptableSize() { 1087 return (long)Math.floor(this.maxSize * this.acceptableFactor); 1088 } 1089 private long minSize() { 1090 return (long)Math.floor(this.maxSize * this.minFactor); 1091 } 1092 private long singleSize() { 1093 return (long)Math.floor(this.maxSize * this.singleFactor * this.minFactor); 1094 } 1095 private long multiSize() { 1096 return (long)Math.floor(this.maxSize * this.multiFactor * this.minFactor); 1097 } 1098 private long memorySize() { 1099 return (long) Math.floor(this.maxSize * this.memoryFactor * this.minFactor); 1100 } 1101 1102 @Override 1103 public void shutdown() { 1104 if (victimHandler != null) { 1105 victimHandler.shutdown(); 1106 } 1107 this.scheduleThreadPool.shutdown(); 1108 for (int i = 0; i < 10; i++) { 1109 if (!this.scheduleThreadPool.isShutdown()) { 1110 try { 1111 Thread.sleep(10); 1112 } catch (InterruptedException e) { 1113 LOG.warn("Interrupted while sleeping"); 1114 Thread.currentThread().interrupt(); 1115 break; 1116 } 1117 } 1118 } 1119 1120 if (!this.scheduleThreadPool.isShutdown()) { 1121 List<Runnable> runnables = this.scheduleThreadPool.shutdownNow(); 1122 LOG.debug("Still running " + runnables); 1123 } 1124 this.evictionThread.shutdown(); 1125 } 1126 1127 /** Clears the cache. Used in tests. */ 1128 @VisibleForTesting 1129 public void clearCache() { 1130 this.map.clear(); 1131 this.elements.set(0); 1132 } 1133 1134 /** 1135 * Used in testing. May be very inefficient. 1136 * 1137 * @return the set of cached file names 1138 */ 1139 @VisibleForTesting 1140 SortedSet<String> getCachedFileNamesForTest() { 1141 SortedSet<String> fileNames = new TreeSet<>(); 1142 for (BlockCacheKey cacheKey : map.keySet()) { 1143 fileNames.add(cacheKey.getHfileName()); 1144 } 1145 return fileNames; 1146 } 1147 1148 @VisibleForTesting 1149 Map<BlockType, Integer> getBlockTypeCountsForTest() { 1150 Map<BlockType, Integer> counts = new EnumMap<>(BlockType.class); 1151 for (LruCachedBlock cb : map.values()) { 1152 BlockType blockType = cb.getBuffer().getBlockType(); 1153 Integer count = counts.get(blockType); 1154 counts.put(blockType, (count == null ? 0 : count) + 1); 1155 } 1156 return counts; 1157 } 1158 1159 @VisibleForTesting 1160 public Map<DataBlockEncoding, Integer> getEncodingCountsForTest() { 1161 Map<DataBlockEncoding, Integer> counts = new EnumMap<>(DataBlockEncoding.class); 1162 for (LruCachedBlock block : map.values()) { 1163 DataBlockEncoding encoding = ((HFileBlock) block.getBuffer()).getDataBlockEncoding(); 1164 Integer count = counts.get(encoding); 1165 counts.put(encoding, (count == null ? 0 : count) + 1); 1166 } 1167 return counts; 1168 } 1169 1170 public void setVictimCache(BlockCache handler) { 1171 assert victimHandler == null; 1172 victimHandler = handler; 1173 } 1174 1175 @VisibleForTesting 1176 Map<BlockCacheKey, LruCachedBlock> getMapForTests() { 1177 return map; 1178 } 1179 1180 @Override 1181 @JsonIgnore 1182 public BlockCache[] getBlockCaches() { 1183 if (victimHandler != null) 1184 return new BlockCache[] {this, this.victimHandler}; 1185 return null; 1186 } 1187}