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