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 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, bucketcachePersistInterval);
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 propperty determines the frequency for saving the
951   * persistent cache, and it has also been made dynamically configurable since HBASE-29249. The
952   * hbase.bucketcache.persistence.chunksize property determines the size of the persistent file
953   * splits (due to the limitation of maximum allowed protobuff size), and it has also been made
954   * dynamically configurable since HBASE-29249.
955   * @param config the new configuration to be updated.
956   */
957  @Override
958  public void onConfigurationChange(Configuration config) {
959    this.acceptableFactor = conf.getFloat(ACCEPT_FACTOR_CONFIG_NAME, DEFAULT_ACCEPT_FACTOR);
960    this.minFactor = conf.getFloat(MIN_FACTOR_CONFIG_NAME, DEFAULT_MIN_FACTOR);
961    this.extraFreeFactor = conf.getFloat(EXTRA_FREE_FACTOR_CONFIG_NAME, DEFAULT_EXTRA_FREE_FACTOR);
962    this.singleFactor = conf.getFloat(SINGLE_FACTOR_CONFIG_NAME, DEFAULT_SINGLE_FACTOR);
963    this.multiFactor = conf.getFloat(MULTI_FACTOR_CONFIG_NAME, DEFAULT_MULTI_FACTOR);
964    this.memoryFactor = conf.getFloat(MEMORY_FACTOR_CONFIG_NAME, DEFAULT_MEMORY_FACTOR);
965    this.queueAdditionWaitTime =
966      conf.getLong(QUEUE_ADDITION_WAIT_TIME, DEFAULT_QUEUE_ADDITION_WAIT_TIME);
967    this.bucketcachePersistInterval = conf.getLong(BUCKETCACHE_PERSIST_INTERVAL_KEY, 1000);
968    this.persistenceChunkSize =
969      conf.getLong(BACKING_MAP_PERSISTENCE_CHUNK_SIZE, DEFAULT_BACKING_MAP_PERSISTENCE_CHUNK_SIZE);
970    sanityCheckConfigs();
971  }
972
973  protected boolean removeFromRamCache(BlockCacheKey cacheKey) {
974    return ramCache.remove(cacheKey, re -> {
975      if (re != null) {
976        this.blockNumber.decrement();
977        this.heapSize.add(-1 * re.getData().heapSize());
978      }
979    });
980  }
981
982  public boolean isCacheInconsistent() {
983    return isCacheInconsistent.get();
984  }
985
986  public void setCacheInconsistent(boolean setCacheInconsistent) {
987    isCacheInconsistent.set(setCacheInconsistent);
988  }
989
990  protected void setCacheState(CacheState state) {
991    cacheState = state;
992  }
993
994  /*
995   * Statistics thread. Periodically output cache statistics to the log.
996   */
997  private static class StatisticsThread extends Thread {
998    private final BucketCache bucketCache;
999
1000    public StatisticsThread(BucketCache bucketCache) {
1001      super("BucketCacheStatsThread");
1002      setDaemon(true);
1003      this.bucketCache = bucketCache;
1004    }
1005
1006    @Override
1007    public void run() {
1008      bucketCache.logStats();
1009    }
1010  }
1011
1012  public void logStats() {
1013    if (!isCacheInitialized("BucketCache::logStats")) {
1014      return;
1015    }
1016
1017    long totalSize = bucketAllocator.getTotalSize();
1018    long usedSize = bucketAllocator.getUsedSize();
1019    long freeSize = totalSize - usedSize;
1020    long cacheSize = getRealCacheSize();
1021    LOG.info("failedBlockAdditions=" + cacheStats.getFailedInserts() + ", " + "totalSize="
1022      + StringUtils.byteDesc(totalSize) + ", " + "freeSize=" + StringUtils.byteDesc(freeSize) + ", "
1023      + "usedSize=" + StringUtils.byteDesc(usedSize) + ", " + "cacheSize="
1024      + StringUtils.byteDesc(cacheSize) + ", " + "accesses=" + cacheStats.getRequestCount() + ", "
1025      + "hits=" + cacheStats.getHitCount() + ", " + "IOhitsPerSecond="
1026      + cacheStats.getIOHitsPerSecond() + ", " + "IOTimePerHit="
1027      + String.format("%.2f", cacheStats.getIOTimePerHit()) + ", " + "hitRatio="
1028      + (cacheStats.getHitCount() == 0
1029        ? "0,"
1030        : (StringUtils.formatPercent(cacheStats.getHitRatio(), 2) + ", "))
1031      + "cachingAccesses=" + cacheStats.getRequestCachingCount() + ", " + "cachingHits="
1032      + cacheStats.getHitCachingCount() + ", " + "cachingHitsRatio="
1033      + (cacheStats.getHitCachingCount() == 0
1034        ? "0,"
1035        : (StringUtils.formatPercent(cacheStats.getHitCachingRatio(), 2) + ", "))
1036      + "evictions=" + cacheStats.getEvictionCount() + ", " + "evicted="
1037      + cacheStats.getEvictedCount() + ", " + "evictedPerRun=" + cacheStats.evictedPerEviction()
1038      + ", " + "allocationFailCount=" + cacheStats.getAllocationFailCount() + ", blocksCount="
1039      + backingMap.size());
1040    cacheStats.reset();
1041
1042    bucketAllocator.logDebugStatistics();
1043  }
1044
1045  public long getRealCacheSize() {
1046    return this.realCacheSize.sum();
1047  }
1048
1049  public long acceptableSize() {
1050    if (!isCacheInitialized("BucketCache::acceptableSize")) {
1051      return 0;
1052    }
1053    return (long) Math.floor(bucketAllocator.getTotalSize() * acceptableFactor);
1054  }
1055
1056  long getPartitionSize(float partitionFactor) {
1057    if (!isCacheInitialized("BucketCache::getPartitionSize")) {
1058      return 0;
1059    }
1060
1061    return (long) Math.floor(bucketAllocator.getTotalSize() * partitionFactor * minFactor);
1062  }
1063
1064  /**
1065   * Return the count of bucketSizeinfos still need free space
1066   */
1067  private int bucketSizesAboveThresholdCount(float minFactor) {
1068    if (!isCacheInitialized("BucketCache::bucketSizesAboveThresholdCount")) {
1069      return 0;
1070    }
1071
1072    BucketAllocator.IndexStatistics[] stats = bucketAllocator.getIndexStatistics();
1073    int fullCount = 0;
1074    for (int i = 0; i < stats.length; i++) {
1075      long freeGoal = (long) Math.floor(stats[i].totalCount() * (1 - minFactor));
1076      freeGoal = Math.max(freeGoal, 1);
1077      if (stats[i].freeCount() < freeGoal) {
1078        fullCount++;
1079      }
1080    }
1081    return fullCount;
1082  }
1083
1084  /**
1085   * This method will find the buckets that are minimally occupied and are not reference counted and
1086   * will free them completely without any constraint on the access times of the elements, and as a
1087   * process will completely free at most the number of buckets passed, sometimes it might not due
1088   * to changing refCounts
1089   * @param completelyFreeBucketsNeeded number of buckets to free
1090   **/
1091  private void freeEntireBuckets(int completelyFreeBucketsNeeded) {
1092    if (!isCacheInitialized("BucketCache::freeEntireBuckets")) {
1093      return;
1094    }
1095
1096    if (completelyFreeBucketsNeeded != 0) {
1097      // First we will build a set where the offsets are reference counted, usually
1098      // this set is small around O(Handler Count) unless something else is wrong
1099      Set<Integer> inUseBuckets = new HashSet<>();
1100      backingMap.forEach((k, be) -> {
1101        if (be.isRpcRef()) {
1102          inUseBuckets.add(bucketAllocator.getBucketIndex(be.offset()));
1103        }
1104      });
1105      Set<Integer> candidateBuckets =
1106        bucketAllocator.getLeastFilledBuckets(inUseBuckets, completelyFreeBucketsNeeded);
1107      for (Map.Entry<BlockCacheKey, BucketEntry> entry : backingMap.entrySet()) {
1108        if (candidateBuckets.contains(bucketAllocator.getBucketIndex(entry.getValue().offset()))) {
1109          evictBucketEntryIfNoRpcReferenced(entry.getKey(), entry.getValue());
1110        }
1111      }
1112    }
1113  }
1114
1115  private long calculateBytesToFree(StringBuilder msgBuffer) {
1116    long bytesToFreeWithoutExtra = 0;
1117    BucketAllocator.IndexStatistics[] stats = bucketAllocator.getIndexStatistics();
1118    long[] bytesToFreeForBucket = new long[stats.length];
1119    for (int i = 0; i < stats.length; i++) {
1120      bytesToFreeForBucket[i] = 0;
1121      long freeGoal = (long) Math.floor(stats[i].totalCount() * (1 - minFactor));
1122      freeGoal = Math.max(freeGoal, 1);
1123      if (stats[i].freeCount() < freeGoal) {
1124        bytesToFreeForBucket[i] = stats[i].itemSize() * (freeGoal - stats[i].freeCount());
1125        bytesToFreeWithoutExtra += bytesToFreeForBucket[i];
1126        if (msgBuffer != null) {
1127          msgBuffer.append("Free for bucketSize(" + stats[i].itemSize() + ")="
1128            + StringUtils.byteDesc(bytesToFreeForBucket[i]) + ", ");
1129        }
1130      }
1131    }
1132    if (msgBuffer != null) {
1133      msgBuffer.append("Free for total=" + StringUtils.byteDesc(bytesToFreeWithoutExtra) + ", ");
1134    }
1135    return bytesToFreeWithoutExtra;
1136  }
1137
1138  /**
1139   * Free the space if the used size reaches acceptableSize() or one size block couldn't be
1140   * allocated. When freeing the space, we use the LRU algorithm and ensure there must be some
1141   * blocks evicted
1142   * @param why Why we are being called
1143   */
1144  void freeSpace(final String why) {
1145    if (!isCacheInitialized("BucketCache::freeSpace")) {
1146      return;
1147    }
1148    // Ensure only one freeSpace progress at a time
1149    if (!freeSpaceLock.tryLock()) {
1150      return;
1151    }
1152    try {
1153      freeInProgress = true;
1154      StringBuilder msgBuffer = LOG.isDebugEnabled() ? new StringBuilder() : null;
1155      long bytesToFreeWithoutExtra = calculateBytesToFree(msgBuffer);
1156      if (bytesToFreeWithoutExtra <= 0) {
1157        return;
1158      }
1159      long currentSize = bucketAllocator.getUsedSize();
1160      long totalSize = bucketAllocator.getTotalSize();
1161      if (LOG.isDebugEnabled() && msgBuffer != null) {
1162        LOG.debug("Free started because \"" + why + "\"; " + msgBuffer + " of current used="
1163          + StringUtils.byteDesc(currentSize) + ", actual cacheSize="
1164          + StringUtils.byteDesc(realCacheSize.sum()) + ", total="
1165          + StringUtils.byteDesc(totalSize));
1166      }
1167      long bytesToFreeWithExtra =
1168        (long) Math.floor(bytesToFreeWithoutExtra * (1 + extraFreeFactor));
1169      // Instantiate priority buckets
1170      BucketEntryGroup bucketSingle =
1171        new BucketEntryGroup(bytesToFreeWithExtra, blockSize, getPartitionSize(singleFactor));
1172      BucketEntryGroup bucketMulti =
1173        new BucketEntryGroup(bytesToFreeWithExtra, blockSize, getPartitionSize(multiFactor));
1174      BucketEntryGroup bucketMemory =
1175        new BucketEntryGroup(bytesToFreeWithExtra, blockSize, getPartitionSize(memoryFactor));
1176
1177      Set<String> allValidFiles = null;
1178      // We need the region/stores/files tree, in order to figure out if a block is "orphan" or not.
1179      // See further comments below for more details.
1180      if (onlineRegions != null) {
1181        allValidFiles = BlockCacheUtil.listAllFilesNames(onlineRegions);
1182      }
1183      // the cached time is recored in nanos, so we need to convert the grace period accordingly
1184      long orphanGracePeriodNanos = orphanBlockGracePeriod * 1000000;
1185      long bytesFreed = 0;
1186      // Check the list of files to determine the cold files which can be readily evicted.
1187      Map<String, String> coldFiles = null;
1188
1189      DataTieringManager dataTieringManager = DataTieringManager.getInstance();
1190      if (dataTieringManager != null) {
1191        coldFiles = dataTieringManager.getColdFilesList();
1192      }
1193      // Scan entire map putting bucket entry into appropriate bucket entry
1194      // group
1195      for (Map.Entry<BlockCacheKey, BucketEntry> bucketEntryWithKey : backingMap.entrySet()) {
1196        BlockCacheKey key = bucketEntryWithKey.getKey();
1197        BucketEntry entry = bucketEntryWithKey.getValue();
1198        // Under certain conditions, blocks for regions not on the current region server might
1199        // be hanging on the cache. For example, when using the persistent cache feature, if the
1200        // RS crashes, then if not the same regions are assigned back once its online again, blocks
1201        // for the previous online regions would be recovered and stay in the cache. These would be
1202        // "orphan" blocks, as the files these blocks belong to are not in any of the online
1203        // regions.
1204        // "Orphan" blocks are a pure waste of cache space and should be evicted first during
1205        // the freespace run.
1206        // Compactions and Flushes may cache blocks before its files are completely written. In
1207        // these cases the file won't be found in any of the online regions stores, but the block
1208        // shouldn't be evicted. To avoid this, we defined this
1209        // hbase.bucketcache.block.orphan.evictgraceperiod property, to account for a grace
1210        // period (default 24 hours) where a block should be checked if it's an orphan block.
1211        if (
1212          allValidFiles != null
1213            && entry.getCachedTime() < (System.nanoTime() - orphanGracePeriodNanos)
1214        ) {
1215          if (!allValidFiles.contains(key.getHfileName())) {
1216            if (evictBucketEntryIfNoRpcReferenced(key, entry)) {
1217              // We calculate the freed bytes, but we don't stop if the goal was reached because
1218              // these are orphan blocks anyway, so let's leverage this run of freeSpace
1219              // to get rid of all orphans at once.
1220              bytesFreed += entry.getLength();
1221              continue;
1222            }
1223          }
1224        }
1225
1226        if (
1227          bytesFreed < bytesToFreeWithExtra && coldFiles != null
1228            && coldFiles.containsKey(bucketEntryWithKey.getKey().getHfileName())
1229        ) {
1230          int freedBlockSize = bucketEntryWithKey.getValue().getLength();
1231          if (evictBlockIfNoRpcReferenced(bucketEntryWithKey.getKey())) {
1232            bytesFreed += freedBlockSize;
1233          }
1234          continue;
1235        }
1236
1237        switch (entry.getPriority()) {
1238          case SINGLE: {
1239            bucketSingle.add(bucketEntryWithKey);
1240            break;
1241          }
1242          case MULTI: {
1243            bucketMulti.add(bucketEntryWithKey);
1244            break;
1245          }
1246          case MEMORY: {
1247            bucketMemory.add(bucketEntryWithKey);
1248            break;
1249          }
1250        }
1251      }
1252
1253      // Check if the cold file eviction is sufficient to create enough space.
1254      bytesToFreeWithExtra -= bytesFreed;
1255      if (bytesToFreeWithExtra <= 0) {
1256        LOG.debug("Bucket cache free space completed; freed space : {} bytes of cold data blocks.",
1257          StringUtils.byteDesc(bytesFreed));
1258        return;
1259      }
1260
1261      if (LOG.isDebugEnabled()) {
1262        LOG.debug(
1263          "Bucket cache free space completed; freed space : {} "
1264            + "bytes of cold data blocks. {} more bytes required to be freed.",
1265          StringUtils.byteDesc(bytesFreed), bytesToFreeWithExtra);
1266      }
1267
1268      PriorityQueue<BucketEntryGroup> bucketQueue =
1269        new PriorityQueue<>(3, Comparator.comparingLong(BucketEntryGroup::overflow));
1270
1271      bucketQueue.add(bucketSingle);
1272      bucketQueue.add(bucketMulti);
1273      bucketQueue.add(bucketMemory);
1274
1275      int remainingBuckets = bucketQueue.size();
1276      BucketEntryGroup bucketGroup;
1277      while ((bucketGroup = bucketQueue.poll()) != null) {
1278        long overflow = bucketGroup.overflow();
1279        if (overflow > 0) {
1280          long bucketBytesToFree =
1281            Math.min(overflow, (bytesToFreeWithoutExtra - bytesFreed) / remainingBuckets);
1282          bytesFreed += bucketGroup.free(bucketBytesToFree);
1283        }
1284        remainingBuckets--;
1285      }
1286
1287      // Check and free if there are buckets that still need freeing of space
1288      if (bucketSizesAboveThresholdCount(minFactor) > 0) {
1289        bucketQueue.clear();
1290        remainingBuckets = 3;
1291        bucketQueue.add(bucketSingle);
1292        bucketQueue.add(bucketMulti);
1293        bucketQueue.add(bucketMemory);
1294        while ((bucketGroup = bucketQueue.poll()) != null) {
1295          long bucketBytesToFree = (bytesToFreeWithExtra - bytesFreed) / remainingBuckets;
1296          bytesFreed += bucketGroup.free(bucketBytesToFree);
1297          remainingBuckets--;
1298        }
1299      }
1300      // Even after the above free we might still need freeing because of the
1301      // De-fragmentation of the buckets (also called Slab Calcification problem), i.e
1302      // there might be some buckets where the occupancy is very sparse and thus are not
1303      // yielding the free for the other bucket sizes, the fix for this to evict some
1304      // of the buckets, we do this by evicting the buckets that are least fulled
1305      freeEntireBuckets(DEFAULT_FREE_ENTIRE_BLOCK_FACTOR * bucketSizesAboveThresholdCount(1.0f));
1306
1307      if (LOG.isDebugEnabled()) {
1308        long single = bucketSingle.totalSize();
1309        long multi = bucketMulti.totalSize();
1310        long memory = bucketMemory.totalSize();
1311        if (LOG.isDebugEnabled()) {
1312          LOG.debug("Bucket cache free space completed; " + "freed="
1313            + StringUtils.byteDesc(bytesFreed) + ", " + "total=" + StringUtils.byteDesc(totalSize)
1314            + ", " + "single=" + StringUtils.byteDesc(single) + ", " + "multi="
1315            + StringUtils.byteDesc(multi) + ", " + "memory=" + StringUtils.byteDesc(memory));
1316        }
1317      }
1318    } catch (Throwable t) {
1319      LOG.warn("Failed freeing space", t);
1320    } finally {
1321      cacheStats.evict();
1322      freeInProgress = false;
1323      freeSpaceLock.unlock();
1324    }
1325  }
1326
1327  // This handles flushing the RAM cache to IOEngine.
1328  class WriterThread extends Thread {
1329    private final BlockingQueue<RAMQueueEntry> inputQueue;
1330    private volatile boolean writerEnabled = true;
1331    private final ByteBuffer metaBuff = ByteBuffer.allocate(HFileBlock.BLOCK_METADATA_SPACE);
1332
1333    WriterThread(BlockingQueue<RAMQueueEntry> queue) {
1334      super("BucketCacheWriterThread");
1335      this.inputQueue = queue;
1336    }
1337
1338    // Used for test
1339    void disableWriter() {
1340      this.writerEnabled = false;
1341    }
1342
1343    @Override
1344    public void run() {
1345      List<RAMQueueEntry> entries = new ArrayList<>();
1346      try {
1347        while (isCacheEnabled() && writerEnabled) {
1348          try {
1349            try {
1350              // Blocks
1351              entries = getRAMQueueEntries(inputQueue, entries);
1352            } catch (InterruptedException ie) {
1353              if (!isCacheEnabled() || !writerEnabled) {
1354                break;
1355              }
1356            }
1357            doDrain(entries, metaBuff);
1358          } catch (Exception ioe) {
1359            LOG.error("WriterThread encountered error", ioe);
1360          }
1361        }
1362      } catch (Throwable t) {
1363        LOG.warn("Failed doing drain", t);
1364      }
1365      LOG.info(this.getName() + " exiting, cacheEnabled=" + isCacheEnabled());
1366    }
1367  }
1368
1369  /**
1370   * Put the new bucket entry into backingMap. Notice that we are allowed to replace the existing
1371   * cache with a new block for the same cache key. there's a corner case: one thread cache a block
1372   * in ramCache, copy to io-engine and add a bucket entry to backingMap. Caching another new block
1373   * with the same cache key do the same thing for the same cache key, so if not evict the previous
1374   * bucket entry, then memory leak happen because the previous bucketEntry is gone but the
1375   * bucketAllocator do not free its memory.
1376   * @see BlockCacheUtil#shouldReplaceExistingCacheBlock(BlockCache blockCache,BlockCacheKey
1377   *      cacheKey, Cacheable newBlock)
1378   * @param key         Block cache key
1379   * @param bucketEntry Bucket entry to put into backingMap.
1380   */
1381  protected void putIntoBackingMap(BlockCacheKey key, BucketEntry bucketEntry) {
1382    BucketEntry previousEntry = backingMap.put(key, bucketEntry);
1383    updateRegionCachedSize(key, bucketEntry.getLength());
1384    if (previousEntry != null && previousEntry != bucketEntry) {
1385      previousEntry.withWriteLock(offsetLock, () -> {
1386        blockEvicted(key, previousEntry, false, false);
1387        return null;
1388      });
1389    }
1390    bucketEntry.withWriteLock(offsetLock, () -> {
1391      if (backingMap.get(key) == bucketEntry) {
1392        blocksByHFile.add(key);
1393      }
1394      return null;
1395    });
1396  }
1397
1398  /**
1399   * Prepare and return a warning message for Bucket Allocator Exception
1400   * @param fle The exception
1401   * @param re  The RAMQueueEntry for which the exception was thrown.
1402   * @return A warning message created from the input RAMQueueEntry object.
1403   */
1404  private static String getAllocationFailWarningMessage(final BucketAllocatorException fle,
1405    final RAMQueueEntry re) {
1406    final StringBuilder sb = new StringBuilder();
1407    sb.append("Most recent failed allocation after ");
1408    sb.append(ALLOCATION_FAIL_LOG_TIME_PERIOD);
1409    sb.append(" ms;");
1410    if (re != null) {
1411      if (re.getData() instanceof HFileBlock) {
1412        final HFileContext fileContext = ((HFileBlock) re.getData()).getHFileContext();
1413        final String columnFamily = Bytes.toString(fileContext.getColumnFamily());
1414        final String tableName = Bytes.toString(fileContext.getTableName());
1415        if (tableName != null) {
1416          sb.append(" Table: ");
1417          sb.append(tableName);
1418        }
1419        if (columnFamily != null) {
1420          sb.append(" CF: ");
1421          sb.append(columnFamily);
1422        }
1423        sb.append(" HFile: ");
1424        if (fileContext.getHFileName() != null) {
1425          sb.append(fileContext.getHFileName());
1426        } else {
1427          sb.append(re.getKey());
1428        }
1429      } else {
1430        sb.append(" HFile: ");
1431        sb.append(re.getKey());
1432      }
1433    }
1434    sb.append(" Message: ");
1435    sb.append(fle.getMessage());
1436    return sb.toString();
1437  }
1438
1439  /**
1440   * Flush the entries in ramCache to IOEngine and add bucket entry to backingMap. Process all that
1441   * are passed in even if failure being sure to remove from ramCache else we'll never undo the
1442   * references and we'll OOME.
1443   * @param entries Presumes list passed in here will be processed by this invocation only. No
1444   *                interference expected.
1445   */
1446  void doDrain(final List<RAMQueueEntry> entries, ByteBuffer metaBuff) throws InterruptedException {
1447    if (entries.isEmpty()) {
1448      return;
1449    }
1450    // This method is a little hard to follow. We run through the passed in entries and for each
1451    // successful add, we add a non-null BucketEntry to the below bucketEntries. Later we must
1452    // do cleanup making sure we've cleared ramCache of all entries regardless of whether we
1453    // successfully added the item to the bucketcache; if we don't do the cleanup, we'll OOME by
1454    // filling ramCache. We do the clean up by again running through the passed in entries
1455    // doing extra work when we find a non-null bucketEntries corresponding entry.
1456    final int size = entries.size();
1457    BucketEntry[] bucketEntries = new BucketEntry[size];
1458    // Index updated inside loop if success or if we can't succeed. We retry if cache is full
1459    // when we go to add an entry by going around the loop again without upping the index.
1460    int index = 0;
1461    while (isCacheEnabled() && index < size) {
1462      RAMQueueEntry re = null;
1463      try {
1464        re = entries.get(index);
1465        if (re == null) {
1466          LOG.warn("Couldn't get entry or changed on us; who else is messing with it?");
1467          index++;
1468          continue;
1469        }
1470        // Reset the position for reuse.
1471        // It should be guaranteed that the data in the metaBuff has been transferred to the
1472        // ioEngine safely. Otherwise, this reuse is problematic. Fortunately, the data is already
1473        // transferred with our current IOEngines. Should take care, when we have new kinds of
1474        // IOEngine in the future.
1475        metaBuff.clear();
1476        BucketEntry bucketEntry = re.writeToCache(ioEngine, bucketAllocator, realCacheSize,
1477          this::createRecycler, metaBuff, acceptableSize());
1478        // Successfully added. Up index and add bucketEntry. Clear io exceptions.
1479        bucketEntries[index] = bucketEntry;
1480        if (ioErrorStartTime > 0) {
1481          ioErrorStartTime = -1;
1482        }
1483        index++;
1484      } catch (BucketAllocatorException fle) {
1485        long currTs = EnvironmentEdgeManager.currentTime();
1486        cacheStats.allocationFailed(); // Record the warning.
1487        if (
1488          allocFailLogPrevTs == 0 || (currTs - allocFailLogPrevTs) > ALLOCATION_FAIL_LOG_TIME_PERIOD
1489        ) {
1490          LOG.warn(getAllocationFailWarningMessage(fle, re));
1491          allocFailLogPrevTs = currTs;
1492        }
1493        // Presume can't add. Too big? Move index on. Entry will be cleared from ramCache below.
1494        bucketEntries[index] = null;
1495        index++;
1496      } catch (CacheFullException cfe) {
1497        // Cache full when we tried to add. Try freeing space and then retrying (don't up index)
1498        if (!freeInProgress && !re.isPrefetch()) {
1499          freeSpace("Full!");
1500        } else if (re.isPrefetch()) {
1501          bucketEntries[index] = null;
1502          index++;
1503        } else {
1504          Thread.sleep(50);
1505        }
1506      } catch (IOException ioex) {
1507        // Hopefully transient. Retry. checkIOErrorIsTolerated disables cache if problem.
1508        LOG.error("Failed writing to bucket cache", ioex);
1509        checkIOErrorIsTolerated();
1510      }
1511    }
1512
1513    // Make sure data pages are written on media before we update maps.
1514    try {
1515      ioEngine.sync();
1516    } catch (IOException ioex) {
1517      LOG.error("Failed syncing IO engine", ioex);
1518      checkIOErrorIsTolerated();
1519      // Since we failed sync, free the blocks in bucket allocator
1520      for (int i = 0; i < entries.size(); ++i) {
1521        BucketEntry bucketEntry = bucketEntries[i];
1522        if (bucketEntry != null) {
1523          bucketAllocator.freeBlock(bucketEntry.offset(), bucketEntry.getLength());
1524          bucketEntries[i] = null;
1525        }
1526      }
1527    }
1528
1529    // Now add to backingMap if successfully added to bucket cache. Remove from ramCache if
1530    // success or error.
1531    for (int i = 0; i < size; ++i) {
1532      BlockCacheKey key = entries.get(i).getKey();
1533      // Only add if non-null entry.
1534      if (bucketEntries[i] != null) {
1535        putIntoBackingMap(key, bucketEntries[i]);
1536        if (ioEngine.isPersistent()) {
1537          setCacheInconsistent(true);
1538        }
1539      }
1540      // Always remove from ramCache even if we failed adding it to the block cache above.
1541      boolean existed = ramCache.remove(key, re -> {
1542        if (re != null) {
1543          heapSize.add(-1 * re.getData().heapSize());
1544        }
1545      });
1546      if (!existed && bucketEntries[i] != null) {
1547        // Block should have already been evicted. Remove it and free space.
1548        final BucketEntry bucketEntry = bucketEntries[i];
1549        bucketEntry.withWriteLock(offsetLock, () -> {
1550          if (backingMap.remove(key, bucketEntry)) {
1551            blockEvicted(key, bucketEntry, false, false);
1552          }
1553          return null;
1554        });
1555      }
1556      long used = bucketAllocator.getUsedSize();
1557      if (!entries.get(i).isPrefetch() && used > acceptableSize()) {
1558        LOG.debug("Calling freeSpace for block: {}", entries.get(i).getKey());
1559        freeSpace("Used=" + used + " > acceptable=" + acceptableSize());
1560      }
1561    }
1562
1563  }
1564
1565  /**
1566   * Blocks until elements available in {@code q} then tries to grab as many as possible before
1567   * returning.
1568   * @param receptacle Where to stash the elements taken from queue. We clear before we use it just
1569   *                   in case.
1570   * @param q          The queue to take from.
1571   * @return {@code receptacle} laden with elements taken from the queue or empty if none found.
1572   */
1573  static List<RAMQueueEntry> getRAMQueueEntries(BlockingQueue<RAMQueueEntry> q,
1574    List<RAMQueueEntry> receptacle) throws InterruptedException {
1575    // Clear sets all entries to null and sets size to 0. We retain allocations. Presume it
1576    // ok even if list grew to accommodate thousands.
1577    receptacle.clear();
1578    receptacle.add(q.take());
1579    q.drainTo(receptacle);
1580    return receptacle;
1581  }
1582
1583  /**
1584   * @see #retrieveFromFile(int[])
1585   */
1586  @edu.umd.cs.findbugs.annotations.SuppressWarnings(value = "OBL_UNSATISFIED_OBLIGATION",
1587      justification = "false positive, try-with-resources ensures close is called.")
1588  void persistToFile() throws IOException {
1589    persistToFile(entry -> {
1590    });
1591  }
1592
1593  private void persistToFile(Consumer<Map.Entry<BlockCacheKey, BucketEntry>> entryCopiedAction)
1594    throws IOException {
1595    LOG.debug("Thread {} started persisting bucket cache to file",
1596      Thread.currentThread().getName());
1597    if (!isCachePersistent()) {
1598      throw new IOException("Attempt to persist non-persistent cache mappings!");
1599    }
1600    File tempPersistencePath = new File(persistencePath + EnvironmentEdgeManager.currentTime());
1601    try (FileOutputStream fos = new FileOutputStream(tempPersistencePath, false)) {
1602      LOG.debug("Persist in new chunked persistence format.");
1603
1604      persistChunkedBackingMap(fos, entryCopiedAction);
1605
1606      LOG.debug(
1607        "PersistToFile: after persisting backing map size: {}, fullycachedFiles size: {},"
1608          + " file name: {}",
1609        backingMap.size(), fullyCachedFiles.size(), tempPersistencePath.getName());
1610    } catch (IOException e) {
1611      LOG.error("Failed to persist bucket cache to file", e);
1612      throw e;
1613    } catch (Throwable e) {
1614      LOG.error("Failed during persist bucket cache to file: ", e);
1615      throw e;
1616    }
1617    LOG.debug("Thread {} finished persisting bucket cache to file, renaming",
1618      Thread.currentThread().getName());
1619    if (!tempPersistencePath.renameTo(new File(persistencePath))) {
1620      LOG.warn("Failed to commit cache persistent file. We might lose cached blocks if "
1621        + "RS crashes/restarts before we successfully checkpoint again.");
1622    }
1623  }
1624
1625  public boolean isCachePersistent() {
1626    return ioEngine.isPersistent() && persistencePath != null;
1627  }
1628
1629  @Override
1630  public Optional<Map<String, Long>> getRegionCachedInfo() {
1631    return Optional.of(Collections.unmodifiableMap(regionCachedSize));
1632  }
1633
1634  /**
1635   * @see #persistToFile()
1636   */
1637  private void retrieveFromFile(int[] bucketSizes) throws IOException {
1638    LOG.info("Started retrieving bucket cache from file");
1639    File persistenceFile = new File(persistencePath);
1640    if (!persistenceFile.exists()) {
1641      LOG.warn("Persistence file missing! "
1642        + "It's ok if it's first run after enabling persistent cache.");
1643      bucketAllocator = new BucketAllocator(cacheCapacity, bucketSizes, backingMap, realCacheSize);
1644      blockNumber.add(backingMap.size());
1645      backingMapValidated.set(true);
1646      return;
1647    }
1648    assert !isCacheEnabled();
1649
1650    try (FileInputStream in = new FileInputStream(persistenceFile)) {
1651      int pblen = ProtobufMagic.lengthOfPBMagic();
1652      byte[] pbuf = new byte[pblen];
1653      IOUtils.readFully(in, pbuf, 0, pblen);
1654
1655      if (ProtobufMagic.isPBMagicPrefix(pbuf)) {
1656        LOG.info("Reading old format of persistence.");
1657        // The old non-chunked version of backing map persistence.
1658        BucketCacheProtos.BucketCacheEntry cacheEntry =
1659          BucketCacheProtos.BucketCacheEntry.parseDelimitedFrom(in);
1660        if (cacheEntry == null) {
1661          throw new IOException(
1662            "Failed to parse cache entry from persistence file: " + persistencePath);
1663        }
1664        parsePB(cacheEntry);
1665      } else if (Arrays.equals(pbuf, BucketProtoUtils.PB_MAGIC_V2)) {
1666        // The new persistence format of chunked persistence.
1667        LOG.info("Reading new chunked format of persistence.");
1668        retrieveChunkedBackingMap(in);
1669      } else {
1670        // In 3.0 we have enough flexibility to dump the old cache data.
1671        // TODO: In 2.x line, this might need to be filled in to support reading the old format
1672        throw new IOException(
1673          "Persistence file does not start with protobuf magic number. " + persistencePath);
1674      }
1675      bucketAllocator = new BucketAllocator(cacheCapacity, bucketSizes, backingMap, realCacheSize);
1676      blockNumber.add(backingMap.size());
1677      LOG.info("Bucket cache retrieved from file successfully with size: {}", backingMap.size());
1678    }
1679  }
1680
1681  private void updateRegionSizeMapWhileRetrievingFromFile() {
1682    // Update the regionCachedSize with the region size while restarting the region server
1683    if (LOG.isDebugEnabled()) {
1684      LOG.debug("Updating region size map after retrieving cached file list");
1685      dumpPrefetchList();
1686    }
1687    regionCachedSize.clear();
1688    backingMap.forEach((k, v) -> updateRegionCachedSize(k, v.getLength()));
1689  }
1690
1691  private void dumpPrefetchList() {
1692    for (Map.Entry<String, Pair<String, Long>> outerEntry : fullyCachedFiles.entrySet()) {
1693      LOG.debug("Cached File Entry:<{},<{},{}>>", outerEntry.getKey(),
1694        outerEntry.getValue().getFirst(), outerEntry.getValue().getSecond());
1695    }
1696  }
1697
1698  private void verifyCapacityAndClasses(long capacitySize, String ioclass, String mapclass)
1699    throws IOException {
1700    if (capacitySize != cacheCapacity) {
1701      throw new IOException("Mismatched cache capacity:" + StringUtils.byteDesc(capacitySize)
1702        + ", expected: " + StringUtils.byteDesc(cacheCapacity));
1703    }
1704    if (!ioEngine.getClass().getName().equals(ioclass)) {
1705      throw new IOException("Class name for IO engine mismatch: " + ioclass + ", expected:"
1706        + ioEngine.getClass().getName());
1707    }
1708    if (!backingMap.getClass().getName().equals(mapclass)) {
1709      throw new IOException("Class name for cache map mismatch: " + mapclass + ", expected:"
1710        + backingMap.getClass().getName());
1711    }
1712  }
1713
1714  private void verifyFileIntegrity(BucketCacheProtos.BucketCacheEntry proto) {
1715    try {
1716      if (proto.hasChecksum()) {
1717        ((PersistentIOEngine) ioEngine).verifyFileIntegrity(proto.getChecksum().toByteArray(),
1718          algorithm);
1719      }
1720      backingMapValidated.set(true);
1721    } catch (IOException e) {
1722      LOG.warn("Checksum for cache file failed. "
1723        + "We need to validate each cache key in the backing map. "
1724        + "This may take some time, so we'll do it in a background thread,");
1725
1726      Runnable cacheValidator = () -> {
1727        while (bucketAllocator == null) {
1728          try {
1729            Thread.sleep(50);
1730          } catch (InterruptedException ex) {
1731            throw new RuntimeException(ex);
1732          }
1733        }
1734        long startTime = EnvironmentEdgeManager.currentTime();
1735        int totalKeysOriginally = backingMap.size();
1736        for (Map.Entry<BlockCacheKey, BucketEntry> keyEntry : backingMap.entrySet()) {
1737          try {
1738            ((FileIOEngine) ioEngine).checkCacheTime(keyEntry.getValue());
1739          } catch (IOException e1) {
1740            LOG.debug("Check for key {} failed. Evicting.", keyEntry.getKey());
1741            evictBlock(keyEntry.getKey());
1742            fullyCachedFiles.remove(keyEntry.getKey().getHfileName());
1743          }
1744        }
1745        backingMapValidated.set(true);
1746        LOG.info("Finished validating {} keys in the backing map. Recovered: {}. This took {}ms.",
1747          totalKeysOriginally, backingMap.size(),
1748          (EnvironmentEdgeManager.currentTime() - startTime));
1749      };
1750      Thread t = new Thread(cacheValidator);
1751      t.setDaemon(true);
1752      t.start();
1753    }
1754  }
1755
1756  private void updateCacheIndex(BucketCacheProtos.BackingMap chunk,
1757    java.util.Map<java.lang.Integer, java.lang.String> deserializer) throws IOException {
1758    Pair<ConcurrentHashMap<BlockCacheKey, BucketEntry>, NavigableSet<BlockCacheKey>> pair2 =
1759      BucketProtoUtils.fromPB(deserializer, chunk, this::createRecycler);
1760    pair2.getFirst().forEach((k, v) -> {
1761      backingMap.put(k, v);
1762      updateRegionCachedSize(k, v.getLength());
1763    });
1764    blocksByHFile.addAll(pair2.getSecond());
1765  }
1766
1767  private void parsePB(BucketCacheProtos.BucketCacheEntry proto) throws IOException {
1768    Pair<ConcurrentHashMap<BlockCacheKey, BucketEntry>, NavigableSet<BlockCacheKey>> pair =
1769      BucketProtoUtils.fromPB(proto.getDeserializersMap(), proto.getBackingMap(),
1770        this::createRecycler);
1771    backingMap = pair.getFirst();
1772    blocksByHFile = pair.getSecond();
1773    fullyCachedFiles.clear();
1774    fullyCachedFiles.putAll(BucketProtoUtils.fromPB(proto.getCachedFilesMap()));
1775
1776    LOG.info("After retrieval Backing map size: {}, fullyCachedFiles size: {}", backingMap.size(),
1777      fullyCachedFiles.size());
1778
1779    verifyFileIntegrity(proto);
1780    updateRegionSizeMapWhileRetrievingFromFile();
1781    verifyCapacityAndClasses(proto.getCacheCapacity(), proto.getIoClass(), proto.getMapClass());
1782  }
1783
1784  private void persistChunkedBackingMap(FileOutputStream fos,
1785    Consumer<Map.Entry<BlockCacheKey, BucketEntry>> entryCopiedAction) throws IOException {
1786    LOG.debug(
1787      "persistToFile: before persisting backing map size: {}, "
1788        + "fullycachedFiles size: {}, chunkSize: {}",
1789      backingMap.size(), fullyCachedFiles.size(), persistenceChunkSize);
1790
1791    BucketProtoUtils.serializeAsPB(this, fos, persistenceChunkSize, entryCopiedAction);
1792
1793    LOG.debug(
1794      "persistToFile: after persisting backing map size: {}, " + "fullycachedFiles size: {}",
1795      backingMap.size(), fullyCachedFiles.size());
1796  }
1797
1798  private void retrieveChunkedBackingMap(FileInputStream in) throws IOException {
1799    // Read the first chunk that has all the details.
1800    BucketCacheProtos.BucketCacheEntry cacheEntry =
1801      BucketCacheProtos.BucketCacheEntry.parseDelimitedFrom(in);
1802
1803    // HBASE-29857: Handle case where persistence file is empty.
1804    // parseDelimitedFrom() returns null when there's no data to read.
1805    // Note: Corrupted files would throw InvalidProtocolBufferException (subclass of IOException).
1806    if (cacheEntry == null) {
1807      throw new IOException("Failed to read cache entry from persistence file (file is empty)");
1808    }
1809
1810    fullyCachedFiles.clear();
1811    fullyCachedFiles.putAll(BucketProtoUtils.fromPB(cacheEntry.getCachedFilesMap()));
1812
1813    backingMap.clear();
1814    blocksByHFile.clear();
1815    regionCachedSize.clear();
1816
1817    // Read the backing map entries in batches.
1818    int numChunks = 0;
1819    while (in.available() > 0) {
1820      updateCacheIndex(BucketCacheProtos.BackingMap.parseDelimitedFrom(in),
1821        cacheEntry.getDeserializersMap());
1822      numChunks++;
1823    }
1824
1825    LOG.info("Retrieved {} of chunks with blockCount = {}.", numChunks, backingMap.size());
1826    verifyFileIntegrity(cacheEntry);
1827    verifyCapacityAndClasses(cacheEntry.getCacheCapacity(), cacheEntry.getIoClass(),
1828      cacheEntry.getMapClass());
1829  }
1830
1831  /**
1832   * Check whether we tolerate IO error this time. If the duration of IOEngine throwing errors
1833   * exceeds ioErrorsDurationTimeTolerated, we will disable the cache
1834   */
1835  private void checkIOErrorIsTolerated() {
1836    long now = EnvironmentEdgeManager.currentTime();
1837    // Do a single read to a local variable to avoid timing issue - HBASE-24454
1838    long ioErrorStartTimeTmp = this.ioErrorStartTime;
1839    if (ioErrorStartTimeTmp > 0) {
1840      if (isCacheEnabled() && (now - ioErrorStartTimeTmp) > this.ioErrorsTolerationDuration) {
1841        LOG.error("IO errors duration time has exceeded " + ioErrorsTolerationDuration
1842          + "ms, disabling cache, please check your IOEngine");
1843        disableCache();
1844      }
1845    } else {
1846      this.ioErrorStartTime = now;
1847    }
1848  }
1849
1850  /**
1851   * Used to shut down the cache -or- turn it off in the case of something broken.
1852   * @return whether explicit shutdown should wait for cleanup
1853   */
1854  private synchronized boolean disableCache() {
1855    if (cacheState == CacheState.DISABLED) {
1856      return false;
1857    }
1858    boolean waitForCleanup = cacheState == CacheState.ENABLED && isCachePersistent();
1859    LOG.info("Disabling cache");
1860    cacheState = CacheState.DISABLED;
1861    this.scheduleThreadPool.shutdown();
1862    for (WriterThread writerThread : writerThreads) {
1863      writerThread.interrupt();
1864    }
1865    // Closing the IO engine helps unblock an in-flight writer before the cleanup thread joins it.
1866    // FileIOEngine can reopen a channel, so cleanup closes the engine again after writers stop.
1867    ioEngine.shutdown();
1868    if (cacheStats.getMetricsRollerScheduler() != null) {
1869      cacheStats.getMetricsRollerScheduler().shutdownNow();
1870    }
1871    cacheCleanupThread = Threads.setDaemonThreadRunning(new Thread(this::cleanupCache),
1872      "BucketCacheCleanup-" + System.identityHashCode(this), Threads.LOGGING_EXCEPTION_HANDLER);
1873    return waitForCleanup;
1874  }
1875
1876  private void cleanupCache() {
1877    try {
1878      Threads.shutdown(persistenceRetrieverThread);
1879      for (WriterThread writerThread : writerThreads) {
1880        Threads.shutdown(writerThread);
1881      }
1882      for (BlockingQueue<RAMQueueEntry> writerQueue : writerQueues) {
1883        writerQueue.clear();
1884      }
1885      ramCache.clear();
1886      if (cachePersister != null) {
1887        LOG.info("Shutting down cache persister thread.");
1888        cachePersister.shutdown();
1889        Threads.shutdown(cachePersister);
1890      }
1891      if (isCachePersistent()) {
1892        try {
1893          // The serializer already visits every entry. Release owner references in the same pass.
1894          persistToFile(this::cleanupBackingMapEntry);
1895        } catch (IOException ex) {
1896          LOG.error("Unable to persist data on exit: " + ex.toString(), ex);
1897        }
1898      }
1899    } finally {
1900      try {
1901        cleanupCacheIndex();
1902      } finally {
1903        ioEngine.shutdown();
1904      }
1905    }
1906  }
1907
1908  private void cleanupCacheIndex() {
1909    // A successful persistent cleanup emptied the map during serialization. Avoid creating a
1910    // second iterator over a large ConcurrentHashMap in that case.
1911    if (!backingMap.isEmpty()) {
1912      for (Map.Entry<BlockCacheKey, BucketEntry> entry : backingMap.entrySet()) {
1913        cleanupBackingMapEntry(entry);
1914      }
1915    }
1916    blocksByHFile.clear();
1917    fullyCachedFiles.clear();
1918    regionCachedSize.clear();
1919  }
1920
1921  private void cleanupBackingMapEntry(Map.Entry<BlockCacheKey, BucketEntry> entry) {
1922    BlockCacheKey cacheKey = entry.getKey();
1923    BucketEntry bucketEntry = entry.getValue();
1924    bucketEntry.withWriteLock(offsetLock, () -> {
1925      if (backingMap.remove(cacheKey, bucketEntry)) {
1926        bucketEntry.markAsEvicted();
1927      }
1928      return null;
1929    });
1930  }
1931
1932  private void waitForCacheCleanup() throws InterruptedException {
1933    Thread cleanupThread = cacheCleanupThread;
1934    if (cleanupThread == null || cleanupThread == Thread.currentThread()) {
1935      return;
1936    }
1937    cleanupThread.join();
1938  }
1939
1940  @Override
1941  public void shutdown() {
1942    if (disableCache()) {
1943      try {
1944        waitForCacheCleanup();
1945      } catch (InterruptedException e) {
1946        Thread.currentThread().interrupt();
1947        LOG.warn("Interrupted while waiting for bucket cache cleanup", e);
1948      }
1949    }
1950    LOG.info("Shutdown bucket cache: IO persistent=" + ioEngine.isPersistent() + "; path to write="
1951      + persistencePath);
1952  }
1953
1954  /**
1955   * Needed mostly for UTs that might run in the same VM and create different BucketCache instances
1956   * on different UT methods.
1957   */
1958  @Override
1959  protected void finalize() {
1960    if (cachePersister != null && !cachePersister.isInterrupted()) {
1961      cachePersister.interrupt();
1962    }
1963  }
1964
1965  @Override
1966  public CacheStats getStats() {
1967    return cacheStats;
1968  }
1969
1970  public BucketAllocator getAllocator() {
1971    return this.bucketAllocator;
1972  }
1973
1974  @Override
1975  public long heapSize() {
1976    return this.heapSize.sum();
1977  }
1978
1979  @Override
1980  public long size() {
1981    return this.realCacheSize.sum();
1982  }
1983
1984  @Override
1985  public long getCurrentDataSize() {
1986    return size();
1987  }
1988
1989  @Override
1990  public long getFreeSize() {
1991    if (!isCacheInitialized("BucketCache:getFreeSize")) {
1992      return 0;
1993    }
1994    return this.bucketAllocator.getFreeSize();
1995  }
1996
1997  @Override
1998  public long getBlockCount() {
1999    return this.blockNumber.sum();
2000  }
2001
2002  @Override
2003  public long getDataBlockCount() {
2004    return getBlockCount();
2005  }
2006
2007  @Override
2008  public long getCurrentSize() {
2009    if (!isCacheInitialized("BucketCache::getCurrentSize")) {
2010      return 0;
2011    }
2012    return this.bucketAllocator.getUsedSize();
2013  }
2014
2015  protected String getAlgorithm() {
2016    return algorithm;
2017  }
2018
2019  /**
2020   * Evicts all blocks for a specific HFile.
2021   * <p>
2022   * This is used for evict-on-close to remove all blocks of a specific HFile.
2023   * @return the number of blocks evicted
2024   */
2025  @Override
2026  public int evictBlocksByHfileName(String hfileName) {
2027    return evictBlocksRangeByHfileName(hfileName, 0, Long.MAX_VALUE);
2028  }
2029
2030  @Override
2031  public int evictBlocksRangeByHfileName(String hfileName, long initOffset, long endOffset) {
2032    Set<BlockCacheKey> keySet = getAllCacheKeysForFile(hfileName, initOffset, endOffset);
2033    // We need to make sure whether we are evicting all blocks for this given file. In case of
2034    // split references, we might be evicting just half of the blocks
2035    LOG.debug("found {} blocks for file {}, starting offset: {}, end offset: {}", keySet.size(),
2036      hfileName, initOffset, endOffset);
2037    return evictBlockSet(keySet);
2038  }
2039
2040  private int evictBlockSet(Set<BlockCacheKey> keySet) {
2041    int numEvicted = 0;
2042    for (BlockCacheKey key : keySet) {
2043      if (evictBlock(key)) {
2044        ++numEvicted;
2045      }
2046    }
2047    return numEvicted;
2048  }
2049
2050  private Set<BlockCacheKey> getAllCacheKeysForFile(String hfileName, long init, long end) {
2051    Set<BlockCacheKey> cacheKeys = new HashSet<>();
2052    // At this moment, Some Bucket Entries may be in the WriterThread queue, and not yet put into
2053    // the backingMap. So, when executing this method, we should check both the RAMCache and
2054    // backingMap to ensure all CacheKeys are obtained.
2055    // For more details, please refer to HBASE-29862.
2056    Set<BlockCacheKey> ramCacheKeySet = ramCache.getRamBlockCacheKeysForHFile(hfileName);
2057    for (BlockCacheKey key : ramCacheKeySet) {
2058      if (key.getOffset() >= init && key.getOffset() <= end) {
2059        cacheKeys.add(key);
2060      }
2061    }
2062
2063    // These keys are just for comparison and are short lived, so we need only file name and offset
2064    cacheKeys.addAll(blocksByHFile.subSet(new BlockCacheKey(hfileName, init), true,
2065      new BlockCacheKey(hfileName, end), true));
2066    return cacheKeys;
2067  }
2068
2069  /**
2070   * Used to group bucket entries into priority buckets. There will be a BucketEntryGroup for each
2071   * priority (single, multi, memory). Once bucketed, the eviction algorithm takes the appropriate
2072   * number of elements out of each according to configuration parameters and their relative sizes.
2073   */
2074  private class BucketEntryGroup {
2075
2076    private CachedEntryQueue queue;
2077    private long totalSize = 0;
2078    private long bucketSize;
2079
2080    public BucketEntryGroup(long bytesToFree, long blockSize, long bucketSize) {
2081      this.bucketSize = bucketSize;
2082      queue = new CachedEntryQueue(bytesToFree, blockSize);
2083      totalSize = 0;
2084    }
2085
2086    public void add(Map.Entry<BlockCacheKey, BucketEntry> block) {
2087      totalSize += block.getValue().getLength();
2088      queue.add(block);
2089    }
2090
2091    public long free(long toFree) {
2092      Map.Entry<BlockCacheKey, BucketEntry> entry;
2093      long freedBytes = 0;
2094      // TODO avoid a cycling siutation. We find no block which is not in use and so no way to free
2095      // What to do then? Caching attempt fail? Need some changes in cacheBlock API?
2096      while ((entry = queue.pollLast()) != null) {
2097        BlockCacheKey blockCacheKey = entry.getKey();
2098        BucketEntry be = entry.getValue();
2099        if (evictBucketEntryIfNoRpcReferenced(blockCacheKey, be)) {
2100          freedBytes += be.getLength();
2101        }
2102        if (freedBytes >= toFree) {
2103          return freedBytes;
2104        }
2105      }
2106      return freedBytes;
2107    }
2108
2109    public long overflow() {
2110      return totalSize - bucketSize;
2111    }
2112
2113    public long totalSize() {
2114      return totalSize;
2115    }
2116  }
2117
2118  /**
2119   * Block Entry stored in the memory with key,data and so on
2120   */
2121  static class RAMQueueEntry {
2122    private final BlockCacheKey key;
2123    private final Cacheable data;
2124    private long accessCounter;
2125    private boolean inMemory;
2126    private boolean isCachePersistent;
2127
2128    private boolean isPrefetch;
2129
2130    RAMQueueEntry(BlockCacheKey bck, Cacheable data, long accessCounter, boolean inMemory,
2131      boolean isCachePersistent, boolean isPrefetch) {
2132      this.key = bck;
2133      this.data = data;
2134      this.accessCounter = accessCounter;
2135      this.inMemory = inMemory;
2136      this.isCachePersistent = isCachePersistent;
2137      this.isPrefetch = isPrefetch;
2138    }
2139
2140    public Cacheable getData() {
2141      return data;
2142    }
2143
2144    public BlockCacheKey getKey() {
2145      return key;
2146    }
2147
2148    public boolean isPrefetch() {
2149      return isPrefetch;
2150    }
2151
2152    public void access(long accessCounter) {
2153      this.accessCounter = accessCounter;
2154    }
2155
2156    private ByteBuffAllocator getByteBuffAllocator() {
2157      if (data instanceof HFileBlock) {
2158        return ((HFileBlock) data).getByteBuffAllocator();
2159      }
2160      return ByteBuffAllocator.HEAP;
2161    }
2162
2163    public BucketEntry writeToCache(final IOEngine ioEngine, final BucketAllocator alloc,
2164      final LongAdder realCacheSize, Function<BucketEntry, Recycler> createRecycler,
2165      ByteBuffer metaBuff, final Long acceptableSize) throws IOException {
2166      int len = data.getSerializedLength();
2167      // This cacheable thing can't be serialized
2168      if (len == 0) {
2169        return null;
2170      }
2171      if (isCachePersistent && data instanceof HFileBlock) {
2172        len += Long.BYTES; // we need to record the cache time for consistency check in case of
2173                           // recovery
2174      }
2175      long offset = alloc.allocateBlock(len);
2176      // In the case of prefetch, we want to avoid freeSpace runs when the cache is full.
2177      // this makes the cache allocation more predictable, and is particularly important
2178      // when persistent cache is enabled, as it won't trigger evictions of the recovered blocks,
2179      // which are likely the most accessed and relevant blocks in the cache.
2180      if (isPrefetch() && alloc.getUsedSize() > acceptableSize) {
2181        alloc.freeBlock(offset, len);
2182        return null;
2183      }
2184      boolean succ = false;
2185      BucketEntry bucketEntry = null;
2186      try {
2187        int diskSizeWithHeader = (data instanceof HFileBlock)
2188          ? ((HFileBlock) data).getOnDiskSizeWithHeader()
2189          : data.getSerializedLength();
2190        bucketEntry = new BucketEntry(offset, len, diskSizeWithHeader, accessCounter, inMemory,
2191          createRecycler, getByteBuffAllocator());
2192        bucketEntry.setDeserializerReference(data.getDeserializer());
2193        if (data instanceof HFileBlock) {
2194          // If an instance of HFileBlock, save on some allocations.
2195          HFileBlock block = (HFileBlock) data;
2196          ByteBuff sliceBuf = block.getBufferReadOnly();
2197          block.getMetaData(metaBuff);
2198          // adds the cache time prior to the block and metadata part
2199          if (isCachePersistent) {
2200            ByteBuffer buffer = ByteBuffer.allocate(Long.BYTES);
2201            buffer.putLong(bucketEntry.getCachedTime());
2202            buffer.rewind();
2203            ioEngine.write(buffer, offset);
2204            ioEngine.write(sliceBuf, (offset + Long.BYTES));
2205          } else {
2206            ioEngine.write(sliceBuf, offset);
2207          }
2208          ioEngine.write(metaBuff, offset + len - metaBuff.limit());
2209        } else {
2210          // Only used for testing.
2211          ByteBuffer bb = ByteBuffer.allocate(len);
2212          data.serialize(bb, true);
2213          ioEngine.write(bb, offset);
2214        }
2215        succ = true;
2216      } finally {
2217        if (!succ) {
2218          alloc.freeBlock(offset, len);
2219        }
2220      }
2221      realCacheSize.add(len);
2222      return bucketEntry;
2223    }
2224  }
2225
2226  /**
2227   * Only used in test
2228   */
2229  void stopWriterThreads() throws InterruptedException {
2230    for (WriterThread writerThread : writerThreads) {
2231      writerThread.disableWriter();
2232      writerThread.interrupt();
2233      writerThread.join();
2234    }
2235  }
2236
2237  @Override
2238  public Iterator<CachedBlock> iterator() {
2239    // Don't bother with ramcache since stuff is in here only a little while.
2240    final Iterator<Map.Entry<BlockCacheKey, BucketEntry>> i = this.backingMap.entrySet().iterator();
2241    return new Iterator<CachedBlock>() {
2242      private final long now = System.nanoTime();
2243
2244      @Override
2245      public boolean hasNext() {
2246        return i.hasNext();
2247      }
2248
2249      @Override
2250      public CachedBlock next() {
2251        final Map.Entry<BlockCacheKey, BucketEntry> e = i.next();
2252        return new CachedBlock() {
2253          @Override
2254          public String toString() {
2255            return BlockCacheUtil.toString(this, now);
2256          }
2257
2258          @Override
2259          public BlockPriority getBlockPriority() {
2260            return e.getValue().getPriority();
2261          }
2262
2263          @Override
2264          public BlockType getBlockType() {
2265            // Not held by BucketEntry. Could add it if wanted on BucketEntry creation.
2266            return null;
2267          }
2268
2269          @Override
2270          public long getOffset() {
2271            return e.getKey().getOffset();
2272          }
2273
2274          @Override
2275          public long getSize() {
2276            return e.getValue().getLength();
2277          }
2278
2279          @Override
2280          public long getCachedTime() {
2281            return e.getValue().getCachedTime();
2282          }
2283
2284          @Override
2285          public String getFilename() {
2286            return e.getKey().getHfileName();
2287          }
2288
2289          @Override
2290          public int compareTo(CachedBlock other) {
2291            int diff = this.getFilename().compareTo(other.getFilename());
2292            if (diff != 0) return diff;
2293
2294            diff = Long.compare(this.getOffset(), other.getOffset());
2295            if (diff != 0) return diff;
2296            if (other.getCachedTime() < 0 || this.getCachedTime() < 0) {
2297              throw new IllegalStateException(
2298                "" + this.getCachedTime() + ", " + other.getCachedTime());
2299            }
2300            return Long.compare(other.getCachedTime(), this.getCachedTime());
2301          }
2302
2303          @Override
2304          public int hashCode() {
2305            return e.getKey().hashCode();
2306          }
2307
2308          @Override
2309          public boolean equals(Object obj) {
2310            if (obj instanceof CachedBlock) {
2311              CachedBlock cb = (CachedBlock) obj;
2312              return compareTo(cb) == 0;
2313            } else {
2314              return false;
2315            }
2316          }
2317        };
2318      }
2319
2320      @Override
2321      public void remove() {
2322        throw new UnsupportedOperationException();
2323      }
2324    };
2325  }
2326
2327  @Override
2328  public BlockCache[] getBlockCaches() {
2329    return null;
2330  }
2331
2332  public int getRpcRefCount(BlockCacheKey cacheKey) {
2333    BucketEntry bucketEntry = backingMap.get(cacheKey);
2334    if (bucketEntry != null) {
2335      return bucketEntry.refCnt() - (bucketEntry.markedAsEvicted.get() ? 0 : 1);
2336    }
2337    return 0;
2338  }
2339
2340  float getAcceptableFactor() {
2341    return acceptableFactor;
2342  }
2343
2344  float getMinFactor() {
2345    return minFactor;
2346  }
2347
2348  float getExtraFreeFactor() {
2349    return extraFreeFactor;
2350  }
2351
2352  float getSingleFactor() {
2353    return singleFactor;
2354  }
2355
2356  float getMultiFactor() {
2357    return multiFactor;
2358  }
2359
2360  float getMemoryFactor() {
2361    return memoryFactor;
2362  }
2363
2364  long getQueueAdditionWaitTime() {
2365    return queueAdditionWaitTime;
2366  }
2367
2368  long getPersistenceChunkSize() {
2369    return persistenceChunkSize;
2370  }
2371
2372  long getBucketcachePersistInterval() {
2373    return bucketcachePersistInterval;
2374  }
2375
2376  public String getPersistencePath() {
2377    return persistencePath;
2378  }
2379
2380  /**
2381   * Wrapped the delegate ConcurrentMap with maintaining its block's reference count.
2382   */
2383  static class RAMCache {
2384    /**
2385     * Defined the map as {@link ConcurrentHashMap} explicitly here, because in
2386     * {@link RAMCache#get(BlockCacheKey)} and
2387     * {@link RAMCache#putIfAbsent(BlockCacheKey, BucketCache.RAMQueueEntry)} , we need to guarantee
2388     * the atomicity of map#computeIfPresent(key, func) and map#putIfAbsent(key, func). Besides, the
2389     * func method can execute exactly once only when the key is present(or absent) and under the
2390     * lock context. Otherwise, the reference count of block will be messed up. Notice that the
2391     * {@link java.util.concurrent.ConcurrentSkipListMap} can not guarantee that.
2392     */
2393    final ConcurrentHashMap<BlockCacheKey, RAMQueueEntry> delegate = new ConcurrentHashMap<>();
2394
2395    public boolean containsKey(BlockCacheKey key) {
2396      return delegate.containsKey(key);
2397    }
2398
2399    public RAMQueueEntry get(BlockCacheKey key) {
2400      return delegate.computeIfPresent(key, (k, re) -> {
2401        // It'll be referenced by RPC, so retain atomically here. if the get and retain is not
2402        // atomic, another thread may remove and release the block, when retaining in this thread we
2403        // may retain a block with refCnt=0 which is disallowed. (see HBASE-22422)
2404        re.getData().retain();
2405        return re;
2406      });
2407    }
2408
2409    /**
2410     * Return the previous associated value, or null if absent. It has the same meaning as
2411     * {@link ConcurrentMap#putIfAbsent(Object, Object)}
2412     */
2413    public RAMQueueEntry putIfAbsent(BlockCacheKey key, RAMQueueEntry entry) {
2414      AtomicBoolean absent = new AtomicBoolean(false);
2415      RAMQueueEntry re = delegate.computeIfAbsent(key, k -> {
2416        // The RAMCache reference to this entry, so reference count should be increment.
2417        entry.getData().retain();
2418        absent.set(true);
2419        return entry;
2420      });
2421      return absent.get() ? null : re;
2422    }
2423
2424    public boolean remove(BlockCacheKey key) {
2425      return remove(key, re -> {
2426      });
2427    }
2428
2429    /**
2430     * Defined an {@link Consumer} here, because once the removed entry release its reference count,
2431     * then it's ByteBuffers may be recycled and accessing it outside this method will be thrown an
2432     * exception. the consumer will access entry to remove before release its reference count.
2433     * Notice, don't change its reference count in the {@link Consumer}
2434     */
2435    public boolean remove(BlockCacheKey key, Consumer<RAMQueueEntry> action) {
2436      RAMQueueEntry previous = delegate.remove(key);
2437      action.accept(previous);
2438      if (previous != null) {
2439        previous.getData().release();
2440      }
2441      return previous != null;
2442    }
2443
2444    public boolean isEmpty() {
2445      return delegate.isEmpty();
2446    }
2447
2448    public void clear() {
2449      Iterator<Map.Entry<BlockCacheKey, RAMQueueEntry>> it = delegate.entrySet().iterator();
2450      while (it.hasNext()) {
2451        RAMQueueEntry re = it.next().getValue();
2452        it.remove();
2453        re.getData().release();
2454      }
2455    }
2456
2457    public boolean hasBlocksForFile(String fileName) {
2458      return delegate.keySet().stream().filter(key -> key.getHfileName().equals(fileName))
2459        .findFirst().isPresent();
2460    }
2461
2462    public Set<BlockCacheKey> getRamBlockCacheKeysForHFile(String fileName) {
2463      Set<BlockCacheKey> ramCacheKeySet = new HashSet<>();
2464      for (BlockCacheKey blockCacheKey : delegate.keySet()) {
2465        if (blockCacheKey.getHfileName().equals(fileName)) {
2466          ramCacheKeySet.add(blockCacheKey);
2467        }
2468      }
2469      return ramCacheKeySet;
2470    }
2471  }
2472
2473  public Map<BlockCacheKey, BucketEntry> getBackingMap() {
2474    return backingMap;
2475  }
2476
2477  public AtomicBoolean getBackingMapValidated() {
2478    return backingMapValidated;
2479  }
2480
2481  @Override
2482  public Optional<Map<String, Pair<String, Long>>> getFullyCachedFiles() {
2483    return Optional.of(fullyCachedFiles);
2484  }
2485
2486  public static Optional<BucketCache> getBucketCacheFromCacheConfig(CacheConfig cacheConf) {
2487    if (cacheConf.getBlockCache().isPresent()) {
2488      BlockCache bc = cacheConf.getBlockCache().get();
2489      if (bc instanceof CombinedBlockCache) {
2490        BlockCache l2 = ((CombinedBlockCache) bc).getSecondLevelCache();
2491        if (l2 instanceof BucketCache) {
2492          return Optional.of((BucketCache) l2);
2493        }
2494      } else if (bc instanceof BucketCache) {
2495        return Optional.of((BucketCache) bc);
2496      }
2497    }
2498    return Optional.empty();
2499  }
2500
2501  private int countBlocksForFile(Path fileName, List<ReentrantReadWriteLock> locks) {
2502    LOG.debug("iterating over {} entries in the backing map", backingMap.size());
2503    Set<BlockCacheKey> result = getAllCacheKeysForFile(fileName.getName(), 0, Long.MAX_VALUE);
2504    if (result.isEmpty() && StoreFileInfo.isReference(fileName)) {
2505      result = getAllCacheKeysForFile(
2506        StoreFileInfo.getReferredToRegionAndFile(fileName.getName()).getSecond(), 0,
2507        Long.MAX_VALUE);
2508    }
2509    int count = 0;
2510    for (BlockCacheKey entry : result) {
2511      LOG.debug("found block for file {} in the backing map. Acquiring read lock for offset {}",
2512        fileName.getName(), entry.getOffset());
2513      ReentrantReadWriteLock lock = offsetLock.getLock(entry.getOffset());
2514      lock.readLock().lock();
2515      locks.add(lock);
2516      if (backingMap.containsKey(entry) && entry.getBlockType().isData()) {
2517        count++;
2518      }
2519    }
2520    return count;
2521  }
2522
2523  private void releaseAllLocks(List<ReentrantReadWriteLock> locks) {
2524    for (ReentrantReadWriteLock lock : locks) {
2525      lock.readLock().unlock();
2526    }
2527  }
2528
2529  @Override
2530  public void notifyFileCachingCompleted(Path fileName, int totalBlockCount, int dataBlockCount,
2531    long size) {
2532    // block eviction may be happening in the background as prefetch runs,
2533    // so we need to count all blocks for this file in the backing map under
2534    // a read lock for the block offset
2535    final List<ReentrantReadWriteLock> locks = new ArrayList<>();
2536    LOG.debug("Notifying caching completed for file {}, with total blocks {}, and data blocks {}",
2537      fileName, totalBlockCount, dataBlockCount);
2538    try {
2539      boolean lastTry = false;
2540      for (;;) {
2541        int count = countBlocksForFile(fileName, locks);
2542        // BucketCache would only have data blocks
2543        if (dataBlockCount == count) {
2544          LOG.debug("File {} has now been fully cached.", fileName);
2545          fileCacheCompleted(fileName, size);
2546          break;
2547        }
2548        if (lastTry) {
2549          LOG.info(
2550            "The total block count was {}. We found only {} data blocks cached from "
2551              + "a total of {} data blocks for file {}, "
2552              + "but no blocks pending caching. Maybe cache is full or evictions "
2553              + "happened concurrently to cache prefetch.",
2554            totalBlockCount, count, dataBlockCount, fileName);
2555          break;
2556        }
2557        if (ramCache.hasBlocksForFile(fileName.getName())) {
2558          releaseAllLocks(locks);
2559          locks.clear();
2560          LOG.debug("There are still blocks pending caching for file {}. Will sleep 100ms "
2561            + "and try the verification again.", fileName);
2562          Thread.sleep(100);
2563        } else {
2564          // there are no pending blocks, so count for the last time, if we still can not get enough
2565          // data blocks, quit
2566          LOG.debug("There are no blocks pending cache for file {}. Will try the verification "
2567            + "for the last time.");
2568          lastTry = true;
2569        }
2570      }
2571    } catch (InterruptedException e) {
2572      throw new RuntimeException(e);
2573    } finally {
2574      releaseAllLocks(locks);
2575    }
2576  }
2577
2578  @Override
2579  public Optional<Boolean> blockFitsIntoTheCache(HFileBlock block) {
2580    if (!isCacheInitialized("blockFitsIntoTheCache")) {
2581      return Optional.of(false);
2582    }
2583
2584    long currentUsed = bucketAllocator.getUsedSize();
2585    boolean result = (currentUsed + block.getOnDiskSizeWithHeader()) < acceptableSize();
2586    return Optional.of(result);
2587  }
2588
2589  @Override
2590  public Optional<Boolean> shouldCacheFile(HFileInfo hFileInfo, Configuration conf) {
2591    String fileName = hFileInfo.getHFileContext().getHFileName();
2592    DataTieringManager dataTieringManager = DataTieringManager.getInstance();
2593    if (dataTieringManager != null && !dataTieringManager.isHotData(hFileInfo, conf)) {
2594      LOG.debug("Custom tiering is enabled for file: '{}' and it is not hot data", fileName);
2595      // If custom tiering has been just enabled for a file that was cached, we now need
2596      // to evict it.
2597      Set<BlockCacheKey> keySet =
2598        getAllCacheKeysForFile(hFileInfo.getHFileContext().getHFileName(), 0, Long.MAX_VALUE);
2599      int evictedBlocks = evictBlockSet(keySet);
2600      if (evictedBlocks > 0) {
2601        LOG.debug(
2602          "Evicted {} blocks for file {} as it is now considered cold by DataTieringManager",
2603          evictedBlocks, fileName);
2604      }
2605      return Optional.of(false);
2606    }
2607    // if we don't have the file in fullyCachedFiles, we should cache it
2608    return Optional.of(!fullyCachedFiles.containsKey(fileName));
2609  }
2610
2611  @Override
2612  public Optional<Boolean> shouldCacheBlock(BlockCacheKey key, long maxTimestamp,
2613    Configuration conf) {
2614    DataTieringManager dataTieringManager = DataTieringManager.getInstance();
2615    if (dataTieringManager != null && !dataTieringManager.isHotData(maxTimestamp, conf)) {
2616      LOG.debug("Data tiering is enabled for file: '{}' and it is not hot data",
2617        key.getHfileName());
2618      return Optional.of(false);
2619    }
2620    return Optional.of(true);
2621  }
2622
2623  @Override
2624  public Optional<Boolean> isAlreadyCached(BlockCacheKey key) {
2625    boolean foundKey = backingMap.containsKey(key);
2626    // if there's no entry for the key itself, we need to check if this key is for a reference,
2627    // and if so, look for a block from the referenced file using this getBlockForReference method.
2628    return Optional.of(foundKey ? true : getBlockForReference(key) != null);
2629  }
2630
2631  @Override
2632  public Optional<Integer> getBlockSize(BlockCacheKey key) {
2633    BucketEntry entry = backingMap.get(key);
2634    if (entry == null) {
2635      // the key might be for a reference tha we had found the block from the referenced file in
2636      // the cache when we first tried to cache it.
2637      entry = getBlockForReference(key);
2638      return entry == null ? Optional.empty() : Optional.of(entry.getOnDiskSizeWithHeader());
2639    } else {
2640      return Optional.of(entry.getOnDiskSizeWithHeader());
2641    }
2642
2643  }
2644
2645  boolean isCacheInitialized(String api) {
2646    if (cacheState == CacheState.INITIALIZING) {
2647      LOG.warn("Bucket initialisation pending at {}", api);
2648      return false;
2649    }
2650    return true;
2651  }
2652
2653  @Override
2654  public boolean waitForCacheInitialization(long timeout) {
2655    while (cacheState == CacheState.INITIALIZING) {
2656      if (timeout <= 0) {
2657        break;
2658      }
2659      try {
2660        Thread.sleep(100);
2661      } catch (InterruptedException e) {
2662        LOG.warn("Interrupted while waiting for cache initialization", e);
2663        Thread.currentThread().interrupt();
2664        break;
2665      }
2666      timeout -= 100;
2667    }
2668    return isCacheEnabled();
2669  }
2670}