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 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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95 @InterfaceAudience.Private
96 public class BucketCache implements BlockCache, HeapSize {
97 private static final Log LOG = LogFactory.getLog(BucketCache.class);
98
99
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
109 private static final int DEFAULT_FREE_ENTIRE_BLOCK_FACTOR = 2;
110
111
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
118 final IOEngine ioEngine;
119
120
121 @VisibleForTesting
122 final ConcurrentMap<BlockCacheKey, RAMQueueEntry> ramCache;
123
124 @VisibleForTesting
125 ConcurrentMap<BlockCacheKey, BucketEntry> backingMap;
126
127
128
129
130
131
132 private volatile boolean cacheEnabled;
133
134
135
136
137
138
139
140
141 @VisibleForTesting
142 final ArrayList<BlockingQueue<RAMQueueEntry>> writerQueues =
143 new ArrayList<BlockingQueue<RAMQueueEntry>>();
144 @VisibleForTesting
145 final WriterThread[] writerThreads;
146
147
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
156 private final AtomicLong blockNumber = new AtomicLong(0);
157
158
159 private final AtomicLong accessCount = new AtomicLong(0);
160
161 private static final int DEFAULT_CACHE_WAIT_TIME = 50;
162
163
164
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
172 private final long blockSize;
173
174
175 private final int ioErrorsTolerationDuration;
176
177 public static final int DEFAULT_ERROR_TOLERATION_DURATION = 60 * 1000;
178
179
180
181 private volatile long ioErrorStartTime = -1;
182
183
184
185
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
209 private final ScheduledExecutorService scheduleThreadPool = Executors.newScheduledThreadPool(1,
210 new ThreadFactoryBuilder().setNameFormat("BucketCacheStatsExecutor").setDaemon(true).build());
211
212
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
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
268
269
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
281
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
305
306
307
308
309
310 private IOEngine getIOEngineFromName(String ioEngineName, long capacity)
311 throws IOException {
312 if (ioEngineName.startsWith("file:") || ioEngineName.startsWith("files:")) {
313
314
315
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
330
331
332
333 @Override
334 public void cacheBlock(BlockCacheKey cacheKey, Cacheable buf) {
335 cacheBlock(cacheKey, buf, false, false);
336 }
337
338
339
340
341
342
343
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
353
354
355
356
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
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
401
402
403
404
405
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
428
429
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
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
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
596
597
598
599
600
601
602
603 private void freeEntireBuckets(int completelyFreeBucketsNeeded) {
604 if (completelyFreeBucketsNeeded != 0) {
605
606
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
625
626
627
628
629 private void freeSpace(final String why) {
630
631 if (!freeSpaceLock.tryLock()) {
632 return;
633 }
634 try {
635 freeInProgress = true;
636 long bytesToFreeWithoutExtra = 0;
637
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
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
681
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
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
736
737
738
739
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
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
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
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
805
806
807
808
809
810
811 @VisibleForTesting
812 void doDrain(final List<RAMQueueEntry> entries) throws InterruptedException {
813 if (entries.isEmpty()) {
814 return;
815 }
816
817
818
819
820
821
822 final int size = entries.size();
823 BucketEntry[] bucketEntries = new BucketEntry[size];
824
825
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
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
847 bucketEntries[index] = null;
848 index++;
849 } catch (CacheFullException cfe) {
850
851 if (!freeInProgress) {
852 freeSpace("Full!");
853 } else {
854 Thread.sleep(50);
855 }
856 } catch (IOException ioex) {
857
858 LOG.error("Failed writing to bucket cache", ioex);
859 checkIOErrorIsTolerated();
860 }
861 }
862
863
864 try {
865 ioEngine.sync();
866 } catch (IOException ioex) {
867 LOG.error("Failed syncing IO engine", ioex);
868 checkIOErrorIsTolerated();
869
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
879
880 for (int i = 0; i < size; ++i) {
881 BlockCacheKey key = entries.get(i).getKey();
882
883 if (bucketEntries[i] != null) {
884 backingMap.put(key, bucketEntries[i]);
885 }
886
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
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
914
915
916
917
918
919
920 @VisibleForTesting
921 static List<RAMQueueEntry> getRAMQueueEntries(final BlockingQueue<RAMQueueEntry> q,
922 final List<RAMQueueEntry> receptical)
923 throws InterruptedException {
924
925
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
1003
1004
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
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
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
1093
1094
1095
1096
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
1116
1117
1118
1119
1120
1121
1122 static class BucketEntry implements Serializable {
1123 private static final long serialVersionUID = -6741504807982257534L;
1124
1125
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
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() {
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
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
1207
1208
1209
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
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
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
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
1320 bucketAllocator.freeBlock(offset);
1321 throw ioe;
1322 }
1323
1324 realCacheSize.addAndGet(len);
1325 return bucketEntry;
1326 }
1327 }
1328
1329
1330
1331
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
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
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 }