View Javadoc

1   /**
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *     http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing, software
13   * distributed under the License is distributed on an "AS IS" BASIS,
14   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15   * See the License for the specific language governing permissions and
16   * limitations under the License.
17   */
18  package org.apache.hadoop.hbase.io.hfile;
19  
20  import static org.apache.hadoop.hbase.HConstants.BUCKET_CACHE_IOENGINE_KEY;
21  import static org.apache.hadoop.hbase.HConstants.BUCKET_CACHE_SIZE_KEY;
22  
23  import java.io.IOException;
24  import java.lang.management.ManagementFactory;
25  import java.lang.management.MemoryUsage;
26  
27  import org.apache.commons.logging.Log;
28  import org.apache.commons.logging.LogFactory;
29  import org.apache.hadoop.hbase.classification.InterfaceAudience;
30  import org.apache.hadoop.conf.Configuration;
31  import org.apache.hadoop.hbase.HColumnDescriptor;
32  import org.apache.hadoop.hbase.HConstants;
33  import org.apache.hadoop.hbase.io.hfile.BlockType.BlockCategory;
34  import org.apache.hadoop.hbase.io.hfile.bucket.BucketCache;
35  import org.apache.hadoop.hbase.io.util.HeapMemorySizeUtil;
36  import org.apache.hadoop.hbase.util.ReflectionUtils;
37  import org.apache.hadoop.util.StringUtils;
38  
39  import com.google.common.annotations.VisibleForTesting;
40  
41  /**
42   * Stores all of the cache objects and configuration for a single HFile.
43   */
44  @InterfaceAudience.Private
45  public class CacheConfig {
46    private static final Log LOG = LogFactory.getLog(CacheConfig.class.getName());
47  
48    /**
49     * Configuration key to cache data blocks on write. There are separate
50     * switches for bloom blocks and non-root index blocks.
51     */
52    public static final String CACHE_BLOCKS_ON_WRITE_KEY =
53        "hbase.rs.cacheblocksonwrite";
54  
55    /**
56     * Configuration key to cache leaf and intermediate-level index blocks on
57     * write.
58     */
59    public static final String CACHE_INDEX_BLOCKS_ON_WRITE_KEY =
60        "hfile.block.index.cacheonwrite";
61  
62    /**
63     * Configuration key to cache compound bloom filter blocks on write.
64     */
65    public static final String CACHE_BLOOM_BLOCKS_ON_WRITE_KEY =
66        "hfile.block.bloom.cacheonwrite";
67  
68    /**
69     * Configuration key to cache data blocks in compressed and/or encrypted format.
70     */
71    public static final String CACHE_DATA_BLOCKS_COMPRESSED_KEY =
72        "hbase.block.data.cachecompressed";
73  
74    /**
75     * Configuration key to evict all blocks of a given file from the block cache
76     * when the file is closed.
77     */
78    public static final String EVICT_BLOCKS_ON_CLOSE_KEY =
79        "hbase.rs.evictblocksonclose";
80  
81    /**
82     * Configuration keys for Bucket cache
83     */
84  
85    /**
86     * If the chosen ioengine can persist its state across restarts, the path to the file to persist
87     * to. This file is NOT the data file. It is a file into which we will serialize the map of
88     * what is in the data file. For example, if you pass the following argument as
89     * BUCKET_CACHE_IOENGINE_KEY ("hbase.bucketcache.ioengine"),
90     * <code>file:/tmp/bucketcache.data </code>, then we will write the bucketcache data to the file
91     * <code>/tmp/bucketcache.data</code> but the metadata on where the data is in the supplied file
92     * is an in-memory map that needs to be persisted across restarts. Where to store this
93     * in-memory state is what you supply here: e.g. <code>/tmp/bucketcache.map</code>.
94     */
95    public static final String BUCKET_CACHE_PERSISTENT_PATH_KEY = 
96        "hbase.bucketcache.persistent.path";
97  
98    /**
99     * If the bucket cache is used in league with the lru on-heap block cache (meta blocks such
100    * as indices and blooms are kept in the lru blockcache and the data blocks in the
101    * bucket cache).
102    */
103   public static final String BUCKET_CACHE_COMBINED_KEY = 
104       "hbase.bucketcache.combinedcache.enabled";
105 
106   public static final String BUCKET_CACHE_WRITER_THREADS_KEY = "hbase.bucketcache.writer.threads";
107   public static final String BUCKET_CACHE_WRITER_QUEUE_KEY = 
108       "hbase.bucketcache.writer.queuelength";
109 
110   /**
111    * A comma-delimited array of values for use as bucket sizes.
112    */
113   public static final String BUCKET_CACHE_BUCKETS_KEY = "hbase.bucketcache.bucket.sizes";
114 
115   /**
116    * Defaults for Bucket cache
117    */
118   public static final boolean DEFAULT_BUCKET_CACHE_COMBINED = true;
119   public static final int DEFAULT_BUCKET_CACHE_WRITER_THREADS = 3;
120   public static final int DEFAULT_BUCKET_CACHE_WRITER_QUEUE = 64;
121 
122  /**
123    * Configuration key to prefetch all blocks of a given file into the block cache
124    * when the file is opened.
125    */
126   public static final String PREFETCH_BLOCKS_ON_OPEN_KEY =
127       "hbase.rs.prefetchblocksonopen";
128 
129   /**
130    * The target block size used by blockcache instances. Defaults to
131    * {@link HConstants#DEFAULT_BLOCKSIZE}.
132    */
133   public static final String BLOCKCACHE_BLOCKSIZE_KEY = "hbase.blockcache.minblocksize";
134 
135   private static final String EXTERNAL_BLOCKCACHE_KEY = "hbase.blockcache.use.external";
136   private static final boolean EXTERNAL_BLOCKCACHE_DEFAULT = false;
137 
138   private static final String EXTERNAL_BLOCKCACHE_CLASS_KEY="hbase.blockcache.external.class";
139   private static final String DROP_BEHIND_CACHE_COMPACTION_KEY="hbase.hfile.drop.behind.compaction";
140   private static final boolean DROP_BEHIND_CACHE_COMPACTION_DEFAULT = true;
141 
142   /**
143    * @deprecated use {@link CacheConfig#BLOCKCACHE_BLOCKSIZE_KEY} instead.
144    */
145   @Deprecated
146   static final String DEPRECATED_BLOCKCACHE_BLOCKSIZE_KEY = "hbase.offheapcache.minblocksize";
147 
148   /**
149    * The config point hbase.offheapcache.minblocksize is completely wrong, which is replaced by
150    * {@link BlockCacheFactory#BLOCKCACHE_BLOCKSIZE_KEY}. Keep the old config key here for backward
151    * compatibility.
152    */
153   static {
154     Configuration.addDeprecation(DEPRECATED_BLOCKCACHE_BLOCKSIZE_KEY, BLOCKCACHE_BLOCKSIZE_KEY);
155   }
156 
157   /**
158    * Enum of all built in external block caches.
159    * This is used for config.
160    */
161   private static enum ExternalBlockCaches {
162     memcached("org.apache.hadoop.hbase.io.hfile.MemcachedBlockCache");
163     // TODO(eclark): Consider more. Redis, etc.
164     Class<? extends BlockCache> clazz;
165     ExternalBlockCaches(String clazzName) {
166       try {
167         clazz = (Class<? extends BlockCache>) Class.forName(clazzName);
168       } catch (ClassNotFoundException cnef) {
169         clazz = null;
170       }
171     }
172     ExternalBlockCaches(Class<? extends BlockCache> clazz) {
173       this.clazz = clazz;
174     }
175   }
176 
177   // Defaults
178   public static final boolean DEFAULT_CACHE_DATA_ON_READ = true;
179   public static final boolean DEFAULT_CACHE_DATA_ON_WRITE = false;
180   public static final boolean DEFAULT_IN_MEMORY = false;
181   public static final boolean DEFAULT_CACHE_INDEXES_ON_WRITE = false;
182   public static final boolean DEFAULT_CACHE_BLOOMS_ON_WRITE = false;
183   public static final boolean DEFAULT_EVICT_ON_CLOSE = false;
184   public static final boolean DEFAULT_CACHE_DATA_COMPRESSED = false;
185   public static final boolean DEFAULT_PREFETCH_ON_OPEN = false;
186 
187   /** Local reference to the block cache, null if completely disabled */
188   private final BlockCache blockCache;
189 
190   /**
191    * Whether blocks should be cached on read (default is on if there is a
192    * cache but this can be turned off on a per-family or per-request basis).
193    * If off we will STILL cache meta blocks; i.e. INDEX and BLOOM types.
194    * This cannot be disabled.
195    */
196   private boolean cacheDataOnRead;
197 
198   /** Whether blocks should be flagged as in-memory when being cached */
199   private final boolean inMemory;
200 
201   /** Whether data blocks should be cached when new files are written */
202   private boolean cacheDataOnWrite;
203 
204   /** Whether index blocks should be cached when new files are written */
205   private final boolean cacheIndexesOnWrite;
206 
207   /** Whether compound bloom filter blocks should be cached on write */
208   private final boolean cacheBloomsOnWrite;
209 
210   /** Whether blocks of a file should be evicted when the file is closed */
211   private boolean evictOnClose;
212 
213   /** Whether data blocks should be stored in compressed and/or encrypted form in the cache */
214   private final boolean cacheDataCompressed;
215 
216   /** Whether data blocks should be prefetched into the cache */
217   private final boolean prefetchOnOpen;
218 
219   /**
220    * If true and if more than one tier in this cache deploy -- e.g. CombinedBlockCache has an L1
221    * and an L2 tier -- then cache data blocks up in the L1 tier (The meta blocks are likely being
222    * cached up in L1 already.  At least this is the case if CombinedBlockCache).
223    */
224   private boolean cacheDataInL1;
225 
226   private final boolean dropBehindCompaction;
227 
228   /**
229    * Create a cache configuration using the specified configuration object and
230    * family descriptor.
231    * @param conf hbase configuration
232    * @param family column family configuration
233    */
234   public CacheConfig(Configuration conf, HColumnDescriptor family) {
235     this(CacheConfig.instantiateBlockCache(conf),
236         family.isBlockCacheEnabled(),
237         family.isInMemory(),
238         // For the following flags we enable them regardless of per-schema settings
239         // if they are enabled in the global configuration.
240         conf.getBoolean(CACHE_BLOCKS_ON_WRITE_KEY,
241             DEFAULT_CACHE_DATA_ON_WRITE) || family.isCacheDataOnWrite(),
242         conf.getBoolean(CACHE_INDEX_BLOCKS_ON_WRITE_KEY,
243             DEFAULT_CACHE_INDEXES_ON_WRITE) || family.isCacheIndexesOnWrite(),
244         conf.getBoolean(CACHE_BLOOM_BLOCKS_ON_WRITE_KEY,
245             DEFAULT_CACHE_BLOOMS_ON_WRITE) || family.isCacheBloomsOnWrite(),
246         conf.getBoolean(EVICT_BLOCKS_ON_CLOSE_KEY,
247             DEFAULT_EVICT_ON_CLOSE) || family.isEvictBlocksOnClose(),
248         conf.getBoolean(CACHE_DATA_BLOCKS_COMPRESSED_KEY, DEFAULT_CACHE_DATA_COMPRESSED),
249         conf.getBoolean(PREFETCH_BLOCKS_ON_OPEN_KEY,
250             DEFAULT_PREFETCH_ON_OPEN) || family.isPrefetchBlocksOnOpen(),
251         conf.getBoolean(HColumnDescriptor.CACHE_DATA_IN_L1,
252             HColumnDescriptor.DEFAULT_CACHE_DATA_IN_L1) || family.isCacheDataInL1(),
253         conf.getBoolean(DROP_BEHIND_CACHE_COMPACTION_KEY,DROP_BEHIND_CACHE_COMPACTION_DEFAULT)
254      );
255     LOG.info("Created cacheConfig for " + family.getNameAsString() + ": " + this);
256   }
257 
258   /**
259    * Create a cache configuration using the specified configuration object and
260    * defaults for family level settings. Only use if no column family context. Prefer
261    * {@link CacheConfig#CacheConfig(Configuration, HColumnDescriptor)}
262    * @see #CacheConfig(Configuration, HColumnDescriptor)
263    * @param conf hbase configuration
264    */
265   public CacheConfig(Configuration conf) {
266     this(CacheConfig.instantiateBlockCache(conf),
267         DEFAULT_CACHE_DATA_ON_READ,
268         DEFAULT_IN_MEMORY, // This is a family-level setting so can't be set
269                            // strictly from conf
270         conf.getBoolean(CACHE_BLOCKS_ON_WRITE_KEY, DEFAULT_CACHE_DATA_ON_WRITE),
271         conf.getBoolean(CACHE_INDEX_BLOCKS_ON_WRITE_KEY, DEFAULT_CACHE_INDEXES_ON_WRITE),
272         conf.getBoolean(CACHE_BLOOM_BLOCKS_ON_WRITE_KEY, DEFAULT_CACHE_BLOOMS_ON_WRITE),
273         conf.getBoolean(EVICT_BLOCKS_ON_CLOSE_KEY, DEFAULT_EVICT_ON_CLOSE),
274         conf.getBoolean(CACHE_DATA_BLOCKS_COMPRESSED_KEY, DEFAULT_CACHE_DATA_COMPRESSED),
275         conf.getBoolean(PREFETCH_BLOCKS_ON_OPEN_KEY, DEFAULT_PREFETCH_ON_OPEN),
276         conf.getBoolean(HColumnDescriptor.CACHE_DATA_IN_L1,
277           HColumnDescriptor.DEFAULT_CACHE_DATA_IN_L1),
278         conf.getBoolean(DROP_BEHIND_CACHE_COMPACTION_KEY,DROP_BEHIND_CACHE_COMPACTION_DEFAULT)
279      );
280     LOG.info("Created cacheConfig: " + this);
281   }
282 
283   /**
284    * Create a block cache configuration with the specified cache and
285    * configuration parameters.
286    * @param blockCache reference to block cache, null if completely disabled
287    * @param cacheDataOnRead whether DATA blocks should be cached on read (we always cache INDEX
288    * blocks and BLOOM blocks; this cannot be disabled).
289    * @param inMemory whether blocks should be flagged as in-memory
290    * @param cacheDataOnWrite whether data blocks should be cached on write
291    * @param cacheIndexesOnWrite whether index blocks should be cached on write
292    * @param cacheBloomsOnWrite whether blooms should be cached on write
293    * @param evictOnClose whether blocks should be evicted when HFile is closed
294    * @param cacheDataCompressed whether to store blocks as compressed in the cache
295    * @param prefetchOnOpen whether to prefetch blocks upon open
296    * @param cacheDataInL1 If more than one cache tier deployed, if true, cache this column families
297    * data blocks up in the L1 tier.
298    */
299   CacheConfig(final BlockCache blockCache,
300       final boolean cacheDataOnRead, final boolean inMemory,
301       final boolean cacheDataOnWrite, final boolean cacheIndexesOnWrite,
302       final boolean cacheBloomsOnWrite, final boolean evictOnClose,
303       final boolean cacheDataCompressed, final boolean prefetchOnOpen,
304       final boolean cacheDataInL1, final boolean dropBehindCompaction) {
305     this.blockCache = blockCache;
306     this.cacheDataOnRead = cacheDataOnRead;
307     this.inMemory = inMemory;
308     this.cacheDataOnWrite = cacheDataOnWrite;
309     this.cacheIndexesOnWrite = cacheIndexesOnWrite;
310     this.cacheBloomsOnWrite = cacheBloomsOnWrite;
311     this.evictOnClose = evictOnClose;
312     this.cacheDataCompressed = cacheDataCompressed;
313     this.prefetchOnOpen = prefetchOnOpen;
314     this.cacheDataInL1 = cacheDataInL1;
315     this.dropBehindCompaction = dropBehindCompaction;
316   }
317 
318   /**
319    * Constructs a cache configuration copied from the specified configuration.
320    * @param cacheConf
321    */
322   public CacheConfig(CacheConfig cacheConf) {
323     this(cacheConf.blockCache, cacheConf.cacheDataOnRead, cacheConf.inMemory,
324         cacheConf.cacheDataOnWrite, cacheConf.cacheIndexesOnWrite,
325         cacheConf.cacheBloomsOnWrite, cacheConf.evictOnClose,
326         cacheConf.cacheDataCompressed, cacheConf.prefetchOnOpen,
327         cacheConf.cacheDataInL1, cacheConf.dropBehindCompaction);
328   }
329 
330   /**
331    * Checks whether the block cache is enabled.
332    */
333   public boolean isBlockCacheEnabled() {
334     return this.blockCache != null;
335   }
336 
337   /**
338    * Returns the block cache.
339    * @return the block cache, or null if caching is completely disabled
340    */
341   public BlockCache getBlockCache() {
342     return this.blockCache;
343   }
344 
345   /**
346    * Returns whether the DATA blocks of this HFile should be cached on read or not (we always
347    * cache the meta blocks, the INDEX and BLOOM blocks).
348    * @return true if blocks should be cached on read, false if not
349    */
350   public boolean shouldCacheDataOnRead() {
351     return isBlockCacheEnabled() && cacheDataOnRead;
352   }
353 
354   public boolean shouldDropBehindCompaction() {
355     return dropBehindCompaction;
356   }
357 
358   /**
359    * Should we cache a block of a particular category? We always cache
360    * important blocks such as index blocks, as long as the block cache is
361    * available.
362    */
363   public boolean shouldCacheBlockOnRead(BlockCategory category) {
364     return isBlockCacheEnabled()
365         && (cacheDataOnRead ||
366             category == BlockCategory.INDEX ||
367             category == BlockCategory.BLOOM ||
368             (prefetchOnOpen &&
369                 (category != BlockCategory.META &&
370                  category != BlockCategory.UNKNOWN)));
371   }
372 
373   /**
374    * @return true if blocks in this file should be flagged as in-memory
375    */
376   public boolean isInMemory() {
377     return isBlockCacheEnabled() && this.inMemory;
378   }
379 
380   /**
381    * @return True if cache data blocks in L1 tier (if more than one tier in block cache deploy).
382    */
383   public boolean isCacheDataInL1() {
384     return isBlockCacheEnabled() && this.cacheDataInL1;
385   }
386 
387   /**
388    * @return true if data blocks should be written to the cache when an HFile is
389    *         written, false if not
390    */
391   public boolean shouldCacheDataOnWrite() {
392     return isBlockCacheEnabled() && this.cacheDataOnWrite;
393   }
394 
395   /**
396    * Only used for testing.
397    * @param cacheDataOnWrite whether data blocks should be written to the cache
398    *                         when an HFile is written
399    */
400   @VisibleForTesting
401   public void setCacheDataOnWrite(boolean cacheDataOnWrite) {
402     this.cacheDataOnWrite = cacheDataOnWrite;
403   }
404 
405   /**
406    * Only used for testing.
407    * @param cacheDataInL1 Whether to cache data blocks up in l1 (if a multi-tier cache
408    * implementation).
409    */
410   @VisibleForTesting
411   public void setCacheDataInL1(boolean cacheDataInL1) {
412     this.cacheDataInL1 = cacheDataInL1;
413   }
414 
415   /**
416    * @return true if index blocks should be written to the cache when an HFile
417    *         is written, false if not
418    */
419   public boolean shouldCacheIndexesOnWrite() {
420     return isBlockCacheEnabled() && this.cacheIndexesOnWrite;
421   }
422 
423   /**
424    * @return true if bloom blocks should be written to the cache when an HFile
425    *         is written, false if not
426    */
427   public boolean shouldCacheBloomsOnWrite() {
428     return isBlockCacheEnabled() && this.cacheBloomsOnWrite;
429   }
430 
431   /**
432    * @return true if blocks should be evicted from the cache when an HFile
433    *         reader is closed, false if not
434    */
435   public boolean shouldEvictOnClose() {
436     return isBlockCacheEnabled() && this.evictOnClose;
437   }
438 
439   /**
440    * Only used for testing.
441    * @param evictOnClose whether blocks should be evicted from the cache when an
442    *                     HFile reader is closed
443    */
444   public void setEvictOnClose(boolean evictOnClose) {
445     this.evictOnClose = evictOnClose;
446   }
447 
448   /**
449    * @return true if data blocks should be compressed in the cache, false if not
450    */
451   public boolean shouldCacheDataCompressed() {
452     return isBlockCacheEnabled() && this.cacheDataCompressed;
453   }
454 
455   /**
456    * @return true if this {@link BlockCategory} should be compressed in blockcache, false otherwise
457    */
458   public boolean shouldCacheCompressed(BlockCategory category) {
459     if (!isBlockCacheEnabled()) return false;
460     switch (category) {
461       case DATA:
462         return this.cacheDataCompressed;
463       default:
464         return false;
465     }
466   }
467 
468   /**
469    * @return true if blocks should be prefetched into the cache on open, false if not
470    */
471   public boolean shouldPrefetchOnOpen() {
472     return isBlockCacheEnabled() && this.prefetchOnOpen;
473   }
474 
475   /**
476    * Return true if we may find this type of block in block cache.
477    * <p/>
478    * TODO: today {@code family.isBlockCacheEnabled()} only means {@code cacheDataOnRead}, so here we
479    * consider lots of other configurations such as {@code cacheDataOnWrite}. We should fix this in
480    * the future, {@code cacheDataOnWrite} should honor the CF level {@code isBlockCacheEnabled}
481    * configuration.
482    */
483   public boolean shouldReadBlockFromCache(BlockType blockType) {
484     if (!isBlockCacheEnabled()) {
485       return false;
486     }
487     if (cacheDataOnRead) {
488       return true;
489     }
490     if (prefetchOnOpen) {
491       return true;
492     }
493     if (cacheDataOnWrite) {
494       return true;
495     }
496     if (blockType == null) {
497       return true;
498     }
499     if (blockType.getCategory() == BlockCategory.BLOOM ||
500             blockType.getCategory() == BlockCategory.INDEX) {
501       return true;
502     }
503     return false;
504   }
505 
506   /**
507    * If we make sure the block could not be cached, we will not acquire the lock
508    * otherwise we will acquire lock
509    */
510   public boolean shouldLockOnCacheMiss(BlockType blockType) {
511     if (blockType == null) {
512       return true;
513     }
514     return shouldCacheBlockOnRead(blockType.getCategory());
515   }
516 
517   @Override
518   public String toString() {
519     if (!isBlockCacheEnabled()) {
520       return "CacheConfig:disabled";
521     }
522     return "blockCache=" + getBlockCache() +
523       ", cacheDataOnRead=" + shouldCacheDataOnRead() +
524       ", cacheDataOnWrite=" + shouldCacheDataOnWrite() +
525       ", cacheIndexesOnWrite=" + shouldCacheIndexesOnWrite() +
526       ", cacheBloomsOnWrite=" + shouldCacheBloomsOnWrite() +
527       ", cacheEvictOnClose=" + shouldEvictOnClose() +
528       ", cacheDataCompressed=" + shouldCacheDataCompressed() +
529       ", prefetchOnOpen=" + shouldPrefetchOnOpen();
530   }
531 
532   // Static block cache reference and methods
533 
534   /**
535    * Static reference to the block cache, or null if no caching should be used
536    * at all.
537    */
538   // Clear this if in tests you'd make more than one block cache instance.
539   @VisibleForTesting
540   static BlockCache GLOBAL_BLOCK_CACHE_INSTANCE;
541   private static LruBlockCache GLOBAL_L1_CACHE_INSTANCE = null;
542   private static BlockCache GLOBAL_L2_CACHE_INSTANCE = null;
543 
544   /** Boolean whether we have disabled the block cache entirely. */
545   @VisibleForTesting
546   static boolean blockCacheDisabled = false;
547 
548   /**
549    * @param c Configuration to use.
550    * @return An L1 instance.  Currently an instance of LruBlockCache.
551    */
552   private static synchronized LruBlockCache getL1(final Configuration c) {
553     if (GLOBAL_L1_CACHE_INSTANCE != null) return GLOBAL_L1_CACHE_INSTANCE;
554     final long lruCacheSize = HeapMemorySizeUtil.getLruCacheSize(c);
555     if (lruCacheSize < 0) {
556       blockCacheDisabled = true;
557     }
558     if (blockCacheDisabled) return null;
559     int blockSize = c.getInt(BLOCKCACHE_BLOCKSIZE_KEY, HConstants.DEFAULT_BLOCKSIZE);
560     LOG.info("Allocating LruBlockCache size=" +
561       StringUtils.byteDesc(lruCacheSize) + ", blockSize=" + StringUtils.byteDesc(blockSize));
562     GLOBAL_L1_CACHE_INSTANCE = new LruBlockCache(lruCacheSize, blockSize, true, c);
563     return GLOBAL_L1_CACHE_INSTANCE;
564   }
565 
566   /**
567    * @param c Configuration to use.
568    * @return Returns L2 block cache instance (for now it is BucketCache BlockCache all the time)
569    * or null if not supposed to be a L2.
570    */
571   @VisibleForTesting
572   static BlockCache getL2(final Configuration c) {
573     final boolean useExternal = c.getBoolean(EXTERNAL_BLOCKCACHE_KEY, EXTERNAL_BLOCKCACHE_DEFAULT);
574     if (LOG.isDebugEnabled()) {
575       LOG.debug("Trying to use " + (useExternal?" External":" Internal") + " l2 cache");
576     }
577 
578     // If we want to use an external block cache then create that.
579     if (useExternal) {
580       GLOBAL_L2_CACHE_INSTANCE = getExternalBlockcache(c);
581     } else {
582       // otherwise use the bucket cache.
583       GLOBAL_L2_CACHE_INSTANCE = getBucketCache(c);
584     }
585     return GLOBAL_L2_CACHE_INSTANCE;
586   }
587 
588   public CacheStats getL1Stats() {
589     if (GLOBAL_L1_CACHE_INSTANCE != null) {
590       return GLOBAL_L1_CACHE_INSTANCE.getStats();
591     }
592     return null;
593   }
594 
595   public CacheStats getL2Stats() {
596     if (GLOBAL_L2_CACHE_INSTANCE != null) {
597       return GLOBAL_L2_CACHE_INSTANCE.getStats();
598     }
599     return null;
600   }
601 
602   private static BlockCache getExternalBlockcache(Configuration c) {
603     Class klass = null;
604 
605     // Get the class, from the config. s
606     try {
607       klass = ExternalBlockCaches.valueOf(c.get(EXTERNAL_BLOCKCACHE_CLASS_KEY, "memcache")).clazz;
608     } catch (IllegalArgumentException exception) {
609       try {
610         klass = c.getClass(EXTERNAL_BLOCKCACHE_CLASS_KEY, Class.forName(
611             "org.apache.hadoop.hbase.io.hfile.MemcachedBlockCache"));
612       } catch (ClassNotFoundException e) {
613         return null;
614       }
615     }
616 
617     // Now try and create an instance of the block cache.
618     try {
619       LOG.info("Creating external block cache of type: " + klass);
620       return (BlockCache) ReflectionUtils.newInstance(klass, c);
621     } catch (Exception e) {
622       LOG.warn("Error creating external block cache", e);
623     }
624     return null;
625 
626   }
627 
628   private static BlockCache getBucketCache(Configuration c) {
629     // Check for L2.  ioengine name must be non-null.
630     String bucketCacheIOEngineName = c.get(BUCKET_CACHE_IOENGINE_KEY, null);
631     if (bucketCacheIOEngineName == null || bucketCacheIOEngineName.length() <= 0) return null;
632 
633     int blockSize = c.getInt(BLOCKCACHE_BLOCKSIZE_KEY, HConstants.DEFAULT_BLOCKSIZE);
634     final long bucketCacheSize = HeapMemorySizeUtil.getBucketCacheSize(c);
635     if (bucketCacheSize <= 0) {
636       throw new IllegalStateException("bucketCacheSize <= 0; Check " +
637         BUCKET_CACHE_SIZE_KEY + " setting and/or server java heap size");
638     }
639     if (c.get("hbase.bucketcache.percentage.in.combinedcache") != null) {
640       LOG.warn("Configuration 'hbase.bucketcache.percentage.in.combinedcache' is no longer "
641           + "respected. See comments in http://hbase.apache.org/book.html#_changes_of_note");
642     }
643     int writerThreads = c.getInt(BUCKET_CACHE_WRITER_THREADS_KEY,
644       DEFAULT_BUCKET_CACHE_WRITER_THREADS);
645     int writerQueueLen = c.getInt(BUCKET_CACHE_WRITER_QUEUE_KEY,
646       DEFAULT_BUCKET_CACHE_WRITER_QUEUE);
647     String persistentPath = c.get(BUCKET_CACHE_PERSISTENT_PATH_KEY);
648     String[] configuredBucketSizes = c.getStrings(BUCKET_CACHE_BUCKETS_KEY);
649     int [] bucketSizes = null;
650     if (configuredBucketSizes != null) {
651       bucketSizes = new int[configuredBucketSizes.length];
652       for (int i = 0; i < configuredBucketSizes.length; i++) {
653         int bucketSize = Integer.parseInt(configuredBucketSizes[i].trim());
654         if (bucketSize % 256 != 0) {
655           // We need all the bucket sizes to be multiples of 256. Having all the configured bucket
656           // sizes to be multiples of 256 will ensure that the block offsets within buckets,
657           // that are calculated, will also be multiples of 256.
658           // See BucketEntry where offset to each block is represented using 5 bytes (instead of 8
659           // bytes long). We would like to save heap overhead as less as possible.
660           throw new IllegalArgumentException("Illegal value: " + bucketSize + " configured for '"
661               + BUCKET_CACHE_BUCKETS_KEY + "'. All bucket sizes to be multiples of 256");
662         }
663         bucketSizes[i] = bucketSize;
664       }
665     }
666     BucketCache bucketCache = null;
667     try {
668       int ioErrorsTolerationDuration = c.getInt(
669         "hbase.bucketcache.ioengine.errors.tolerated.duration",
670         BucketCache.DEFAULT_ERROR_TOLERATION_DURATION);
671       // Bucket cache logs its stats on creation internal to the constructor.
672       bucketCache = new BucketCache(bucketCacheIOEngineName,
673         bucketCacheSize, blockSize, bucketSizes, writerThreads, writerQueueLen, persistentPath,
674         ioErrorsTolerationDuration, c);
675     } catch (IOException ioex) {
676       LOG.error("Can't instantiate bucket cache", ioex); throw new RuntimeException(ioex);
677     }
678     return bucketCache;
679   }
680 
681   /**
682    * Returns the block cache or <code>null</code> in case none should be used.
683    * Sets GLOBAL_BLOCK_CACHE_INSTANCE
684    *
685    * @param conf  The current configuration.
686    * @return The block cache or <code>null</code>.
687    */
688   public static synchronized BlockCache instantiateBlockCache(Configuration conf) {
689     if (GLOBAL_BLOCK_CACHE_INSTANCE != null) return GLOBAL_BLOCK_CACHE_INSTANCE;
690     if (blockCacheDisabled) return null;
691     if (conf.get(DEPRECATED_BLOCKCACHE_BLOCKSIZE_KEY) != null) {
692       LOG.warn("The config key " + DEPRECATED_BLOCKCACHE_BLOCKSIZE_KEY +
693           " is deprecated now, instead please use " + BLOCKCACHE_BLOCKSIZE_KEY  +". "
694           + "In future release we will remove the deprecated config.");
695     }
696     LruBlockCache l1 = getL1(conf);
697     // blockCacheDisabled is set as a side-effect of getL1Internal(), so check it again after the call.
698     if (blockCacheDisabled) return null;
699     BlockCache l2 = getL2(conf);
700     if (l2 == null) {
701       GLOBAL_BLOCK_CACHE_INSTANCE = l1;
702     } else {
703       boolean useExternal = conf.getBoolean(EXTERNAL_BLOCKCACHE_KEY, EXTERNAL_BLOCKCACHE_DEFAULT);
704       boolean combinedWithLru = conf.getBoolean(BUCKET_CACHE_COMBINED_KEY,
705         DEFAULT_BUCKET_CACHE_COMBINED);
706       if (useExternal) {
707         GLOBAL_BLOCK_CACHE_INSTANCE = new InclusiveCombinedBlockCache(l1, l2);
708       } else {
709         if (combinedWithLru) {
710           GLOBAL_BLOCK_CACHE_INSTANCE = new CombinedBlockCache(l1, l2);
711         } else {
712           // L1 and L2 are not 'combined'.  They are connected via the LruBlockCache victimhandler
713           // mechanism.  It is a little ugly but works according to the following: when the
714           // background eviction thread runs, blocks evicted from L1 will go to L2 AND when we get
715           // a block from the L1 cache, if not in L1, we will search L2.
716           GLOBAL_BLOCK_CACHE_INSTANCE = l1;
717         }
718       }
719       l1.setVictimCache(l2);
720     }
721     return GLOBAL_BLOCK_CACHE_INSTANCE;
722   }
723   
724   @VisibleForTesting
725   static synchronized void clearGlobalInstances() {
726     GLOBAL_L1_CACHE_INSTANCE = null;
727     GLOBAL_L2_CACHE_INSTANCE = null;
728     GLOBAL_BLOCK_CACHE_INSTANCE = null;
729   }
730 }