1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100 @InterfaceAudience.Private
101 public class BucketCache implements BlockCache, HeapSize {
102 private static final Log LOG = LogFactory.getLog(BucketCache.class);
103
104
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
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
123 private static final int DEFAULT_FREE_ENTIRE_BLOCK_FACTOR = 2;
124
125
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
132 transient final IOEngine ioEngine;
133
134
135 @VisibleForTesting
136 transient final ConcurrentMap<BlockCacheKey, RAMQueueEntry> ramCache;
137
138 @VisibleForTesting
139 transient ConcurrentMap<BlockCacheKey, BucketEntry> backingMap;
140
141
142
143
144
145
146 private volatile boolean cacheEnabled;
147
148
149
150
151
152
153
154
155 @VisibleForTesting
156 transient final ArrayList<BlockingQueue<RAMQueueEntry>> writerQueues =
157 new ArrayList<BlockingQueue<RAMQueueEntry>>();
158 @VisibleForTesting
159 transient final WriterThread[] writerThreads;
160
161
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
170 private final AtomicLong blockNumber = new AtomicLong(0);
171
172
173 private final AtomicLong accessCount = new AtomicLong(0);
174
175 private static final int DEFAULT_CACHE_WAIT_TIME = 50;
176
177
178
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
186 private final long blockSize;
187
188
189 private final int ioErrorsTolerationDuration;
190
191 public static final int DEFAULT_ERROR_TOLERATION_DURATION = 60 * 1000;
192
193
194
195 private volatile long ioErrorStartTime = -1;
196
197
198
199
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
223 private transient final ScheduledExecutorService scheduleThreadPool =
224 Executors.newScheduledThreadPool(1,
225 new ThreadFactoryBuilder().setNameFormat("BucketCacheStatsExecutor").setDaemon(true).build());
226
227
228 private transient BucketAllocator bucketAllocator;
229
230
231 private float acceptableFactor;
232
233
234 private float minFactor;
235
236
237 private float extraFreeFactor;
238
239
240 private float singleFactor;
241
242
243 private float multiFactor;
244
245
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
254
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
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
326
327
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
351
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
376
377
378
379
380
381 private IOEngine getIOEngineFromName(String ioEngineName, long capacity)
382 throws IOException {
383 if (ioEngineName.startsWith("file:") || ioEngineName.startsWith("files:")) {
384
385
386
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
401
402
403
404 @Override
405 public void cacheBlock(BlockCacheKey cacheKey, Cacheable buf) {
406 cacheBlock(cacheKey, buf, false, false);
407 }
408
409
410
411
412
413
414
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
424
425
426
427
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
451 RAMQueueEntry re =
452 new RAMQueueEntry(cacheKey, cachedItem, accessCount.incrementAndGet(), inMemory);
453
454
455
456
457
458
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
487
488
489
490
491
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
514
515
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
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
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
672
673
674
675
676
677
678
679 private void freeEntireBuckets(int completelyFreeBucketsNeeded) {
680 if (completelyFreeBucketsNeeded != 0) {
681
682
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
701
702
703
704
705 private void freeSpace(final String why) {
706
707 if (!freeSpaceLock.tryLock()) {
708 return;
709 }
710 try {
711 freeInProgress = true;
712 long bytesToFreeWithoutExtra = 0;
713
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
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
757
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
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
812
813
814
815
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
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
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
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
884
885
886
887
888
889
890
891
892
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
909
910
911
912
913
914
915 @VisibleForTesting
916 void doDrain(final List<RAMQueueEntry> entries) throws InterruptedException {
917 if (entries.isEmpty()) {
918 return;
919 }
920
921
922
923
924
925
926 final int size = entries.size();
927 BucketEntry[] bucketEntries = new BucketEntry[size];
928
929
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
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
951 bucketEntries[index] = null;
952 index++;
953 } catch (CacheFullException cfe) {
954
955 if (!freeInProgress) {
956 freeSpace("Full!");
957 } else {
958 Thread.sleep(50);
959 }
960 } catch (IOException ioex) {
961
962 LOG.error("Failed writing to bucket cache", ioex);
963 checkIOErrorIsTolerated();
964 }
965 }
966
967
968 try {
969 ioEngine.sync();
970 } catch (IOException ioex) {
971 LOG.error("Failed syncing IO engine", ioex);
972 checkIOErrorIsTolerated();
973
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
983
984 for (int i = 0; i < size; ++i) {
985 BlockCacheKey key = entries.get(i).getKey();
986
987 if (bucketEntries[i] != null) {
988 putIntoBackingMap(key, bucketEntries[i]);
989 }
990
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
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
1018
1019
1020
1021
1022
1023
1024 @VisibleForTesting
1025 static List<RAMQueueEntry> getRAMQueueEntries(final BlockingQueue<RAMQueueEntry> q,
1026 final List<RAMQueueEntry> receptical)
1027 throws InterruptedException {
1028
1029
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
1097
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
1137
1138
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
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
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
1237
1238
1239
1240
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
1260
1261
1262
1263
1264
1265
1266 static class BucketEntry implements Serializable {
1267 private static final long serialVersionUID = -6741504807982257534L;
1268
1269
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
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() {
1301 long o = ((long) offsetBase) & 0xFFFFFFFFL;
1302 o += (((long) (offset1)) & 0xFF) << 32;
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
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
1351
1352
1353
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
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
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
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
1505 bucketAllocator.freeBlock(offset);
1506 throw ioe;
1507 }
1508
1509 realCacheSize.addAndGet(len);
1510 return bucketEntry;
1511 }
1512 }
1513
1514
1515
1516
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
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
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 }