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.io.hfile.HFileBlock.FILL_HEADER;
021
022import java.io.IOException;
023import java.lang.reflect.Modifier;
024import java.nio.ByteBuffer;
025import java.util.HashSet;
026import java.util.Map;
027import java.util.NavigableMap;
028import java.util.NavigableSet;
029import java.util.Set;
030import java.util.concurrent.ConcurrentSkipListMap;
031import java.util.concurrent.ConcurrentSkipListSet;
032import org.apache.hadoop.conf.Configuration;
033import org.apache.hadoop.hbase.metrics.impl.FastLongHistogram;
034import org.apache.hadoop.hbase.nio.ByteBuff;
035import org.apache.hadoop.hbase.regionserver.HRegion;
036import org.apache.hadoop.hbase.util.Bytes;
037import org.apache.hadoop.hbase.util.ChecksumType;
038import org.apache.hadoop.hbase.util.GsonUtil;
039import org.apache.yetus.audience.InterfaceAudience;
040import org.slf4j.Logger;
041import org.slf4j.LoggerFactory;
042
043import org.apache.hbase.thirdparty.com.google.gson.Gson;
044import org.apache.hbase.thirdparty.com.google.gson.TypeAdapter;
045import org.apache.hbase.thirdparty.com.google.gson.stream.JsonReader;
046import org.apache.hbase.thirdparty.com.google.gson.stream.JsonWriter;
047
048/**
049 * Utilty for aggregating counts in CachedBlocks and toString/toJSON CachedBlocks and BlockCaches.
050 * No attempt has been made at making this thread safe.
051 */
052@InterfaceAudience.Private
053public class BlockCacheUtil {
054
055  private static final Logger LOG = LoggerFactory.getLogger(BlockCacheUtil.class);
056
057  public static final long NANOS_PER_SECOND = 1000000000;
058
059  /**
060   * Needed generating JSON. {@code excludeFieldsWithModifiers} replaces Gson's default exclusion of
061   * static and transient fields rather than adding to it, so they have to be listed explicitly.
062   * Otherwise cache internals such as {@code BucketCache.backingMap} end up in the JSON.
063   */
064  private static final Gson GSON = GsonUtil.createGson()
065    .excludeFieldsWithModifiers(Modifier.PRIVATE, Modifier.TRANSIENT, Modifier.STATIC)
066    .registerTypeAdapter(FastLongHistogram.class, new TypeAdapter<FastLongHistogram>() {
067
068      @Override
069      public void write(JsonWriter out, FastLongHistogram value) throws IOException {
070        AgeSnapshot snapshot = new AgeSnapshot(value);
071        out.beginObject();
072        out.name("mean").value(snapshot.getMean());
073        out.name("min").value(snapshot.getMin());
074        out.name("max").value(snapshot.getMax());
075        out.name("75thPercentile").value(snapshot.get75thPercentile());
076        out.name("95thPercentile").value(snapshot.get95thPercentile());
077        out.name("98thPercentile").value(snapshot.get98thPercentile());
078        out.name("99thPercentile").value(snapshot.get99thPercentile());
079        out.name("999thPercentile").value(snapshot.get999thPercentile());
080        out.endObject();
081      }
082
083      @Override
084      public FastLongHistogram read(JsonReader in) throws IOException {
085        throw new UnsupportedOperationException();
086      }
087    }).setPrettyPrinting().create();
088
089  /** Returns The block content as String. */
090  public static String toString(final CachedBlock cb, final long now) {
091    return "filename=" + cb.getFilename() + ", " + toStringMinusFileName(cb, now);
092  }
093
094  /**
095   * Little data structure to hold counts for a file. Used doing a toJSON.
096   */
097  static class CachedBlockCountsPerFile {
098    private int count = 0;
099    private long size = 0;
100    private int countData = 0;
101    private long sizeData = 0;
102    private final String filename;
103
104    CachedBlockCountsPerFile(final String filename) {
105      this.filename = filename;
106    }
107
108    public int getCount() {
109      return count;
110    }
111
112    public long getSize() {
113      return size;
114    }
115
116    public int getCountData() {
117      return countData;
118    }
119
120    public long getSizeData() {
121      return sizeData;
122    }
123
124    public String getFilename() {
125      return filename;
126    }
127  }
128
129  /** Returns A JSON String of <code>filename</code> and counts of <code>blocks</code> */
130  public static String toJSON(String filename, NavigableSet<CachedBlock> blocks)
131    throws IOException {
132    CachedBlockCountsPerFile counts = new CachedBlockCountsPerFile(filename);
133    for (CachedBlock cb : blocks) {
134      counts.count++;
135      counts.size += cb.getSize();
136      BlockType bt = cb.getBlockType();
137      if (bt != null && bt.isData()) {
138        counts.countData++;
139        counts.sizeData += cb.getSize();
140      }
141    }
142    return GSON.toJson(counts);
143  }
144
145  /** Returns JSON string of <code>cbsf</code> aggregated */
146  public static String toJSON(CachedBlocksByFile cbsbf) throws IOException {
147    return GSON.toJson(cbsbf);
148  }
149
150  /** Returns JSON string of <code>bc</code> content. */
151  public static String toJSON(BlockCache bc) throws IOException {
152    return GSON.toJson(bc);
153  }
154
155  /** Returns The block content of <code>bc</code> as a String minus the filename. */
156  public static String toStringMinusFileName(final CachedBlock cb, final long now) {
157    return "offset=" + cb.getOffset() + ", size=" + cb.getSize() + ", age="
158      + (now - cb.getCachedTime()) + ", type=" + cb.getBlockType() + ", priority="
159      + cb.getBlockPriority();
160  }
161
162  /**
163   * Get a {@link CachedBlocksByFile} instance and load it up by iterating content in
164   * {@link BlockCache}.
165   * @param conf Used to read configurations
166   * @param bc   Block Cache to iterate.
167   * @return Laoded up instance of CachedBlocksByFile
168   */
169  public static CachedBlocksByFile getLoadedCachedBlocksByFile(final Configuration conf,
170    final BlockCache bc) {
171    CachedBlocksByFile cbsbf = new CachedBlocksByFile(conf);
172    for (CachedBlock cb : bc) {
173      if (cbsbf.update(cb)) break;
174    }
175    return cbsbf;
176  }
177
178  private static int compareCacheBlock(Cacheable left, Cacheable right,
179    boolean includeNextBlockMetadata) {
180    ByteBuffer l = ByteBuffer.allocate(left.getSerializedLength());
181    left.serialize(l, includeNextBlockMetadata);
182    ByteBuffer r = ByteBuffer.allocate(right.getSerializedLength());
183    right.serialize(r, includeNextBlockMetadata);
184    return Bytes.compareTo(l.array(), l.arrayOffset(), l.limit(), r.array(), r.arrayOffset(),
185      r.limit());
186  }
187
188  /**
189   * Validate that the existing and newBlock are the same without including the nextBlockMetadata,
190   * if not, throw an exception. If they are the same without the nextBlockMetadata, return the
191   * comparison.
192   * @param existing block that is existing in the cache.
193   * @param newBlock block that is trying to be cached.
194   * @param cacheKey the cache key of the blocks.
195   * @return comparison of the existing block to the newBlock.
196   */
197  public static int validateBlockAddition(Cacheable existing, Cacheable newBlock,
198    BlockCacheKey cacheKey) {
199    int comparison = compareCacheBlock(existing, newBlock, false);
200    if (comparison != 0) {
201      throw new RuntimeException(
202        "Cached block contents differ, which should not have happened." + "cacheKey:" + cacheKey);
203    }
204    if ((existing instanceof HFileBlock) && (newBlock instanceof HFileBlock)) {
205      comparison = ((HFileBlock) existing).getNextBlockOnDiskSize()
206        - ((HFileBlock) newBlock).getNextBlockOnDiskSize();
207    }
208    return comparison;
209  }
210
211  /**
212   * Because of the region splitting, it's possible that the split key locate in the middle of a
213   * block. So it's possible that both the daughter regions load the same block from their parent
214   * HFile. When pread, we don't force the read to read all of the next block header. So when two
215   * threads try to cache the same block, it's possible that one thread read all of the next block
216   * header but the other one didn't. if the already cached block hasn't next block header but the
217   * new block to cache has, then we can replace the existing block with the new block for better
218   * performance.(HBASE-20447)
219   * @param blockCache BlockCache to check
220   * @param cacheKey   the block cache key
221   * @param newBlock   the new block which try to put into the block cache.
222   * @return true means need to replace existing block with new block for the same block cache key.
223   *         false means just keep the existing block.
224   */
225  public static boolean shouldReplaceExistingCacheBlock(BlockCache blockCache,
226    BlockCacheKey cacheKey, Cacheable newBlock) {
227    // NOTICE: The getBlock has retained the existingBlock inside.
228    Cacheable existingBlock = blockCache.getBlock(cacheKey, false, false, false);
229    if (existingBlock == null) {
230      return true;
231    }
232    try {
233      int comparison = BlockCacheUtil.validateBlockAddition(existingBlock, newBlock, cacheKey);
234      if (comparison < 0) {
235        LOG.warn("Cached block contents differ by nextBlockOnDiskSize, the new block has "
236          + "nextBlockOnDiskSize set. Caching new block.");
237        return true;
238      } else if (comparison > 0) {
239        LOG.warn("Cached block contents differ by nextBlockOnDiskSize, the existing block has "
240          + "nextBlockOnDiskSize set, Keeping cached block.");
241        return false;
242      } else {
243        LOG.debug("Caching an already cached block: {}. This is harmless and can happen in rare "
244          + "cases (see HBASE-8547)", cacheKey);
245        return false;
246      }
247    } finally {
248      // Release this block to decrement the reference count.
249      existingBlock.release();
250    }
251  }
252
253  public static Set<String> listAllFilesNames(Map<String, HRegion> onlineRegions) {
254    Set<String> files = new HashSet<>();
255    onlineRegions.values().forEach(r -> {
256      r.getStores().forEach(s -> {
257        s.getStorefiles().forEach(f -> files.add(f.getPath().getName()));
258      });
259    });
260    return files;
261  }
262
263  private static final int DEFAULT_MAX = 1000000;
264
265  public static int getMaxCachedBlocksByFile(Configuration conf) {
266    return conf == null ? DEFAULT_MAX : conf.getInt("hbase.ui.blockcache.by.file.max", DEFAULT_MAX);
267  }
268
269  /**
270   * Similarly to HFileBlock.Writer.getBlockForCaching(), creates a HFileBlock instance without
271   * checksum for caching. This is needed for when we cache blocks via readers (either prefetch or
272   * client read), otherwise we may fail equality comparison when checking against same block that
273   * may already have been cached at write time.
274   * @param cacheConf the related CacheConfig object.
275   * @param block     the HFileBlock instance to be converted.
276   * @return the resulting HFileBlock instance without checksum.
277   */
278  public static HFileBlock getBlockForCaching(CacheConfig cacheConf, HFileBlock block) {
279    // Calculate how many bytes we need for checksum on the tail of the block.
280    int numBytes = cacheConf.shouldCacheCompressed(block.getBlockType().getCategory())
281      ? 0
282      : (int) ChecksumUtil.numBytes(block.getOnDiskDataSizeWithHeader(),
283        block.getHFileContext().getBytesPerChecksum());
284    ByteBuff buff = block.getBufferReadOnly();
285    HFileBlockBuilder builder = new HFileBlockBuilder();
286    return builder.withBlockType(block.getBlockType())
287      .withOnDiskSizeWithoutHeader(block.getOnDiskSizeWithoutHeader())
288      .withUncompressedSizeWithoutHeader(block.getUncompressedSizeWithoutHeader())
289      .withPrevBlockOffset(block.getPrevBlockOffset()).withByteBuff(buff)
290      .withFillHeader(FILL_HEADER).withOffset(block.getOffset())
291      .withOnDiskDataSizeWithHeader(block.getOnDiskDataSizeWithHeader() + numBytes)
292      .withNextBlockOnDiskSize(block.getNextBlockOnDiskSize())
293      .withHFileContext(cloneContext(block.getHFileContext()))
294      .withByteBuffAllocator(cacheConf.getByteBuffAllocator()).withShared(!buff.hasArray()).build();
295  }
296
297  public static HFileContext cloneContext(HFileContext context) {
298    HFileContext newContext = new HFileContextBuilder().withBlockSize(context.getBlocksize())
299      .withBytesPerCheckSum(0).withChecksumType(ChecksumType.NULL) // no checksums in cached data
300      .withCompression(context.getCompression()).withHFileName(context.getHFileName())
301      .withDataBlockEncoding(context.getDataBlockEncoding())
302      .withHBaseCheckSum(context.isUseHBaseChecksum()).withCompressTags(context.isCompressTags())
303      .withIncludesMvcc(context.isIncludesMvcc()).withIncludesTags(context.isIncludesTags())
304      .withColumnFamily(context.getColumnFamily()).withTableName(context.getTableName()).build();
305    return newContext;
306  }
307
308  /**
309   * Use one of these to keep a running account of cached blocks by file. Throw it away when done.
310   * This is different than metrics in that it is stats on current state of a cache. See
311   * getLoadedCachedBlocksByFile
312   */
313  public static class CachedBlocksByFile {
314    private int count;
315    private int dataBlockCount;
316    private long size;
317    private long dataSize;
318    private final long now = System.nanoTime();
319    /**
320     * How many blocks to look at before we give up. There could be many millions of blocks. We
321     * don't want the ui to freeze while we run through 1B blocks... users will think hbase dead. UI
322     * displays warning in red when stats are incomplete.
323     */
324    private final int max;
325
326    CachedBlocksByFile() {
327      this(null);
328    }
329
330    CachedBlocksByFile(final Configuration c) {
331      this.max = getMaxCachedBlocksByFile(c);
332    }
333
334    /**
335     * Map by filename. use concurent utils because we want our Map and contained blocks sorted.
336     */
337    private transient NavigableMap<String, NavigableSet<CachedBlock>> cachedBlockByFile =
338      new ConcurrentSkipListMap<>();
339    FastLongHistogram hist = new FastLongHistogram();
340
341    /** Returns True if full.... if we won't be adding any more. */
342    public boolean update(final CachedBlock cb) {
343      if (isFull()) return true;
344      NavigableSet<CachedBlock> set = this.cachedBlockByFile.get(cb.getFilename());
345      if (set == null) {
346        set = new ConcurrentSkipListSet<>();
347        this.cachedBlockByFile.put(cb.getFilename(), set);
348      }
349      set.add(cb);
350      this.size += cb.getSize();
351      this.count++;
352      BlockType bt = cb.getBlockType();
353      if (bt != null && bt.isData()) {
354        this.dataBlockCount++;
355        this.dataSize += cb.getSize();
356      }
357      long age = (this.now - cb.getCachedTime()) / NANOS_PER_SECOND;
358      this.hist.add(age, 1);
359      return false;
360    }
361
362    /**
363     * @return True if full; i.e. there are more items in the cache but we only loaded up the
364     *         maximum set in configuration <code>hbase.ui.blockcache.by.file.max</code> (Default:
365     *         DEFAULT_MAX).
366     */
367    public boolean isFull() {
368      return this.count >= this.max;
369    }
370
371    public NavigableMap<String, NavigableSet<CachedBlock>> getCachedBlockStatsByFile() {
372      return this.cachedBlockByFile;
373    }
374
375    /** Returns count of blocks in the cache */
376    public int getCount() {
377      return count;
378    }
379
380    public int getDataCount() {
381      return dataBlockCount;
382    }
383
384    /** Returns size of blocks in the cache */
385    public long getSize() {
386      return size;
387    }
388
389    /** Returns Size of data. */
390    public long getDataSize() {
391      return dataSize;
392    }
393
394    public AgeSnapshot getAgeInCacheSnapshot() {
395      return new AgeSnapshot(this.hist);
396    }
397
398    @Override
399    public String toString() {
400      AgeSnapshot snapshot = getAgeInCacheSnapshot();
401      return "count=" + count + ", dataBlockCount=" + dataBlockCount + ", size=" + size
402        + ", dataSize=" + getDataSize() + ", mean age=" + snapshot.getMean() + ", min age="
403        + snapshot.getMin() + ", max age=" + snapshot.getMax() + ", 75th percentile age="
404        + snapshot.get75thPercentile() + ", 95th percentile age=" + snapshot.get95thPercentile()
405        + ", 98th percentile age=" + snapshot.get98thPercentile() + ", 99th percentile age="
406        + snapshot.get99thPercentile() + ", 99.9th percentile age=" + snapshot.get999thPercentile();
407    }
408  }
409}