001/*
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License.  You may obtain a copy of the License at
009 *
010 *     http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018package org.apache.hadoop.hbase.io.hfile;
019
020import static org.apache.hadoop.hbase.HConstants.BUCKET_CACHE_IOENGINE_KEY;
021import static org.apache.hadoop.hbase.HConstants.BUCKET_CACHE_PERSISTENT_PATH_KEY;
022import static org.apache.hadoop.hbase.HConstants.BUCKET_CACHE_SIZE_KEY;
023
024import java.io.IOException;
025import java.util.concurrent.ForkJoinPool;
026import org.apache.hadoop.conf.Configuration;
027import org.apache.hadoop.hbase.HConstants;
028import org.apache.hadoop.hbase.io.hfile.bucket.BucketCache;
029import org.apache.hadoop.hbase.io.util.MemorySizeUtil;
030import org.apache.hadoop.hbase.util.ReflectionUtils;
031import org.apache.hadoop.util.StringUtils;
032import org.apache.yetus.audience.InterfaceAudience;
033import org.slf4j.Logger;
034import org.slf4j.LoggerFactory;
035
036@InterfaceAudience.Private
037public final class BlockCacheFactory {
038
039  private static final Logger LOG = LoggerFactory.getLogger(BlockCacheFactory.class.getName());
040
041  /**
042   * Configuration keys for Bucket cache
043   */
044
045  /**
046   * Configuration key to cache block policy (Lru, TinyLfu, AdaptiveLRU, IndexOnlyLRU).
047   */
048  public static final String BLOCKCACHE_POLICY_KEY = "hfile.block.cache.policy";
049  public static final String BLOCKCACHE_POLICY_DEFAULT = "LRU";
050
051  public static final String BUCKET_CACHE_WRITER_THREADS_KEY = "hbase.bucketcache.writer.threads";
052
053  public static final String BUCKET_CACHE_WRITER_QUEUE_KEY = "hbase.bucketcache.writer.queuelength";
054
055  /**
056   * A comma-delimited array of values for use as bucket sizes.
057   */
058  public static final String BUCKET_CACHE_BUCKETS_KEY = "hbase.bucketcache.bucket.sizes";
059
060  /**
061   * Defaults for Bucket cache
062   */
063  public static final int DEFAULT_BUCKET_CACHE_WRITER_THREADS = 3;
064  public static final int DEFAULT_BUCKET_CACHE_WRITER_QUEUE = 64;
065
066  /**
067   * The target block size used by blockcache instances. Defaults to
068   * {@link HConstants#DEFAULT_BLOCKSIZE}.
069   */
070  public static final String BLOCKCACHE_BLOCKSIZE_KEY = "hbase.blockcache.minblocksize";
071
072  private static final String EXTERNAL_BLOCKCACHE_KEY = "hbase.blockcache.use.external";
073  private static final boolean EXTERNAL_BLOCKCACHE_DEFAULT = false;
074
075  private static final String EXTERNAL_BLOCKCACHE_CLASS_KEY = "hbase.blockcache.external.class";
076
077  /**
078   * @deprecated use {@link BlockCacheFactory#BLOCKCACHE_BLOCKSIZE_KEY} instead.
079   */
080  @Deprecated
081  static final String DEPRECATED_BLOCKCACHE_BLOCKSIZE_KEY = "hbase.offheapcache.minblocksize";
082
083  private BlockCacheFactory() {
084  }
085
086  public static BlockCache createBlockCache(Configuration conf) {
087    FirstLevelBlockCache l1Cache = createFirstLevelCache(conf);
088    if (l1Cache == null) {
089      return null;
090    }
091    boolean useExternal = conf.getBoolean(EXTERNAL_BLOCKCACHE_KEY, EXTERNAL_BLOCKCACHE_DEFAULT);
092    if (useExternal) {
093      BlockCache l2CacheInstance = createExternalBlockcache(conf);
094      return l2CacheInstance == null
095        ? l1Cache
096        : new InclusiveCombinedBlockCache(l1Cache, l2CacheInstance);
097    } else {
098      // otherwise use the bucket cache.
099      BucketCache bucketCache = createBucketCache(conf);
100      if (!conf.getBoolean("hbase.bucketcache.combinedcache.enabled", true)) {
101        // Non combined mode is off from 2.0
102        LOG.warn(
103          "From HBase 2.0 onwards only combined mode of LRU cache and bucket cache is available");
104      }
105      return bucketCache == null ? l1Cache : new CombinedBlockCache(l1Cache, bucketCache);
106    }
107  }
108
109  private static FirstLevelBlockCache createFirstLevelCache(final Configuration c) {
110    final long cacheSize = MemorySizeUtil.getOnHeapCacheSize(c);
111    if (cacheSize < 0) {
112      return null;
113    }
114    String policy = c.get(BLOCKCACHE_POLICY_KEY, BLOCKCACHE_POLICY_DEFAULT);
115    int blockSize = c.getInt(BLOCKCACHE_BLOCKSIZE_KEY, HConstants.DEFAULT_BLOCKSIZE);
116    LOG.info("Allocating BlockCache size=" + StringUtils.byteDesc(cacheSize) + ", blockSize="
117      + StringUtils.byteDesc(blockSize));
118    if (policy.equalsIgnoreCase("LRU")) {
119      return new LruBlockCache(cacheSize, blockSize, true, c);
120    } else if (policy.equalsIgnoreCase("IndexOnlyLRU")) {
121      return new IndexOnlyLruBlockCache(cacheSize, blockSize, true, c);
122    } else if (policy.equalsIgnoreCase("TinyLFU")) {
123      return new TinyLfuBlockCache(cacheSize, blockSize, ForkJoinPool.commonPool(), c);
124    } else if (policy.equalsIgnoreCase("AdaptiveLRU")) {
125      return new LruAdaptiveBlockCache(cacheSize, blockSize, true, c);
126    } else {
127      throw new IllegalArgumentException("Unknown policy: " + policy);
128    }
129  }
130
131  /**
132   * Enum of all built in external block caches. This is used for config.
133   */
134  private static enum ExternalBlockCaches {
135    memcached("org.apache.hadoop.hbase.io.hfile.MemcachedBlockCache");
136
137    // TODO(eclark): Consider more. Redis, etc.
138    Class<? extends BlockCache> clazz;
139
140    ExternalBlockCaches(String clazzName) {
141      try {
142        clazz = (Class<? extends BlockCache>) Class.forName(clazzName);
143      } catch (ClassNotFoundException cnef) {
144        clazz = null;
145      }
146    }
147
148    ExternalBlockCaches(Class<? extends BlockCache> clazz) {
149      this.clazz = clazz;
150    }
151  }
152
153  private static BlockCache createExternalBlockcache(Configuration c) {
154    if (LOG.isDebugEnabled()) {
155      LOG.debug("Trying to use External l2 cache");
156    }
157    Class klass = null;
158
159    // Get the class, from the config. s
160    try {
161      klass = ExternalBlockCaches.valueOf(c.get(EXTERNAL_BLOCKCACHE_CLASS_KEY, "memcache")).clazz;
162    } catch (IllegalArgumentException exception) {
163      try {
164        klass = c.getClass(EXTERNAL_BLOCKCACHE_CLASS_KEY,
165          Class.forName("org.apache.hadoop.hbase.io.hfile.MemcachedBlockCache"));
166      } catch (ClassNotFoundException e) {
167        return null;
168      }
169    }
170
171    // Now try and create an instance of the block cache.
172    try {
173      LOG.info("Creating external block cache of type: " + klass);
174      return (BlockCache) ReflectionUtils.newInstance(klass, c);
175    } catch (Exception e) {
176      LOG.warn("Error creating external block cache", e);
177    }
178    return null;
179
180  }
181
182  private static BucketCache createBucketCache(Configuration c) {
183    // Check for L2. ioengine name must be non-null.
184    String bucketCacheIOEngineName = c.get(BUCKET_CACHE_IOENGINE_KEY, null);
185    if (bucketCacheIOEngineName == null || bucketCacheIOEngineName.length() <= 0) {
186      return null;
187    }
188
189    int blockSize = c.getInt(BLOCKCACHE_BLOCKSIZE_KEY, HConstants.DEFAULT_BLOCKSIZE);
190    final long bucketCacheSize = MemorySizeUtil.getBucketCacheSize(c);
191    if (bucketCacheSize <= 0) {
192      throw new IllegalStateException("bucketCacheSize <= 0; Check " + BUCKET_CACHE_SIZE_KEY
193        + " setting and/or server java heap size");
194    }
195    if (c.get("hbase.bucketcache.percentage.in.combinedcache") != null) {
196      LOG.warn("Configuration 'hbase.bucketcache.percentage.in.combinedcache' is no longer "
197        + "respected. See comments in http://hbase.apache.org/book.html#_changes_of_note");
198    }
199    int writerThreads =
200      c.getInt(BUCKET_CACHE_WRITER_THREADS_KEY, DEFAULT_BUCKET_CACHE_WRITER_THREADS);
201    int writerQueueLen = c.getInt(BUCKET_CACHE_WRITER_QUEUE_KEY, DEFAULT_BUCKET_CACHE_WRITER_QUEUE);
202    String persistentPath = c.get(BUCKET_CACHE_PERSISTENT_PATH_KEY);
203    String[] configuredBucketSizes = c.getStrings(BUCKET_CACHE_BUCKETS_KEY);
204    int[] bucketSizes = null;
205    if (configuredBucketSizes != null) {
206      bucketSizes = new int[configuredBucketSizes.length];
207      for (int i = 0; i < configuredBucketSizes.length; i++) {
208        int bucketSize = Integer.parseInt(configuredBucketSizes[i].trim());
209        if (bucketSize % 256 != 0) {
210          // We need all the bucket sizes to be multiples of 256. Having all the configured bucket
211          // sizes to be multiples of 256 will ensure that the block offsets within buckets,
212          // that are calculated, will also be multiples of 256.
213          // See BucketEntry where offset to each block is represented using 5 bytes (instead of 8
214          // bytes long). We would like to save heap overhead as less as possible.
215          throw new IllegalArgumentException("Illegal value: " + bucketSize + " configured for '"
216            + BUCKET_CACHE_BUCKETS_KEY + "'. All bucket sizes to be multiples of 256");
217        }
218        bucketSizes[i] = bucketSize;
219      }
220    }
221    BucketCache bucketCache = null;
222    try {
223      int ioErrorsTolerationDuration =
224        c.getInt("hbase.bucketcache.ioengine.errors.tolerated.duration",
225          BucketCache.DEFAULT_ERROR_TOLERATION_DURATION);
226      // Bucket cache logs its stats on creation internal to the constructor.
227      bucketCache = new BucketCache(bucketCacheIOEngineName, bucketCacheSize, blockSize,
228        bucketSizes, writerThreads, writerQueueLen, persistentPath, ioErrorsTolerationDuration, c);
229    } catch (IOException ioex) {
230      LOG.error("Can't instantiate bucket cache", ioex);
231      throw new RuntimeException(ioex);
232    }
233    return bucketCache;
234  }
235}