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 java.io.IOException;
021import java.nio.ByteBuffer;
022import java.util.NavigableMap;
023import java.util.NavigableSet;
024import java.util.concurrent.ConcurrentSkipListMap;
025import java.util.concurrent.ConcurrentSkipListSet;
026
027import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
028import com.fasterxml.jackson.core.JsonGenerationException;
029import com.fasterxml.jackson.databind.JsonMappingException;
030import com.fasterxml.jackson.databind.ObjectMapper;
031import com.fasterxml.jackson.databind.SerializationFeature;
032import org.apache.yetus.audience.InterfaceAudience;
033import org.apache.hadoop.conf.Configuration;
034import org.apache.hadoop.hbase.metrics.impl.FastLongHistogram;
035import org.apache.hadoop.hbase.util.Bytes;
036
037/**
038 * Utilty for aggregating counts in CachedBlocks and toString/toJSON CachedBlocks and BlockCaches.
039 * No attempt has been made at making this thread safe.
040 */
041@InterfaceAudience.Private
042public class BlockCacheUtil {
043
044
045  public static final long NANOS_PER_SECOND = 1000000000;
046
047  /**
048   * Needed generating JSON.
049   */
050  private static final ObjectMapper MAPPER = new ObjectMapper();
051  static {
052    MAPPER.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
053    MAPPER.configure(SerializationFeature.FLUSH_AFTER_WRITE_VALUE, true);
054    MAPPER.configure(SerializationFeature.INDENT_OUTPUT, true);
055  }
056
057  /**
058   * @param cb
059   * @return The block content as String.
060   */
061  public static String toString(final CachedBlock cb, final long now) {
062    return "filename=" + cb.getFilename() + ", " + toStringMinusFileName(cb, now);
063  }
064
065  /**
066   * Little data structure to hold counts for a file.
067   * Used doing a toJSON.
068   */
069  static class CachedBlockCountsPerFile {
070    private int count = 0;
071    private long size = 0;
072    private int countData = 0;
073    private long sizeData = 0;
074    private final String filename;
075
076    CachedBlockCountsPerFile(final String filename) {
077      this.filename = filename;
078    }
079
080    public int getCount() {
081      return count;
082    }
083
084    public long getSize() {
085      return size;
086    }
087
088    public int getCountData() {
089      return countData;
090    }
091
092    public long getSizeData() {
093      return sizeData;
094    }
095
096    public String getFilename() {
097      return filename;
098    }
099  }
100
101  /**
102   * @param filename
103   * @param blocks
104   * @return A JSON String of <code>filename</code> and counts of <code>blocks</code>
105   * @throws JsonGenerationException
106   * @throws JsonMappingException
107   * @throws IOException
108   */
109  public static String toJSON(final String filename, final NavigableSet<CachedBlock> blocks)
110  throws JsonGenerationException, JsonMappingException, IOException {
111    CachedBlockCountsPerFile counts = new CachedBlockCountsPerFile(filename);
112    for (CachedBlock cb: blocks) {
113      counts.count++;
114      counts.size += cb.getSize();
115      BlockType bt = cb.getBlockType();
116      if (bt != null && bt.isData()) {
117        counts.countData++;
118        counts.sizeData += cb.getSize();
119      }
120    }
121    return MAPPER.writeValueAsString(counts);
122  }
123
124  /**
125   * @param cbsbf
126   * @return JSON string of <code>cbsf</code> aggregated
127   * @throws JsonGenerationException
128   * @throws JsonMappingException
129   * @throws IOException
130   */
131  public static String toJSON(final CachedBlocksByFile cbsbf)
132  throws JsonGenerationException, JsonMappingException, IOException {
133    return MAPPER.writeValueAsString(cbsbf);
134  }
135
136  /**
137   * @param bc
138   * @return JSON string of <code>bc</code> content.
139   * @throws JsonGenerationException
140   * @throws JsonMappingException
141   * @throws IOException
142   */
143  public static String toJSON(final BlockCache bc)
144  throws JsonGenerationException, JsonMappingException, IOException {
145    return MAPPER.writeValueAsString(bc);
146  }
147
148  /**
149   * @param cb
150   * @return The block content of <code>bc</code> as a String minus the filename.
151   */
152  public static String toStringMinusFileName(final CachedBlock cb, final long now) {
153    return "offset=" + cb.getOffset() +
154      ", size=" + cb.getSize() +
155      ", age=" + (now - cb.getCachedTime()) +
156      ", type=" + cb.getBlockType() +
157      ", priority=" + cb.getBlockPriority();
158  }
159
160  /**
161   * Get a {@link CachedBlocksByFile} instance and load it up by iterating content in
162   * {@link BlockCache}.
163   * @param conf Used to read configurations
164   * @param bc Block Cache to iterate.
165   * @return Laoded up instance of CachedBlocksByFile
166   */
167  public static CachedBlocksByFile getLoadedCachedBlocksByFile(final Configuration conf,
168      final BlockCache bc) {
169    CachedBlocksByFile cbsbf = new CachedBlocksByFile(conf);
170    for (CachedBlock cb: bc) {
171      if (cbsbf.update(cb)) break;
172    }
173    return cbsbf;
174  }
175
176  public static int compareCacheBlock(Cacheable left, Cacheable right) {
177    ByteBuffer l = ByteBuffer.allocate(left.getSerializedLength());
178    left.serialize(l);
179    ByteBuffer r = ByteBuffer.allocate(right.getSerializedLength());
180    right.serialize(r);
181    return Bytes.compareTo(l.array(), l.arrayOffset(), l.limit(),
182        r.array(), r.arrayOffset(), r.limit());
183  }
184
185  /**
186   * Use one of these to keep a running account of cached blocks by file.  Throw it away when done.
187   * This is different than metrics in that it is stats on current state of a cache.
188   * See getLoadedCachedBlocksByFile
189   */
190  @JsonIgnoreProperties({"cachedBlockStatsByFile"})
191  public static class CachedBlocksByFile {
192    private int count;
193    private int dataBlockCount;
194    private long size;
195    private long dataSize;
196    private final long now = System.nanoTime();
197    /**
198     * How many blocks to look at before we give up.
199     * There could be many millions of blocks. We don't want the
200     * ui to freeze while we run through 1B blocks... users will
201     * think hbase dead. UI displays warning in red when stats
202     * are incomplete.
203     */
204    private final int max;
205    public static final int DEFAULT_MAX = 1000000;
206
207    CachedBlocksByFile() {
208      this(null);
209    }
210
211    CachedBlocksByFile(final Configuration c) {
212      this.max = c == null? DEFAULT_MAX: c.getInt("hbase.ui.blockcache.by.file.max", DEFAULT_MAX);
213    }
214
215    /**
216     * Map by filename. use concurent utils because we want our Map and contained blocks sorted.
217     */
218    private NavigableMap<String, NavigableSet<CachedBlock>> cachedBlockByFile = new ConcurrentSkipListMap<>();
219    FastLongHistogram hist = new FastLongHistogram();
220
221    /**
222     * @param cb
223     * @return True if full.... if we won't be adding any more.
224     */
225    public boolean update(final CachedBlock cb) {
226      if (isFull()) return true;
227      NavigableSet<CachedBlock> set = this.cachedBlockByFile.get(cb.getFilename());
228      if (set == null) {
229        set = new ConcurrentSkipListSet<>();
230        this.cachedBlockByFile.put(cb.getFilename(), set);
231      }
232      set.add(cb);
233      this.size += cb.getSize();
234      this.count++;
235      BlockType bt = cb.getBlockType();
236      if (bt != null && bt.isData()) {
237        this.dataBlockCount++;
238        this.dataSize += cb.getSize();
239      }
240      long age = (this.now - cb.getCachedTime())/NANOS_PER_SECOND;
241      this.hist.add(age, 1);
242      return false;
243    }
244
245    /**
246     * @return True if full; i.e. there are more items in the cache but we only loaded up
247     * the maximum set in configuration <code>hbase.ui.blockcache.by.file.max</code>
248     * (Default: DEFAULT_MAX).
249     */
250    public boolean isFull() {
251      return this.count >= this.max;
252    }
253
254    public NavigableMap<String, NavigableSet<CachedBlock>> getCachedBlockStatsByFile() {
255      return this.cachedBlockByFile;
256    }
257
258    /**
259     * @return count of blocks in the cache
260     */
261    public int getCount() {
262      return count;
263    }
264
265    public int getDataCount() {
266      return dataBlockCount;
267    }
268
269    /**
270     * @return size of blocks in the cache
271     */
272    public long getSize() {
273      return size;
274    }
275
276    /**
277     * @return Size of data.
278     */
279    public long getDataSize() {
280      return dataSize;
281    }
282
283    public AgeSnapshot getAgeInCacheSnapshot() {
284      return new AgeSnapshot(this.hist);
285    }
286
287    @Override
288    public String toString() {
289      AgeSnapshot snapshot = getAgeInCacheSnapshot();
290      return "count=" + count + ", dataBlockCount=" + dataBlockCount + ", size=" + size +
291          ", dataSize=" + getDataSize() +
292          ", mean age=" + snapshot.getMean() +
293          ", min age=" + snapshot.getMin() +
294          ", max age=" + snapshot.getMax() +
295          ", 75th percentile age="   + snapshot.get75thPercentile() +
296          ", 95th percentile age="   + snapshot.get95thPercentile() +
297          ", 98th percentile age="   + snapshot.get98thPercentile() +
298          ", 99th percentile age="   + snapshot.get99thPercentile() +
299          ", 99.9th percentile age=" + snapshot.get99thPercentile();
300    }
301  }
302}