View Javadoc

1   /**
2    * Copyright The Apache Software Foundation
3    *
4    * Licensed to the Apache Software Foundation (ASF) under one
5    * or more contributor license agreements.  See the NOTICE file
6    * distributed with this work for additional information
7    * regarding copyright ownership.  The ASF licenses this file
8    * to you under the Apache License, Version 2.0 (the
9    * "License"); you may not use this file except in compliance
10   * with the License.  You may obtain a copy of the License at
11   *
12   *     http://www.apache.org/licenses/LICENSE-2.0
13   *
14   * Unless required by applicable law or agreed to in writing, software
15  
16   * distributed under the License is distributed on an "AS IS" BASIS,
17   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18   * See the License for the specific language governing permissions and
19   * limitations under the License.
20   */
21  package org.apache.hadoop.hbase.io.hfile.bucket;
22  
23  import java.io.File;
24  import java.io.FileInputStream;
25  import java.io.FileNotFoundException;
26  import java.io.FileOutputStream;
27  import java.io.IOException;
28  import java.io.ObjectInputStream;
29  import java.io.ObjectOutputStream;
30  import java.io.Serializable;
31  import java.nio.ByteBuffer;
32  import java.util.ArrayList;
33  import java.util.Comparator;
34  import java.util.HashSet;
35  import java.util.Iterator;
36  import java.util.List;
37  import java.util.Map;
38  import java.util.NavigableSet;
39  import java.util.PriorityQueue;
40  import java.util.Set;
41  import java.util.concurrent.ArrayBlockingQueue;
42  import java.util.concurrent.BlockingQueue;
43  import java.util.concurrent.ConcurrentHashMap;
44  import java.util.concurrent.ConcurrentMap;
45  import java.util.concurrent.ConcurrentSkipListSet;
46  import java.util.concurrent.Executors;
47  import java.util.concurrent.ScheduledExecutorService;
48  import java.util.concurrent.TimeUnit;
49  import java.util.concurrent.atomic.AtomicLong;
50  import java.util.concurrent.locks.Lock;
51  import java.util.concurrent.locks.ReentrantLock;
52  import java.util.concurrent.locks.ReentrantReadWriteLock;
53  
54  import com.google.common.base.Preconditions;
55  import org.apache.commons.logging.Log;
56  import org.apache.commons.logging.LogFactory;
57  import org.apache.hadoop.conf.Configuration;
58  import org.apache.hadoop.hbase.HBaseConfiguration;
59  import org.apache.hadoop.hbase.classification.InterfaceAudience;
60  import org.apache.hadoop.hbase.io.HeapSize;
61  import org.apache.hadoop.hbase.io.hfile.BlockCache;
62  import org.apache.hadoop.hbase.io.hfile.BlockCacheKey;
63  import org.apache.hadoop.hbase.io.hfile.BlockCacheUtil;
64  import org.apache.hadoop.hbase.io.hfile.BlockPriority;
65  import org.apache.hadoop.hbase.io.hfile.BlockType;
66  import org.apache.hadoop.hbase.io.hfile.CacheStats;
67  import org.apache.hadoop.hbase.io.hfile.Cacheable;
68  import org.apache.hadoop.hbase.io.hfile.CacheableDeserializer;
69  import org.apache.hadoop.hbase.io.hfile.CacheableDeserializerIdManager;
70  import org.apache.hadoop.hbase.io.hfile.CachedBlock;
71  import org.apache.hadoop.hbase.io.hfile.HFileBlock;
72  import org.apache.hadoop.hbase.protobuf.ProtobufUtil;
73  import org.apache.hadoop.hbase.util.Bytes;
74  import org.apache.hadoop.hbase.util.EnvironmentEdgeManager;
75  import org.apache.hadoop.hbase.util.HasThread;
76  import org.apache.hadoop.hbase.util.IdReadWriteLock;
77  import org.apache.hadoop.util.StringUtils;
78  
79  import com.google.common.annotations.VisibleForTesting;
80  import com.google.common.util.concurrent.ThreadFactoryBuilder;
81  
82  /**
83   * BucketCache uses {@link BucketAllocator} to allocate/free blocks, and uses
84   * BucketCache#ramCache and BucketCache#backingMap in order to
85   * determine if a given element is in the cache. The bucket cache can use on-heap or
86   * off-heap memory {@link ByteBufferIOEngine} or in a file {@link FileIOEngine} to
87   * store/read the block data.
88   *
89   * <p>Eviction is via a similar algorithm as used in
90   * {@link org.apache.hadoop.hbase.io.hfile.LruBlockCache}
91   *
92   * <p>BucketCache can be used as mainly a block cache (see
93   * {@link org.apache.hadoop.hbase.io.hfile.CombinedBlockCache}), combined with
94   * combined with LruBlockCache to decrease CMS GC and heap fragmentation.
95   *
96   * <p>It also can be used as a secondary cache (e.g. using a file on ssd/fusionio to store
97   * blocks) to enlarge cache space via
98   * {@link org.apache.hadoop.hbase.io.hfile.LruBlockCache#setVictimCache}
99   */
100 @InterfaceAudience.Private
101 public class BucketCache implements BlockCache, HeapSize {
102   private static final Log LOG = LogFactory.getLog(BucketCache.class);
103 
104   /** Priority buckets config */
105   static final String SINGLE_FACTOR_CONFIG_NAME = "hbase.bucketcache.single.factor";
106   static final String MULTI_FACTOR_CONFIG_NAME = "hbase.bucketcache.multi.factor";
107   static final String MEMORY_FACTOR_CONFIG_NAME = "hbase.bucketcache.memory.factor";
108   static final String EXTRA_FREE_FACTOR_CONFIG_NAME = "hbase.bucketcache.extrafreefactor";
109   static final String ACCEPT_FACTOR_CONFIG_NAME = "hbase.bucketcache.acceptfactor";
110   static final String MIN_FACTOR_CONFIG_NAME = "hbase.bucketcache.minfactor";
111 
112   /** Priority buckets */
113   @VisibleForTesting
114   static final float DEFAULT_SINGLE_FACTOR = 0.25f;
115   static final float DEFAULT_MULTI_FACTOR = 0.50f;
116   static final float DEFAULT_MEMORY_FACTOR = 0.25f;
117   static final float DEFAULT_MIN_FACTOR = 0.85f;
118 
119   private static final float DEFAULT_EXTRA_FREE_FACTOR = 0.10f;
120   private static final float DEFAULT_ACCEPT_FACTOR = 0.95f;
121 
122   // Number of blocks to clear for each of the bucket size that is full
123   private static final int DEFAULT_FREE_ENTIRE_BLOCK_FACTOR = 2;
124 
125   /** Statistics thread */
126   private static final int statThreadPeriod = 5 * 60;
127 
128   final static int DEFAULT_WRITER_THREADS = 3;
129   final static int DEFAULT_WRITER_QUEUE_ITEMS = 64;
130 
131   // Store/read block data
132   transient final IOEngine ioEngine;
133 
134   // Store the block in this map before writing it to cache
135   @VisibleForTesting
136   transient final ConcurrentMap<BlockCacheKey, RAMQueueEntry> ramCache;
137   // In this map, store the block's meta data like offset, length
138   @VisibleForTesting
139   transient ConcurrentMap<BlockCacheKey, BucketEntry> backingMap;
140 
141   /**
142    * Flag if the cache is enabled or not... We shut it off if there are IO
143    * errors for some time, so that Bucket IO exceptions/errors don't bring down
144    * the HBase server.
145    */
146   private volatile boolean cacheEnabled;
147 
148   /**
149    * A list of writer queues.  We have a queue per {@link WriterThread} we have running.
150    * In other words, the work adding blocks to the BucketCache is divided up amongst the
151    * running WriterThreads.  Its done by taking hash of the cache key modulo queue count.
152    * WriterThread when it runs takes whatever has been recently added and 'drains' the entries
153    * to the BucketCache.  It then updates the ramCache and backingMap accordingly.
154    */
155   @VisibleForTesting
156   transient final ArrayList<BlockingQueue<RAMQueueEntry>> writerQueues =
157       new ArrayList<BlockingQueue<RAMQueueEntry>>();
158   @VisibleForTesting
159   transient final WriterThread[] writerThreads;
160 
161   /** Volatile boolean to track if free space is in process or not */
162   private volatile boolean freeInProgress = false;
163   private transient final Lock freeSpaceLock = new ReentrantLock();
164 
165   private UniqueIndexMap<Integer> deserialiserMap = new UniqueIndexMap<Integer>();
166 
167   private final AtomicLong realCacheSize = new AtomicLong(0);
168   private final AtomicLong heapSize = new AtomicLong(0);
169   /** Current number of cached elements */
170   private final AtomicLong blockNumber = new AtomicLong(0);
171 
172   /** Cache access count (sequential ID) */
173   private final AtomicLong accessCount = new AtomicLong(0);
174 
175   private static final int DEFAULT_CACHE_WAIT_TIME = 50;
176   // Used in test now. If the flag is false and the cache speed is very fast,
177   // bucket cache will skip some blocks when caching. If the flag is true, we
178   // will wait blocks flushed to IOEngine for some time when caching
179   boolean wait_when_cache = false;
180 
181   private final BucketCacheStats cacheStats = new BucketCacheStats();
182 
183   private final String persistencePath;
184   private final long cacheCapacity;
185   /** Approximate block size */
186   private final long blockSize;
187 
188   /** Duration of IO errors tolerated before we disable cache, 1 min as default */
189   private final int ioErrorsTolerationDuration;
190   // 1 min
191   public static final int DEFAULT_ERROR_TOLERATION_DURATION = 60 * 1000;
192 
193   // Start time of first IO error when reading or writing IO Engine, it will be
194   // reset after a successful read/write.
195   private volatile long ioErrorStartTime = -1;
196 
197   /**
198    * A ReentrantReadWriteLock to lock on a particular block identified by offset.
199    * The purpose of this is to avoid freeing the block which is being read.
200    */
201   @VisibleForTesting
202   transient final IdReadWriteLock offsetLock = new IdReadWriteLock();
203 
204   private final NavigableSet<BlockCacheKey> blocksByHFile =
205       new ConcurrentSkipListSet<BlockCacheKey>(new Comparator<BlockCacheKey>() {
206         @Override
207         public int compare(BlockCacheKey a, BlockCacheKey b) {
208           int nameComparison = a.getHfileName().compareTo(b.getHfileName());
209           if (nameComparison != 0) {
210             return nameComparison;
211           }
212 
213           if (a.getOffset() == b.getOffset()) {
214             return 0;
215           } else if (a.getOffset() < b.getOffset()) {
216             return -1;
217           }
218           return 1;
219         }
220       });
221 
222   /** Statistics thread schedule pool (for heavy debugging, could remove) */
223   private transient final ScheduledExecutorService scheduleThreadPool =
224     Executors.newScheduledThreadPool(1,
225       new ThreadFactoryBuilder().setNameFormat("BucketCacheStatsExecutor").setDaemon(true).build());
226 
227   // Allocate or free space for the block
228   private transient BucketAllocator bucketAllocator;
229 
230   /** Acceptable size of cache (no evictions if size < acceptable) */
231   private float acceptableFactor;
232 
233   /** Minimum threshold of cache (when evicting, evict until size < min) */
234   private float minFactor;
235 
236   /** Free this floating point factor of extra blocks when evicting. For example free the number of blocks requested * (1 + extraFreeFactor) */
237   private float extraFreeFactor;
238 
239   /** Single access bucket size */
240   private float singleFactor;
241 
242   /** Multiple access bucket size */
243   private float multiFactor;
244 
245   /** In-memory bucket size */
246   private float memoryFactor;
247 
248   private static final String FILE_VERIFY_ALGORITHM =
249     "hbase.bucketcache.persistent.file.integrity.check.algorithm";
250   private static final String DEFAULT_FILE_VERIFY_ALGORITHM = "MD5";
251 
252   /**
253    * Use {@link java.security.MessageDigest} class's encryption algorithms to check
254    * persistent file integrity, default algorithm is MD5
255    * */
256   private String algorithm;
257 
258   public BucketCache(String ioEngineName, long capacity, int blockSize, int[] bucketSizes,
259       int writerThreadNum, int writerQLen, String persistencePath) throws FileNotFoundException,
260       IOException {
261     this(ioEngineName, capacity, blockSize, bucketSizes, writerThreadNum, writerQLen,
262       persistencePath, DEFAULT_ERROR_TOLERATION_DURATION, HBaseConfiguration.create());
263   }
264 
265   public BucketCache(String ioEngineName, long capacity, int blockSize, int[] bucketSizes,
266                      int writerThreadNum, int writerQLen, String persistencePath, int ioErrorsTolerationDuration,
267                      Configuration conf)
268       throws IOException {
269     this.algorithm = conf.get(FILE_VERIFY_ALGORITHM, DEFAULT_FILE_VERIFY_ALGORITHM);
270     ioEngine = getIOEngineFromName(ioEngineName, capacity);
271     this.writerThreads = new WriterThread[writerThreadNum];
272     long blockNumCapacity = capacity / blockSize;
273     if (blockNumCapacity >= Integer.MAX_VALUE) {
274       // Enough for about 32TB of cache!
275       throw new IllegalArgumentException("Cache capacity is too large, only support 32TB now");
276     }
277 
278     this.acceptableFactor = conf.getFloat(ACCEPT_FACTOR_CONFIG_NAME, DEFAULT_ACCEPT_FACTOR);
279     this.minFactor = conf.getFloat(MIN_FACTOR_CONFIG_NAME, DEFAULT_MIN_FACTOR);
280     this.extraFreeFactor = conf.getFloat(EXTRA_FREE_FACTOR_CONFIG_NAME, DEFAULT_EXTRA_FREE_FACTOR);
281     this.singleFactor = conf.getFloat(SINGLE_FACTOR_CONFIG_NAME, DEFAULT_SINGLE_FACTOR);
282     this.multiFactor = conf.getFloat(MULTI_FACTOR_CONFIG_NAME, DEFAULT_MULTI_FACTOR);
283     this.memoryFactor = conf.getFloat(MEMORY_FACTOR_CONFIG_NAME, DEFAULT_MEMORY_FACTOR);
284 
285     sanityCheckConfigs();
286 
287     LOG.info("Instantiating BucketCache with acceptableFactor: " + acceptableFactor + ", minFactor: " + minFactor +
288         ", extraFreeFactor: " + extraFreeFactor + ", singleFactor: " + singleFactor + ", multiFactor: " + multiFactor +
289         ", memoryFactor: " + memoryFactor);
290 
291     this.cacheCapacity = capacity;
292     this.persistencePath = persistencePath;
293     this.blockSize = blockSize;
294     this.ioErrorsTolerationDuration = ioErrorsTolerationDuration;
295 
296     bucketAllocator = new BucketAllocator(capacity, bucketSizes);
297     for (int i = 0; i < writerThreads.length; ++i) {
298       writerQueues.add(new ArrayBlockingQueue<RAMQueueEntry>(writerQLen));
299     }
300 
301     assert writerQueues.size() == writerThreads.length;
302     this.ramCache = new ConcurrentHashMap<BlockCacheKey, RAMQueueEntry>();
303 
304     this.backingMap = new ConcurrentHashMap<BlockCacheKey, BucketEntry>((int) blockNumCapacity);
305 
306     if (ioEngine.isPersistent() && persistencePath != null) {
307       try {
308         retrieveFromFile(bucketSizes);
309       } catch (IOException ioex) {
310         LOG.error("Can't restore from file because of", ioex);
311       } catch (ClassNotFoundException cnfe) {
312         LOG.error("Can't restore from file in rebuild because can't deserialise", cnfe);
313         throw new RuntimeException(cnfe);
314       }
315     }
316     final String threadName = Thread.currentThread().getName();
317     this.cacheEnabled = true;
318     for (int i = 0; i < writerThreads.length; ++i) {
319       writerThreads[i] = new WriterThread(writerQueues.get(i));
320       writerThreads[i].setName(threadName + "-BucketCacheWriter-" + i);
321       writerThreads[i].setDaemon(true);
322     }
323     startWriterThreads();
324 
325     // Run the statistics thread periodically to print the cache statistics log
326     // TODO: Add means of turning this off.  Bit obnoxious running thread just to make a log
327     // every five minutes.
328     this.scheduleThreadPool.scheduleAtFixedRate(new StatisticsThread(this),
329         statThreadPeriod, statThreadPeriod, TimeUnit.SECONDS);
330     LOG.info("Started bucket cache; ioengine=" + ioEngineName +
331         ", capacity=" + StringUtils.byteDesc(capacity) +
332       ", blockSize=" + StringUtils.byteDesc(blockSize) + ", writerThreadNum=" +
333         writerThreadNum + ", writerQLen=" + writerQLen + ", persistencePath=" +
334       persistencePath + ", bucketAllocator=" + this.bucketAllocator.getClass().getName());
335   }
336 
337   private void sanityCheckConfigs() {
338     Preconditions.checkArgument(acceptableFactor <= 1 && acceptableFactor >= 0, ACCEPT_FACTOR_CONFIG_NAME + " must be between 0.0 and 1.0");
339     Preconditions.checkArgument(minFactor <= 1 && minFactor >= 0, MIN_FACTOR_CONFIG_NAME + " must be between 0.0 and 1.0");
340     Preconditions.checkArgument(minFactor <= acceptableFactor, MIN_FACTOR_CONFIG_NAME + " must be <= " + ACCEPT_FACTOR_CONFIG_NAME);
341     Preconditions.checkArgument(extraFreeFactor >= 0, EXTRA_FREE_FACTOR_CONFIG_NAME + " must be greater than 0.0");
342     Preconditions.checkArgument(singleFactor <= 1 && singleFactor >= 0, SINGLE_FACTOR_CONFIG_NAME + " must be between 0.0 and 1.0");
343     Preconditions.checkArgument(multiFactor <= 1 && multiFactor >= 0, MULTI_FACTOR_CONFIG_NAME + " must be between 0.0 and 1.0");
344     Preconditions.checkArgument(memoryFactor <= 1 && memoryFactor >= 0, MEMORY_FACTOR_CONFIG_NAME + " must be between 0.0 and 1.0");
345     Preconditions.checkArgument((singleFactor + multiFactor + memoryFactor) == 1, SINGLE_FACTOR_CONFIG_NAME + ", " +
346         MULTI_FACTOR_CONFIG_NAME + ", and " + MEMORY_FACTOR_CONFIG_NAME + " segments must add up to 1.0");
347   }
348 
349   /**
350    * Called by the constructor to start the writer threads. Used by tests that need to override
351    * starting the threads.
352    */
353   @VisibleForTesting
354   protected void startWriterThreads() {
355     for (WriterThread thread : writerThreads) {
356       thread.start();
357     }
358   }
359 
360   @VisibleForTesting
361   boolean isCacheEnabled() {
362     return this.cacheEnabled;
363   }
364 
365   @Override
366   public long getMaxSize() {
367     return this.cacheCapacity;
368   }
369 
370   public String getIoEngine() {
371     return ioEngine.toString();
372   }
373 
374   /**
375    * Get the IOEngine from the IO engine name
376    * @param ioEngineName
377    * @param capacity
378    * @return the IOEngine
379    * @throws IOException
380    */
381   private IOEngine getIOEngineFromName(String ioEngineName, long capacity)
382       throws IOException {
383     if (ioEngineName.startsWith("file:") || ioEngineName.startsWith("files:")) {
384       // In order to make the usage simple, we only need the prefix 'files:' in
385       // document whether one or multiple file(s), but also support 'file:' for
386       // the compatibility
387       String[] filePaths =
388           ioEngineName.substring(ioEngineName.indexOf(":") + 1).split(FileIOEngine.FILE_DELIMITER);
389       return new FileIOEngine(capacity, filePaths);
390     } else if (ioEngineName.startsWith("offheap"))
391       return new ByteBufferIOEngine(capacity, true);
392     else if (ioEngineName.startsWith("heap"))
393       return new ByteBufferIOEngine(capacity, false);
394     else
395       throw new IllegalArgumentException(
396           "Don't understand io engine name for cache - prefix with file:, heap or offheap");
397   }
398 
399   /**
400    * Cache the block with the specified name and buffer.
401    * @param cacheKey block's cache key
402    * @param buf block buffer
403    */
404   @Override
405   public void cacheBlock(BlockCacheKey cacheKey, Cacheable buf) {
406     cacheBlock(cacheKey, buf, false, false);
407   }
408 
409   /**
410    * Cache the block with the specified name and buffer.
411    * @param cacheKey block's cache key
412    * @param cachedItem block buffer
413    * @param inMemory if block is in-memory
414    * @param cacheDataInL1
415    */
416   @Override
417   public void cacheBlock(BlockCacheKey cacheKey, Cacheable cachedItem, boolean inMemory,
418       final boolean cacheDataInL1) {
419     cacheBlockWithWait(cacheKey, cachedItem, inMemory, cacheDataInL1, wait_when_cache);
420   }
421 
422   /**
423    * Cache the block to ramCache
424    * @param cacheKey block's cache key
425    * @param cachedItem block buffer
426    * @param inMemory if block is in-memory
427    * @param wait if true, blocking wait when queue is full
428    */
429   public void cacheBlockWithWait(BlockCacheKey cacheKey, Cacheable cachedItem, boolean inMemory,
430       boolean cacheDataInL1, boolean wait) {
431     if (cacheEnabled) {
432       if (backingMap.containsKey(cacheKey) || ramCache.containsKey(cacheKey)) {
433         if (!cacheDataInL1
434             && BlockCacheUtil.shouldReplaceExistingCacheBlock(this, cacheKey, cachedItem)) {
435           cacheBlockWithWaitInternal(cacheKey, cachedItem, inMemory, cacheDataInL1, wait);
436         }
437       } else {
438         cacheBlockWithWaitInternal(cacheKey, cachedItem, inMemory, cacheDataInL1, wait);
439       }
440     }
441   }
442 
443   private void cacheBlockWithWaitInternal(BlockCacheKey cacheKey, Cacheable cachedItem,
444       boolean inMemory, boolean cacheDataInL1, boolean wait) {
445     if (LOG.isTraceEnabled()) LOG.trace("Caching key=" + cacheKey + ", item=" + cachedItem);
446     if (!cacheEnabled) {
447       return;
448     }
449 
450     // Stuff the entry into the RAM cache so it can get drained to the persistent store
451     RAMQueueEntry re =
452         new RAMQueueEntry(cacheKey, cachedItem, accessCount.incrementAndGet(), inMemory);
453     /**
454      * Don't use ramCache.put(cacheKey, re) here. because there may be a existing entry with same
455      * key in ramCache, the heap size of bucket cache need to update if replacing entry from
456      * ramCache. But WriterThread will also remove entry from ramCache and update heap size, if
457      * using ramCache.put(), It's possible that the removed entry in WriterThread is not the correct
458      * one, then the heap size will mess up (HBASE-20789)
459      */
460     if (ramCache.putIfAbsent(cacheKey, re) != null) {
461       return;
462     }
463     int queueNum = (cacheKey.hashCode() & 0x7FFFFFFF) % writerQueues.size();
464     BlockingQueue<RAMQueueEntry> bq = writerQueues.get(queueNum);
465     boolean successfulAddition = false;
466     if (wait) {
467       try {
468         successfulAddition = bq.offer(re, DEFAULT_CACHE_WAIT_TIME, TimeUnit.MILLISECONDS);
469       } catch (InterruptedException e) {
470         Thread.currentThread().interrupt();
471       }
472     } else {
473       successfulAddition = bq.offer(re);
474     }
475     if (!successfulAddition) {
476       ramCache.remove(cacheKey);
477       cacheStats.failInsert();
478     } else {
479       this.blockNumber.incrementAndGet();
480       this.heapSize.addAndGet(cachedItem.heapSize());
481       blocksByHFile.add(cacheKey);
482     }
483   }
484 
485   /**
486    * Get the buffer of the block with the specified key.
487    * @param key block's cache key
488    * @param caching true if the caller caches blocks on cache misses
489    * @param repeat Whether this is a repeat lookup for the same block
490    * @param updateCacheMetrics Whether we should update cache metrics or not
491    * @return buffer of specified cache key, or null if not in cache
492    */
493   @Override
494   public Cacheable getBlock(BlockCacheKey key, boolean caching, boolean repeat,
495       boolean updateCacheMetrics) {
496     if (!cacheEnabled) {
497       return null;
498     }
499     RAMQueueEntry re = ramCache.get(key);
500     if (re != null) {
501       if (updateCacheMetrics) {
502         cacheStats.hit(caching, key.isPrimary(), key.getBlockType());
503       }
504       re.access(accessCount.incrementAndGet());
505       return re.getData();
506     }
507     BucketEntry bucketEntry = backingMap.get(key);
508     if (bucketEntry != null) {
509       long start = System.nanoTime();
510       ReentrantReadWriteLock lock = offsetLock.getLock(bucketEntry.offset());
511       try {
512         lock.readLock().lock();
513         // We can not read here even if backingMap does contain the given key because its offset
514         // maybe changed. If we lock BlockCacheKey instead of offset, then we can only check
515         // existence here.
516         if (bucketEntry.equals(backingMap.get(key))) {
517           int len = bucketEntry.getLength();
518           if (LOG.isTraceEnabled()) {
519             LOG.trace("Read offset=" + bucketEntry.offset() + ", len=" + len);
520           }
521           ByteBuffer bb = ByteBuffer.allocate(len);
522           int lenRead = ioEngine.read(bb, bucketEntry.offset());
523           if (lenRead != len) {
524             throw new RuntimeException("Only " + lenRead + " bytes read, " + len + " expected");
525           }
526           CacheableDeserializer<Cacheable> deserializer =
527             bucketEntry.deserializerReference(this.deserialiserMap);
528           Cacheable cachedBlock = deserializer.deserialize(bb, true);
529           long timeTaken = System.nanoTime() - start;
530           if (updateCacheMetrics) {
531             cacheStats.hit(caching, key.isPrimary(), key.getBlockType());
532             cacheStats.ioHit(timeTaken);
533           }
534           bucketEntry.access(accessCount.incrementAndGet());
535           if (this.ioErrorStartTime > 0) {
536             ioErrorStartTime = -1;
537           }
538           return cachedBlock;
539         }
540       } catch (IOException ioex) {
541         LOG.error("Failed reading block " + key + " from bucket cache", ioex);
542         checkIOErrorIsTolerated();
543       } finally {
544         lock.readLock().unlock();
545       }
546     }
547     if (!repeat && updateCacheMetrics) {
548       cacheStats.miss(caching, key.isPrimary(), key.getBlockType());
549     }
550     return null;
551   }
552 
553   @VisibleForTesting
554   void blockEvicted(BlockCacheKey cacheKey, BucketEntry bucketEntry, boolean decrementBlockNumber) {
555     bucketAllocator.freeBlock(bucketEntry.offset());
556     realCacheSize.addAndGet(-1 * bucketEntry.getLength());
557     blocksByHFile.remove(cacheKey);
558     if (decrementBlockNumber) {
559       this.blockNumber.decrementAndGet();
560     }
561   }
562 
563   @Override
564   public boolean evictBlock(BlockCacheKey cacheKey) {
565     if (!cacheEnabled) {
566       return false;
567     }
568     RAMQueueEntry removedBlock = ramCache.remove(cacheKey);
569     if (removedBlock != null) {
570       this.blockNumber.decrementAndGet();
571       this.heapSize.addAndGet(-1 * removedBlock.getData().heapSize());
572     }
573     BucketEntry bucketEntry = backingMap.get(cacheKey);
574     if (bucketEntry == null) {
575       if (removedBlock != null) {
576         cacheStats.evicted(0, cacheKey.isPrimary());
577         return true;
578       } else {
579         return false;
580       }
581     }
582     ReentrantReadWriteLock lock = offsetLock.getLock(bucketEntry.offset());
583     try {
584       lock.writeLock().lock();
585       if (backingMap.remove(cacheKey, bucketEntry)) {
586         blockEvicted(cacheKey, bucketEntry, removedBlock == null);
587       } else {
588         return false;
589       }
590     } finally {
591       lock.writeLock().unlock();
592     }
593     cacheStats.evicted(bucketEntry.getCachedTime(), cacheKey.isPrimary());
594     return true;
595   }
596 
597   /*
598    * Statistics thread.  Periodically output cache statistics to the log.
599    */
600   private static class StatisticsThread extends Thread {
601     private final BucketCache bucketCache;
602 
603     public StatisticsThread(BucketCache bucketCache) {
604       super("BucketCacheStatsThread");
605       setDaemon(true);
606       this.bucketCache = bucketCache;
607     }
608 
609     @Override
610     public void run() {
611       bucketCache.logStats();
612     }
613   }
614 
615   public void logStats() {
616     long totalSize = bucketAllocator.getTotalSize();
617     long usedSize = bucketAllocator.getUsedSize();
618     long freeSize = totalSize - usedSize;
619     long cacheSize = getRealCacheSize();
620     LOG.info("failedBlockAdditions=" + cacheStats.getFailedInserts() + ", " +
621         "totalSize=" + StringUtils.byteDesc(totalSize) + ", " +
622         "freeSize=" + StringUtils.byteDesc(freeSize) + ", " +
623         "usedSize=" + StringUtils.byteDesc(usedSize) +", " +
624         "cacheSize=" + StringUtils.byteDesc(cacheSize) +", " +
625         "accesses=" + cacheStats.getRequestCount() + ", " +
626         "hits=" + cacheStats.getHitCount() + ", " +
627         "IOhitsPerSecond=" + cacheStats.getIOHitsPerSecond() + ", " +
628         "IOTimePerHit=" + String.format("%.2f", cacheStats.getIOTimePerHit())+ ", " +
629         "hitRatio=" + (cacheStats.getHitCount() == 0 ? "0," :
630           (StringUtils.formatPercent(cacheStats.getHitRatio(), 2)+ ", ")) +
631         "cachingAccesses=" + cacheStats.getRequestCachingCount() + ", " +
632         "cachingHits=" + cacheStats.getHitCachingCount() + ", " +
633         "cachingHitsRatio=" +(cacheStats.getHitCachingCount() == 0 ? "0," :
634           (StringUtils.formatPercent(cacheStats.getHitCachingRatio(), 2)+ ", ")) +
635         "evictions=" + cacheStats.getEvictionCount() + ", " +
636         "evicted=" + cacheStats.getEvictedCount() + ", " +
637         "evictedPerRun=" + cacheStats.evictedPerEviction());
638     cacheStats.reset();
639   }
640 
641   public long getRealCacheSize() {
642     return this.realCacheSize.get();
643   }
644 
645   private long acceptableSize() {
646     return (long) Math.floor(bucketAllocator.getTotalSize() * acceptableFactor);
647   }
648 
649   @VisibleForTesting
650   long getPartitionSize(float partitionFactor) {
651     return (long) Math.floor(bucketAllocator.getTotalSize() * partitionFactor * minFactor);
652   }
653 
654   /**
655    * Return the count of bucketSizeinfos still need free space
656    */
657   private int bucketSizesAboveThresholdCount(float minFactor) {
658     BucketAllocator.IndexStatistics[] stats = bucketAllocator.getIndexStatistics();
659     int fullCount = 0;
660     for (int i = 0; i < stats.length; i++) {
661       long freeGoal = (long) Math.floor(stats[i].totalCount() * (1 - minFactor));
662       freeGoal = Math.max(freeGoal, 1);
663       if (stats[i].freeCount() < freeGoal) {
664         fullCount++;
665       }
666     }
667     return fullCount;
668   }
669 
670   /**
671    * This method will find the buckets that are minimally occupied
672    * and are not reference counted and will free them completely
673    * without any constraint on the access times of the elements,
674    * and as a process will completely free at most the number of buckets
675    * passed, sometimes it might not due to changing refCounts
676    *
677    * @param completelyFreeBucketsNeeded number of buckets to free
678    **/
679   private void freeEntireBuckets(int completelyFreeBucketsNeeded) {
680     if (completelyFreeBucketsNeeded != 0) {
681       // First we will build a set where the offsets are reference counted, usually
682       // this set is small around O(Handler Count) unless something else is wrong
683       Set<Integer> inUseBuckets = new HashSet<Integer>();
684       for (BucketEntry entry : backingMap.values()) {
685         inUseBuckets.add(bucketAllocator.getBucketIndex(entry.offset()));
686       }
687 
688       Set<Integer> candidateBuckets = bucketAllocator.getLeastFilledBuckets(
689           inUseBuckets, completelyFreeBucketsNeeded);
690       for (Map.Entry<BlockCacheKey, BucketEntry> entry : backingMap.entrySet()) {
691         if (candidateBuckets.contains(bucketAllocator
692             .getBucketIndex(entry.getValue().offset()))) {
693           evictBlock(entry.getKey());
694         }
695       }
696     }
697   }
698 
699   /**
700    * Free the space if the used size reaches acceptableSize() or one size block
701    * couldn't be allocated. When freeing the space, we use the LRU algorithm and
702    * ensure there must be some blocks evicted
703    * @param why Why we are being called
704    */
705   private void freeSpace(final String why) {
706     // Ensure only one freeSpace progress at a time
707     if (!freeSpaceLock.tryLock()) {
708       return;
709     }
710     try {
711       freeInProgress = true;
712       long bytesToFreeWithoutExtra = 0;
713       // Calculate free byte for each bucketSizeinfo
714       StringBuffer msgBuffer = LOG.isDebugEnabled()? new StringBuffer(): null;
715       BucketAllocator.IndexStatistics[] stats = bucketAllocator.getIndexStatistics();
716       long[] bytesToFreeForBucket = new long[stats.length];
717       for (int i = 0; i < stats.length; i++) {
718         bytesToFreeForBucket[i] = 0;
719         long freeGoal = (long) Math.floor(stats[i].totalCount() * (1 - minFactor));
720         freeGoal = Math.max(freeGoal, 1);
721         if (stats[i].freeCount() < freeGoal) {
722           bytesToFreeForBucket[i] = stats[i].itemSize() * (freeGoal - stats[i].freeCount());
723           bytesToFreeWithoutExtra += bytesToFreeForBucket[i];
724           if (msgBuffer != null) {
725             msgBuffer.append("Free for bucketSize(" + stats[i].itemSize() + ")="
726               + StringUtils.byteDesc(bytesToFreeForBucket[i]) + ", ");
727           }
728         }
729       }
730       if (msgBuffer != null) {
731         msgBuffer.append("Free for total=" + StringUtils.byteDesc(bytesToFreeWithoutExtra) + ", ");
732       }
733 
734       if (bytesToFreeWithoutExtra <= 0) {
735         return;
736       }
737       long currentSize = bucketAllocator.getUsedSize();
738       long totalSize = bucketAllocator.getTotalSize();
739       if (LOG.isDebugEnabled() && msgBuffer != null) {
740         LOG.debug("Free started because \"" + why + "\"; " + msgBuffer.toString() +
741           " of current used=" + StringUtils.byteDesc(currentSize) + ", actual cacheSize=" +
742           StringUtils.byteDesc(realCacheSize.get()) + ", total=" + StringUtils.byteDesc(totalSize));
743       }
744 
745       long bytesToFreeWithExtra = (long) Math.floor(bytesToFreeWithoutExtra
746           * (1 + extraFreeFactor));
747 
748       // Instantiate priority buckets
749       BucketEntryGroup bucketSingle = new BucketEntryGroup(bytesToFreeWithExtra,
750           blockSize, getPartitionSize(singleFactor));
751       BucketEntryGroup bucketMulti = new BucketEntryGroup(bytesToFreeWithExtra,
752           blockSize, getPartitionSize(multiFactor));
753       BucketEntryGroup bucketMemory = new BucketEntryGroup(bytesToFreeWithExtra,
754           blockSize, getPartitionSize(memoryFactor));
755 
756       // Scan entire map putting bucket entry into appropriate bucket entry
757       // group
758       for (Map.Entry<BlockCacheKey, BucketEntry> bucketEntryWithKey : backingMap.entrySet()) {
759         switch (bucketEntryWithKey.getValue().getPriority()) {
760           case SINGLE: {
761             bucketSingle.add(bucketEntryWithKey);
762             break;
763           }
764           case MULTI: {
765             bucketMulti.add(bucketEntryWithKey);
766             break;
767           }
768           case MEMORY: {
769             bucketMemory.add(bucketEntryWithKey);
770             break;
771           }
772         }
773       }
774 
775       PriorityQueue<BucketEntryGroup> bucketQueue = new PriorityQueue<BucketEntryGroup>(3);
776 
777       bucketQueue.add(bucketSingle);
778       bucketQueue.add(bucketMulti);
779       bucketQueue.add(bucketMemory);
780 
781       int remainingBuckets = bucketQueue.size();
782       long bytesFreed = 0;
783 
784       BucketEntryGroup bucketGroup;
785       while ((bucketGroup = bucketQueue.poll()) != null) {
786         long overflow = bucketGroup.overflow();
787         if (overflow > 0) {
788           long bucketBytesToFree = Math.min(overflow,
789               (bytesToFreeWithoutExtra - bytesFreed) / remainingBuckets);
790           bytesFreed += bucketGroup.free(bucketBytesToFree);
791         }
792         remainingBuckets--;
793       }
794 
795       // Check and free if there are buckets that still need freeing of space
796       if (bucketSizesAboveThresholdCount(minFactor) > 0) {
797         bucketQueue.clear();
798         remainingBuckets = 3;
799 
800         bucketQueue.add(bucketSingle);
801         bucketQueue.add(bucketMulti);
802         bucketQueue.add(bucketMemory);
803 
804         while ((bucketGroup = bucketQueue.poll()) != null) {
805           long bucketBytesToFree = (bytesToFreeWithExtra - bytesFreed) / remainingBuckets;
806           bytesFreed += bucketGroup.free(bucketBytesToFree);
807           remainingBuckets--;
808         }
809       }
810 
811       // Even after the above free we might still need freeing because of the
812       // De-fragmentation of the buckets (also called Slab Calcification problem), i.e
813       // there might be some buckets where the occupancy is very sparse and thus are not
814       // yielding the free for the other bucket sizes, the fix for this to evict some
815       // of the buckets, we do this by evicting the buckets that are least fulled
816       freeEntireBuckets(DEFAULT_FREE_ENTIRE_BLOCK_FACTOR *
817           bucketSizesAboveThresholdCount(1.0f));
818 
819       if (LOG.isDebugEnabled()) {
820         long single = bucketSingle.totalSize();
821         long multi = bucketMulti.totalSize();
822         long memory = bucketMemory.totalSize();
823         if (LOG.isDebugEnabled()) {
824           LOG.debug("Bucket cache free space completed; " + "freed="
825             + StringUtils.byteDesc(bytesFreed) + ", " + "total="
826             + StringUtils.byteDesc(totalSize) + ", " + "single="
827             + StringUtils.byteDesc(single) + ", " + "multi="
828             + StringUtils.byteDesc(multi) + ", " + "memory="
829             + StringUtils.byteDesc(memory));
830         }
831       }
832 
833     } catch (Throwable t) {
834       LOG.warn("Failed freeing space", t);
835     } finally {
836       cacheStats.evict();
837       freeInProgress = false;
838       freeSpaceLock.unlock();
839     }
840   }
841 
842   // This handles flushing the RAM cache to IOEngine.
843   @VisibleForTesting
844   class WriterThread extends HasThread {
845     private final BlockingQueue<RAMQueueEntry> inputQueue;
846     private volatile boolean writerEnabled = true;
847 
848     WriterThread(BlockingQueue<RAMQueueEntry> queue) {
849       super("BucketCacheWriterThread");
850       this.inputQueue = queue;
851     }
852 
853     // Used for test
854     @VisibleForTesting
855     void disableWriter() {
856       this.writerEnabled = false;
857     }
858 
859     @Override
860     public void run() {
861       List<RAMQueueEntry> entries = new ArrayList<RAMQueueEntry>();
862       try {
863         while (cacheEnabled && writerEnabled) {
864           try {
865             try {
866               // Blocks
867               entries = getRAMQueueEntries(inputQueue, entries);
868             } catch (InterruptedException ie) {
869               if (!cacheEnabled) break;
870             }
871             doDrain(entries);
872           } catch (Exception ioe) {
873             LOG.error("WriterThread encountered error", ioe);
874           }
875         }
876       } catch (Throwable t) {
877         LOG.warn("Failed doing drain", t);
878       }
879       LOG.info(this.getName() + " exiting, cacheEnabled=" + cacheEnabled);
880     }
881 
882     /**
883      * Put the new bucket entry into backingMap. Notice that we are allowed to replace the existing
884      * cache with a new block for the same cache key. there's a corner case: one thread cache a
885      * block in ramCache, copy to io-engine and add a bucket entry to backingMap. Caching another
886      * new block with the same cache key do the same thing for the same cache key, so if not evict
887      * the previous bucket entry, then memory leak happen because the previous bucketEntry is gone
888      * but the bucketAllocator do not free its memory.
889      * @see BlockCacheUtil#shouldReplaceExistingCacheBlock(BlockCache blockCache,BlockCacheKey
890      *      cacheKey, Cacheable newBlock)
891      * @param key Block cache key
892      * @param bucketEntry Bucket entry to put into backingMap.
893      */
894     private void putIntoBackingMap(BlockCacheKey key, BucketEntry bucketEntry) {
895       BucketEntry previousEntry = backingMap.put(key, bucketEntry);
896       if (previousEntry != null && previousEntry != bucketEntry) {
897         ReentrantReadWriteLock lock = offsetLock.getLock(previousEntry.offset());
898         lock.writeLock().lock();
899         try {
900           blockEvicted(key, previousEntry, false);
901         } finally {
902           lock.writeLock().unlock();
903         }
904       }
905     }
906 
907     /**
908      * Flush the entries in ramCache to IOEngine and add bucket entry to backingMap.
909      * Process all that are passed in even if failure being sure to remove from ramCache else we'll
910      * never undo the references and we'll OOME.
911      * @param entries Presumes list passed in here will be processed by this invocation only. No
912      * interference expected.
913      * @throws InterruptedException
914      */
915     @VisibleForTesting
916     void doDrain(final List<RAMQueueEntry> entries) throws InterruptedException {
917       if (entries.isEmpty()) {
918         return;
919       }
920       // This method is a little hard to follow. We run through the passed in entries and for each
921       // successful add, we add a non-null BucketEntry to the below bucketEntries.  Later we must
922       // do cleanup making sure we've cleared ramCache of all entries regardless of whether we
923       // successfully added the item to the bucketcache; if we don't do the cleanup, we'll OOME by
924       // filling ramCache.  We do the clean up by again running through the passed in entries
925       // doing extra work when we find a non-null bucketEntries corresponding entry.
926       final int size = entries.size();
927       BucketEntry[] bucketEntries = new BucketEntry[size];
928       // Index updated inside loop if success or if we can't succeed. We retry if cache is full
929       // when we go to add an entry by going around the loop again without upping the index.
930       int index = 0;
931       while (cacheEnabled && index < size) {
932         RAMQueueEntry re = null;
933         try {
934           re = entries.get(index);
935           if (re == null) {
936             LOG.warn("Couldn't get entry or changed on us; who else is messing with it?");
937             index++;
938             continue;
939           }
940           BucketEntry bucketEntry =
941             re.writeToCache(ioEngine, bucketAllocator, deserialiserMap, realCacheSize);
942           // Successfully added.  Up index and add bucketEntry. Clear io exceptions.
943           bucketEntries[index] = bucketEntry;
944           if (ioErrorStartTime > 0) {
945             ioErrorStartTime = -1;
946           }
947           index++;
948         } catch (BucketAllocatorException fle) {
949           LOG.warn("Failed allocation for " + (re == null ? "" : re.getKey()) + "; " + fle);
950           // Presume can't add. Too big? Move index on. Entry will be cleared from ramCache below.
951           bucketEntries[index] = null;
952           index++;
953         } catch (CacheFullException cfe) {
954           // Cache full when we tried to add. Try freeing space and then retrying (don't up index)
955           if (!freeInProgress) {
956             freeSpace("Full!");
957           } else {
958             Thread.sleep(50);
959           }
960         } catch (IOException ioex) {
961           // Hopefully transient. Retry. checkIOErrorIsTolerated disables cache if problem.
962           LOG.error("Failed writing to bucket cache", ioex);
963           checkIOErrorIsTolerated();
964         }
965       }
966 
967       // Make sure data pages are written on media before we update maps.
968       try {
969         ioEngine.sync();
970       } catch (IOException ioex) {
971         LOG.error("Failed syncing IO engine", ioex);
972         checkIOErrorIsTolerated();
973         // Since we failed sync, free the blocks in bucket allocator
974         for (int i = 0; i < entries.size(); ++i) {
975           if (bucketEntries[i] != null) {
976             bucketAllocator.freeBlock(bucketEntries[i].offset());
977             bucketEntries[i] = null;
978           }
979         }
980       }
981 
982       // Now add to backingMap if successfully added to bucket cache.  Remove from ramCache if
983       // success or error.
984       for (int i = 0; i < size; ++i) {
985         BlockCacheKey key = entries.get(i).getKey();
986         // Only add if non-null entry.
987         if (bucketEntries[i] != null) {
988           putIntoBackingMap(key, bucketEntries[i]);
989         }
990         // Always remove from ramCache even if we failed adding it to the block cache above.
991         RAMQueueEntry ramCacheEntry = ramCache.remove(key);
992         if (ramCacheEntry != null) {
993           heapSize.addAndGet(-1 * entries.get(i).getData().heapSize());
994         } else if (bucketEntries[i] != null){
995           // Block should have already been evicted. Remove it and free space.
996           ReentrantReadWriteLock lock = offsetLock.getLock(bucketEntries[i].offset());
997           try {
998             lock.writeLock().lock();
999             if (backingMap.remove(key, bucketEntries[i])) {
1000               blockEvicted(key, bucketEntries[i], false);
1001             }
1002           } finally {
1003             lock.writeLock().unlock();
1004           }
1005         }
1006       }
1007 
1008       long used = bucketAllocator.getUsedSize();
1009       if (used > acceptableSize()) {
1010         freeSpace("Used=" + used + " > acceptable=" + acceptableSize());
1011       }
1012       return;
1013     }
1014   }
1015 
1016   /**
1017    * Blocks until elements available in <code>q</code> then tries to grab as many as possible
1018    * before returning.
1019    * @param receptical Where to stash the elements taken from queue. We clear before we use it
1020    * just in case.
1021    * @param q The queue to take from.
1022    * @return receptical laden with elements taken from the queue or empty if none found.
1023    */
1024   @VisibleForTesting
1025   static List<RAMQueueEntry> getRAMQueueEntries(final BlockingQueue<RAMQueueEntry> q,
1026       final List<RAMQueueEntry> receptical)
1027   throws InterruptedException {
1028     // Clear sets all entries to null and sets size to 0. We retain allocations. Presume it
1029     // ok even if list grew to accommodate thousands.
1030     receptical.clear();
1031     receptical.add(q.take());
1032     q.drainTo(receptical);
1033     return receptical;
1034   }
1035 
1036   private void persistToFile() throws IOException {
1037     assert !cacheEnabled;
1038     try (ObjectOutputStream oos = new ObjectOutputStream(
1039       new FileOutputStream(persistencePath, false))){
1040       if (!ioEngine.isPersistent()) {
1041         throw new IOException("Attempt to persist non-persistent cache mappings!");
1042       }
1043       byte[] checksum = ((PersistentIOEngine) ioEngine).calculateChecksum(algorithm);
1044       if (checksum != null) {
1045         oos.write(ProtobufUtil.PB_MAGIC);
1046         oos.writeInt(checksum.length);
1047         oos.write(checksum);
1048       }
1049       oos.writeLong(cacheCapacity);
1050       oos.writeUTF(ioEngine.getClass().getName());
1051       oos.writeUTF(backingMap.getClass().getName());
1052       oos.writeObject(deserialiserMap);
1053       oos.writeObject(backingMap);
1054     }
1055   }
1056 
1057   @SuppressWarnings("unchecked")
1058   private void retrieveFromFile(int[] bucketSizes) throws IOException,
1059       ClassNotFoundException {
1060     File persistenceFile = new File(persistencePath);
1061     if (!persistenceFile.exists()) {
1062       return;
1063     }
1064     assert !cacheEnabled;
1065     ObjectInputStream ois = null;
1066     try {
1067       if (!ioEngine.isPersistent())
1068         throw new IOException(
1069             "Attempt to restore non-persistent cache mappings!");
1070       ois = new ObjectInputStream(new FileInputStream(persistencePath));
1071       int pblen = ProtobufUtil.lengthOfPBMagic();
1072       byte[] pbuf = new byte[pblen];
1073       int read = ois.read(pbuf);
1074       if (read != pblen) {
1075         LOG.warn("Can't restore from file because of incorrect number of bytes read while " +
1076           "checking for protobuf magic number. Requested=" + pblen + ", but received= " +
1077           read + ".");
1078         return;
1079       }
1080       if (Bytes.equals(ProtobufUtil.PB_MAGIC, pbuf)) {
1081         int length = ois.readInt();
1082         byte[] persistentChecksum = new byte[length];
1083         int readLen = ois.read(persistentChecksum);
1084         if (readLen != length) {
1085           LOG.warn("Can't restore from file because of incorrect number of bytes read while " +
1086             "checking for persistent checksum. Requested=" + length + ", but received=" +
1087             readLen + ". ");
1088           return;
1089         }
1090         if (!((PersistentIOEngine) ioEngine).verifyFileIntegrity(
1091             persistentChecksum, algorithm)) {
1092           LOG.warn("Can't restore from file because of verification failed.");
1093           return;
1094         }
1095       } else {
1096         // persistent file may be an old version of file, it's not support verification,
1097         // so reopen ObjectInputStream and read the persistent file from head
1098         ois.close();
1099         ois = new ObjectInputStream(new FileInputStream(persistencePath));
1100       }
1101       long capacitySize = ois.readLong();
1102       if (capacitySize != cacheCapacity)
1103         throw new IOException("Mismatched cache capacity:"
1104             + StringUtils.byteDesc(capacitySize) + ", expected: "
1105             + StringUtils.byteDesc(cacheCapacity));
1106       String ioclass = ois.readUTF();
1107       String mapclass = ois.readUTF();
1108       if (!ioEngine.getClass().getName().equals(ioclass))
1109         throw new IOException("Class name for IO engine mismatch: " + ioclass
1110             + ", expected:" + ioEngine.getClass().getName());
1111       if (!backingMap.getClass().getName().equals(mapclass))
1112         throw new IOException("Class name for cache map mismatch: " + mapclass
1113             + ", expected:" + backingMap.getClass().getName());
1114       UniqueIndexMap<Integer> deserMap = (UniqueIndexMap<Integer>) ois
1115           .readObject();
1116       ConcurrentHashMap<BlockCacheKey, BucketEntry> backingMapFromFile =
1117           (ConcurrentHashMap<BlockCacheKey, BucketEntry>) ois.readObject();
1118       BucketAllocator allocator = new BucketAllocator(cacheCapacity, bucketSizes,
1119         backingMapFromFile, realCacheSize);
1120       bucketAllocator = allocator;
1121       deserialiserMap = deserMap;
1122       backingMap = backingMapFromFile;
1123       blockNumber.set(backingMap.size());
1124     } finally {
1125       if (ois != null) {
1126         ois.close();
1127       }
1128       if (!persistenceFile.delete()) {
1129         throw new IOException("Failed deleting persistence file "
1130             + persistenceFile.getAbsolutePath());
1131       }
1132     }
1133   }
1134 
1135   /**
1136    * Check whether we tolerate IO error this time. If the duration of IOEngine
1137    * throwing errors exceeds ioErrorsDurationTimeTolerated, we will disable the
1138    * cache
1139    */
1140   private void checkIOErrorIsTolerated() {
1141     long now = EnvironmentEdgeManager.currentTime();
1142     if (this.ioErrorStartTime > 0) {
1143       if (cacheEnabled && (now - ioErrorStartTime) > this.ioErrorsTolerationDuration) {
1144         LOG.error("IO errors duration time has exceeded " + ioErrorsTolerationDuration +
1145           "ms, disabling cache, please check your IOEngine");
1146         disableCache();
1147       }
1148     } else {
1149       this.ioErrorStartTime = now;
1150     }
1151   }
1152 
1153   /**
1154    * Used to shut down the cache -or- turn it off in the case of something broken.
1155    */
1156   private void disableCache() {
1157     if (!cacheEnabled) return;
1158     cacheEnabled = false;
1159     ioEngine.shutdown();
1160     this.scheduleThreadPool.shutdown();
1161     for (int i = 0; i < writerThreads.length; ++i) writerThreads[i].interrupt();
1162     this.ramCache.clear();
1163     if (!ioEngine.isPersistent() || persistencePath == null) {
1164       // If persistent ioengine and a path, we will serialize out the backingMap.
1165       this.backingMap.clear();
1166     }
1167   }
1168 
1169   private void join() throws InterruptedException {
1170     for (int i = 0; i < writerThreads.length; ++i)
1171       writerThreads[i].join();
1172   }
1173 
1174   @Override
1175   public void shutdown() {
1176     disableCache();
1177     LOG.info("Shutdown bucket cache: IO persistent=" + ioEngine.isPersistent()
1178         + "; path to write=" + persistencePath);
1179     if (ioEngine.isPersistent() && persistencePath != null) {
1180       try {
1181         join();
1182         persistToFile();
1183       } catch (IOException ex) {
1184         LOG.error("Unable to persist data on exit: " + ex.toString(), ex);
1185       } catch (InterruptedException e) {
1186         LOG.warn("Failed to persist data on exit", e);
1187       }
1188     }
1189   }
1190 
1191   @Override
1192   public CacheStats getStats() {
1193     return cacheStats;
1194   }
1195 
1196   public BucketAllocator getAllocator() {
1197     return this.bucketAllocator;
1198   }
1199 
1200   @Override
1201   public long heapSize() {
1202     return this.heapSize.get();
1203   }
1204 
1205   @Override
1206   public long size() {
1207     return this.realCacheSize.get();
1208   }
1209 
1210   @Override
1211   public long getCurrentDataSize() {
1212     return size();
1213   }
1214 
1215   @Override
1216   public long getFreeSize() {
1217     return this.bucketAllocator.getFreeSize();
1218   }
1219 
1220   @Override
1221   public long getBlockCount() {
1222     return this.blockNumber.get();
1223   }
1224 
1225   @Override
1226   public long getDataBlockCount() {
1227     return getBlockCount();
1228   }
1229 
1230   @Override
1231   public long getCurrentSize() {
1232     return this.bucketAllocator.getUsedSize();
1233   }
1234 
1235   /**
1236    * Evicts all blocks for a specific HFile.
1237    * <p>
1238    * This is used for evict-on-close to remove all blocks of a specific HFile.
1239    *
1240    * @return the number of blocks evicted
1241    */
1242   @Override
1243   public int evictBlocksByHfileName(String hfileName) {
1244     Set<BlockCacheKey> keySet = blocksByHFile.subSet(
1245         new BlockCacheKey(hfileName, Long.MIN_VALUE), true,
1246         new BlockCacheKey(hfileName, Long.MAX_VALUE), true);
1247 
1248     int numEvicted = 0;
1249     for (BlockCacheKey key : keySet) {
1250       if (evictBlock(key)) {
1251           ++numEvicted;
1252       }
1253     }
1254 
1255     return numEvicted;
1256   }
1257 
1258   /**
1259    * Item in cache. We expect this to be where most memory goes. Java uses 8
1260    * bytes just for object headers; after this, we want to use as little as
1261    * possible - so we only use 8 bytes, but in order to do so we end up messing
1262    * around with all this Java casting stuff. Offset stored as 5 bytes that make
1263    * up the long. Doubt we'll see devices this big for ages. Offsets are divided
1264    * by 256. So 5 bytes gives us 256TB or so.
1265    */
1266   static class BucketEntry implements Serializable {
1267     private static final long serialVersionUID = -6741504807982257534L;
1268 
1269     // access counter comparator, descending order
1270     static final Comparator<BucketEntry> COMPARATOR = new Comparator<BucketCache.BucketEntry>() {
1271 
1272       @Override
1273       public int compare(BucketEntry o1, BucketEntry o2) {
1274         return Long.compare(o2.accessCounter, o1.accessCounter);
1275       }
1276     };
1277 
1278     private int offsetBase;
1279     private int length;
1280     private byte offset1;
1281     byte deserialiserIndex;
1282     private volatile long accessCounter;
1283     private BlockPriority priority;
1284     /**
1285      * Time this block was cached.  Presumes we are created just before we are added to the cache.
1286      */
1287     private final long cachedTime = System.nanoTime();
1288 
1289     BucketEntry(long offset, int length, long accessCounter, boolean inMemory) {
1290       setOffset(offset);
1291       this.length = length;
1292       this.accessCounter = accessCounter;
1293       if (inMemory) {
1294         this.priority = BlockPriority.MEMORY;
1295       } else {
1296         this.priority = BlockPriority.SINGLE;
1297       }
1298     }
1299 
1300     long offset() { // Java has no unsigned numbers
1301       long o = ((long) offsetBase) & 0xFFFFFFFFL; //This needs the L cast otherwise it will be sign extended as a negative number.
1302       o += (((long) (offset1)) & 0xFF) << 32; //The 0xFF here does not need the L cast because it is treated as a positive int.
1303       return o << 8;
1304     }
1305 
1306     private void setOffset(long value) {
1307       assert (value & 0xFF) == 0;
1308       value >>= 8;
1309       offsetBase = (int) value;
1310       offset1 = (byte) (value >> 32);
1311     }
1312 
1313     public int getLength() {
1314       return length;
1315     }
1316 
1317     protected CacheableDeserializer<Cacheable> deserializerReference(
1318         UniqueIndexMap<Integer> deserialiserMap) {
1319       return CacheableDeserializerIdManager.getDeserializer(deserialiserMap
1320           .unmap(deserialiserIndex));
1321     }
1322 
1323     protected void setDeserialiserReference(
1324         CacheableDeserializer<Cacheable> deserializer,
1325         UniqueIndexMap<Integer> deserialiserMap) {
1326       this.deserialiserIndex = ((byte) deserialiserMap.map(deserializer
1327           .getDeserialiserIdentifier()));
1328     }
1329 
1330     /**
1331      * Block has been accessed. Update its local access counter.
1332      */
1333     public void access(long accessCounter) {
1334       this.accessCounter = accessCounter;
1335       if (this.priority == BlockPriority.SINGLE) {
1336         this.priority = BlockPriority.MULTI;
1337       }
1338     }
1339 
1340     public BlockPriority getPriority() {
1341       return this.priority;
1342     }
1343 
1344     public long getCachedTime() {
1345       return cachedTime;
1346     }
1347   }
1348 
1349   /**
1350    * Used to group bucket entries into priority buckets. There will be a
1351    * BucketEntryGroup for each priority (single, multi, memory). Once bucketed,
1352    * the eviction algorithm takes the appropriate number of elements out of each
1353    * according to configuration parameters and their relative sizes.
1354    */
1355   private class BucketEntryGroup implements Comparable<BucketEntryGroup> {
1356 
1357     private CachedEntryQueue queue;
1358     private long totalSize = 0;
1359     private long bucketSize;
1360 
1361     public BucketEntryGroup(long bytesToFree, long blockSize, long bucketSize) {
1362       this.bucketSize = bucketSize;
1363       queue = new CachedEntryQueue(bytesToFree, blockSize);
1364       totalSize = 0;
1365     }
1366 
1367     public void add(Map.Entry<BlockCacheKey, BucketEntry> block) {
1368       totalSize += block.getValue().getLength();
1369       queue.add(block);
1370     }
1371 
1372     public long free(long toFree) {
1373       Map.Entry<BlockCacheKey, BucketEntry> entry;
1374       long freedBytes = 0;
1375       while ((entry = queue.pollLast()) != null) {
1376         evictBlock(entry.getKey());
1377         freedBytes += entry.getValue().getLength();
1378         if (freedBytes >= toFree) {
1379           return freedBytes;
1380         }
1381       }
1382       return freedBytes;
1383     }
1384 
1385     public long overflow() {
1386       return totalSize - bucketSize;
1387     }
1388 
1389     public long totalSize() {
1390       return totalSize;
1391     }
1392 
1393     @Override
1394     public int compareTo(BucketEntryGroup that) {
1395       return Long.compare(this.overflow(), that.overflow());
1396     }
1397 
1398     @Override
1399     public int hashCode() {
1400       final int prime = 31;
1401       int result = 1;
1402       result = prime * result + getOuterType().hashCode();
1403       result = prime * result + (int) (bucketSize ^ (bucketSize >>> 32));
1404       result = prime * result + ((queue == null) ? 0 : queue.hashCode());
1405       result = prime * result + (int) (totalSize ^ (totalSize >>> 32));
1406       return result;
1407     }
1408 
1409     @Override
1410     public boolean equals(Object obj) {
1411       if (this == obj) {
1412         return true;
1413       }
1414       if (obj == null) {
1415         return false;
1416       }
1417       if (getClass() != obj.getClass()) {
1418         return false;
1419       }
1420       BucketEntryGroup other = (BucketEntryGroup) obj;
1421       if (!getOuterType().equals(other.getOuterType())) {
1422         return false;
1423       }
1424       if (bucketSize != other.bucketSize) {
1425         return false;
1426       }
1427       if (queue == null) {
1428         if (other.queue != null) {
1429           return false;
1430         }
1431       } else if (!queue.equals(other.queue)) {
1432         return false;
1433       }
1434       if (totalSize != other.totalSize) {
1435         return false;
1436       }
1437       return true;
1438     }
1439 
1440     private BucketCache getOuterType() {
1441       return BucketCache.this;
1442     }
1443 
1444   }
1445 
1446   /**
1447    * Block Entry stored in the memory with key,data and so on
1448    */
1449   @VisibleForTesting
1450   static class RAMQueueEntry {
1451     private BlockCacheKey key;
1452     private Cacheable data;
1453     private long accessCounter;
1454     private boolean inMemory;
1455 
1456     public RAMQueueEntry(BlockCacheKey bck, Cacheable data, long accessCounter,
1457         boolean inMemory) {
1458       this.key = bck;
1459       this.data = data;
1460       this.accessCounter = accessCounter;
1461       this.inMemory = inMemory;
1462     }
1463 
1464     public Cacheable getData() {
1465       return data;
1466     }
1467 
1468     public BlockCacheKey getKey() {
1469       return key;
1470     }
1471 
1472     public void access(long accessCounter) {
1473       this.accessCounter = accessCounter;
1474     }
1475 
1476     public BucketEntry writeToCache(final IOEngine ioEngine,
1477         final BucketAllocator bucketAllocator,
1478         final UniqueIndexMap<Integer> deserialiserMap,
1479         final AtomicLong realCacheSize) throws CacheFullException, IOException,
1480         BucketAllocatorException {
1481       int len = data.getSerializedLength();
1482       // This cacheable thing can't be serialized
1483       if (len == 0) return null;
1484       long offset = bucketAllocator.allocateBlock(len);
1485       BucketEntry bucketEntry = new BucketEntry(offset, len, accessCounter, inMemory);
1486       bucketEntry.setDeserialiserReference(data.getDeserializer(), deserialiserMap);
1487       try {
1488         if (data instanceof HFileBlock) {
1489           // If an instance of HFileBlock, save on some allocations.
1490           HFileBlock block = (HFileBlock)data;
1491           ByteBuffer sliceBuf = block.getBufferReadOnly();
1492           ByteBuffer metadata = block.getMetaData();
1493           if (LOG.isTraceEnabled()) {
1494             LOG.trace("Write offset=" + offset + ", len=" + len);
1495           }
1496           ioEngine.write(sliceBuf, offset);
1497           ioEngine.write(metadata, offset + len - metadata.limit());
1498         } else {
1499           ByteBuffer bb = ByteBuffer.allocate(len);
1500           data.serialize(bb, true);
1501           ioEngine.write(bb, offset);
1502         }
1503       } catch (IOException ioe) {
1504         // free it in bucket allocator
1505         bucketAllocator.freeBlock(offset);
1506         throw ioe;
1507       }
1508 
1509       realCacheSize.addAndGet(len);
1510       return bucketEntry;
1511     }
1512   }
1513 
1514   /**
1515    * Only used in test
1516    * @throws InterruptedException
1517    */
1518   void stopWriterThreads() throws InterruptedException {
1519     for (WriterThread writerThread : writerThreads) {
1520       writerThread.disableWriter();
1521       writerThread.interrupt();
1522       writerThread.join();
1523     }
1524   }
1525 
1526   @Override
1527   public Iterator<CachedBlock> iterator() {
1528     // Don't bother with ramcache since stuff is in here only a little while.
1529     final Iterator<Map.Entry<BlockCacheKey, BucketEntry>> i =
1530         this.backingMap.entrySet().iterator();
1531     return new Iterator<CachedBlock>() {
1532       private final long now = System.nanoTime();
1533 
1534       @Override
1535       public boolean hasNext() {
1536         return i.hasNext();
1537       }
1538 
1539       @Override
1540       public CachedBlock next() {
1541         final Map.Entry<BlockCacheKey, BucketEntry> e = i.next();
1542         return new CachedBlock() {
1543           @Override
1544           public String toString() {
1545             return BlockCacheUtil.toString(this, now);
1546           }
1547 
1548           @Override
1549           public BlockPriority getBlockPriority() {
1550             return e.getValue().getPriority();
1551           }
1552 
1553           @Override
1554           public BlockType getBlockType() {
1555             // Not held by BucketEntry.  Could add it if wanted on BucketEntry creation.
1556             return null;
1557           }
1558 
1559           @Override
1560           public long getOffset() {
1561             return e.getKey().getOffset();
1562           }
1563 
1564           @Override
1565           public long getSize() {
1566             return e.getValue().getLength();
1567           }
1568 
1569           @Override
1570           public long getCachedTime() {
1571             return e.getValue().getCachedTime();
1572           }
1573 
1574           @Override
1575           public String getFilename() {
1576             return e.getKey().getHfileName();
1577           }
1578 
1579           @Override
1580           public int compareTo(CachedBlock other) {
1581             int diff = this.getFilename().compareTo(other.getFilename());
1582             if (diff != 0) return diff;
1583 
1584             diff = Long.compare(this.getOffset(), other.getOffset());
1585             if (diff != 0) return diff;
1586             if (other.getCachedTime() < 0 || this.getCachedTime() < 0) {
1587               throw new IllegalStateException("" + this.getCachedTime() + ", " +
1588                 other.getCachedTime());
1589             }
1590             return Long.compare(other.getCachedTime(), this.getCachedTime());
1591           }
1592 
1593           @Override
1594           public int hashCode() {
1595             return e.getKey().hashCode();
1596           }
1597 
1598           @Override
1599           public boolean equals(Object obj) {
1600             if (obj instanceof CachedBlock) {
1601               CachedBlock cb = (CachedBlock)obj;
1602               return compareTo(cb) == 0;
1603             } else {
1604               return false;
1605             }
1606           }
1607         };
1608       }
1609 
1610       @Override
1611       public void remove() {
1612         throw new UnsupportedOperationException();
1613       }
1614     };
1615   }
1616 
1617   @Override
1618   public BlockCache[] getBlockCaches() {
1619     return null;
1620   }
1621 
1622   float getAcceptableFactor() {
1623     return acceptableFactor;
1624   }
1625 
1626   float getMinFactor() {
1627     return minFactor;
1628   }
1629 
1630   float getExtraFreeFactor() {
1631     return extraFreeFactor;
1632   }
1633 
1634   float getSingleFactor() {
1635     return singleFactor;
1636   }
1637 
1638   float getMultiFactor() {
1639     return multiFactor;
1640   }
1641 
1642   float getMemoryFactor() {
1643     return memoryFactor;
1644   }
1645 
1646   @VisibleForTesting
1647   public UniqueIndexMap<Integer> getDeserialiserMap() {
1648     return deserialiserMap;
1649   }
1650 }