001/*
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License.  You may obtain a copy of the License at
009 *
010 *     http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018package org.apache.hadoop.hbase.io.hfile.bucket;
019
020import static org.apache.hadoop.hbase.io.hfile.BlockCacheFactory.BLOCKCACHE_STATS_PERIODS;
021import static org.apache.hadoop.hbase.io.hfile.BlockCacheFactory.BLOCKCACHE_STATS_PERIOD_MINUTES_KEY;
022import static org.apache.hadoop.hbase.io.hfile.BlockCacheFactory.DEFAULT_BLOCKCACHE_STATS_PERIODS;
023import static org.apache.hadoop.hbase.io.hfile.BlockCacheFactory.DEFAULT_BLOCKCACHE_STATS_PERIOD_MINUTES;
024import static org.apache.hadoop.hbase.io.hfile.CacheConfig.BUCKETCACHE_PERSIST_INTERVAL_KEY;
025
026import java.io.File;
027import java.io.FileInputStream;
028import java.io.FileOutputStream;
029import java.io.IOException;
030import java.nio.ByteBuffer;
031import java.util.ArrayList;
032import java.util.Arrays;
033import java.util.Collections;
034import java.util.Comparator;
035import java.util.HashSet;
036import java.util.Iterator;
037import java.util.List;
038import java.util.Map;
039import java.util.NavigableSet;
040import java.util.Optional;
041import java.util.PriorityQueue;
042import java.util.Set;
043import java.util.concurrent.ArrayBlockingQueue;
044import java.util.concurrent.BlockingQueue;
045import java.util.concurrent.ConcurrentHashMap;
046import java.util.concurrent.ConcurrentMap;
047import java.util.concurrent.ConcurrentSkipListSet;
048import java.util.concurrent.Executors;
049import java.util.concurrent.ScheduledExecutorService;
050import java.util.concurrent.TimeUnit;
051import java.util.concurrent.atomic.AtomicBoolean;
052import java.util.concurrent.atomic.AtomicLong;
053import java.util.concurrent.atomic.LongAdder;
054import java.util.concurrent.locks.Lock;
055import java.util.concurrent.locks.ReentrantLock;
056import java.util.concurrent.locks.ReentrantReadWriteLock;
057import java.util.function.Consumer;
058import java.util.function.Function;
059import org.apache.commons.io.IOUtils;
060import org.apache.hadoop.conf.Configuration;
061import org.apache.hadoop.fs.Path;
062import org.apache.hadoop.hbase.HBaseConfiguration;
063import org.apache.hadoop.hbase.HBaseIOException;
064import org.apache.hadoop.hbase.TableName;
065import org.apache.hadoop.hbase.client.Admin;
066import org.apache.hadoop.hbase.io.ByteBuffAllocator;
067import org.apache.hadoop.hbase.io.ByteBuffAllocator.Recycler;
068import org.apache.hadoop.hbase.io.HeapSize;
069import org.apache.hadoop.hbase.io.hfile.BlockCache;
070import org.apache.hadoop.hbase.io.hfile.BlockCacheKey;
071import org.apache.hadoop.hbase.io.hfile.BlockCacheUtil;
072import org.apache.hadoop.hbase.io.hfile.BlockPriority;
073import org.apache.hadoop.hbase.io.hfile.BlockType;
074import org.apache.hadoop.hbase.io.hfile.CacheConfig;
075import org.apache.hadoop.hbase.io.hfile.CacheStats;
076import org.apache.hadoop.hbase.io.hfile.Cacheable;
077import org.apache.hadoop.hbase.io.hfile.CachedBlock;
078import org.apache.hadoop.hbase.io.hfile.CombinedBlockCache;
079import org.apache.hadoop.hbase.io.hfile.HFileBlock;
080import org.apache.hadoop.hbase.io.hfile.HFileContext;
081import org.apache.hadoop.hbase.io.hfile.HFileInfo;
082import org.apache.hadoop.hbase.nio.ByteBuff;
083import org.apache.hadoop.hbase.nio.RefCnt;
084import org.apache.hadoop.hbase.protobuf.ProtobufMagic;
085import org.apache.hadoop.hbase.regionserver.DataTieringManager;
086import org.apache.hadoop.hbase.regionserver.HRegion;
087import org.apache.hadoop.hbase.regionserver.StoreFileInfo;
088import org.apache.hadoop.hbase.util.Bytes;
089import org.apache.hadoop.hbase.util.EnvironmentEdgeManager;
090import org.apache.hadoop.hbase.util.IdReadWriteLock;
091import org.apache.hadoop.hbase.util.IdReadWriteLockStrongRef;
092import org.apache.hadoop.hbase.util.IdReadWriteLockWithObjectPool;
093import org.apache.hadoop.hbase.util.IdReadWriteLockWithObjectPool.ReferenceType;
094import org.apache.hadoop.hbase.util.Pair;
095import org.apache.hadoop.hbase.util.Threads;
096import org.apache.hadoop.util.StringUtils;
097import org.apache.yetus.audience.InterfaceAudience;
098import org.slf4j.Logger;
099import org.slf4j.LoggerFactory;
100
101import org.apache.hbase.thirdparty.com.google.common.base.Preconditions;
102import org.apache.hbase.thirdparty.com.google.common.util.concurrent.ThreadFactoryBuilder;
103
104import org.apache.hadoop.hbase.shaded.protobuf.generated.BucketCacheProtos;
105
106/**
107 * BucketCache uses {@link BucketAllocator} to allocate/free blocks, and uses BucketCache#ramCache
108 * and BucketCache#backingMap in order to determine if a given element is in the cache. The bucket
109 * cache can use off-heap memory {@link ByteBufferIOEngine} or mmap
110 * {@link ExclusiveMemoryMmapIOEngine} or pmem {@link SharedMemoryMmapIOEngine} or local files
111 * {@link FileIOEngine} to store/read the block data.
112 * <p>
113 * Eviction is via a similar algorithm as used in
114 * {@link org.apache.hadoop.hbase.io.hfile.LruBlockCache}
115 * <p>
116 * BucketCache can be used as mainly a block cache (see
117 * {@link org.apache.hadoop.hbase.io.hfile.CombinedBlockCache}), combined with a BlockCache to
118 * decrease CMS GC and heap fragmentation.
119 * <p>
120 * It also can be used as a secondary cache (e.g. using a file on ssd/fusionio to store blocks) to
121 * enlarge cache space via a victim cache.
122 */
123@InterfaceAudience.Private
124public class BucketCache implements BlockCache, HeapSize {
125  private static final Logger LOG = LoggerFactory.getLogger(BucketCache.class);
126
127  /** Priority buckets config */
128  static final String SINGLE_FACTOR_CONFIG_NAME = "hbase.bucketcache.single.factor";
129  static final String MULTI_FACTOR_CONFIG_NAME = "hbase.bucketcache.multi.factor";
130  static final String MEMORY_FACTOR_CONFIG_NAME = "hbase.bucketcache.memory.factor";
131  static final String EXTRA_FREE_FACTOR_CONFIG_NAME = "hbase.bucketcache.extrafreefactor";
132  static final String ACCEPT_FACTOR_CONFIG_NAME = "hbase.bucketcache.acceptfactor";
133  static final String MIN_FACTOR_CONFIG_NAME = "hbase.bucketcache.minfactor";
134  static final String BACKING_MAP_PERSISTENCE_CHUNK_SIZE =
135    "hbase.bucketcache.persistence.chunksize";
136
137  /** Use strong reference for offsetLock or not */
138  private static final String STRONG_REF_KEY = "hbase.bucketcache.offsetlock.usestrongref";
139  private static final boolean STRONG_REF_DEFAULT = false;
140
141  /** The cache age of blocks to check if the related file is present on any online regions. */
142  static final String BLOCK_ORPHAN_GRACE_PERIOD =
143    "hbase.bucketcache.block.orphan.evictgraceperiod.seconds";
144
145  static final long BLOCK_ORPHAN_GRACE_PERIOD_DEFAULT = 24 * 60 * 60 * 1000L;
146
147  /** Priority buckets */
148  static final float DEFAULT_SINGLE_FACTOR = 0.25f;
149  static final float DEFAULT_MULTI_FACTOR = 0.50f;
150  static final float DEFAULT_MEMORY_FACTOR = 0.25f;
151  static final float DEFAULT_MIN_FACTOR = 0.85f;
152
153  static final float DEFAULT_EXTRA_FREE_FACTOR = 0.10f;
154  static final float DEFAULT_ACCEPT_FACTOR = 0.95f;
155
156  // Number of blocks to clear for each of the bucket size that is full
157  static final int DEFAULT_FREE_ENTIRE_BLOCK_FACTOR = 2;
158
159  /** Statistics thread */
160  private static final int statThreadPeriod = 5 * 60;
161
162  final static int DEFAULT_WRITER_THREADS = 3;
163  final static int DEFAULT_WRITER_QUEUE_ITEMS = 64;
164
165  final static long DEFAULT_BACKING_MAP_PERSISTENCE_CHUNK_SIZE = 10000;
166
167  // Store/read block data
168  transient final IOEngine ioEngine;
169
170  // Store the block in this map before writing it to cache
171  transient final RAMCache ramCache;
172
173  // In this map, store the block's meta data like offset, length
174  transient Map<BlockCacheKey, BucketEntry> backingMap;
175
176  private AtomicBoolean backingMapValidated = new AtomicBoolean(false);
177
178  /**
179   * Map of hFile -> Region -> File size. This map is used to track all files completed prefetch,
180   * together with the region those belong to and the total cached size for the
181   * region.TestBlockEvictionOnRegionMovement
182   */
183  transient final Map<String, Pair<String, Long>> fullyCachedFiles = new ConcurrentHashMap<>();
184  /**
185   * Map of region -> total size of the region prefetched on this region server. This is the total
186   * size of hFiles for this region prefetched on this region server
187   */
188  final Map<String, Long> regionCachedSize = new ConcurrentHashMap<>();
189
190  private transient BucketCachePersister cachePersister;
191
192  /**
193   * Enum to represent the state of cache
194   */
195  protected enum CacheState {
196    // Initializing: State when the cache is being initialised from persistence.
197    INITIALIZING,
198    // Enabled: State when cache is initialised and is ready.
199    ENABLED,
200    // Disabled: State when the cache is disabled.
201    DISABLED
202  }
203
204  /**
205   * Flag if the cache is enabled or not... We shut it off if there are IO errors for some time, so
206   * that Bucket IO exceptions/errors don't bring down the HBase server.
207   */
208  private volatile CacheState cacheState;
209
210  /** The single cleanup thread shared by disable and explicit shutdown calls. */
211  private volatile Thread cacheCleanupThread;
212
213  /** The thread restoring the persistent cache index during initialization. */
214  private volatile Thread persistenceRetrieverThread;
215
216  /**
217   * A list of writer queues. We have a queue per {@link WriterThread} we have running. In other
218   * words, the work adding blocks to the BucketCache is divided up amongst the running
219   * WriterThreads. Its done by taking hash of the cache key modulo queue count. WriterThread when
220   * it runs takes whatever has been recently added and 'drains' the entries to the BucketCache. It
221   * then updates the ramCache and backingMap accordingly.
222   */
223  transient final ArrayList<BlockingQueue<RAMQueueEntry>> writerQueues = new ArrayList<>();
224  transient final WriterThread[] writerThreads;
225
226  /** Volatile boolean to track if free space is in process or not */
227  private volatile boolean freeInProgress = false;
228  private transient final Lock freeSpaceLock = new ReentrantLock();
229
230  private final LongAdder realCacheSize = new LongAdder();
231  private final LongAdder heapSize = new LongAdder();
232  /** Current number of cached elements */
233  private final LongAdder blockNumber = new LongAdder();
234
235  /** Cache access count (sequential ID) */
236  private final AtomicLong accessCount = new AtomicLong();
237
238  private final BucketCacheStats cacheStats;
239  private final String persistencePath;
240  static AtomicBoolean isCacheInconsistent = new AtomicBoolean(false);
241  private final long cacheCapacity;
242  /** Approximate block size */
243  private final long blockSize;
244
245  /** Duration of IO errors tolerated before we disable cache, 1 min as default */
246  private final int ioErrorsTolerationDuration;
247  // 1 min
248  public static final int DEFAULT_ERROR_TOLERATION_DURATION = 60 * 1000;
249
250  // Start time of first IO error when reading or writing IO Engine, it will be
251  // reset after a successful read/write.
252  private volatile long ioErrorStartTime = -1;
253
254  private transient Configuration conf;
255
256  /**
257   * A ReentrantReadWriteLock to lock on a particular block identified by offset. The purpose of
258   * this is to avoid freeing the block which is being read.
259   * <p>
260   */
261  transient final IdReadWriteLock<Long> offsetLock;
262
263  transient NavigableSet<BlockCacheKey> blocksByHFile = new ConcurrentSkipListSet<>(
264    Comparator.comparing(BlockCacheKey::getHfileName).thenComparingLong(BlockCacheKey::getOffset));
265
266  /** Statistics thread schedule pool (for heavy debugging, could remove) */
267  private transient final ScheduledExecutorService scheduleThreadPool =
268    Executors.newScheduledThreadPool(1,
269      new ThreadFactoryBuilder().setNameFormat("BucketCacheStatsExecutor").setDaemon(true).build());
270
271  // Allocate or free space for the block
272  private transient BucketAllocator bucketAllocator;
273
274  /** Acceptable size of cache (no evictions if size < acceptable) */
275  private float acceptableFactor;
276
277  /** Minimum threshold of cache (when evicting, evict until size < min) */
278  private float minFactor;
279
280  /**
281   * Free this floating point factor of extra blocks when evicting. For example free the number of
282   * blocks requested * (1 + extraFreeFactor)
283   */
284  private float extraFreeFactor;
285
286  /** Single access bucket size */
287  private float singleFactor;
288
289  /** Multiple access bucket size */
290  private float multiFactor;
291
292  /** In-memory bucket size */
293  private float memoryFactor;
294
295  private volatile long bucketcachePersistInterval;
296
297  private static final String FILE_VERIFY_ALGORITHM =
298    "hbase.bucketcache.persistent.file.integrity.check.algorithm";
299  private static final String DEFAULT_FILE_VERIFY_ALGORITHM = "MD5";
300
301  static final String QUEUE_ADDITION_WAIT_TIME = "hbase.bucketcache.queue.addition.waittime";
302  private static final long DEFAULT_QUEUE_ADDITION_WAIT_TIME = 0;
303  private long queueAdditionWaitTime;
304  /**
305   * Use {@link java.security.MessageDigest} class's encryption algorithms to check persistent file
306   * integrity, default algorithm is MD5
307   */
308  private String algorithm;
309
310  private long persistenceChunkSize;
311
312  /* Tracing failed Bucket Cache allocations. */
313  private long allocFailLogPrevTs; // time of previous log event for allocation failure.
314  private static final int ALLOCATION_FAIL_LOG_TIME_PERIOD = 60000; // Default 1 minute.
315
316  private transient Map<String, HRegion> onlineRegions;
317
318  private long orphanBlockGracePeriod = 0;
319
320  public BucketCache(String ioEngineName, long capacity, int blockSize, int[] bucketSizes,
321    int writerThreadNum, int writerQLen, String persistencePath) throws IOException {
322    this(ioEngineName, capacity, blockSize, bucketSizes, writerThreadNum, writerQLen,
323      persistencePath, DEFAULT_ERROR_TOLERATION_DURATION, HBaseConfiguration.create());
324  }
325
326  public BucketCache(String ioEngineName, long capacity, int blockSize, int[] bucketSizes,
327    int writerThreadNum, int writerQLen, String persistencePath, int ioErrorsTolerationDuration,
328    Configuration conf) throws IOException {
329    this(ioEngineName, capacity, blockSize, bucketSizes, writerThreadNum, writerQLen,
330      persistencePath, ioErrorsTolerationDuration, conf, null);
331  }
332
333  public BucketCache(String ioEngineName, long capacity, int blockSize, int[] bucketSizes,
334    int writerThreadNum, int writerQLen, String persistencePath, int ioErrorsTolerationDuration,
335    Configuration conf, Map<String, HRegion> onlineRegions) throws IOException {
336    Preconditions.checkArgument(blockSize > 0,
337      "BucketCache capacity is set to " + blockSize + ", can not be less than 0");
338    boolean useStrongRef = conf.getBoolean(STRONG_REF_KEY, STRONG_REF_DEFAULT);
339    if (useStrongRef) {
340      this.offsetLock = new IdReadWriteLockStrongRef<>();
341    } else {
342      this.offsetLock = new IdReadWriteLockWithObjectPool<>(ReferenceType.SOFT);
343    }
344    this.conf = conf;
345    this.algorithm = conf.get(FILE_VERIFY_ALGORITHM, DEFAULT_FILE_VERIFY_ALGORITHM);
346    this.ioEngine = getIOEngineFromName(ioEngineName, capacity, persistencePath);
347    this.writerThreads = new WriterThread[writerThreadNum];
348    this.onlineRegions = onlineRegions;
349    this.orphanBlockGracePeriod =
350      conf.getLong(BLOCK_ORPHAN_GRACE_PERIOD, BLOCK_ORPHAN_GRACE_PERIOD_DEFAULT);
351    long blockNumCapacity = capacity / blockSize;
352    if (blockNumCapacity >= Integer.MAX_VALUE) {
353      // Enough for about 32TB of cache!
354      throw new IllegalArgumentException("Cache capacity is too large, only support 32TB now");
355    }
356
357    // these sets the dynamic configs
358    this.onConfigurationChange(conf);
359    this.cacheStats =
360      new BucketCacheStats(conf.getInt(BLOCKCACHE_STATS_PERIODS, DEFAULT_BLOCKCACHE_STATS_PERIODS),
361        conf.getInt(BLOCKCACHE_STATS_PERIOD_MINUTES_KEY, DEFAULT_BLOCKCACHE_STATS_PERIOD_MINUTES));
362
363    LOG.info("Instantiating BucketCache with acceptableFactor: " + acceptableFactor
364      + ", minFactor: " + minFactor + ", extraFreeFactor: " + extraFreeFactor + ", singleFactor: "
365      + singleFactor + ", multiFactor: " + multiFactor + ", memoryFactor: " + memoryFactor
366      + ", useStrongRef: " + useStrongRef);
367
368    this.cacheCapacity = capacity;
369    this.persistencePath = persistencePath;
370    this.blockSize = blockSize;
371    this.ioErrorsTolerationDuration = ioErrorsTolerationDuration;
372    this.cacheState = CacheState.INITIALIZING;
373
374    this.allocFailLogPrevTs = 0;
375
376    for (int i = 0; i < writerThreads.length; ++i) {
377      writerQueues.add(new ArrayBlockingQueue<>(writerQLen));
378    }
379
380    assert writerQueues.size() == writerThreads.length;
381    this.ramCache = new RAMCache();
382
383    this.backingMap = new ConcurrentHashMap<>((int) blockNumCapacity);
384    instantiateWriterThreads();
385
386    if (isCachePersistent()) {
387      if (ioEngine instanceof FileIOEngine) {
388        startBucketCachePersisterThread();
389      }
390      startPersistenceRetriever(bucketSizes, capacity);
391    } else {
392      bucketAllocator = new BucketAllocator(capacity, bucketSizes);
393      this.cacheState = CacheState.ENABLED;
394      startWriterThreads();
395    }
396
397    // Run the statistics thread periodically to print the cache statistics log
398    // TODO: Add means of turning this off. Bit obnoxious running thread just to make a log
399    // every five minutes.
400    this.scheduleThreadPool.scheduleAtFixedRate(new StatisticsThread(this), statThreadPeriod,
401      statThreadPeriod, TimeUnit.SECONDS);
402    LOG.info("Started bucket cache; ioengine=" + ioEngineName + ", capacity="
403      + StringUtils.byteDesc(capacity) + ", blockSize=" + StringUtils.byteDesc(blockSize)
404      + ", writerThreadNum=" + writerThreadNum + ", writerQLen=" + writerQLen + ", persistencePath="
405      + persistencePath + ", bucketAllocator=" + BucketAllocator.class.getName());
406  }
407
408  private void startPersistenceRetriever(int[] bucketSizes, long capacity) {
409    Runnable persistentCacheRetriever = () -> {
410      try {
411        retrieveFromFile(bucketSizes);
412        LOG.info("Persistent bucket cache recovery from {} is complete.", persistencePath);
413      } catch (Throwable ex) {
414        LOG.warn("Can't restore from file[{}]. The bucket cache will be reset and rebuilt."
415          + " Exception seen: ", persistencePath, ex);
416        backingMap.clear();
417        fullyCachedFiles.clear();
418        backingMapValidated.set(true);
419        regionCachedSize.clear();
420        try {
421          bucketAllocator = new BucketAllocator(capacity, bucketSizes);
422        } catch (BucketAllocatorException allocatorException) {
423          LOG.error("Exception during Bucket Allocation", allocatorException);
424        }
425      } finally {
426        synchronized (BucketCache.this) {
427          if (cacheState == CacheState.INITIALIZING) {
428            cacheState = CacheState.ENABLED;
429            startWriterThreads();
430          }
431        }
432      }
433    };
434    persistenceRetrieverThread = new Thread(persistentCacheRetriever,
435      "BucketCachePersistenceRetriever-" + System.identityHashCode(this));
436    persistenceRetrieverThread.start();
437  }
438
439  private void sanityCheckConfigs() {
440    Preconditions.checkArgument(acceptableFactor <= 1 && acceptableFactor >= 0,
441      ACCEPT_FACTOR_CONFIG_NAME + " must be between 0.0 and 1.0");
442    Preconditions.checkArgument(minFactor <= 1 && minFactor >= 0,
443      MIN_FACTOR_CONFIG_NAME + " must be between 0.0 and 1.0");
444    Preconditions.checkArgument(minFactor <= acceptableFactor,
445      MIN_FACTOR_CONFIG_NAME + " must be <= " + ACCEPT_FACTOR_CONFIG_NAME);
446    Preconditions.checkArgument(extraFreeFactor >= 0,
447      EXTRA_FREE_FACTOR_CONFIG_NAME + " must be greater than 0.0");
448    Preconditions.checkArgument(singleFactor <= 1 && singleFactor >= 0,
449      SINGLE_FACTOR_CONFIG_NAME + " must be between 0.0 and 1.0");
450    Preconditions.checkArgument(multiFactor <= 1 && multiFactor >= 0,
451      MULTI_FACTOR_CONFIG_NAME + " must be between 0.0 and 1.0");
452    Preconditions.checkArgument(memoryFactor <= 1 && memoryFactor >= 0,
453      MEMORY_FACTOR_CONFIG_NAME + " must be between 0.0 and 1.0");
454    Preconditions.checkArgument((singleFactor + multiFactor + memoryFactor) == 1,
455      SINGLE_FACTOR_CONFIG_NAME + ", " + MULTI_FACTOR_CONFIG_NAME + ", and "
456        + MEMORY_FACTOR_CONFIG_NAME + " segments must add up to 1.0");
457    if (this.persistenceChunkSize <= 0) {
458      persistenceChunkSize = DEFAULT_BACKING_MAP_PERSISTENCE_CHUNK_SIZE;
459    }
460  }
461
462  /**
463   * Called by the constructor to instantiate the writer threads.
464   */
465  private void instantiateWriterThreads() {
466    final String threadName = Thread.currentThread().getName();
467    for (int i = 0; i < this.writerThreads.length; ++i) {
468      this.writerThreads[i] = new WriterThread(this.writerQueues.get(i));
469      this.writerThreads[i].setName(threadName + "-BucketCacheWriter-" + i);
470      this.writerThreads[i].setDaemon(true);
471    }
472  }
473
474  /**
475   * Called by the constructor to start the writer threads. Used by tests that need to override
476   * starting the threads.
477   */
478  protected void startWriterThreads() {
479    for (WriterThread thread : writerThreads) {
480      thread.start();
481    }
482  }
483
484  void startBucketCachePersisterThread() {
485    LOG.info("Starting BucketCachePersisterThread");
486    cachePersister = new BucketCachePersister(this);
487    cachePersister.setDaemon(true);
488    cachePersister.start();
489  }
490
491  @Override
492  public boolean isCacheEnabled() {
493    return this.cacheState == CacheState.ENABLED;
494  }
495
496  @Override
497  public long getMaxSize() {
498    return this.cacheCapacity;
499  }
500
501  public String getIoEngine() {
502    return ioEngine.toString();
503  }
504
505  /**
506   * Get the IOEngine from the IO engine name
507   * @return the IOEngine
508   */
509  private IOEngine getIOEngineFromName(String ioEngineName, long capacity, String persistencePath)
510    throws IOException {
511    if (ioEngineName.startsWith("file:") || ioEngineName.startsWith("files:")) {
512      // In order to make the usage simple, we only need the prefix 'files:' in
513      // document whether one or multiple file(s), but also support 'file:' for
514      // the compatibility
515      String[] filePaths =
516        ioEngineName.substring(ioEngineName.indexOf(":") + 1).split(FileIOEngine.FILE_DELIMITER);
517      return new FileIOEngine(capacity, persistencePath != null, filePaths);
518    } else if (ioEngineName.startsWith("offheap")) {
519      return new ByteBufferIOEngine(capacity);
520    } else if (ioEngineName.startsWith("mmap:")) {
521      return new ExclusiveMemoryMmapIOEngine(ioEngineName.substring(5), capacity);
522    } else if (ioEngineName.startsWith("pmem:")) {
523      // This mode of bucket cache creates an IOEngine over a file on the persistent memory
524      // device. Since the persistent memory device has its own address space the contents
525      // mapped to this address space does not get swapped out like in the case of mmapping
526      // on to DRAM. Hence the cells created out of the hfile blocks in the pmem bucket cache
527      // can be directly referred to without having to copy them onheap. Once the RPC is done,
528      // the blocks can be returned back as in case of ByteBufferIOEngine.
529      return new SharedMemoryMmapIOEngine(ioEngineName.substring(5), capacity);
530    } else {
531      throw new IllegalArgumentException(
532        "Don't understand io engine name for cache- prefix with file:, files:, mmap: or offheap");
533    }
534  }
535
536  public boolean isCachePersistenceEnabled() {
537    return persistencePath != null;
538  }
539
540  /**
541   * Cache the block with the specified name and buffer.
542   * @param cacheKey block's cache key
543   * @param buf      block buffer
544   */
545  @Override
546  public void cacheBlock(BlockCacheKey cacheKey, Cacheable buf) {
547    cacheBlock(cacheKey, buf, false);
548  }
549
550  /**
551   * Cache the block with the specified name and buffer.
552   * @param cacheKey   block's cache key
553   * @param cachedItem block buffer
554   * @param inMemory   if block is in-memory
555   */
556  @Override
557  public void cacheBlock(BlockCacheKey cacheKey, Cacheable cachedItem, boolean inMemory) {
558    cacheBlockWithWait(cacheKey, cachedItem, inMemory, false);
559  }
560
561  /**
562   * Cache the block with the specified name and buffer.
563   * @param cacheKey   block's cache key
564   * @param cachedItem block buffer
565   * @param inMemory   if block is in-memory
566   */
567  @Override
568  public void cacheBlock(BlockCacheKey cacheKey, Cacheable cachedItem, boolean inMemory,
569    boolean waitWhenCache) {
570    cacheBlockWithWait(cacheKey, cachedItem, inMemory, waitWhenCache && queueAdditionWaitTime > 0);
571  }
572
573  /**
574   * Cache the block to ramCache
575   * @param cacheKey   block's cache key
576   * @param cachedItem block buffer
577   * @param inMemory   if block is in-memory
578   * @param wait       if true, blocking wait when queue is full
579   */
580  public void cacheBlockWithWait(BlockCacheKey cacheKey, Cacheable cachedItem, boolean inMemory,
581    boolean wait) {
582    if (isCacheEnabled()) {
583      if (backingMap.containsKey(cacheKey) || ramCache.containsKey(cacheKey)) {
584        if (shouldReplaceExistingCacheBlock(cacheKey, cachedItem)) {
585          BucketEntry bucketEntry = backingMap.get(cacheKey);
586          if (bucketEntry != null && bucketEntry.isRpcRef()) {
587            // avoid replace when there are RPC refs for the bucket entry in bucket cache
588            return;
589          }
590          cacheBlockWithWaitInternal(cacheKey, cachedItem, inMemory, wait);
591        }
592      } else {
593        cacheBlockWithWaitInternal(cacheKey, cachedItem, inMemory, wait);
594      }
595    }
596  }
597
598  protected boolean shouldReplaceExistingCacheBlock(BlockCacheKey cacheKey, Cacheable newBlock) {
599    return BlockCacheUtil.shouldReplaceExistingCacheBlock(this, cacheKey, newBlock);
600  }
601
602  protected void cacheBlockWithWaitInternal(BlockCacheKey cacheKey, Cacheable cachedItem,
603    boolean inMemory, boolean wait) {
604    if (!isCacheEnabled()) {
605      return;
606    }
607    if (cacheKey.getBlockType() == null && cachedItem.getBlockType() != null) {
608      cacheKey.setBlockType(cachedItem.getBlockType());
609    }
610    LOG.debug("Caching key={}, item={}, key heap size={}", cacheKey, cachedItem,
611      cacheKey.heapSize());
612    // Stuff the entry into the RAM cache so it can get drained to the persistent store
613    RAMQueueEntry re = new RAMQueueEntry(cacheKey, cachedItem, accessCount.incrementAndGet(),
614      inMemory, isCachePersistent() && ioEngine instanceof FileIOEngine, wait);
615    /**
616     * Don't use ramCache.put(cacheKey, re) here. because there may be a existing entry with same
617     * key in ramCache, the heap size of bucket cache need to update if replacing entry from
618     * ramCache. But WriterThread will also remove entry from ramCache and update heap size, if
619     * using ramCache.put(), It's possible that the removed entry in WriterThread is not the correct
620     * one, then the heap size will mess up (HBASE-20789)
621     */
622    if (ramCache.putIfAbsent(cacheKey, re) != null) {
623      return;
624    }
625    int queueNum = (cacheKey.hashCode() & 0x7FFFFFFF) % writerQueues.size();
626    BlockingQueue<RAMQueueEntry> bq = writerQueues.get(queueNum);
627    boolean successfulAddition = false;
628    if (wait) {
629      try {
630        successfulAddition = bq.offer(re, queueAdditionWaitTime, TimeUnit.MILLISECONDS);
631      } catch (InterruptedException e) {
632        LOG.error("Thread interrupted: ", e);
633        Thread.currentThread().interrupt();
634      }
635    } else {
636      successfulAddition = bq.offer(re);
637    }
638    if (!successfulAddition) {
639      LOG.debug("Failed to insert block {} into the cache writers queue", cacheKey);
640      ramCache.remove(cacheKey);
641      cacheStats.failInsert();
642    } else {
643      this.blockNumber.increment();
644      this.heapSize.add(cachedItem.heapSize());
645    }
646  }
647
648  /**
649   * If the passed cache key relates to a reference (&lt;hfile&gt;.&lt;parentEncRegion&gt;), this
650   * method looks for the block from the referred file, in the cache. If present in the cache, the
651   * block for the referred file is returned, otherwise, this method returns null. It will also
652   * return null if the passed cache key doesn't relate to a reference.
653   * @param key the BlockCacheKey instance to look for in the cache.
654   * @return the cached block from the referred file, null if there's no such block in the cache or
655   *         the passed key doesn't relate to a reference.
656   */
657  public BucketEntry getBlockForReference(BlockCacheKey key) {
658    BlockCacheKey referredKey = getBlockKeyForReference(key);
659    BucketEntry foundEntry = referredKey != null ? backingMap.get(referredKey) : null;
660    if (referredKey != null) {
661      LOG.debug("Got a link/ref: {}. Related cacheKey: {}. Found entry: {}", key.getHfileName(),
662        referredKey, foundEntry);
663    }
664    return foundEntry;
665  }
666
667  private BlockCacheKey getBlockKeyForReference(BlockCacheKey key) {
668    if (!StoreFileInfo.isReference(key.getHfileName())) {
669      return null;
670    }
671    String referredFileName =
672      StoreFileInfo.getReferredToRegionAndFile(key.getHfileName()).getSecond();
673    return referredFileName != null ? new BlockCacheKey(referredFileName, key.getOffset()) : null;
674  }
675
676  /**
677   * Get the buffer of the block with the specified key.
678   * @param key                block's cache key
679   * @param caching            true if the caller caches blocks on cache misses
680   * @param repeat             Whether this is a repeat lookup for the same block
681   * @param updateCacheMetrics Whether we should update cache metrics or not
682   * @return buffer of specified cache key, or null if not in cache
683   */
684  @Override
685  public Cacheable getBlock(BlockCacheKey key, boolean caching, boolean repeat,
686    boolean updateCacheMetrics) {
687    if (!isCacheEnabled()) {
688      cacheStats.miss(caching, key.isPrimary(), key.getBlockType());
689      return null;
690    }
691    RAMQueueEntry re = ramCache.get(key);
692    if (re != null) {
693      if (updateCacheMetrics) {
694        cacheStats.hit(caching, key.isPrimary(), key.getBlockType());
695      }
696      re.access(accessCount.incrementAndGet());
697      return re.getData();
698    }
699    BlockCacheKey backingMapLookupKey = key;
700    BucketEntry bucketEntry = backingMap.get(backingMapLookupKey);
701    LOG.debug("bucket entry for key {}: {}", key,
702      bucketEntry == null ? null : bucketEntry.offset());
703    if (bucketEntry == null) {
704      backingMapLookupKey = getBlockKeyForReference(key);
705      if (backingMapLookupKey != null) {
706        bucketEntry = backingMap.get(backingMapLookupKey);
707        LOG.debug("Got a link/ref: {}. Related cacheKey: {}. Found entry: {}", key.getHfileName(),
708          backingMapLookupKey, bucketEntry);
709      }
710    }
711    if (bucketEntry != null) {
712      long start = System.nanoTime();
713      ReentrantReadWriteLock lock = offsetLock.getLock(bucketEntry.offset());
714      boolean inconsistentEntry = false;
715      try {
716        lock.readLock().lock();
717        // We can not read here even if backingMap does contain the given key because its offset
718        // maybe changed. If we lock BlockCacheKey instead of offset, then we can only check
719        // existence here.
720        if (bucketEntry.equals(backingMap.get(backingMapLookupKey))) {
721          // Read the block from IOEngine based on the bucketEntry's offset and length, NOTICE: the
722          // block will use the refCnt of bucketEntry, which means if two HFileBlock mapping to
723          // the same BucketEntry, then all of the three will share the same refCnt.
724          Cacheable cachedBlock = ioEngine.read(bucketEntry);
725          if (ioEngine.usesSharedMemory()) {
726            // If IOEngine use shared memory, cachedBlock and BucketEntry will share the
727            // same RefCnt, do retain here, in order to count the number of RPC references
728            cachedBlock.retain();
729          }
730          // Update the cache statistics.
731          if (updateCacheMetrics) {
732            cacheStats.hit(caching, key.isPrimary(), key.getBlockType());
733            cacheStats.ioHit(System.nanoTime() - start);
734          }
735          bucketEntry.access(accessCount.incrementAndGet());
736          if (this.ioErrorStartTime > 0) {
737            ioErrorStartTime = -1;
738          }
739          return cachedBlock;
740        }
741      } catch (HBaseIOException hioex) {
742        // FileIOEngine throws this when its cached time differs from the persisted index. A plain
743        // IOException still follows the configured tolerance policy below.
744        inconsistentEntry = true;
745        LOG.debug("Failed to fetch block for cache key: {}.", key, hioex);
746      } catch (IOException ioex) {
747        LOG.error("Failed reading block " + key + " from bucket cache", ioex);
748        checkIOErrorIsTolerated();
749      } finally {
750        lock.readLock().unlock();
751      }
752      if (inconsistentEntry) {
753        evictInconsistentEntry(backingMapLookupKey, bucketEntry);
754      }
755    }
756    if (!repeat && updateCacheMetrics) {
757      cacheStats.miss(caching, key.isPrimary(), key.getBlockType());
758    }
759    return null;
760  }
761
762  private void evictInconsistentEntry(BlockCacheKey lookupKey, BucketEntry bucketEntry) {
763    BlockCacheKey storedKey = blocksByHFile.ceiling(lookupKey);
764    if (storedKey == null || !storedKey.equals(lookupKey)) {
765      return;
766    }
767    bucketEntry.withWriteLock(offsetLock, () -> {
768      if (backingMap.remove(storedKey, bucketEntry)) {
769        blockEvicted(storedKey, bucketEntry, true, false);
770      }
771      return null;
772    });
773  }
774
775  /**
776   * This method is invoked after the bucketEntry is removed from {@link BucketCache#backingMap}
777   */
778  void blockEvicted(BlockCacheKey cacheKey, BucketEntry bucketEntry, boolean decrementBlockNumber,
779    boolean evictedByEvictionProcess) {
780    bucketEntry.markAsEvicted();
781    blocksByHFile.remove(cacheKey);
782    // putIntoBackingMap accounts every entry added to the backingMap, regardless of the IOEngine,
783    // so every entry removed from it must be decremented as well.
784    updateRegionCachedSize(cacheKey, (bucketEntry.getLength() * -1));
785    if (decrementBlockNumber) {
786      this.blockNumber.decrement();
787      if (ioEngine.isPersistent()) {
788        fullyCachedFiles.remove(cacheKey.getHfileName());
789      }
790    }
791    if (evictedByEvictionProcess) {
792      cacheStats.evicted(bucketEntry.getCachedTime(), cacheKey.isPrimary());
793    }
794    if (ioEngine.isPersistent()) {
795      setCacheInconsistent(true);
796    }
797  }
798
799  public void fileCacheCompleted(Path filePath, long size) {
800    Pair<String, Long> pair = new Pair<>();
801    // sets the region name
802    String regionName = filePath.getParent().getParent().getName();
803    pair.setFirst(regionName);
804    pair.setSecond(size);
805    fullyCachedFiles.put(filePath.getName(), pair);
806  }
807
808  private void updateRegionCachedSize(BlockCacheKey key, long cachedSize) {
809    if (key.getRegionName() != null) {
810      if (key.isArchived()) {
811        LOG.trace("Skipping region cached size update for archived file:{} from region: {}",
812          key.getHfileName(), key.getRegionName());
813      } else {
814        String regionName = key.getRegionName();
815        regionCachedSize.merge(regionName, cachedSize,
816          (previousSize, newBlockSize) -> previousSize + newBlockSize);
817        // If all the blocks for a region are evicted from the cache,
818        // remove the entry for that region from regionCachedSize map.
819        if (regionCachedSize.getOrDefault(regionName, 0L) <= 0) {
820          regionCachedSize.remove(regionName);
821        }
822      }
823    }
824  }
825
826  /**
827   * Free the {{@link BucketEntry} actually,which could only be invoked when the
828   * {@link BucketEntry#refCnt} becoming 0.
829   */
830  void freeBucketEntry(BucketEntry bucketEntry) {
831    bucketAllocator.freeBlock(bucketEntry.offset(), bucketEntry.getLength());
832    realCacheSize.add(-1 * bucketEntry.getLength());
833  }
834
835  /**
836   * Try to evict the block from {@link BlockCache} by force. We'll call this in few cases:<br>
837   * 1. Close an HFile, and clear all cached blocks. <br>
838   * 2. Call {@link Admin#clearBlockCache(TableName)} to clear all blocks for a given table.<br>
839   * <p>
840   * Firstly, we'll try to remove the block from RAMCache,and then try to evict from backingMap.
841   * Here we evict the block from backingMap immediately, but only free the reference from bucket
842   * cache by calling {@link BucketEntry#markedAsEvicted}. If there're still some RPC referring this
843   * block, block can only be de-allocated when all of them release the block.
844   * <p>
845   * NOTICE: we need to grab the write offset lock firstly before releasing the reference from
846   * bucket cache. if we don't, we may read an {@link BucketEntry} with refCnt = 0 when
847   * {@link BucketCache#getBlock(BlockCacheKey, boolean, boolean, boolean)}, it's a memory leak.
848   * @param cacheKey Block to evict
849   * @return true to indicate whether we've evicted successfully or not.
850   */
851  @Override
852  public boolean evictBlock(BlockCacheKey cacheKey) {
853    return doEvictBlock(cacheKey, null, false);
854  }
855
856  /**
857   * Evict the {@link BlockCacheKey} and {@link BucketEntry} from {@link BucketCache#backingMap} and
858   * {@link BucketCache#ramCache}. <br/>
859   * NOTE:When Evict from {@link BucketCache#backingMap},only the matched {@link BlockCacheKey} and
860   * {@link BucketEntry} could be removed.
861   * @param cacheKey    {@link BlockCacheKey} to evict.
862   * @param bucketEntry {@link BucketEntry} matched {@link BlockCacheKey} to evict.
863   * @return true to indicate whether we've evicted successfully or not.
864   */
865  private boolean doEvictBlock(BlockCacheKey cacheKey, BucketEntry bucketEntry,
866    boolean evictedByEvictionProcess) {
867    if (!isCacheEnabled()) {
868      return false;
869    }
870    boolean existedInRamCache = removeFromRamCache(cacheKey);
871    if (bucketEntry == null) {
872      bucketEntry = backingMap.get(cacheKey);
873    }
874    final BucketEntry bucketEntryToUse = bucketEntry;
875
876    if (bucketEntryToUse == null) {
877      if (existedInRamCache && evictedByEvictionProcess) {
878        cacheStats.evicted(0, cacheKey.isPrimary());
879      }
880      return existedInRamCache;
881    } else {
882      return bucketEntryToUse.withWriteLock(offsetLock, () -> {
883        if (backingMap.remove(cacheKey, bucketEntryToUse)) {
884          LOG.debug("removed key {} from back map with offset lock {} in the evict process",
885            cacheKey, bucketEntryToUse.offset());
886          blockEvicted(cacheKey, bucketEntryToUse, !existedInRamCache, evictedByEvictionProcess);
887          return true;
888        }
889        return false;
890      });
891    }
892  }
893
894  /**
895   * <pre>
896   * Create the {@link Recycler} for {@link BucketEntry#refCnt},which would be used as
897   * {@link RefCnt#recycler} of {@link HFileBlock#buf} returned from {@link BucketCache#getBlock}.
898   * NOTE: for {@link BucketCache#getBlock},the {@link RefCnt#recycler} of {@link HFileBlock#buf}
899   * from {@link BucketCache#backingMap} and {@link BucketCache#ramCache} are different:
900   * 1.For {@link RefCnt#recycler} of {@link HFileBlock#buf} from {@link BucketCache#backingMap},
901   *   it is the return value of current {@link BucketCache#createRecycler} method.
902   *
903   * 2.For {@link RefCnt#recycler} of {@link HFileBlock#buf} from {@link BucketCache#ramCache},
904   *   it is {@link ByteBuffAllocator#putbackBuffer}.
905   * </pre>
906   */
907  public Recycler createRecycler(final BucketEntry bucketEntry) {
908    return () -> {
909      freeBucketEntry(bucketEntry);
910      return;
911    };
912  }
913
914  /**
915   * NOTE: This method is only for test.
916   */
917  public boolean evictBlockIfNoRpcReferenced(BlockCacheKey blockCacheKey) {
918    BucketEntry bucketEntry = backingMap.get(blockCacheKey);
919    if (bucketEntry == null) {
920      return false;
921    }
922    return evictBucketEntryIfNoRpcReferenced(blockCacheKey, bucketEntry);
923  }
924
925  /**
926   * Evict {@link BlockCacheKey} and its corresponding {@link BucketEntry} only if
927   * {@link BucketEntry#isRpcRef} is false. <br/>
928   * NOTE:When evict from {@link BucketCache#backingMap},only the matched {@link BlockCacheKey} and
929   * {@link BucketEntry} could be removed.
930   * @param blockCacheKey {@link BlockCacheKey} to evict.
931   * @param bucketEntry   {@link BucketEntry} matched {@link BlockCacheKey} to evict.
932   * @return true to indicate whether we've evicted successfully or not.
933   */
934  boolean evictBucketEntryIfNoRpcReferenced(BlockCacheKey blockCacheKey, BucketEntry bucketEntry) {
935    if (!bucketEntry.isRpcRef()) {
936      return doEvictBlock(blockCacheKey, bucketEntry, true);
937    }
938    return false;
939  }
940
941  /**
942   * Since HBASE-29249, the following properties governin freeSpace behaviour and block priorities
943   * were made dynamically configurable: - hbase.bucketcache.acceptfactor -
944   * hbase.bucketcache.minfactor - hbase.bucketcache.extrafreefactor -
945   * hbase.bucketcache.single.factor - hbase.bucketcache.multi.factor -
946   * hbase.bucketcache.multi.factor - hbase.bucketcache.memory.factor The
947   * hbase.bucketcache.queue.addition.waittime property allows for introducing a delay in the
948   * publishing of blocks for the cache writer threads during prefetch reads only (client reads
949   * wouldn't get delayed). It has also been made dynamic configurable since HBASE-29249. The
950   * hbase.bucketcache.persist.intervalinmillis property determines the frequency for saving the
951   * persistent cache, and it has also been made dynamically configurable since HBASE-29249. The new
952   * interval applies to subsequent sleeps without interrupting a sleep already in progress. The
953   * hbase.bucketcache.persistence.chunksize property determines the size of the persistent file
954   * splits (due to the limitation of maximum allowed protobuff size), and it has also been made
955   * dynamically configurable since HBASE-29249.
956   * @param config the new configuration to be updated.
957   */
958  @Override
959  public void onConfigurationChange(Configuration config) {
960    this.acceptableFactor = conf.getFloat(ACCEPT_FACTOR_CONFIG_NAME, DEFAULT_ACCEPT_FACTOR);
961    this.minFactor = conf.getFloat(MIN_FACTOR_CONFIG_NAME, DEFAULT_MIN_FACTOR);
962    this.extraFreeFactor = conf.getFloat(EXTRA_FREE_FACTOR_CONFIG_NAME, DEFAULT_EXTRA_FREE_FACTOR);
963    this.singleFactor = conf.getFloat(SINGLE_FACTOR_CONFIG_NAME, DEFAULT_SINGLE_FACTOR);
964    this.multiFactor = conf.getFloat(MULTI_FACTOR_CONFIG_NAME, DEFAULT_MULTI_FACTOR);
965    this.memoryFactor = conf.getFloat(MEMORY_FACTOR_CONFIG_NAME, DEFAULT_MEMORY_FACTOR);
966    this.queueAdditionWaitTime =
967      conf.getLong(QUEUE_ADDITION_WAIT_TIME, DEFAULT_QUEUE_ADDITION_WAIT_TIME);
968    this.bucketcachePersistInterval = conf.getLong(BUCKETCACHE_PERSIST_INTERVAL_KEY, 1000);
969    this.persistenceChunkSize =
970      conf.getLong(BACKING_MAP_PERSISTENCE_CHUNK_SIZE, DEFAULT_BACKING_MAP_PERSISTENCE_CHUNK_SIZE);
971    sanityCheckConfigs();
972  }
973
974  protected boolean removeFromRamCache(BlockCacheKey cacheKey) {
975    return ramCache.remove(cacheKey, re -> {
976      if (re != null) {
977        this.blockNumber.decrement();
978        this.heapSize.add(-1 * re.getData().heapSize());
979      }
980    });
981  }
982
983  public boolean isCacheInconsistent() {
984    return isCacheInconsistent.get();
985  }
986
987  public void setCacheInconsistent(boolean setCacheInconsistent) {
988    isCacheInconsistent.set(setCacheInconsistent);
989  }
990
991  protected void setCacheState(CacheState state) {
992    cacheState = state;
993  }
994
995  /*
996   * Statistics thread. Periodically output cache statistics to the log.
997   */
998  private static class StatisticsThread extends Thread {
999    private final BucketCache bucketCache;
1000
1001    public StatisticsThread(BucketCache bucketCache) {
1002      super("BucketCacheStatsThread");
1003      setDaemon(true);
1004      this.bucketCache = bucketCache;
1005    }
1006
1007    @Override
1008    public void run() {
1009      bucketCache.logStats();
1010    }
1011  }
1012
1013  public void logStats() {
1014    if (!isCacheInitialized("BucketCache::logStats")) {
1015      return;
1016    }
1017
1018    long totalSize = bucketAllocator.getTotalSize();
1019    long usedSize = bucketAllocator.getUsedSize();
1020    long freeSize = totalSize - usedSize;
1021    long cacheSize = getRealCacheSize();
1022    LOG.info("failedBlockAdditions=" + cacheStats.getFailedInserts() + ", " + "totalSize="
1023      + StringUtils.byteDesc(totalSize) + ", " + "freeSize=" + StringUtils.byteDesc(freeSize) + ", "
1024      + "usedSize=" + StringUtils.byteDesc(usedSize) + ", " + "cacheSize="
1025      + StringUtils.byteDesc(cacheSize) + ", " + "accesses=" + cacheStats.getRequestCount() + ", "
1026      + "hits=" + cacheStats.getHitCount() + ", " + "IOhitsPerSecond="
1027      + cacheStats.getIOHitsPerSecond() + ", " + "IOTimePerHit="
1028      + String.format("%.2f", cacheStats.getIOTimePerHit()) + ", " + "hitRatio="
1029      + (cacheStats.getHitCount() == 0
1030        ? "0,"
1031        : (StringUtils.formatPercent(cacheStats.getHitRatio(), 2) + ", "))
1032      + "cachingAccesses=" + cacheStats.getRequestCachingCount() + ", " + "cachingHits="
1033      + cacheStats.getHitCachingCount() + ", " + "cachingHitsRatio="
1034      + (cacheStats.getHitCachingCount() == 0
1035        ? "0,"
1036        : (StringUtils.formatPercent(cacheStats.getHitCachingRatio(), 2) + ", "))
1037      + "evictions=" + cacheStats.getEvictionCount() + ", " + "evicted="
1038      + cacheStats.getEvictedCount() + ", " + "evictedPerRun=" + cacheStats.evictedPerEviction()
1039      + ", " + "allocationFailCount=" + cacheStats.getAllocationFailCount() + ", blocksCount="
1040      + backingMap.size());
1041    cacheStats.reset();
1042
1043    bucketAllocator.logDebugStatistics();
1044  }
1045
1046  public long getRealCacheSize() {
1047    return this.realCacheSize.sum();
1048  }
1049
1050  public long acceptableSize() {
1051    if (!isCacheInitialized("BucketCache::acceptableSize")) {
1052      return 0;
1053    }
1054    return (long) Math.floor(bucketAllocator.getTotalSize() * acceptableFactor);
1055  }
1056
1057  long getPartitionSize(float partitionFactor) {
1058    if (!isCacheInitialized("BucketCache::getPartitionSize")) {
1059      return 0;
1060    }
1061
1062    return (long) Math.floor(bucketAllocator.getTotalSize() * partitionFactor * minFactor);
1063  }
1064
1065  /**
1066   * Return the count of bucketSizeinfos still need free space
1067   */
1068  private int bucketSizesAboveThresholdCount(float minFactor) {
1069    if (!isCacheInitialized("BucketCache::bucketSizesAboveThresholdCount")) {
1070      return 0;
1071    }
1072
1073    BucketAllocator.IndexStatistics[] stats = bucketAllocator.getIndexStatistics();
1074    int fullCount = 0;
1075    for (int i = 0; i < stats.length; i++) {
1076      long freeGoal = (long) Math.floor(stats[i].totalCount() * (1 - minFactor));
1077      freeGoal = Math.max(freeGoal, 1);
1078      if (stats[i].freeCount() < freeGoal) {
1079        fullCount++;
1080      }
1081    }
1082    return fullCount;
1083  }
1084
1085  /**
1086   * This method will find the buckets that are minimally occupied and are not reference counted and
1087   * will free them completely without any constraint on the access times of the elements, and as a
1088   * process will completely free at most the number of buckets passed, sometimes it might not due
1089   * to changing refCounts
1090   * @param completelyFreeBucketsNeeded number of buckets to free
1091   **/
1092  private void freeEntireBuckets(int completelyFreeBucketsNeeded) {
1093    if (!isCacheInitialized("BucketCache::freeEntireBuckets")) {
1094      return;
1095    }
1096
1097    if (completelyFreeBucketsNeeded != 0) {
1098      // First we will build a set where the offsets are reference counted, usually
1099      // this set is small around O(Handler Count) unless something else is wrong
1100      Set<Integer> inUseBuckets = new HashSet<>();
1101      backingMap.forEach((k, be) -> {
1102        if (be.isRpcRef()) {
1103          inUseBuckets.add(bucketAllocator.getBucketIndex(be.offset()));
1104        }
1105      });
1106      Set<Integer> candidateBuckets =
1107        bucketAllocator.getLeastFilledBuckets(inUseBuckets, completelyFreeBucketsNeeded);
1108      for (Map.Entry<BlockCacheKey, BucketEntry> entry : backingMap.entrySet()) {
1109        if (candidateBuckets.contains(bucketAllocator.getBucketIndex(entry.getValue().offset()))) {
1110          evictBucketEntryIfNoRpcReferenced(entry.getKey(), entry.getValue());
1111        }
1112      }
1113    }
1114  }
1115
1116  private long calculateBytesToFree(StringBuilder msgBuffer) {
1117    long bytesToFreeWithoutExtra = 0;
1118    BucketAllocator.IndexStatistics[] stats = bucketAllocator.getIndexStatistics();
1119    long[] bytesToFreeForBucket = new long[stats.length];
1120    for (int i = 0; i < stats.length; i++) {
1121      bytesToFreeForBucket[i] = 0;
1122      long freeGoal = (long) Math.floor(stats[i].totalCount() * (1 - minFactor));
1123      freeGoal = Math.max(freeGoal, 1);
1124      if (stats[i].freeCount() < freeGoal) {
1125        bytesToFreeForBucket[i] = stats[i].itemSize() * (freeGoal - stats[i].freeCount());
1126        bytesToFreeWithoutExtra += bytesToFreeForBucket[i];
1127        if (msgBuffer != null) {
1128          msgBuffer.append("Free for bucketSize(" + stats[i].itemSize() + ")="
1129            + StringUtils.byteDesc(bytesToFreeForBucket[i]) + ", ");
1130        }
1131      }
1132    }
1133    if (msgBuffer != null) {
1134      msgBuffer.append("Free for total=" + StringUtils.byteDesc(bytesToFreeWithoutExtra) + ", ");
1135    }
1136    return bytesToFreeWithoutExtra;
1137  }
1138
1139  /**
1140   * Free the space if the used size reaches acceptableSize() or one size block couldn't be
1141   * allocated. When freeing the space, we use the LRU algorithm and ensure there must be some
1142   * blocks evicted
1143   * @param why Why we are being called
1144   */
1145  void freeSpace(final String why) {
1146    if (!isCacheInitialized("BucketCache::freeSpace")) {
1147      return;
1148    }
1149    // Ensure only one freeSpace progress at a time
1150    if (!freeSpaceLock.tryLock()) {
1151      return;
1152    }
1153    try {
1154      freeInProgress = true;
1155      StringBuilder msgBuffer = LOG.isDebugEnabled() ? new StringBuilder() : null;
1156      long bytesToFreeWithoutExtra = calculateBytesToFree(msgBuffer);
1157      if (bytesToFreeWithoutExtra <= 0) {
1158        return;
1159      }
1160      long currentSize = bucketAllocator.getUsedSize();
1161      long totalSize = bucketAllocator.getTotalSize();
1162      if (LOG.isDebugEnabled() && msgBuffer != null) {
1163        LOG.debug("Free started because \"" + why + "\"; " + msgBuffer + " of current used="
1164          + StringUtils.byteDesc(currentSize) + ", actual cacheSize="
1165          + StringUtils.byteDesc(realCacheSize.sum()) + ", total="
1166          + StringUtils.byteDesc(totalSize));
1167      }
1168      long bytesToFreeWithExtra =
1169        (long) Math.floor(bytesToFreeWithoutExtra * (1 + extraFreeFactor));
1170      // Instantiate priority buckets
1171      BucketEntryGroup bucketSingle =
1172        new BucketEntryGroup(bytesToFreeWithExtra, blockSize, getPartitionSize(singleFactor));
1173      BucketEntryGroup bucketMulti =
1174        new BucketEntryGroup(bytesToFreeWithExtra, blockSize, getPartitionSize(multiFactor));
1175      BucketEntryGroup bucketMemory =
1176        new BucketEntryGroup(bytesToFreeWithExtra, blockSize, getPartitionSize(memoryFactor));
1177
1178      Set<String> allValidFiles = null;
1179      // We need the region/stores/files tree, in order to figure out if a block is "orphan" or not.
1180      // See further comments below for more details.
1181      if (onlineRegions != null) {
1182        allValidFiles = BlockCacheUtil.listAllFilesNames(onlineRegions);
1183      }
1184      // the cached time is recored in nanos, so we need to convert the grace period accordingly
1185      long orphanGracePeriodNanos = orphanBlockGracePeriod * 1000000;
1186      long bytesFreed = 0;
1187      // Check the list of files to determine the cold files which can be readily evicted.
1188      Map<String, String> coldFiles = null;
1189
1190      DataTieringManager dataTieringManager = DataTieringManager.getInstance();
1191      if (dataTieringManager != null) {
1192        coldFiles = dataTieringManager.getColdFilesList();
1193      }
1194      // Scan entire map putting bucket entry into appropriate bucket entry
1195      // group
1196      for (Map.Entry<BlockCacheKey, BucketEntry> bucketEntryWithKey : backingMap.entrySet()) {
1197        BlockCacheKey key = bucketEntryWithKey.getKey();
1198        BucketEntry entry = bucketEntryWithKey.getValue();
1199        // Under certain conditions, blocks for regions not on the current region server might
1200        // be hanging on the cache. For example, when using the persistent cache feature, if the
1201        // RS crashes, then if not the same regions are assigned back once its online again, blocks
1202        // for the previous online regions would be recovered and stay in the cache. These would be
1203        // "orphan" blocks, as the files these blocks belong to are not in any of the online
1204        // regions.
1205        // "Orphan" blocks are a pure waste of cache space and should be evicted first during
1206        // the freespace run.
1207        // Compactions and Flushes may cache blocks before its files are completely written. In
1208        // these cases the file won't be found in any of the online regions stores, but the block
1209        // shouldn't be evicted. To avoid this, we defined this
1210        // hbase.bucketcache.block.orphan.evictgraceperiod property, to account for a grace
1211        // period (default 24 hours) where a block should be checked if it's an orphan block.
1212        if (
1213          allValidFiles != null
1214            && entry.getCachedTime() < (System.nanoTime() - orphanGracePeriodNanos)
1215        ) {
1216          if (!allValidFiles.contains(key.getHfileName())) {
1217            if (evictBucketEntryIfNoRpcReferenced(key, entry)) {
1218              // We calculate the freed bytes, but we don't stop if the goal was reached because
1219              // these are orphan blocks anyway, so let's leverage this run of freeSpace
1220              // to get rid of all orphans at once.
1221              bytesFreed += entry.getLength();
1222              continue;
1223            }
1224          }
1225        }
1226
1227        if (
1228          bytesFreed < bytesToFreeWithExtra && coldFiles != null
1229            && coldFiles.containsKey(bucketEntryWithKey.getKey().getHfileName())
1230        ) {
1231          int freedBlockSize = bucketEntryWithKey.getValue().getLength();
1232          if (evictBlockIfNoRpcReferenced(bucketEntryWithKey.getKey())) {
1233            bytesFreed += freedBlockSize;
1234          }
1235          continue;
1236        }
1237
1238        switch (entry.getPriority()) {
1239          case SINGLE: {
1240            bucketSingle.add(bucketEntryWithKey);
1241            break;
1242          }
1243          case MULTI: {
1244            bucketMulti.add(bucketEntryWithKey);
1245            break;
1246          }
1247          case MEMORY: {
1248            bucketMemory.add(bucketEntryWithKey);
1249            break;
1250          }
1251        }
1252      }
1253
1254      // Check if the cold file eviction is sufficient to create enough space.
1255      bytesToFreeWithExtra -= bytesFreed;
1256      if (bytesToFreeWithExtra <= 0) {
1257        LOG.debug("Bucket cache free space completed; freed space : {} bytes of cold data blocks.",
1258          StringUtils.byteDesc(bytesFreed));
1259        return;
1260      }
1261
1262      if (LOG.isDebugEnabled()) {
1263        LOG.debug(
1264          "Bucket cache free space completed; freed space : {} "
1265            + "bytes of cold data blocks. {} more bytes required to be freed.",
1266          StringUtils.byteDesc(bytesFreed), bytesToFreeWithExtra);
1267      }
1268
1269      PriorityQueue<BucketEntryGroup> bucketQueue =
1270        new PriorityQueue<>(3, Comparator.comparingLong(BucketEntryGroup::overflow));
1271
1272      bucketQueue.add(bucketSingle);
1273      bucketQueue.add(bucketMulti);
1274      bucketQueue.add(bucketMemory);
1275
1276      int remainingBuckets = bucketQueue.size();
1277      BucketEntryGroup bucketGroup;
1278      while ((bucketGroup = bucketQueue.poll()) != null) {
1279        long overflow = bucketGroup.overflow();
1280        if (overflow > 0) {
1281          long bucketBytesToFree =
1282            Math.min(overflow, (bytesToFreeWithoutExtra - bytesFreed) / remainingBuckets);
1283          bytesFreed += bucketGroup.free(bucketBytesToFree);
1284        }
1285        remainingBuckets--;
1286      }
1287
1288      // Check and free if there are buckets that still need freeing of space
1289      if (bucketSizesAboveThresholdCount(minFactor) > 0) {
1290        bucketQueue.clear();
1291        remainingBuckets = 3;
1292        bucketQueue.add(bucketSingle);
1293        bucketQueue.add(bucketMulti);
1294        bucketQueue.add(bucketMemory);
1295        while ((bucketGroup = bucketQueue.poll()) != null) {
1296          long bucketBytesToFree = (bytesToFreeWithExtra - bytesFreed) / remainingBuckets;
1297          bytesFreed += bucketGroup.free(bucketBytesToFree);
1298          remainingBuckets--;
1299        }
1300      }
1301      // Even after the above free we might still need freeing because of the
1302      // De-fragmentation of the buckets (also called Slab Calcification problem), i.e
1303      // there might be some buckets where the occupancy is very sparse and thus are not
1304      // yielding the free for the other bucket sizes, the fix for this to evict some
1305      // of the buckets, we do this by evicting the buckets that are least fulled
1306      freeEntireBuckets(DEFAULT_FREE_ENTIRE_BLOCK_FACTOR * bucketSizesAboveThresholdCount(1.0f));
1307
1308      if (LOG.isDebugEnabled()) {
1309        long single = bucketSingle.totalSize();
1310        long multi = bucketMulti.totalSize();
1311        long memory = bucketMemory.totalSize();
1312        if (LOG.isDebugEnabled()) {
1313          LOG.debug("Bucket cache free space completed; " + "freed="
1314            + StringUtils.byteDesc(bytesFreed) + ", " + "total=" + StringUtils.byteDesc(totalSize)
1315            + ", " + "single=" + StringUtils.byteDesc(single) + ", " + "multi="
1316            + StringUtils.byteDesc(multi) + ", " + "memory=" + StringUtils.byteDesc(memory));
1317        }
1318      }
1319    } catch (Throwable t) {
1320      LOG.warn("Failed freeing space", t);
1321    } finally {
1322      cacheStats.evict();
1323      freeInProgress = false;
1324      freeSpaceLock.unlock();
1325    }
1326  }
1327
1328  // This handles flushing the RAM cache to IOEngine.
1329  class WriterThread extends Thread {
1330    private final BlockingQueue<RAMQueueEntry> inputQueue;
1331    private volatile boolean writerEnabled = true;
1332    private final ByteBuffer metaBuff = ByteBuffer.allocate(HFileBlock.BLOCK_METADATA_SPACE);
1333
1334    WriterThread(BlockingQueue<RAMQueueEntry> queue) {
1335      super("BucketCacheWriterThread");
1336      this.inputQueue = queue;
1337    }
1338
1339    // Used for test
1340    void disableWriter() {
1341      this.writerEnabled = false;
1342    }
1343
1344    @Override
1345    public void run() {
1346      List<RAMQueueEntry> entries = new ArrayList<>();
1347      try {
1348        while (isCacheEnabled() && writerEnabled) {
1349          try {
1350            try {
1351              // Blocks
1352              entries = getRAMQueueEntries(inputQueue, entries);
1353            } catch (InterruptedException ie) {
1354              if (!isCacheEnabled() || !writerEnabled) {
1355                break;
1356              }
1357            }
1358            doDrain(entries, metaBuff);
1359          } catch (Exception ioe) {
1360            LOG.error("WriterThread encountered error", ioe);
1361          }
1362        }
1363      } catch (Throwable t) {
1364        LOG.warn("Failed doing drain", t);
1365      }
1366      LOG.info(this.getName() + " exiting, cacheEnabled=" + isCacheEnabled());
1367    }
1368  }
1369
1370  /**
1371   * Put the new bucket entry into backingMap. Notice that we are allowed to replace the existing
1372   * cache with a new block for the same cache key. there's a corner case: one thread cache a block
1373   * in ramCache, copy to io-engine and add a bucket entry to backingMap. Caching another new block
1374   * with the same cache key do the same thing for the same cache key, so if not evict the previous
1375   * bucket entry, then memory leak happen because the previous bucketEntry is gone but the
1376   * bucketAllocator do not free its memory.
1377   * @see BlockCacheUtil#shouldReplaceExistingCacheBlock(BlockCache blockCache,BlockCacheKey
1378   *      cacheKey, Cacheable newBlock)
1379   * @param key         Block cache key
1380   * @param bucketEntry Bucket entry to put into backingMap.
1381   */
1382  protected void putIntoBackingMap(BlockCacheKey key, BucketEntry bucketEntry) {
1383    BucketEntry previousEntry = backingMap.put(key, bucketEntry);
1384    updateRegionCachedSize(key, bucketEntry.getLength());
1385    if (previousEntry != null && previousEntry != bucketEntry) {
1386      previousEntry.withWriteLock(offsetLock, () -> {
1387        blockEvicted(key, previousEntry, false, false);
1388        return null;
1389      });
1390    }
1391    bucketEntry.withWriteLock(offsetLock, () -> {
1392      if (backingMap.get(key) == bucketEntry) {
1393        blocksByHFile.add(key);
1394      }
1395      return null;
1396    });
1397  }
1398
1399  /**
1400   * Prepare and return a warning message for Bucket Allocator Exception
1401   * @param fle The exception
1402   * @param re  The RAMQueueEntry for which the exception was thrown.
1403   * @return A warning message created from the input RAMQueueEntry object.
1404   */
1405  private static String getAllocationFailWarningMessage(final BucketAllocatorException fle,
1406    final RAMQueueEntry re) {
1407    final StringBuilder sb = new StringBuilder();
1408    sb.append("Most recent failed allocation after ");
1409    sb.append(ALLOCATION_FAIL_LOG_TIME_PERIOD);
1410    sb.append(" ms;");
1411    if (re != null) {
1412      if (re.getData() instanceof HFileBlock) {
1413        final HFileContext fileContext = ((HFileBlock) re.getData()).getHFileContext();
1414        final String columnFamily = Bytes.toString(fileContext.getColumnFamily());
1415        final String tableName = Bytes.toString(fileContext.getTableName());
1416        if (tableName != null) {
1417          sb.append(" Table: ");
1418          sb.append(tableName);
1419        }
1420        if (columnFamily != null) {
1421          sb.append(" CF: ");
1422          sb.append(columnFamily);
1423        }
1424        sb.append(" HFile: ");
1425        if (fileContext.getHFileName() != null) {
1426          sb.append(fileContext.getHFileName());
1427        } else {
1428          sb.append(re.getKey());
1429        }
1430      } else {
1431        sb.append(" HFile: ");
1432        sb.append(re.getKey());
1433      }
1434    }
1435    sb.append(" Message: ");
1436    sb.append(fle.getMessage());
1437    return sb.toString();
1438  }
1439
1440  /**
1441   * Flush the entries in ramCache to IOEngine and add bucket entry to backingMap. Process all that
1442   * are passed in even if failure being sure to remove from ramCache else we'll never undo the
1443   * references and we'll OOME.
1444   * @param entries Presumes list passed in here will be processed by this invocation only. No
1445   *                interference expected.
1446   */
1447  void doDrain(final List<RAMQueueEntry> entries, ByteBuffer metaBuff) throws InterruptedException {
1448    if (entries.isEmpty()) {
1449      return;
1450    }
1451    // This method is a little hard to follow. We run through the passed in entries and for each
1452    // successful add, we add a non-null BucketEntry to the below bucketEntries. Later we must
1453    // do cleanup making sure we've cleared ramCache of all entries regardless of whether we
1454    // successfully added the item to the bucketcache; if we don't do the cleanup, we'll OOME by
1455    // filling ramCache. We do the clean up by again running through the passed in entries
1456    // doing extra work when we find a non-null bucketEntries corresponding entry.
1457    final int size = entries.size();
1458    BucketEntry[] bucketEntries = new BucketEntry[size];
1459    // Index updated inside loop if success or if we can't succeed. We retry if cache is full
1460    // when we go to add an entry by going around the loop again without upping the index.
1461    int index = 0;
1462    while (isCacheEnabled() && index < size) {
1463      RAMQueueEntry re = null;
1464      try {
1465        re = entries.get(index);
1466        if (re == null) {
1467          LOG.warn("Couldn't get entry or changed on us; who else is messing with it?");
1468          index++;
1469          continue;
1470        }
1471        // Reset the position for reuse.
1472        // It should be guaranteed that the data in the metaBuff has been transferred to the
1473        // ioEngine safely. Otherwise, this reuse is problematic. Fortunately, the data is already
1474        // transferred with our current IOEngines. Should take care, when we have new kinds of
1475        // IOEngine in the future.
1476        metaBuff.clear();
1477        BucketEntry bucketEntry = re.writeToCache(ioEngine, bucketAllocator, realCacheSize,
1478          this::createRecycler, metaBuff, acceptableSize());
1479        // Successfully added. Up index and add bucketEntry. Clear io exceptions.
1480        bucketEntries[index] = bucketEntry;
1481        if (ioErrorStartTime > 0) {
1482          ioErrorStartTime = -1;
1483        }
1484        index++;
1485      } catch (BucketAllocatorException fle) {
1486        long currTs = EnvironmentEdgeManager.currentTime();
1487        cacheStats.allocationFailed(); // Record the warning.
1488        if (
1489          allocFailLogPrevTs == 0 || (currTs - allocFailLogPrevTs) > ALLOCATION_FAIL_LOG_TIME_PERIOD
1490        ) {
1491          LOG.warn(getAllocationFailWarningMessage(fle, re));
1492          allocFailLogPrevTs = currTs;
1493        }
1494        // Presume can't add. Too big? Move index on. Entry will be cleared from ramCache below.
1495        bucketEntries[index] = null;
1496        index++;
1497      } catch (CacheFullException cfe) {
1498        // Cache full when we tried to add. Try freeing space and then retrying (don't up index)
1499        if (!freeInProgress && !re.isPrefetch()) {
1500          freeSpace("Full!");
1501        } else if (re.isPrefetch()) {
1502          bucketEntries[index] = null;
1503          index++;
1504        } else {
1505          Thread.sleep(50);
1506        }
1507      } catch (IOException ioex) {
1508        // Hopefully transient. Retry. checkIOErrorIsTolerated disables cache if problem.
1509        LOG.error("Failed writing to bucket cache", ioex);
1510        checkIOErrorIsTolerated();
1511      }
1512    }
1513
1514    // Make sure data pages are written on media before we update maps.
1515    try {
1516      ioEngine.sync();
1517    } catch (IOException ioex) {
1518      LOG.error("Failed syncing IO engine", ioex);
1519      checkIOErrorIsTolerated();
1520      // Since we failed sync, free the blocks in bucket allocator
1521      for (int i = 0; i < entries.size(); ++i) {
1522        BucketEntry bucketEntry = bucketEntries[i];
1523        if (bucketEntry != null) {
1524          bucketAllocator.freeBlock(bucketEntry.offset(), bucketEntry.getLength());
1525          bucketEntries[i] = null;
1526        }
1527      }
1528    }
1529
1530    // Now add to backingMap if successfully added to bucket cache. Remove from ramCache if
1531    // success or error.
1532    for (int i = 0; i < size; ++i) {
1533      BlockCacheKey key = entries.get(i).getKey();
1534      // Only add if non-null entry.
1535      if (bucketEntries[i] != null) {
1536        putIntoBackingMap(key, bucketEntries[i]);
1537        if (ioEngine.isPersistent()) {
1538          setCacheInconsistent(true);
1539        }
1540      }
1541      // Always remove from ramCache even if we failed adding it to the block cache above.
1542      boolean existed = ramCache.remove(key, re -> {
1543        if (re != null) {
1544          heapSize.add(-1 * re.getData().heapSize());
1545        }
1546      });
1547      if (!existed && bucketEntries[i] != null) {
1548        // Block should have already been evicted. Remove it and free space.
1549        final BucketEntry bucketEntry = bucketEntries[i];
1550        bucketEntry.withWriteLock(offsetLock, () -> {
1551          if (backingMap.remove(key, bucketEntry)) {
1552            blockEvicted(key, bucketEntry, false, false);
1553          }
1554          return null;
1555        });
1556      }
1557      long used = bucketAllocator.getUsedSize();
1558      if (!entries.get(i).isPrefetch() && used > acceptableSize()) {
1559        LOG.debug("Calling freeSpace for block: {}", entries.get(i).getKey());
1560        freeSpace("Used=" + used + " > acceptable=" + acceptableSize());
1561      }
1562    }
1563
1564  }
1565
1566  /**
1567   * Blocks until elements available in {@code q} then tries to grab as many as possible before
1568   * returning.
1569   * @param receptacle Where to stash the elements taken from queue. We clear before we use it just
1570   *                   in case.
1571   * @param q          The queue to take from.
1572   * @return {@code receptacle} laden with elements taken from the queue or empty if none found.
1573   */
1574  static List<RAMQueueEntry> getRAMQueueEntries(BlockingQueue<RAMQueueEntry> q,
1575    List<RAMQueueEntry> receptacle) throws InterruptedException {
1576    // Clear sets all entries to null and sets size to 0. We retain allocations. Presume it
1577    // ok even if list grew to accommodate thousands.
1578    receptacle.clear();
1579    receptacle.add(q.take());
1580    q.drainTo(receptacle);
1581    return receptacle;
1582  }
1583
1584  /**
1585   * @see #retrieveFromFile(int[])
1586   */
1587  @edu.umd.cs.findbugs.annotations.SuppressWarnings(value = "OBL_UNSATISFIED_OBLIGATION",
1588      justification = "false positive, try-with-resources ensures close is called.")
1589  void persistToFile() throws IOException {
1590    persistToFile(entry -> {
1591    });
1592  }
1593
1594  private void persistToFile(Consumer<Map.Entry<BlockCacheKey, BucketEntry>> entryCopiedAction)
1595    throws IOException {
1596    LOG.debug("Thread {} started persisting bucket cache to file",
1597      Thread.currentThread().getName());
1598    if (!isCachePersistent()) {
1599      throw new IOException("Attempt to persist non-persistent cache mappings!");
1600    }
1601    File tempPersistencePath = new File(persistencePath + EnvironmentEdgeManager.currentTime());
1602    try (FileOutputStream fos = new FileOutputStream(tempPersistencePath, false)) {
1603      LOG.debug("Persist in new chunked persistence format.");
1604
1605      persistChunkedBackingMap(fos, entryCopiedAction);
1606
1607      LOG.debug(
1608        "PersistToFile: after persisting backing map size: {}, fullycachedFiles size: {},"
1609          + " file name: {}",
1610        backingMap.size(), fullyCachedFiles.size(), tempPersistencePath.getName());
1611    } catch (IOException e) {
1612      LOG.error("Failed to persist bucket cache to file", e);
1613      throw e;
1614    } catch (Throwable e) {
1615      LOG.error("Failed during persist bucket cache to file: ", e);
1616      throw e;
1617    }
1618    LOG.debug("Thread {} finished persisting bucket cache to file, renaming",
1619      Thread.currentThread().getName());
1620    if (!tempPersistencePath.renameTo(new File(persistencePath))) {
1621      LOG.warn("Failed to commit cache persistent file. We might lose cached blocks if "
1622        + "RS crashes/restarts before we successfully checkpoint again.");
1623    }
1624  }
1625
1626  public boolean isCachePersistent() {
1627    return ioEngine.isPersistent() && persistencePath != null;
1628  }
1629
1630  @Override
1631  public Optional<Map<String, Long>> getRegionCachedInfo() {
1632    return Optional.of(Collections.unmodifiableMap(regionCachedSize));
1633  }
1634
1635  /**
1636   * @see #persistToFile()
1637   */
1638  private void retrieveFromFile(int[] bucketSizes) throws IOException {
1639    LOG.info("Started retrieving bucket cache from file");
1640    File persistenceFile = new File(persistencePath);
1641    if (!persistenceFile.exists()) {
1642      LOG.warn("Persistence file missing! "
1643        + "It's ok if it's first run after enabling persistent cache.");
1644      bucketAllocator = new BucketAllocator(cacheCapacity, bucketSizes, backingMap, realCacheSize);
1645      blockNumber.add(backingMap.size());
1646      backingMapValidated.set(true);
1647      return;
1648    }
1649    assert !isCacheEnabled();
1650
1651    try (FileInputStream in = new FileInputStream(persistenceFile)) {
1652      int pblen = ProtobufMagic.lengthOfPBMagic();
1653      byte[] pbuf = new byte[pblen];
1654      IOUtils.readFully(in, pbuf, 0, pblen);
1655
1656      if (ProtobufMagic.isPBMagicPrefix(pbuf)) {
1657        LOG.info("Reading old format of persistence.");
1658        // The old non-chunked version of backing map persistence.
1659        BucketCacheProtos.BucketCacheEntry cacheEntry =
1660          BucketCacheProtos.BucketCacheEntry.parseDelimitedFrom(in);
1661        if (cacheEntry == null) {
1662          throw new IOException(
1663            "Failed to parse cache entry from persistence file: " + persistencePath);
1664        }
1665        parsePB(cacheEntry);
1666      } else if (Arrays.equals(pbuf, BucketProtoUtils.PB_MAGIC_V2)) {
1667        // The new persistence format of chunked persistence.
1668        LOG.info("Reading new chunked format of persistence.");
1669        retrieveChunkedBackingMap(in);
1670      } else {
1671        // In 3.0 we have enough flexibility to dump the old cache data.
1672        // TODO: In 2.x line, this might need to be filled in to support reading the old format
1673        throw new IOException(
1674          "Persistence file does not start with protobuf magic number. " + persistencePath);
1675      }
1676      bucketAllocator = new BucketAllocator(cacheCapacity, bucketSizes, backingMap, realCacheSize);
1677      blockNumber.add(backingMap.size());
1678      LOG.info("Bucket cache retrieved from file successfully with size: {}", backingMap.size());
1679    }
1680  }
1681
1682  private void updateRegionSizeMapWhileRetrievingFromFile() {
1683    // Update the regionCachedSize with the region size while restarting the region server
1684    if (LOG.isDebugEnabled()) {
1685      LOG.debug("Updating region size map after retrieving cached file list");
1686      dumpPrefetchList();
1687    }
1688    regionCachedSize.clear();
1689    backingMap.forEach((k, v) -> updateRegionCachedSize(k, v.getLength()));
1690  }
1691
1692  private void dumpPrefetchList() {
1693    for (Map.Entry<String, Pair<String, Long>> outerEntry : fullyCachedFiles.entrySet()) {
1694      LOG.debug("Cached File Entry:<{},<{},{}>>", outerEntry.getKey(),
1695        outerEntry.getValue().getFirst(), outerEntry.getValue().getSecond());
1696    }
1697  }
1698
1699  private void verifyCapacityAndClasses(long capacitySize, String ioclass, String mapclass)
1700    throws IOException {
1701    if (capacitySize != cacheCapacity) {
1702      throw new IOException("Mismatched cache capacity:" + StringUtils.byteDesc(capacitySize)
1703        + ", expected: " + StringUtils.byteDesc(cacheCapacity));
1704    }
1705    if (!ioEngine.getClass().getName().equals(ioclass)) {
1706      throw new IOException("Class name for IO engine mismatch: " + ioclass + ", expected:"
1707        + ioEngine.getClass().getName());
1708    }
1709    if (!backingMap.getClass().getName().equals(mapclass)) {
1710      throw new IOException("Class name for cache map mismatch: " + mapclass + ", expected:"
1711        + backingMap.getClass().getName());
1712    }
1713  }
1714
1715  private void verifyFileIntegrity(BucketCacheProtos.BucketCacheEntry proto) {
1716    try {
1717      if (proto.hasChecksum()) {
1718        ((PersistentIOEngine) ioEngine).verifyFileIntegrity(proto.getChecksum().toByteArray(),
1719          algorithm);
1720      }
1721      backingMapValidated.set(true);
1722    } catch (IOException e) {
1723      LOG.warn("Checksum for cache file failed. "
1724        + "We need to validate each cache key in the backing map. "
1725        + "This may take some time, so we'll do it in a background thread,");
1726
1727      Runnable cacheValidator = () -> {
1728        while (bucketAllocator == null) {
1729          try {
1730            Thread.sleep(50);
1731          } catch (InterruptedException ex) {
1732            throw new RuntimeException(ex);
1733          }
1734        }
1735        long startTime = EnvironmentEdgeManager.currentTime();
1736        int totalKeysOriginally = backingMap.size();
1737        for (Map.Entry<BlockCacheKey, BucketEntry> keyEntry : backingMap.entrySet()) {
1738          try {
1739            ((FileIOEngine) ioEngine).checkCacheTime(keyEntry.getValue());
1740          } catch (IOException e1) {
1741            LOG.debug("Check for key {} failed. Evicting.", keyEntry.getKey());
1742            evictBlock(keyEntry.getKey());
1743            fullyCachedFiles.remove(keyEntry.getKey().getHfileName());
1744          }
1745        }
1746        backingMapValidated.set(true);
1747        LOG.info("Finished validating {} keys in the backing map. Recovered: {}. This took {}ms.",
1748          totalKeysOriginally, backingMap.size(),
1749          (EnvironmentEdgeManager.currentTime() - startTime));
1750      };
1751      Thread t = new Thread(cacheValidator);
1752      t.setDaemon(true);
1753      t.start();
1754    }
1755  }
1756
1757  private void updateCacheIndex(BucketCacheProtos.BackingMap chunk,
1758    java.util.Map<java.lang.Integer, java.lang.String> deserializer) throws IOException {
1759    Pair<ConcurrentHashMap<BlockCacheKey, BucketEntry>, NavigableSet<BlockCacheKey>> pair2 =
1760      BucketProtoUtils.fromPB(deserializer, chunk, this::createRecycler);
1761    pair2.getFirst().forEach((k, v) -> {
1762      backingMap.put(k, v);
1763      updateRegionCachedSize(k, v.getLength());
1764    });
1765    blocksByHFile.addAll(pair2.getSecond());
1766  }
1767
1768  private void parsePB(BucketCacheProtos.BucketCacheEntry proto) throws IOException {
1769    Pair<ConcurrentHashMap<BlockCacheKey, BucketEntry>, NavigableSet<BlockCacheKey>> pair =
1770      BucketProtoUtils.fromPB(proto.getDeserializersMap(), proto.getBackingMap(),
1771        this::createRecycler);
1772    backingMap = pair.getFirst();
1773    blocksByHFile = pair.getSecond();
1774    fullyCachedFiles.clear();
1775    fullyCachedFiles.putAll(BucketProtoUtils.fromPB(proto.getCachedFilesMap()));
1776
1777    LOG.info("After retrieval Backing map size: {}, fullyCachedFiles size: {}", backingMap.size(),
1778      fullyCachedFiles.size());
1779
1780    verifyFileIntegrity(proto);
1781    updateRegionSizeMapWhileRetrievingFromFile();
1782    verifyCapacityAndClasses(proto.getCacheCapacity(), proto.getIoClass(), proto.getMapClass());
1783  }
1784
1785  private void persistChunkedBackingMap(FileOutputStream fos,
1786    Consumer<Map.Entry<BlockCacheKey, BucketEntry>> entryCopiedAction) throws IOException {
1787    LOG.debug(
1788      "persistToFile: before persisting backing map size: {}, "
1789        + "fullycachedFiles size: {}, chunkSize: {}",
1790      backingMap.size(), fullyCachedFiles.size(), persistenceChunkSize);
1791
1792    BucketProtoUtils.serializeAsPB(this, fos, persistenceChunkSize, entryCopiedAction);
1793
1794    LOG.debug(
1795      "persistToFile: after persisting backing map size: {}, " + "fullycachedFiles size: {}",
1796      backingMap.size(), fullyCachedFiles.size());
1797  }
1798
1799  private void retrieveChunkedBackingMap(FileInputStream in) throws IOException {
1800    // Read the first chunk that has all the details.
1801    BucketCacheProtos.BucketCacheEntry cacheEntry =
1802      BucketCacheProtos.BucketCacheEntry.parseDelimitedFrom(in);
1803
1804    // HBASE-29857: Handle case where persistence file is empty.
1805    // parseDelimitedFrom() returns null when there's no data to read.
1806    // Note: Corrupted files would throw InvalidProtocolBufferException (subclass of IOException).
1807    if (cacheEntry == null) {
1808      throw new IOException("Failed to read cache entry from persistence file (file is empty)");
1809    }
1810
1811    fullyCachedFiles.clear();
1812    fullyCachedFiles.putAll(BucketProtoUtils.fromPB(cacheEntry.getCachedFilesMap()));
1813
1814    backingMap.clear();
1815    blocksByHFile.clear();
1816    regionCachedSize.clear();
1817
1818    // Read the backing map entries in batches.
1819    int numChunks = 0;
1820    while (in.available() > 0) {
1821      updateCacheIndex(BucketCacheProtos.BackingMap.parseDelimitedFrom(in),
1822        cacheEntry.getDeserializersMap());
1823      numChunks++;
1824    }
1825
1826    LOG.info("Retrieved {} of chunks with blockCount = {}.", numChunks, backingMap.size());
1827    verifyFileIntegrity(cacheEntry);
1828    verifyCapacityAndClasses(cacheEntry.getCacheCapacity(), cacheEntry.getIoClass(),
1829      cacheEntry.getMapClass());
1830  }
1831
1832  /**
1833   * Check whether we tolerate IO error this time. If the duration of IOEngine throwing errors
1834   * exceeds ioErrorsDurationTimeTolerated, we will disable the cache
1835   */
1836  private void checkIOErrorIsTolerated() {
1837    long now = EnvironmentEdgeManager.currentTime();
1838    // Do a single read to a local variable to avoid timing issue - HBASE-24454
1839    long ioErrorStartTimeTmp = this.ioErrorStartTime;
1840    if (ioErrorStartTimeTmp > 0) {
1841      if (isCacheEnabled() && (now - ioErrorStartTimeTmp) > this.ioErrorsTolerationDuration) {
1842        LOG.error("IO errors duration time has exceeded " + ioErrorsTolerationDuration
1843          + "ms, disabling cache, please check your IOEngine");
1844        disableCache();
1845      }
1846    } else {
1847      this.ioErrorStartTime = now;
1848    }
1849  }
1850
1851  /**
1852   * Used to shut down the cache -or- turn it off in the case of something broken.
1853   * @return whether explicit shutdown should wait for cleanup
1854   */
1855  private synchronized boolean disableCache() {
1856    if (cacheState == CacheState.DISABLED) {
1857      return false;
1858    }
1859    boolean waitForCleanup = cacheState == CacheState.ENABLED && isCachePersistent();
1860    LOG.info("Disabling cache");
1861    cacheState = CacheState.DISABLED;
1862    this.scheduleThreadPool.shutdown();
1863    for (WriterThread writerThread : writerThreads) {
1864      writerThread.interrupt();
1865    }
1866    // Closing the IO engine helps unblock an in-flight writer before the cleanup thread joins it.
1867    // FileIOEngine can reopen a channel, so cleanup closes the engine again after writers stop.
1868    ioEngine.shutdown();
1869    if (cacheStats.getMetricsRollerScheduler() != null) {
1870      cacheStats.getMetricsRollerScheduler().shutdownNow();
1871    }
1872    cacheCleanupThread = Threads.setDaemonThreadRunning(new Thread(this::cleanupCache),
1873      "BucketCacheCleanup-" + System.identityHashCode(this), Threads.LOGGING_EXCEPTION_HANDLER);
1874    return waitForCleanup;
1875  }
1876
1877  private void cleanupCache() {
1878    try {
1879      Threads.shutdown(persistenceRetrieverThread);
1880      for (WriterThread writerThread : writerThreads) {
1881        Threads.shutdown(writerThread);
1882      }
1883      for (BlockingQueue<RAMQueueEntry> writerQueue : writerQueues) {
1884        writerQueue.clear();
1885      }
1886      ramCache.clear();
1887      if (cachePersister != null) {
1888        LOG.info("Shutting down cache persister thread.");
1889        cachePersister.shutdown();
1890        Threads.shutdown(cachePersister);
1891      }
1892      if (isCachePersistent()) {
1893        try {
1894          // The serializer already visits every entry. Release owner references in the same pass.
1895          persistToFile(this::cleanupBackingMapEntry);
1896        } catch (IOException ex) {
1897          LOG.error("Unable to persist data on exit: " + ex.toString(), ex);
1898        }
1899      }
1900    } finally {
1901      try {
1902        cleanupCacheIndex();
1903      } finally {
1904        ioEngine.shutdown();
1905      }
1906    }
1907  }
1908
1909  private void cleanupCacheIndex() {
1910    // A successful persistent cleanup emptied the map during serialization. Avoid creating a
1911    // second iterator over a large ConcurrentHashMap in that case.
1912    if (!backingMap.isEmpty()) {
1913      for (Map.Entry<BlockCacheKey, BucketEntry> entry : backingMap.entrySet()) {
1914        cleanupBackingMapEntry(entry);
1915      }
1916    }
1917    blocksByHFile.clear();
1918    fullyCachedFiles.clear();
1919    regionCachedSize.clear();
1920  }
1921
1922  private void cleanupBackingMapEntry(Map.Entry<BlockCacheKey, BucketEntry> entry) {
1923    BlockCacheKey cacheKey = entry.getKey();
1924    BucketEntry bucketEntry = entry.getValue();
1925    bucketEntry.withWriteLock(offsetLock, () -> {
1926      if (backingMap.remove(cacheKey, bucketEntry)) {
1927        bucketEntry.markAsEvicted();
1928      }
1929      return null;
1930    });
1931  }
1932
1933  private void waitForCacheCleanup() throws InterruptedException {
1934    Thread cleanupThread = cacheCleanupThread;
1935    if (cleanupThread == null || cleanupThread == Thread.currentThread()) {
1936      return;
1937    }
1938    cleanupThread.join();
1939  }
1940
1941  @Override
1942  public void shutdown() {
1943    if (disableCache()) {
1944      try {
1945        waitForCacheCleanup();
1946      } catch (InterruptedException e) {
1947        Thread.currentThread().interrupt();
1948        LOG.warn("Interrupted while waiting for bucket cache cleanup", e);
1949      }
1950    }
1951    LOG.info("Shutdown bucket cache: IO persistent=" + ioEngine.isPersistent() + "; path to write="
1952      + persistencePath);
1953  }
1954
1955  /**
1956   * Needed mostly for UTs that might run in the same VM and create different BucketCache instances
1957   * on different UT methods.
1958   */
1959  @Override
1960  protected void finalize() {
1961    if (cachePersister != null && !cachePersister.isInterrupted()) {
1962      cachePersister.interrupt();
1963    }
1964  }
1965
1966  @Override
1967  public CacheStats getStats() {
1968    return cacheStats;
1969  }
1970
1971  public BucketAllocator getAllocator() {
1972    return this.bucketAllocator;
1973  }
1974
1975  @Override
1976  public long heapSize() {
1977    return this.heapSize.sum();
1978  }
1979
1980  @Override
1981  public long size() {
1982    return this.realCacheSize.sum();
1983  }
1984
1985  @Override
1986  public long getCurrentDataSize() {
1987    return size();
1988  }
1989
1990  @Override
1991  public long getFreeSize() {
1992    if (!isCacheInitialized("BucketCache:getFreeSize")) {
1993      return 0;
1994    }
1995    return this.bucketAllocator.getFreeSize();
1996  }
1997
1998  @Override
1999  public long getBlockCount() {
2000    return this.blockNumber.sum();
2001  }
2002
2003  @Override
2004  public long getDataBlockCount() {
2005    return getBlockCount();
2006  }
2007
2008  @Override
2009  public long getCurrentSize() {
2010    if (!isCacheInitialized("BucketCache::getCurrentSize")) {
2011      return 0;
2012    }
2013    return this.bucketAllocator.getUsedSize();
2014  }
2015
2016  protected String getAlgorithm() {
2017    return algorithm;
2018  }
2019
2020  /**
2021   * Evicts all blocks for a specific HFile.
2022   * <p>
2023   * This is used for evict-on-close to remove all blocks of a specific HFile.
2024   * @return the number of blocks evicted
2025   */
2026  @Override
2027  public int evictBlocksByHfileName(String hfileName) {
2028    return evictBlocksRangeByHfileName(hfileName, 0, Long.MAX_VALUE);
2029  }
2030
2031  @Override
2032  public int evictBlocksRangeByHfileName(String hfileName, long initOffset, long endOffset) {
2033    Set<BlockCacheKey> keySet = getAllCacheKeysForFile(hfileName, initOffset, endOffset);
2034    // We need to make sure whether we are evicting all blocks for this given file. In case of
2035    // split references, we might be evicting just half of the blocks
2036    LOG.debug("found {} blocks for file {}, starting offset: {}, end offset: {}", keySet.size(),
2037      hfileName, initOffset, endOffset);
2038    return evictBlockSet(keySet);
2039  }
2040
2041  private int evictBlockSet(Set<BlockCacheKey> keySet) {
2042    int numEvicted = 0;
2043    for (BlockCacheKey key : keySet) {
2044      if (evictBlock(key)) {
2045        ++numEvicted;
2046      }
2047    }
2048    return numEvicted;
2049  }
2050
2051  private Set<BlockCacheKey> getAllCacheKeysForFile(String hfileName, long init, long end) {
2052    Set<BlockCacheKey> cacheKeys = new HashSet<>();
2053    // At this moment, Some Bucket Entries may be in the WriterThread queue, and not yet put into
2054    // the backingMap. So, when executing this method, we should check both the RAMCache and
2055    // backingMap to ensure all CacheKeys are obtained.
2056    // For more details, please refer to HBASE-29862.
2057    Set<BlockCacheKey> ramCacheKeySet = ramCache.getRamBlockCacheKeysForHFile(hfileName);
2058    for (BlockCacheKey key : ramCacheKeySet) {
2059      if (key.getOffset() >= init && key.getOffset() <= end) {
2060        cacheKeys.add(key);
2061      }
2062    }
2063
2064    // These keys are just for comparison and are short lived, so we need only file name and offset
2065    cacheKeys.addAll(blocksByHFile.subSet(new BlockCacheKey(hfileName, init), true,
2066      new BlockCacheKey(hfileName, end), true));
2067    return cacheKeys;
2068  }
2069
2070  /**
2071   * Used to group bucket entries into priority buckets. There will be a BucketEntryGroup for each
2072   * priority (single, multi, memory). Once bucketed, the eviction algorithm takes the appropriate
2073   * number of elements out of each according to configuration parameters and their relative sizes.
2074   */
2075  private class BucketEntryGroup {
2076
2077    private CachedEntryQueue queue;
2078    private long totalSize = 0;
2079    private long bucketSize;
2080
2081    public BucketEntryGroup(long bytesToFree, long blockSize, long bucketSize) {
2082      this.bucketSize = bucketSize;
2083      queue = new CachedEntryQueue(bytesToFree, blockSize);
2084      totalSize = 0;
2085    }
2086
2087    public void add(Map.Entry<BlockCacheKey, BucketEntry> block) {
2088      totalSize += block.getValue().getLength();
2089      queue.add(block);
2090    }
2091
2092    public long free(long toFree) {
2093      Map.Entry<BlockCacheKey, BucketEntry> entry;
2094      long freedBytes = 0;
2095      // TODO avoid a cycling siutation. We find no block which is not in use and so no way to free
2096      // What to do then? Caching attempt fail? Need some changes in cacheBlock API?
2097      while ((entry = queue.pollLast()) != null) {
2098        BlockCacheKey blockCacheKey = entry.getKey();
2099        BucketEntry be = entry.getValue();
2100        if (evictBucketEntryIfNoRpcReferenced(blockCacheKey, be)) {
2101          freedBytes += be.getLength();
2102        }
2103        if (freedBytes >= toFree) {
2104          return freedBytes;
2105        }
2106      }
2107      return freedBytes;
2108    }
2109
2110    public long overflow() {
2111      return totalSize - bucketSize;
2112    }
2113
2114    public long totalSize() {
2115      return totalSize;
2116    }
2117  }
2118
2119  /**
2120   * Block Entry stored in the memory with key,data and so on
2121   */
2122  static class RAMQueueEntry {
2123    private final BlockCacheKey key;
2124    private final Cacheable data;
2125    private long accessCounter;
2126    private boolean inMemory;
2127    private boolean isCachePersistent;
2128
2129    private boolean isPrefetch;
2130
2131    RAMQueueEntry(BlockCacheKey bck, Cacheable data, long accessCounter, boolean inMemory,
2132      boolean isCachePersistent, boolean isPrefetch) {
2133      this.key = bck;
2134      this.data = data;
2135      this.accessCounter = accessCounter;
2136      this.inMemory = inMemory;
2137      this.isCachePersistent = isCachePersistent;
2138      this.isPrefetch = isPrefetch;
2139    }
2140
2141    public Cacheable getData() {
2142      return data;
2143    }
2144
2145    public BlockCacheKey getKey() {
2146      return key;
2147    }
2148
2149    public boolean isPrefetch() {
2150      return isPrefetch;
2151    }
2152
2153    public void access(long accessCounter) {
2154      this.accessCounter = accessCounter;
2155    }
2156
2157    private ByteBuffAllocator getByteBuffAllocator() {
2158      if (data instanceof HFileBlock) {
2159        return ((HFileBlock) data).getByteBuffAllocator();
2160      }
2161      return ByteBuffAllocator.HEAP;
2162    }
2163
2164    public BucketEntry writeToCache(final IOEngine ioEngine, final BucketAllocator alloc,
2165      final LongAdder realCacheSize, Function<BucketEntry, Recycler> createRecycler,
2166      ByteBuffer metaBuff, final Long acceptableSize) throws IOException {
2167      int len = data.getSerializedLength();
2168      // This cacheable thing can't be serialized
2169      if (len == 0) {
2170        return null;
2171      }
2172      if (isCachePersistent && data instanceof HFileBlock) {
2173        len += Long.BYTES; // we need to record the cache time for consistency check in case of
2174                           // recovery
2175      }
2176      long offset = alloc.allocateBlock(len);
2177      // In the case of prefetch, we want to avoid freeSpace runs when the cache is full.
2178      // this makes the cache allocation more predictable, and is particularly important
2179      // when persistent cache is enabled, as it won't trigger evictions of the recovered blocks,
2180      // which are likely the most accessed and relevant blocks in the cache.
2181      if (isPrefetch() && alloc.getUsedSize() > acceptableSize) {
2182        alloc.freeBlock(offset, len);
2183        return null;
2184      }
2185      boolean succ = false;
2186      BucketEntry bucketEntry = null;
2187      try {
2188        int diskSizeWithHeader = (data instanceof HFileBlock)
2189          ? ((HFileBlock) data).getOnDiskSizeWithHeader()
2190          : data.getSerializedLength();
2191        bucketEntry = new BucketEntry(offset, len, diskSizeWithHeader, accessCounter, inMemory,
2192          createRecycler, getByteBuffAllocator());
2193        bucketEntry.setDeserializerReference(data.getDeserializer());
2194        if (data instanceof HFileBlock) {
2195          // If an instance of HFileBlock, save on some allocations.
2196          HFileBlock block = (HFileBlock) data;
2197          ByteBuff sliceBuf = block.getBufferReadOnly();
2198          block.getMetaData(metaBuff);
2199          // adds the cache time prior to the block and metadata part
2200          if (isCachePersistent) {
2201            ByteBuffer buffer = ByteBuffer.allocate(Long.BYTES);
2202            buffer.putLong(bucketEntry.getCachedTime());
2203            buffer.rewind();
2204            ioEngine.write(buffer, offset);
2205            ioEngine.write(sliceBuf, (offset + Long.BYTES));
2206          } else {
2207            ioEngine.write(sliceBuf, offset);
2208          }
2209          ioEngine.write(metaBuff, offset + len - metaBuff.limit());
2210        } else {
2211          // Only used for testing.
2212          ByteBuffer bb = ByteBuffer.allocate(len);
2213          data.serialize(bb, true);
2214          ioEngine.write(bb, offset);
2215        }
2216        succ = true;
2217      } finally {
2218        if (!succ) {
2219          alloc.freeBlock(offset, len);
2220        }
2221      }
2222      realCacheSize.add(len);
2223      return bucketEntry;
2224    }
2225  }
2226
2227  /**
2228   * Only used in test
2229   */
2230  void stopWriterThreads() throws InterruptedException {
2231    for (WriterThread writerThread : writerThreads) {
2232      writerThread.disableWriter();
2233      writerThread.interrupt();
2234      writerThread.join();
2235    }
2236  }
2237
2238  @Override
2239  public Iterator<CachedBlock> iterator() {
2240    // Don't bother with ramcache since stuff is in here only a little while.
2241    final Iterator<Map.Entry<BlockCacheKey, BucketEntry>> i = this.backingMap.entrySet().iterator();
2242    return new Iterator<CachedBlock>() {
2243      private final long now = System.nanoTime();
2244
2245      @Override
2246      public boolean hasNext() {
2247        return i.hasNext();
2248      }
2249
2250      @Override
2251      public CachedBlock next() {
2252        final Map.Entry<BlockCacheKey, BucketEntry> e = i.next();
2253        return new CachedBlock() {
2254          @Override
2255          public String toString() {
2256            return BlockCacheUtil.toString(this, now);
2257          }
2258
2259          @Override
2260          public BlockPriority getBlockPriority() {
2261            return e.getValue().getPriority();
2262          }
2263
2264          @Override
2265          public BlockType getBlockType() {
2266            // Not held by BucketEntry. Could add it if wanted on BucketEntry creation.
2267            return null;
2268          }
2269
2270          @Override
2271          public long getOffset() {
2272            return e.getKey().getOffset();
2273          }
2274
2275          @Override
2276          public long getSize() {
2277            return e.getValue().getLength();
2278          }
2279
2280          @Override
2281          public long getCachedTime() {
2282            return e.getValue().getCachedTime();
2283          }
2284
2285          @Override
2286          public String getFilename() {
2287            return e.getKey().getHfileName();
2288          }
2289
2290          @Override
2291          public int compareTo(CachedBlock other) {
2292            int diff = this.getFilename().compareTo(other.getFilename());
2293            if (diff != 0) return diff;
2294
2295            diff = Long.compare(this.getOffset(), other.getOffset());
2296            if (diff != 0) return diff;
2297            if (other.getCachedTime() < 0 || this.getCachedTime() < 0) {
2298              throw new IllegalStateException(
2299                "" + this.getCachedTime() + ", " + other.getCachedTime());
2300            }
2301            return Long.compare(other.getCachedTime(), this.getCachedTime());
2302          }
2303
2304          @Override
2305          public int hashCode() {
2306            return e.getKey().hashCode();
2307          }
2308
2309          @Override
2310          public boolean equals(Object obj) {
2311            if (obj instanceof CachedBlock) {
2312              CachedBlock cb = (CachedBlock) obj;
2313              return compareTo(cb) == 0;
2314            } else {
2315              return false;
2316            }
2317          }
2318        };
2319      }
2320
2321      @Override
2322      public void remove() {
2323        throw new UnsupportedOperationException();
2324      }
2325    };
2326  }
2327
2328  @Override
2329  public BlockCache[] getBlockCaches() {
2330    return null;
2331  }
2332
2333  public int getRpcRefCount(BlockCacheKey cacheKey) {
2334    BucketEntry bucketEntry = backingMap.get(cacheKey);
2335    if (bucketEntry != null) {
2336      return bucketEntry.refCnt() - (bucketEntry.markedAsEvicted.get() ? 0 : 1);
2337    }
2338    return 0;
2339  }
2340
2341  float getAcceptableFactor() {
2342    return acceptableFactor;
2343  }
2344
2345  float getMinFactor() {
2346    return minFactor;
2347  }
2348
2349  float getExtraFreeFactor() {
2350    return extraFreeFactor;
2351  }
2352
2353  float getSingleFactor() {
2354    return singleFactor;
2355  }
2356
2357  float getMultiFactor() {
2358    return multiFactor;
2359  }
2360
2361  float getMemoryFactor() {
2362    return memoryFactor;
2363  }
2364
2365  long getQueueAdditionWaitTime() {
2366    return queueAdditionWaitTime;
2367  }
2368
2369  long getPersistenceChunkSize() {
2370    return persistenceChunkSize;
2371  }
2372
2373  long getBucketcachePersistInterval() {
2374    return bucketcachePersistInterval;
2375  }
2376
2377  public String getPersistencePath() {
2378    return persistencePath;
2379  }
2380
2381  /**
2382   * Wrapped the delegate ConcurrentMap with maintaining its block's reference count.
2383   */
2384  static class RAMCache {
2385    /**
2386     * Defined the map as {@link ConcurrentHashMap} explicitly here, because in
2387     * {@link RAMCache#get(BlockCacheKey)} and
2388     * {@link RAMCache#putIfAbsent(BlockCacheKey, BucketCache.RAMQueueEntry)} , we need to guarantee
2389     * the atomicity of map#computeIfPresent(key, func) and map#putIfAbsent(key, func). Besides, the
2390     * func method can execute exactly once only when the key is present(or absent) and under the
2391     * lock context. Otherwise, the reference count of block will be messed up. Notice that the
2392     * {@link java.util.concurrent.ConcurrentSkipListMap} can not guarantee that.
2393     */
2394    final ConcurrentHashMap<BlockCacheKey, RAMQueueEntry> delegate = new ConcurrentHashMap<>();
2395
2396    public boolean containsKey(BlockCacheKey key) {
2397      return delegate.containsKey(key);
2398    }
2399
2400    public RAMQueueEntry get(BlockCacheKey key) {
2401      return delegate.computeIfPresent(key, (k, re) -> {
2402        // It'll be referenced by RPC, so retain atomically here. if the get and retain is not
2403        // atomic, another thread may remove and release the block, when retaining in this thread we
2404        // may retain a block with refCnt=0 which is disallowed. (see HBASE-22422)
2405        re.getData().retain();
2406        return re;
2407      });
2408    }
2409
2410    /**
2411     * Return the previous associated value, or null if absent. It has the same meaning as
2412     * {@link ConcurrentMap#putIfAbsent(Object, Object)}
2413     */
2414    public RAMQueueEntry putIfAbsent(BlockCacheKey key, RAMQueueEntry entry) {
2415      AtomicBoolean absent = new AtomicBoolean(false);
2416      RAMQueueEntry re = delegate.computeIfAbsent(key, k -> {
2417        // The RAMCache reference to this entry, so reference count should be increment.
2418        entry.getData().retain();
2419        absent.set(true);
2420        return entry;
2421      });
2422      return absent.get() ? null : re;
2423    }
2424
2425    public boolean remove(BlockCacheKey key) {
2426      return remove(key, re -> {
2427      });
2428    }
2429
2430    /**
2431     * Defined an {@link Consumer} here, because once the removed entry release its reference count,
2432     * then it's ByteBuffers may be recycled and accessing it outside this method will be thrown an
2433     * exception. the consumer will access entry to remove before release its reference count.
2434     * Notice, don't change its reference count in the {@link Consumer}
2435     */
2436    public boolean remove(BlockCacheKey key, Consumer<RAMQueueEntry> action) {
2437      RAMQueueEntry previous = delegate.remove(key);
2438      action.accept(previous);
2439      if (previous != null) {
2440        previous.getData().release();
2441      }
2442      return previous != null;
2443    }
2444
2445    public boolean isEmpty() {
2446      return delegate.isEmpty();
2447    }
2448
2449    public void clear() {
2450      Iterator<Map.Entry<BlockCacheKey, RAMQueueEntry>> it = delegate.entrySet().iterator();
2451      while (it.hasNext()) {
2452        RAMQueueEntry re = it.next().getValue();
2453        it.remove();
2454        re.getData().release();
2455      }
2456    }
2457
2458    public boolean hasBlocksForFile(String fileName) {
2459      return delegate.keySet().stream().filter(key -> key.getHfileName().equals(fileName))
2460        .findFirst().isPresent();
2461    }
2462
2463    public Set<BlockCacheKey> getRamBlockCacheKeysForHFile(String fileName) {
2464      Set<BlockCacheKey> ramCacheKeySet = new HashSet<>();
2465      for (BlockCacheKey blockCacheKey : delegate.keySet()) {
2466        if (blockCacheKey.getHfileName().equals(fileName)) {
2467          ramCacheKeySet.add(blockCacheKey);
2468        }
2469      }
2470      return ramCacheKeySet;
2471    }
2472  }
2473
2474  public Map<BlockCacheKey, BucketEntry> getBackingMap() {
2475    return backingMap;
2476  }
2477
2478  public AtomicBoolean getBackingMapValidated() {
2479    return backingMapValidated;
2480  }
2481
2482  @Override
2483  public Optional<Map<String, Pair<String, Long>>> getFullyCachedFiles() {
2484    return Optional.of(fullyCachedFiles);
2485  }
2486
2487  public static Optional<BucketCache> getBucketCacheFromCacheConfig(CacheConfig cacheConf) {
2488    if (cacheConf.getBlockCache().isPresent()) {
2489      BlockCache bc = cacheConf.getBlockCache().get();
2490      if (bc instanceof CombinedBlockCache) {
2491        BlockCache l2 = ((CombinedBlockCache) bc).getSecondLevelCache();
2492        if (l2 instanceof BucketCache) {
2493          return Optional.of((BucketCache) l2);
2494        }
2495      } else if (bc instanceof BucketCache) {
2496        return Optional.of((BucketCache) bc);
2497      }
2498    }
2499    return Optional.empty();
2500  }
2501
2502  private int countBlocksForFile(Path fileName, List<ReentrantReadWriteLock> locks) {
2503    LOG.debug("iterating over {} entries in the backing map", backingMap.size());
2504    Set<BlockCacheKey> result = getAllCacheKeysForFile(fileName.getName(), 0, Long.MAX_VALUE);
2505    if (result.isEmpty() && StoreFileInfo.isReference(fileName)) {
2506      result = getAllCacheKeysForFile(
2507        StoreFileInfo.getReferredToRegionAndFile(fileName.getName()).getSecond(), 0,
2508        Long.MAX_VALUE);
2509    }
2510    int count = 0;
2511    for (BlockCacheKey entry : result) {
2512      LOG.debug("found block for file {} in the backing map. Acquiring read lock for offset {}",
2513        fileName.getName(), entry.getOffset());
2514      ReentrantReadWriteLock lock = offsetLock.getLock(entry.getOffset());
2515      lock.readLock().lock();
2516      locks.add(lock);
2517      if (backingMap.containsKey(entry) && entry.getBlockType().isData()) {
2518        count++;
2519      }
2520    }
2521    return count;
2522  }
2523
2524  private void releaseAllLocks(List<ReentrantReadWriteLock> locks) {
2525    for (ReentrantReadWriteLock lock : locks) {
2526      lock.readLock().unlock();
2527    }
2528  }
2529
2530  @Override
2531  public void notifyFileCachingCompleted(Path fileName, int totalBlockCount, int dataBlockCount,
2532    long size) {
2533    // block eviction may be happening in the background as prefetch runs,
2534    // so we need to count all blocks for this file in the backing map under
2535    // a read lock for the block offset
2536    final List<ReentrantReadWriteLock> locks = new ArrayList<>();
2537    LOG.debug("Notifying caching completed for file {}, with total blocks {}, and data blocks {}",
2538      fileName, totalBlockCount, dataBlockCount);
2539    try {
2540      boolean lastTry = false;
2541      for (;;) {
2542        int count = countBlocksForFile(fileName, locks);
2543        // BucketCache would only have data blocks
2544        if (dataBlockCount == count) {
2545          LOG.debug("File {} has now been fully cached.", fileName);
2546          fileCacheCompleted(fileName, size);
2547          break;
2548        }
2549        if (lastTry) {
2550          LOG.info(
2551            "The total block count was {}. We found only {} data blocks cached from "
2552              + "a total of {} data blocks for file {}, "
2553              + "but no blocks pending caching. Maybe cache is full or evictions "
2554              + "happened concurrently to cache prefetch.",
2555            totalBlockCount, count, dataBlockCount, fileName);
2556          break;
2557        }
2558        if (ramCache.hasBlocksForFile(fileName.getName())) {
2559          releaseAllLocks(locks);
2560          locks.clear();
2561          LOG.debug("There are still blocks pending caching for file {}. Will sleep 100ms "
2562            + "and try the verification again.", fileName);
2563          Thread.sleep(100);
2564        } else {
2565          // there are no pending blocks, so count for the last time, if we still can not get enough
2566          // data blocks, quit
2567          LOG.debug("There are no blocks pending cache for file {}. Will try the verification "
2568            + "for the last time.");
2569          lastTry = true;
2570        }
2571      }
2572    } catch (InterruptedException e) {
2573      throw new RuntimeException(e);
2574    } finally {
2575      releaseAllLocks(locks);
2576    }
2577  }
2578
2579  @Override
2580  public Optional<Boolean> blockFitsIntoTheCache(HFileBlock block) {
2581    if (!isCacheInitialized("blockFitsIntoTheCache")) {
2582      return Optional.of(false);
2583    }
2584
2585    long currentUsed = bucketAllocator.getUsedSize();
2586    boolean result = (currentUsed + block.getOnDiskSizeWithHeader()) < acceptableSize();
2587    return Optional.of(result);
2588  }
2589
2590  @Override
2591  public Optional<Boolean> shouldCacheFile(HFileInfo hFileInfo, Configuration conf) {
2592    String fileName = hFileInfo.getHFileContext().getHFileName();
2593    DataTieringManager dataTieringManager = DataTieringManager.getInstance();
2594    if (dataTieringManager != null && !dataTieringManager.isHotData(hFileInfo, conf)) {
2595      LOG.debug("Custom tiering is enabled for file: '{}' and it is not hot data", fileName);
2596      // If custom tiering has been just enabled for a file that was cached, we now need
2597      // to evict it.
2598      Set<BlockCacheKey> keySet =
2599        getAllCacheKeysForFile(hFileInfo.getHFileContext().getHFileName(), 0, Long.MAX_VALUE);
2600      int evictedBlocks = evictBlockSet(keySet);
2601      if (evictedBlocks > 0) {
2602        LOG.debug(
2603          "Evicted {} blocks for file {} as it is now considered cold by DataTieringManager",
2604          evictedBlocks, fileName);
2605      }
2606      return Optional.of(false);
2607    }
2608    // if we don't have the file in fullyCachedFiles, we should cache it
2609    return Optional.of(!fullyCachedFiles.containsKey(fileName));
2610  }
2611
2612  @Override
2613  public Optional<Boolean> shouldCacheBlock(BlockCacheKey key, long maxTimestamp,
2614    Configuration conf) {
2615    DataTieringManager dataTieringManager = DataTieringManager.getInstance();
2616    if (dataTieringManager != null && !dataTieringManager.isHotData(maxTimestamp, conf)) {
2617      LOG.debug("Data tiering is enabled for file: '{}' and it is not hot data",
2618        key.getHfileName());
2619      return Optional.of(false);
2620    }
2621    return Optional.of(true);
2622  }
2623
2624  @Override
2625  public Optional<Boolean> isAlreadyCached(BlockCacheKey key) {
2626    boolean foundKey = backingMap.containsKey(key);
2627    // if there's no entry for the key itself, we need to check if this key is for a reference,
2628    // and if so, look for a block from the referenced file using this getBlockForReference method.
2629    return Optional.of(foundKey ? true : getBlockForReference(key) != null);
2630  }
2631
2632  @Override
2633  public Optional<Integer> getBlockSize(BlockCacheKey key) {
2634    BucketEntry entry = backingMap.get(key);
2635    if (entry == null) {
2636      // the key might be for a reference tha we had found the block from the referenced file in
2637      // the cache when we first tried to cache it.
2638      entry = getBlockForReference(key);
2639      return entry == null ? Optional.empty() : Optional.of(entry.getOnDiskSizeWithHeader());
2640    } else {
2641      return Optional.of(entry.getOnDiskSizeWithHeader());
2642    }
2643
2644  }
2645
2646  boolean isCacheInitialized(String api) {
2647    if (cacheState == CacheState.INITIALIZING) {
2648      LOG.warn("Bucket initialisation pending at {}", api);
2649      return false;
2650    }
2651    return true;
2652  }
2653
2654  @Override
2655  public boolean waitForCacheInitialization(long timeout) {
2656    while (cacheState == CacheState.INITIALIZING) {
2657      if (timeout <= 0) {
2658        break;
2659      }
2660      try {
2661        Thread.sleep(100);
2662      } catch (InterruptedException e) {
2663        LOG.warn("Interrupted while waiting for cache initialization", e);
2664        Thread.currentThread().interrupt();
2665        break;
2666      }
2667      timeout -= 100;
2668    }
2669    return isCacheEnabled();
2670  }
2671}