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 transient final IOEngine ioEngine;
119
120
121 @VisibleForTesting
122 transient final ConcurrentMap<BlockCacheKey, RAMQueueEntry> ramCache;
123
124 @VisibleForTesting
125 transient 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 transient final ArrayList<BlockingQueue<RAMQueueEntry>> writerQueues =
143 new ArrayList<BlockingQueue<RAMQueueEntry>>();
144 @VisibleForTesting
145 transient final WriterThread[] writerThreads;
146
147
148 private volatile boolean freeInProgress = false;
149 private transient 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 transient 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 transient final ScheduledExecutorService scheduleThreadPool =
210 Executors.newScheduledThreadPool(1,
211 new ThreadFactoryBuilder().setNameFormat("BucketCacheStatsExecutor").setDaemon(true).build());
212
213
214 private transient BucketAllocator bucketAllocator;
215
216 public BucketCache(String ioEngineName, long capacity, int blockSize, int[] bucketSizes,
217 int writerThreadNum, int writerQLen, String persistencePath) throws FileNotFoundException,
218 IOException {
219 this(ioEngineName, capacity, blockSize, bucketSizes, writerThreadNum, writerQLen,
220 persistencePath, DEFAULT_ERROR_TOLERATION_DURATION);
221 }
222
223 public BucketCache(String ioEngineName, long capacity, int blockSize, int[] bucketSizes,
224 int writerThreadNum, int writerQLen, String persistencePath, int ioErrorsTolerationDuration)
225 throws FileNotFoundException, IOException {
226 this.ioEngine = getIOEngineFromName(ioEngineName, capacity);
227 this.writerThreads = new WriterThread[writerThreadNum];
228 long blockNumCapacity = capacity / blockSize;
229 if (blockNumCapacity >= Integer.MAX_VALUE) {
230
231 throw new IllegalArgumentException("Cache capacity is too large, only support 32TB now");
232 }
233
234 this.cacheCapacity = capacity;
235 this.persistencePath = persistencePath;
236 this.blockSize = blockSize;
237 this.ioErrorsTolerationDuration = ioErrorsTolerationDuration;
238
239 bucketAllocator = new BucketAllocator(capacity, bucketSizes);
240 for (int i = 0; i < writerThreads.length; ++i) {
241 writerQueues.add(new ArrayBlockingQueue<RAMQueueEntry>(writerQLen));
242 }
243
244 assert writerQueues.size() == writerThreads.length;
245 this.ramCache = new ConcurrentHashMap<BlockCacheKey, RAMQueueEntry>();
246
247 this.backingMap = new ConcurrentHashMap<BlockCacheKey, BucketEntry>((int) blockNumCapacity);
248
249 if (ioEngine.isPersistent() && persistencePath != null) {
250 try {
251 retrieveFromFile(bucketSizes);
252 } catch (IOException ioex) {
253 LOG.error("Can't restore from file because of", ioex);
254 } catch (ClassNotFoundException cnfe) {
255 LOG.error("Can't restore from file in rebuild because can't deserialise",cnfe);
256 throw new RuntimeException(cnfe);
257 }
258 }
259 final String threadName = Thread.currentThread().getName();
260 this.cacheEnabled = true;
261 for (int i = 0; i < writerThreads.length; ++i) {
262 writerThreads[i] = new WriterThread(writerQueues.get(i));
263 writerThreads[i].setName(threadName + "-BucketCacheWriter-" + i);
264 writerThreads[i].setDaemon(true);
265 }
266 startWriterThreads();
267
268
269
270
271 this.scheduleThreadPool.scheduleAtFixedRate(new StatisticsThread(this),
272 statThreadPeriod, statThreadPeriod, TimeUnit.SECONDS);
273 LOG.info("Started bucket cache; ioengine=" + ioEngineName +
274 ", capacity=" + StringUtils.byteDesc(capacity) +
275 ", blockSize=" + StringUtils.byteDesc(blockSize) + ", writerThreadNum=" +
276 writerThreadNum + ", writerQLen=" + writerQLen + ", persistencePath=" +
277 persistencePath + ", bucketAllocator=" + this.bucketAllocator.getClass().getName());
278 }
279
280
281
282
283
284 @VisibleForTesting
285 protected void startWriterThreads() {
286 for (WriterThread thread : writerThreads) {
287 thread.start();
288 }
289 }
290
291 @VisibleForTesting
292 boolean isCacheEnabled() {
293 return this.cacheEnabled;
294 }
295
296 public long getMaxSize() {
297 return this.cacheCapacity;
298 }
299
300 public String getIoEngine() {
301 return ioEngine.toString();
302 }
303
304
305
306
307
308
309
310
311 private IOEngine getIOEngineFromName(String ioEngineName, long capacity)
312 throws IOException {
313 if (ioEngineName.startsWith("file:") || ioEngineName.startsWith("files:")) {
314
315
316
317 String[] filePaths =
318 ioEngineName.substring(ioEngineName.indexOf(":") + 1).split(FileIOEngine.FILE_DELIMITER);
319 return new FileIOEngine(capacity, filePaths);
320 } else if (ioEngineName.startsWith("offheap"))
321 return new ByteBufferIOEngine(capacity, true);
322 else if (ioEngineName.startsWith("heap"))
323 return new ByteBufferIOEngine(capacity, false);
324 else
325 throw new IllegalArgumentException(
326 "Don't understand io engine name for cache - prefix with file:, heap or offheap");
327 }
328
329
330
331
332
333
334 @Override
335 public void cacheBlock(BlockCacheKey cacheKey, Cacheable buf) {
336 cacheBlock(cacheKey, buf, false, false);
337 }
338
339
340
341
342
343
344
345
346 @Override
347 public void cacheBlock(BlockCacheKey cacheKey, Cacheable cachedItem, boolean inMemory,
348 final boolean cacheDataInL1) {
349 cacheBlockWithWait(cacheKey, cachedItem, inMemory, wait_when_cache);
350 }
351
352
353
354
355
356
357
358
359 public void cacheBlockWithWait(BlockCacheKey cacheKey, Cacheable cachedItem, boolean inMemory,
360 boolean wait) {
361 if (LOG.isTraceEnabled()) LOG.trace("Caching key=" + cacheKey + ", item=" + cachedItem);
362 if (!cacheEnabled) {
363 return;
364 }
365
366 if (backingMap.containsKey(cacheKey)) {
367 return;
368 }
369
370
371
372
373 RAMQueueEntry re =
374 new RAMQueueEntry(cacheKey, cachedItem, accessCount.incrementAndGet(), inMemory);
375 if (ramCache.putIfAbsent(cacheKey, re) != null) {
376 return;
377 }
378 int queueNum = (cacheKey.hashCode() & 0x7FFFFFFF) % writerQueues.size();
379 BlockingQueue<RAMQueueEntry> bq = writerQueues.get(queueNum);
380 boolean successfulAddition = false;
381 if (wait) {
382 try {
383 successfulAddition = bq.offer(re, DEFAULT_CACHE_WAIT_TIME, TimeUnit.MILLISECONDS);
384 } catch (InterruptedException e) {
385 Thread.currentThread().interrupt();
386 }
387 } else {
388 successfulAddition = bq.offer(re);
389 }
390 if (!successfulAddition) {
391 ramCache.remove(cacheKey);
392 cacheStats.failInsert();
393 } else {
394 this.blockNumber.incrementAndGet();
395 this.heapSize.addAndGet(cachedItem.heapSize());
396 blocksByHFile.add(cacheKey);
397 }
398 }
399
400
401
402
403
404
405
406
407
408 @Override
409 public Cacheable getBlock(BlockCacheKey key, boolean caching, boolean repeat,
410 boolean updateCacheMetrics) {
411 if (!cacheEnabled) {
412 return null;
413 }
414 RAMQueueEntry re = ramCache.get(key);
415 if (re != null) {
416 if (updateCacheMetrics) {
417 cacheStats.hit(caching, key.isPrimary(), key.getBlockType());
418 }
419 re.access(accessCount.incrementAndGet());
420 return re.getData();
421 }
422 BucketEntry bucketEntry = backingMap.get(key);
423 if (bucketEntry != null) {
424 long start = System.nanoTime();
425 ReentrantReadWriteLock lock = offsetLock.getLock(bucketEntry.offset());
426 try {
427 lock.readLock().lock();
428
429
430
431 if (bucketEntry.equals(backingMap.get(key))) {
432 int len = bucketEntry.getLength();
433 if (LOG.isTraceEnabled()) {
434 LOG.trace("Read offset=" + bucketEntry.offset() + ", len=" + len);
435 }
436 ByteBuffer bb = ByteBuffer.allocate(len);
437 int lenRead = ioEngine.read(bb, bucketEntry.offset());
438 if (lenRead != len) {
439 throw new RuntimeException("Only " + lenRead + " bytes read, " + len + " expected");
440 }
441 CacheableDeserializer<Cacheable> deserializer =
442 bucketEntry.deserializerReference(this.deserialiserMap);
443 Cacheable cachedBlock = deserializer.deserialize(bb, true);
444 long timeTaken = System.nanoTime() - start;
445 if (updateCacheMetrics) {
446 cacheStats.hit(caching, key.isPrimary(), key.getBlockType());
447 cacheStats.ioHit(timeTaken);
448 }
449 bucketEntry.access(accessCount.incrementAndGet());
450 if (this.ioErrorStartTime > 0) {
451 ioErrorStartTime = -1;
452 }
453 return cachedBlock;
454 }
455 } catch (IOException ioex) {
456 LOG.error("Failed reading block " + key + " from bucket cache", ioex);
457 checkIOErrorIsTolerated();
458 } finally {
459 lock.readLock().unlock();
460 }
461 }
462 if (!repeat && updateCacheMetrics) {
463 cacheStats.miss(caching, key.isPrimary(), key.getBlockType());
464 }
465 return null;
466 }
467
468 @VisibleForTesting
469 void blockEvicted(BlockCacheKey cacheKey, BucketEntry bucketEntry, boolean decrementBlockNumber) {
470 bucketAllocator.freeBlock(bucketEntry.offset());
471 realCacheSize.addAndGet(-1 * bucketEntry.getLength());
472 blocksByHFile.remove(cacheKey);
473 if (decrementBlockNumber) {
474 this.blockNumber.decrementAndGet();
475 }
476 }
477
478 @Override
479 public boolean evictBlock(BlockCacheKey cacheKey) {
480 if (!cacheEnabled) {
481 return false;
482 }
483 RAMQueueEntry removedBlock = ramCache.remove(cacheKey);
484 if (removedBlock != null) {
485 this.blockNumber.decrementAndGet();
486 this.heapSize.addAndGet(-1 * removedBlock.getData().heapSize());
487 }
488 BucketEntry bucketEntry = backingMap.get(cacheKey);
489 if (bucketEntry == null) {
490 if (removedBlock != null) {
491 cacheStats.evicted(0, cacheKey.isPrimary());
492 return true;
493 } else {
494 return false;
495 }
496 }
497 ReentrantReadWriteLock lock = offsetLock.getLock(bucketEntry.offset());
498 try {
499 lock.writeLock().lock();
500 if (backingMap.remove(cacheKey, bucketEntry)) {
501 blockEvicted(cacheKey, bucketEntry, removedBlock == null);
502 } else {
503 return false;
504 }
505 } finally {
506 lock.writeLock().unlock();
507 }
508 cacheStats.evicted(bucketEntry.getCachedTime(), cacheKey.isPrimary());
509 return true;
510 }
511
512
513
514
515 private static class StatisticsThread extends Thread {
516 private final BucketCache bucketCache;
517
518 public StatisticsThread(BucketCache bucketCache) {
519 super("BucketCacheStatsThread");
520 setDaemon(true);
521 this.bucketCache = bucketCache;
522 }
523
524 @Override
525 public void run() {
526 bucketCache.logStats();
527 }
528 }
529
530 public void logStats() {
531 long totalSize = bucketAllocator.getTotalSize();
532 long usedSize = bucketAllocator.getUsedSize();
533 long freeSize = totalSize - usedSize;
534 long cacheSize = getRealCacheSize();
535 LOG.info("failedBlockAdditions=" + cacheStats.getFailedInserts() + ", " +
536 "totalSize=" + StringUtils.byteDesc(totalSize) + ", " +
537 "freeSize=" + StringUtils.byteDesc(freeSize) + ", " +
538 "usedSize=" + StringUtils.byteDesc(usedSize) +", " +
539 "cacheSize=" + StringUtils.byteDesc(cacheSize) +", " +
540 "accesses=" + cacheStats.getRequestCount() + ", " +
541 "hits=" + cacheStats.getHitCount() + ", " +
542 "IOhitsPerSecond=" + cacheStats.getIOHitsPerSecond() + ", " +
543 "IOTimePerHit=" + String.format("%.2f", cacheStats.getIOTimePerHit())+ ", " +
544 "hitRatio=" + (cacheStats.getHitCount() == 0 ? "0," :
545 (StringUtils.formatPercent(cacheStats.getHitRatio(), 2)+ ", ")) +
546 "cachingAccesses=" + cacheStats.getRequestCachingCount() + ", " +
547 "cachingHits=" + cacheStats.getHitCachingCount() + ", " +
548 "cachingHitsRatio=" +(cacheStats.getHitCachingCount() == 0 ? "0," :
549 (StringUtils.formatPercent(cacheStats.getHitCachingRatio(), 2)+ ", ")) +
550 "evictions=" + cacheStats.getEvictionCount() + ", " +
551 "evicted=" + cacheStats.getEvictedCount() + ", " +
552 "evictedPerRun=" + cacheStats.evictedPerEviction());
553 cacheStats.reset();
554 }
555
556 public long getRealCacheSize() {
557 return this.realCacheSize.get();
558 }
559
560 private long acceptableSize() {
561 return (long) Math.floor(bucketAllocator.getTotalSize() * DEFAULT_ACCEPT_FACTOR);
562 }
563
564 private long singleSize() {
565 return (long) Math.floor(bucketAllocator.getTotalSize()
566 * DEFAULT_SINGLE_FACTOR * DEFAULT_MIN_FACTOR);
567 }
568
569 private long multiSize() {
570 return (long) Math.floor(bucketAllocator.getTotalSize() * DEFAULT_MULTI_FACTOR
571 * DEFAULT_MIN_FACTOR);
572 }
573
574 private long memorySize() {
575 return (long) Math.floor(bucketAllocator.getTotalSize() * DEFAULT_MEMORY_FACTOR
576 * DEFAULT_MIN_FACTOR);
577 }
578
579
580
581
582 private int bucketSizesAboveThresholdCount(float minFactor) {
583 BucketAllocator.IndexStatistics[] stats = bucketAllocator.getIndexStatistics();
584 int fullCount = 0;
585 for (int i = 0; i < stats.length; i++) {
586 long freeGoal = (long) Math.floor(stats[i].totalCount() * (1 - minFactor));
587 freeGoal = Math.max(freeGoal, 1);
588 if (stats[i].freeCount() < freeGoal) {
589 fullCount++;
590 }
591 }
592 return fullCount;
593 }
594
595
596
597
598
599
600
601
602
603
604 private void freeEntireBuckets(int completelyFreeBucketsNeeded) {
605 if (completelyFreeBucketsNeeded != 0) {
606
607
608 Set<Integer> inUseBuckets = new HashSet<Integer>();
609 for (BucketEntry entry : backingMap.values()) {
610 inUseBuckets.add(bucketAllocator.getBucketIndex(entry.offset()));
611 }
612
613 Set<Integer> candidateBuckets = bucketAllocator.getLeastFilledBuckets(
614 inUseBuckets, completelyFreeBucketsNeeded);
615 for (Map.Entry<BlockCacheKey, BucketEntry> entry : backingMap.entrySet()) {
616 if (candidateBuckets.contains(bucketAllocator
617 .getBucketIndex(entry.getValue().offset()))) {
618 evictBlock(entry.getKey());
619 }
620 }
621 }
622 }
623
624
625
626
627
628
629
630 private void freeSpace(final String why) {
631
632 if (!freeSpaceLock.tryLock()) {
633 return;
634 }
635 try {
636 freeInProgress = true;
637 long bytesToFreeWithoutExtra = 0;
638
639 StringBuffer msgBuffer = LOG.isDebugEnabled()? new StringBuffer(): null;
640 BucketAllocator.IndexStatistics[] stats = bucketAllocator.getIndexStatistics();
641 long[] bytesToFreeForBucket = new long[stats.length];
642 for (int i = 0; i < stats.length; i++) {
643 bytesToFreeForBucket[i] = 0;
644 long freeGoal = (long) Math.floor(stats[i].totalCount() * (1 - DEFAULT_MIN_FACTOR));
645 freeGoal = Math.max(freeGoal, 1);
646 if (stats[i].freeCount() < freeGoal) {
647 bytesToFreeForBucket[i] = stats[i].itemSize() * (freeGoal - stats[i].freeCount());
648 bytesToFreeWithoutExtra += bytesToFreeForBucket[i];
649 if (msgBuffer != null) {
650 msgBuffer.append("Free for bucketSize(" + stats[i].itemSize() + ")="
651 + StringUtils.byteDesc(bytesToFreeForBucket[i]) + ", ");
652 }
653 }
654 }
655 if (msgBuffer != null) {
656 msgBuffer.append("Free for total=" + StringUtils.byteDesc(bytesToFreeWithoutExtra) + ", ");
657 }
658
659 if (bytesToFreeWithoutExtra <= 0) {
660 return;
661 }
662 long currentSize = bucketAllocator.getUsedSize();
663 long totalSize = bucketAllocator.getTotalSize();
664 if (LOG.isDebugEnabled() && msgBuffer != null) {
665 LOG.debug("Free started because \"" + why + "\"; " + msgBuffer.toString() +
666 " of current used=" + StringUtils.byteDesc(currentSize) + ", actual cacheSize=" +
667 StringUtils.byteDesc(realCacheSize.get()) + ", total=" + StringUtils.byteDesc(totalSize));
668 }
669
670 long bytesToFreeWithExtra = (long) Math.floor(bytesToFreeWithoutExtra
671 * (1 + DEFAULT_EXTRA_FREE_FACTOR));
672
673
674 BucketEntryGroup bucketSingle = new BucketEntryGroup(bytesToFreeWithExtra,
675 blockSize, singleSize());
676 BucketEntryGroup bucketMulti = new BucketEntryGroup(bytesToFreeWithExtra,
677 blockSize, multiSize());
678 BucketEntryGroup bucketMemory = new BucketEntryGroup(bytesToFreeWithExtra,
679 blockSize, memorySize());
680
681
682
683 for (Map.Entry<BlockCacheKey, BucketEntry> bucketEntryWithKey : backingMap.entrySet()) {
684 switch (bucketEntryWithKey.getValue().getPriority()) {
685 case SINGLE: {
686 bucketSingle.add(bucketEntryWithKey);
687 break;
688 }
689 case MULTI: {
690 bucketMulti.add(bucketEntryWithKey);
691 break;
692 }
693 case MEMORY: {
694 bucketMemory.add(bucketEntryWithKey);
695 break;
696 }
697 }
698 }
699
700 PriorityQueue<BucketEntryGroup> bucketQueue = new PriorityQueue<BucketEntryGroup>(3);
701
702 bucketQueue.add(bucketSingle);
703 bucketQueue.add(bucketMulti);
704 bucketQueue.add(bucketMemory);
705
706 int remainingBuckets = bucketQueue.size();
707 long bytesFreed = 0;
708
709 BucketEntryGroup bucketGroup;
710 while ((bucketGroup = bucketQueue.poll()) != null) {
711 long overflow = bucketGroup.overflow();
712 if (overflow > 0) {
713 long bucketBytesToFree = Math.min(overflow,
714 (bytesToFreeWithoutExtra - bytesFreed) / remainingBuckets);
715 bytesFreed += bucketGroup.free(bucketBytesToFree);
716 }
717 remainingBuckets--;
718 }
719
720
721 if (bucketSizesAboveThresholdCount(DEFAULT_MIN_FACTOR) > 0) {
722 bucketQueue.clear();
723 remainingBuckets = 3;
724
725 bucketQueue.add(bucketSingle);
726 bucketQueue.add(bucketMulti);
727 bucketQueue.add(bucketMemory);
728
729 while ((bucketGroup = bucketQueue.poll()) != null) {
730 long bucketBytesToFree = (bytesToFreeWithExtra - bytesFreed) / remainingBuckets;
731 bytesFreed += bucketGroup.free(bucketBytesToFree);
732 remainingBuckets--;
733 }
734 }
735
736
737
738
739
740
741 freeEntireBuckets(DEFAULT_FREE_ENTIRE_BLOCK_FACTOR *
742 bucketSizesAboveThresholdCount(1.0f));
743
744 if (LOG.isDebugEnabled()) {
745 long single = bucketSingle.totalSize();
746 long multi = bucketMulti.totalSize();
747 long memory = bucketMemory.totalSize();
748 if (LOG.isDebugEnabled()) {
749 LOG.debug("Bucket cache free space completed; " + "freed="
750 + StringUtils.byteDesc(bytesFreed) + ", " + "total="
751 + StringUtils.byteDesc(totalSize) + ", " + "single="
752 + StringUtils.byteDesc(single) + ", " + "multi="
753 + StringUtils.byteDesc(multi) + ", " + "memory="
754 + StringUtils.byteDesc(memory));
755 }
756 }
757
758 } catch (Throwable t) {
759 LOG.warn("Failed freeing space", t);
760 } finally {
761 cacheStats.evict();
762 freeInProgress = false;
763 freeSpaceLock.unlock();
764 }
765 }
766
767
768 @VisibleForTesting
769 class WriterThread extends HasThread {
770 private final BlockingQueue<RAMQueueEntry> inputQueue;
771 private volatile boolean writerEnabled = true;
772
773 WriterThread(BlockingQueue<RAMQueueEntry> queue) {
774 super("BucketCacheWriterThread");
775 this.inputQueue = queue;
776 }
777
778
779 @VisibleForTesting
780 void disableWriter() {
781 this.writerEnabled = false;
782 }
783
784 public void run() {
785 List<RAMQueueEntry> entries = new ArrayList<RAMQueueEntry>();
786 try {
787 while (cacheEnabled && writerEnabled) {
788 try {
789 try {
790
791 entries = getRAMQueueEntries(inputQueue, entries);
792 } catch (InterruptedException ie) {
793 if (!cacheEnabled) break;
794 }
795 doDrain(entries);
796 } catch (Exception ioe) {
797 LOG.error("WriterThread encountered error", ioe);
798 }
799 }
800 } catch (Throwable t) {
801 LOG.warn("Failed doing drain", t);
802 }
803 LOG.info(this.getName() + " exiting, cacheEnabled=" + cacheEnabled);
804 }
805
806
807
808
809
810
811
812
813
814 @VisibleForTesting
815 void doDrain(final List<RAMQueueEntry> entries) throws InterruptedException {
816 if (entries.isEmpty()) {
817 return;
818 }
819
820
821
822
823
824
825 final int size = entries.size();
826 BucketEntry[] bucketEntries = new BucketEntry[size];
827
828
829 int index = 0;
830 while (cacheEnabled && index < size) {
831 RAMQueueEntry re = null;
832 try {
833 re = entries.get(index);
834 if (re == null) {
835 LOG.warn("Couldn't get entry or changed on us; who else is messing with it?");
836 index++;
837 continue;
838 }
839 BucketEntry bucketEntry =
840 re.writeToCache(ioEngine, bucketAllocator, deserialiserMap, realCacheSize);
841
842 bucketEntries[index] = bucketEntry;
843 if (ioErrorStartTime > 0) {
844 ioErrorStartTime = -1;
845 }
846 index++;
847 } catch (BucketAllocatorException fle) {
848 LOG.warn("Failed allocation for " + (re == null ? "" : re.getKey()) + "; " + fle);
849
850 bucketEntries[index] = null;
851 index++;
852 } catch (CacheFullException cfe) {
853
854 if (!freeInProgress) {
855 freeSpace("Full!");
856 } else {
857 Thread.sleep(50);
858 }
859 } catch (IOException ioex) {
860
861 LOG.error("Failed writing to bucket cache", ioex);
862 checkIOErrorIsTolerated();
863 }
864 }
865
866
867 try {
868 ioEngine.sync();
869 } catch (IOException ioex) {
870 LOG.error("Failed syncing IO engine", ioex);
871 checkIOErrorIsTolerated();
872
873 for (int i = 0; i < entries.size(); ++i) {
874 if (bucketEntries[i] != null) {
875 bucketAllocator.freeBlock(bucketEntries[i].offset());
876 bucketEntries[i] = null;
877 }
878 }
879 }
880
881
882
883 for (int i = 0; i < size; ++i) {
884 BlockCacheKey key = entries.get(i).getKey();
885
886 if (bucketEntries[i] != null) {
887 backingMap.put(key, bucketEntries[i]);
888 }
889
890 RAMQueueEntry ramCacheEntry = ramCache.remove(key);
891 if (ramCacheEntry != null) {
892 heapSize.addAndGet(-1 * entries.get(i).getData().heapSize());
893 } else if (bucketEntries[i] != null){
894
895 ReentrantReadWriteLock lock = offsetLock.getLock(bucketEntries[i].offset());
896 try {
897 lock.writeLock().lock();
898 if (backingMap.remove(key, bucketEntries[i])) {
899 blockEvicted(key, bucketEntries[i], false);
900 }
901 } finally {
902 lock.writeLock().unlock();
903 }
904 }
905 }
906
907 long used = bucketAllocator.getUsedSize();
908 if (used > acceptableSize()) {
909 freeSpace("Used=" + used + " > acceptable=" + acceptableSize());
910 }
911 return;
912 }
913 }
914
915
916
917
918
919
920
921
922
923 @VisibleForTesting
924 static List<RAMQueueEntry> getRAMQueueEntries(final BlockingQueue<RAMQueueEntry> q,
925 final List<RAMQueueEntry> receptical)
926 throws InterruptedException {
927
928
929 receptical.clear();
930 receptical.add(q.take());
931 q.drainTo(receptical);
932 return receptical;
933 }
934
935 private void persistToFile() throws IOException {
936 assert !cacheEnabled;
937 FileOutputStream fos = null;
938 ObjectOutputStream oos = null;
939 try {
940 if (!ioEngine.isPersistent()) {
941 throw new IOException("Attempt to persist non-persistent cache mappings!");
942 }
943 fos = new FileOutputStream(persistencePath, false);
944 oos = new ObjectOutputStream(fos);
945 oos.writeLong(cacheCapacity);
946 oos.writeUTF(ioEngine.getClass().getName());
947 oos.writeUTF(backingMap.getClass().getName());
948 oos.writeObject(deserialiserMap);
949 oos.writeObject(backingMap);
950 } finally {
951 if (oos != null) oos.close();
952 if (fos != null) fos.close();
953 }
954 }
955
956 @SuppressWarnings("unchecked")
957 private void retrieveFromFile(int[] bucketSizes) throws IOException, BucketAllocatorException,
958 ClassNotFoundException {
959 File persistenceFile = new File(persistencePath);
960 if (!persistenceFile.exists()) {
961 return;
962 }
963 assert !cacheEnabled;
964 FileInputStream fis = null;
965 ObjectInputStream ois = null;
966 try {
967 if (!ioEngine.isPersistent())
968 throw new IOException(
969 "Attempt to restore non-persistent cache mappings!");
970 fis = new FileInputStream(persistencePath);
971 ois = new ObjectInputStream(fis);
972 long capacitySize = ois.readLong();
973 if (capacitySize != cacheCapacity)
974 throw new IOException("Mismatched cache capacity:"
975 + StringUtils.byteDesc(capacitySize) + ", expected: "
976 + StringUtils.byteDesc(cacheCapacity));
977 String ioclass = ois.readUTF();
978 String mapclass = ois.readUTF();
979 if (!ioEngine.getClass().getName().equals(ioclass))
980 throw new IOException("Class name for IO engine mismatch: " + ioclass
981 + ", expected:" + ioEngine.getClass().getName());
982 if (!backingMap.getClass().getName().equals(mapclass))
983 throw new IOException("Class name for cache map mismatch: " + mapclass
984 + ", expected:" + backingMap.getClass().getName());
985 UniqueIndexMap<Integer> deserMap = (UniqueIndexMap<Integer>) ois
986 .readObject();
987 ConcurrentHashMap<BlockCacheKey, BucketEntry> backingMapFromFile =
988 (ConcurrentHashMap<BlockCacheKey, BucketEntry>) ois.readObject();
989 BucketAllocator allocator = new BucketAllocator(cacheCapacity, bucketSizes,
990 backingMapFromFile, realCacheSize);
991 bucketAllocator = allocator;
992 deserialiserMap = deserMap;
993 backingMap = backingMapFromFile;
994 } finally {
995 if (ois != null) ois.close();
996 if (fis != null) fis.close();
997 if (!persistenceFile.delete()) {
998 throw new IOException("Failed deleting persistence file "
999 + persistenceFile.getAbsolutePath());
1000 }
1001 }
1002 }
1003
1004
1005
1006
1007
1008
1009 private void checkIOErrorIsTolerated() {
1010 long now = EnvironmentEdgeManager.currentTime();
1011 if (this.ioErrorStartTime > 0) {
1012 if (cacheEnabled && (now - ioErrorStartTime) > this.ioErrorsTolerationDuration) {
1013 LOG.error("IO errors duration time has exceeded " + ioErrorsTolerationDuration +
1014 "ms, disabling cache, please check your IOEngine");
1015 disableCache();
1016 }
1017 } else {
1018 this.ioErrorStartTime = now;
1019 }
1020 }
1021
1022
1023
1024
1025 private void disableCache() {
1026 if (!cacheEnabled) return;
1027 cacheEnabled = false;
1028 ioEngine.shutdown();
1029 this.scheduleThreadPool.shutdown();
1030 for (int i = 0; i < writerThreads.length; ++i) writerThreads[i].interrupt();
1031 this.ramCache.clear();
1032 if (!ioEngine.isPersistent() || persistencePath == null) {
1033
1034 this.backingMap.clear();
1035 }
1036 }
1037
1038 private void join() throws InterruptedException {
1039 for (int i = 0; i < writerThreads.length; ++i)
1040 writerThreads[i].join();
1041 }
1042
1043 @Override
1044 public void shutdown() {
1045 disableCache();
1046 LOG.info("Shutdown bucket cache: IO persistent=" + ioEngine.isPersistent()
1047 + "; path to write=" + persistencePath);
1048 if (ioEngine.isPersistent() && persistencePath != null) {
1049 try {
1050 join();
1051 persistToFile();
1052 } catch (IOException ex) {
1053 LOG.error("Unable to persist data on exit: " + ex.toString(), ex);
1054 } catch (InterruptedException e) {
1055 LOG.warn("Failed to persist data on exit", e);
1056 }
1057 }
1058 }
1059
1060 @Override
1061 public CacheStats getStats() {
1062 return cacheStats;
1063 }
1064
1065 public BucketAllocator getAllocator() {
1066 return this.bucketAllocator;
1067 }
1068
1069 @Override
1070 public long heapSize() {
1071 return this.heapSize.get();
1072 }
1073
1074 @Override
1075 public long size() {
1076 return this.realCacheSize.get();
1077 }
1078
1079 @Override
1080 public long getFreeSize() {
1081 return this.bucketAllocator.getFreeSize();
1082 }
1083
1084 @Override
1085 public long getBlockCount() {
1086 return this.blockNumber.get();
1087 }
1088
1089 @Override
1090 public long getCurrentSize() {
1091 return this.bucketAllocator.getUsedSize();
1092 }
1093
1094
1095
1096
1097
1098
1099
1100
1101 @Override
1102 public int evictBlocksByHfileName(String hfileName) {
1103 Set<BlockCacheKey> keySet = blocksByHFile.subSet(
1104 new BlockCacheKey(hfileName, Long.MIN_VALUE), true,
1105 new BlockCacheKey(hfileName, Long.MAX_VALUE), true);
1106
1107 int numEvicted = 0;
1108 for (BlockCacheKey key : keySet) {
1109 if (evictBlock(key)) {
1110 ++numEvicted;
1111 }
1112 }
1113
1114 return numEvicted;
1115 }
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125 static class BucketEntry implements Serializable {
1126 private static final long serialVersionUID = -6741504807982257534L;
1127
1128
1129 static final Comparator<BucketEntry> COMPARATOR = new Comparator<BucketCache.BucketEntry>() {
1130
1131 @Override
1132 public int compare(BucketEntry o1, BucketEntry o2) {
1133 return Long.compare(o2.accessCounter, o1.accessCounter);
1134 }
1135 };
1136
1137 private int offsetBase;
1138 private int length;
1139 private byte offset1;
1140 byte deserialiserIndex;
1141 private volatile long accessCounter;
1142 private BlockPriority priority;
1143
1144
1145
1146 private final long cachedTime = System.nanoTime();
1147
1148 BucketEntry(long offset, int length, long accessCounter, boolean inMemory) {
1149 setOffset(offset);
1150 this.length = length;
1151 this.accessCounter = accessCounter;
1152 if (inMemory) {
1153 this.priority = BlockPriority.MEMORY;
1154 } else {
1155 this.priority = BlockPriority.SINGLE;
1156 }
1157 }
1158
1159 long offset() {
1160 long o = ((long) offsetBase) & 0xFFFFFFFFL;
1161 o += (((long) (offset1)) & 0xFF) << 32;
1162 return o << 8;
1163 }
1164
1165 private void setOffset(long value) {
1166 assert (value & 0xFF) == 0;
1167 value >>= 8;
1168 offsetBase = (int) value;
1169 offset1 = (byte) (value >> 32);
1170 }
1171
1172 public int getLength() {
1173 return length;
1174 }
1175
1176 protected CacheableDeserializer<Cacheable> deserializerReference(
1177 UniqueIndexMap<Integer> deserialiserMap) {
1178 return CacheableDeserializerIdManager.getDeserializer(deserialiserMap
1179 .unmap(deserialiserIndex));
1180 }
1181
1182 protected void setDeserialiserReference(
1183 CacheableDeserializer<Cacheable> deserializer,
1184 UniqueIndexMap<Integer> deserialiserMap) {
1185 this.deserialiserIndex = ((byte) deserialiserMap.map(deserializer
1186 .getDeserialiserIdentifier()));
1187 }
1188
1189
1190
1191
1192 public void access(long accessCounter) {
1193 this.accessCounter = accessCounter;
1194 if (this.priority == BlockPriority.SINGLE) {
1195 this.priority = BlockPriority.MULTI;
1196 }
1197 }
1198
1199 public BlockPriority getPriority() {
1200 return this.priority;
1201 }
1202
1203 public long getCachedTime() {
1204 return cachedTime;
1205 }
1206 }
1207
1208
1209
1210
1211
1212
1213
1214 private class BucketEntryGroup implements Comparable<BucketEntryGroup> {
1215
1216 private CachedEntryQueue queue;
1217 private long totalSize = 0;
1218 private long bucketSize;
1219
1220 public BucketEntryGroup(long bytesToFree, long blockSize, long bucketSize) {
1221 this.bucketSize = bucketSize;
1222 queue = new CachedEntryQueue(bytesToFree, blockSize);
1223 totalSize = 0;
1224 }
1225
1226 public void add(Map.Entry<BlockCacheKey, BucketEntry> block) {
1227 totalSize += block.getValue().getLength();
1228 queue.add(block);
1229 }
1230
1231 public long free(long toFree) {
1232 Map.Entry<BlockCacheKey, BucketEntry> entry;
1233 long freedBytes = 0;
1234 while ((entry = queue.pollLast()) != null) {
1235 evictBlock(entry.getKey());
1236 freedBytes += entry.getValue().getLength();
1237 if (freedBytes >= toFree) {
1238 return freedBytes;
1239 }
1240 }
1241 return freedBytes;
1242 }
1243
1244 public long overflow() {
1245 return totalSize - bucketSize;
1246 }
1247
1248 public long totalSize() {
1249 return totalSize;
1250 }
1251
1252 @Override
1253 public int compareTo(BucketEntryGroup that) {
1254 return Long.compare(this.overflow(), that.overflow());
1255 }
1256
1257 @Override
1258 public boolean equals(Object that) {
1259 return this == that;
1260 }
1261
1262 }
1263
1264
1265
1266
1267 @VisibleForTesting
1268 static class RAMQueueEntry {
1269 private BlockCacheKey key;
1270 private Cacheable data;
1271 private long accessCounter;
1272 private boolean inMemory;
1273
1274 public RAMQueueEntry(BlockCacheKey bck, Cacheable data, long accessCounter,
1275 boolean inMemory) {
1276 this.key = bck;
1277 this.data = data;
1278 this.accessCounter = accessCounter;
1279 this.inMemory = inMemory;
1280 }
1281
1282 public Cacheable getData() {
1283 return data;
1284 }
1285
1286 public BlockCacheKey getKey() {
1287 return key;
1288 }
1289
1290 public void access(long accessCounter) {
1291 this.accessCounter = accessCounter;
1292 }
1293
1294 public BucketEntry writeToCache(final IOEngine ioEngine,
1295 final BucketAllocator bucketAllocator,
1296 final UniqueIndexMap<Integer> deserialiserMap,
1297 final AtomicLong realCacheSize) throws CacheFullException, IOException,
1298 BucketAllocatorException {
1299 int len = data.getSerializedLength();
1300
1301 if (len == 0) return null;
1302 long offset = bucketAllocator.allocateBlock(len);
1303 BucketEntry bucketEntry = new BucketEntry(offset, len, accessCounter, inMemory);
1304 bucketEntry.setDeserialiserReference(data.getDeserializer(), deserialiserMap);
1305 try {
1306 if (data instanceof HFileBlock) {
1307
1308 HFileBlock block = (HFileBlock)data;
1309 ByteBuffer sliceBuf = block.getBufferReadOnly();
1310 ByteBuffer metadata = block.getMetaData();
1311 if (LOG.isTraceEnabled()) {
1312 LOG.trace("Write offset=" + offset + ", len=" + len);
1313 }
1314 ioEngine.write(sliceBuf, offset);
1315 ioEngine.write(metadata, offset + len - metadata.limit());
1316 } else {
1317 ByteBuffer bb = ByteBuffer.allocate(len);
1318 data.serialize(bb);
1319 ioEngine.write(bb, offset);
1320 }
1321 } catch (IOException ioe) {
1322
1323 bucketAllocator.freeBlock(offset);
1324 throw ioe;
1325 }
1326
1327 realCacheSize.addAndGet(len);
1328 return bucketEntry;
1329 }
1330 }
1331
1332
1333
1334
1335
1336 void stopWriterThreads() throws InterruptedException {
1337 for (WriterThread writerThread : writerThreads) {
1338 writerThread.disableWriter();
1339 writerThread.interrupt();
1340 writerThread.join();
1341 }
1342 }
1343
1344 @Override
1345 public Iterator<CachedBlock> iterator() {
1346
1347 final Iterator<Map.Entry<BlockCacheKey, BucketEntry>> i =
1348 this.backingMap.entrySet().iterator();
1349 return new Iterator<CachedBlock>() {
1350 private final long now = System.nanoTime();
1351
1352 @Override
1353 public boolean hasNext() {
1354 return i.hasNext();
1355 }
1356
1357 @Override
1358 public CachedBlock next() {
1359 final Map.Entry<BlockCacheKey, BucketEntry> e = i.next();
1360 return new CachedBlock() {
1361 @Override
1362 public String toString() {
1363 return BlockCacheUtil.toString(this, now);
1364 }
1365
1366 @Override
1367 public BlockPriority getBlockPriority() {
1368 return e.getValue().getPriority();
1369 }
1370
1371 @Override
1372 public BlockType getBlockType() {
1373
1374 return null;
1375 }
1376
1377 @Override
1378 public long getOffset() {
1379 return e.getKey().getOffset();
1380 }
1381
1382 @Override
1383 public long getSize() {
1384 return e.getValue().getLength();
1385 }
1386
1387 @Override
1388 public long getCachedTime() {
1389 return e.getValue().getCachedTime();
1390 }
1391
1392 @Override
1393 public String getFilename() {
1394 return e.getKey().getHfileName();
1395 }
1396
1397 @Override
1398 public int compareTo(CachedBlock other) {
1399 int diff = this.getFilename().compareTo(other.getFilename());
1400 if (diff != 0) return diff;
1401
1402 diff = Long.compare(this.getOffset(), other.getOffset());
1403 if (diff != 0) return diff;
1404 if (other.getCachedTime() < 0 || this.getCachedTime() < 0) {
1405 throw new IllegalStateException("" + this.getCachedTime() + ", " +
1406 other.getCachedTime());
1407 }
1408 return Long.compare(other.getCachedTime(), this.getCachedTime());
1409 }
1410
1411 @Override
1412 public int hashCode() {
1413 return e.getKey().hashCode();
1414 }
1415
1416 @Override
1417 public boolean equals(Object obj) {
1418 if (obj instanceof CachedBlock) {
1419 CachedBlock cb = (CachedBlock)obj;
1420 return compareTo(cb) == 0;
1421 } else {
1422 return false;
1423 }
1424 }
1425 };
1426 }
1427
1428 @Override
1429 public void remove() {
1430 throw new UnsupportedOperationException();
1431 }
1432 };
1433 }
1434
1435 @Override
1436 public BlockCache[] getBlockCaches() {
1437 return null;
1438 }
1439 }