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 java.io.IOException;
21  import java.util.NavigableMap;
22  import java.util.NavigableSet;
23  import java.util.concurrent.ConcurrentSkipListMap;
24  import java.util.concurrent.ConcurrentSkipListSet;
25  
26  import org.apache.hadoop.hbase.classification.InterfaceAudience;
27  import org.apache.hadoop.conf.Configuration;
28  import org.apache.hadoop.hbase.util.FastLongHistogram;
29  import org.apache.hadoop.hbase.util.GsonUtil;
30  
31  
32  import org.apache.hbase.thirdparty.com.google.gson.Gson;
33  import org.apache.hbase.thirdparty.com.google.gson.TypeAdapter;
34  import org.apache.hbase.thirdparty.com.google.gson.stream.JsonReader;
35  import org.apache.hbase.thirdparty.com.google.gson.stream.JsonWriter;
36  
37  /**
38   * Utilty for aggregating counts in CachedBlocks and toString/toJSON CachedBlocks and BlockCaches.
39   * No attempt has been made at making this thread safe.
40   */
41  @InterfaceAudience.Private
42  public class BlockCacheUtil {
43    /**
44     * Needed generating JSON.
45     */
46    private static final Gson GSON = GsonUtil.createGson()
47      .registerTypeAdapter(FastLongHistogram.class, new TypeAdapter<FastLongHistogram>() {
48  
49        @Override
50        public void write(JsonWriter out, FastLongHistogram value) throws IOException {
51          AgeSnapshot snapshot = new AgeSnapshot(value);
52          out.beginObject();
53          out.name("mean").value(snapshot.getMean());
54          out.name("min").value(snapshot.getMin());
55          out.name("max").value(snapshot.getMax());
56          out.name("75thPercentile").value(snapshot.get75thPercentile());
57          out.name("95thPercentile").value(snapshot.get95thPercentile());
58          out.name("98thPercentile").value(snapshot.get98thPercentile());
59          out.name("99thPercentile").value(snapshot.get99thPercentile());
60          out.name("999thPercentile").value(snapshot.get999thPercentile());
61          out.endObject();
62        }
63  
64        @Override
65        public FastLongHistogram read(JsonReader in) throws IOException {
66          throw new UnsupportedOperationException();
67        }
68      }).setPrettyPrinting().create();
69  
70    /**
71     * @param cb
72     * @return The block content as String.
73     */
74    public static String toString(final CachedBlock cb, final long now) {
75      return "filename=" + cb.getFilename() + ", " + toStringMinusFileName(cb, now);
76    }
77  
78    /**
79     * Little data structure to hold counts for a file.
80     * Used doing a toJSON.
81     */
82    static class CachedBlockCountsPerFile {
83      private int count = 0;
84      private long size = 0;
85      private int countData = 0;
86      private long sizeData = 0;
87      private final String filename;
88  
89      CachedBlockCountsPerFile(final String filename) {
90        this.filename = filename;
91      }
92  
93      public int getCount() {
94        return count;
95      }
96  
97      public long getSize() {
98        return size;
99      }
100 
101     public int getCountData() {
102       return countData;
103     }
104 
105     public long getSizeData() {
106       return sizeData;
107     }
108 
109     public String getFilename() {
110       return filename;
111     }
112   }
113 
114   /**
115    * @return A JSON String of <code>filename</code> and counts of <code>blocks</code>
116    */
117   public static String toJSON(final String filename, final NavigableSet<CachedBlock> blocks)
118       throws IOException {
119     CachedBlockCountsPerFile counts = new CachedBlockCountsPerFile(filename);
120     for (CachedBlock cb: blocks) {
121       counts.count++;
122       counts.size += cb.getSize();
123       BlockType bt = cb.getBlockType();
124       if (bt != null && bt.isData()) {
125         counts.countData++;
126         counts.sizeData += cb.getSize();
127       }
128     }
129     return GSON.toJson(counts);
130   }
131 
132   /**
133    * @return JSON string of <code>cbsf</code> aggregated
134    */
135   public static String toJSON(final CachedBlocksByFile cbsbf) throws IOException {
136     return GSON.toJson(cbsbf);
137   }
138 
139   /**
140    * @return JSON string of <code>bc</code> content.
141    */
142   public static String toJSON(final BlockCache bc) throws IOException {
143     return GSON.toJson(bc);
144   }
145 
146   /**
147    * @param cb
148    * @return The block content of <code>bc</code> as a String minus the filename.
149    */
150   public static String toStringMinusFileName(final CachedBlock cb, final long now) {
151     return "offset=" + cb.getOffset() +
152       ", size=" + cb.getSize() +
153       ", age=" + (now - cb.getCachedTime()) +
154       ", type=" + cb.getBlockType() +
155       ", priority=" + cb.getBlockPriority();
156   }
157 
158   /**
159    * Get a {@link CachedBlocksByFile} instance and load it up by iterating content in
160    * {@link BlockCache}.
161    * @param conf Used to read configurations
162    * @param bc Block Cache to iterate.
163    * @return Laoded up instance of CachedBlocksByFile
164    */
165   public static CachedBlocksByFile getLoadedCachedBlocksByFile(final Configuration conf,
166       final BlockCache bc) {
167     CachedBlocksByFile cbsbf = new CachedBlocksByFile(conf);
168     for (CachedBlock cb: bc) {
169       if (cbsbf.update(cb)) break;
170     }
171     return cbsbf;
172   }
173 
174   /**
175    * Use one of these to keep a running account of cached blocks by file.  Throw it away when done.
176    * This is different than metrics in that it is stats on current state of a cache.
177    * See getLoadedCachedBlocksByFile
178    */
179   public static class CachedBlocksByFile {
180     private int count;
181     private int dataBlockCount;
182     private long size;
183     private long dataSize;
184     private final long now = System.nanoTime();
185     /**
186      * How many blocks to look at before we give up.
187      * There could be many millions of blocks. We don't want the
188      * ui to freeze while we run through 1B blocks... users will
189      * think hbase dead. UI displays warning in red when stats
190      * are incomplete.
191      */
192     private final int max;
193     public static final int DEFAULT_MAX = 1000000;
194 
195     CachedBlocksByFile() {
196       this(null);
197     }
198 
199     CachedBlocksByFile(final Configuration c) {
200       this.max = c == null? DEFAULT_MAX: c.getInt("hbase.ui.blockcache.by.file.max", DEFAULT_MAX);
201     }
202 
203     /**
204      * Map by filename. use concurent utils because we want our Map and contained blocks sorted.
205      */
206     private transient NavigableMap<String, NavigableSet<CachedBlock>> cachedBlockByFile =
207       new ConcurrentSkipListMap<String, NavigableSet<CachedBlock>>();
208     FastLongHistogram hist = new FastLongHistogram();
209 
210     /**
211      * @param cb
212      * @return True if full.... if we won't be adding any more.
213      */
214     public boolean update(final CachedBlock cb) {
215       if (isFull()) return true;
216       NavigableSet<CachedBlock> set = this.cachedBlockByFile.get(cb.getFilename());
217       if (set == null) {
218         set = new ConcurrentSkipListSet<CachedBlock>();
219         this.cachedBlockByFile.put(cb.getFilename(), set);
220       }
221       set.add(cb);
222       this.size += cb.getSize();
223       this.count++;
224       BlockType bt = cb.getBlockType();
225       if (bt != null && bt.isData()) {
226         this.dataBlockCount++;
227         this.dataSize += cb.getSize();
228       }
229       long age = this.now - cb.getCachedTime();
230       this.hist.add(age, 1);
231       return false;
232     }
233 
234     /**
235      * @return True if full; i.e. there are more items in the cache but we only loaded up
236      * the maximum set in configuration <code>hbase.ui.blockcache.by.file.max</code>
237      * (Default: DEFAULT_MAX).
238      */
239     public boolean isFull() {
240       return this.count >= this.max;
241     }
242 
243     public NavigableMap<String, NavigableSet<CachedBlock>> getCachedBlockStatsByFile() {
244       return this.cachedBlockByFile;
245     }
246 
247     /**
248      * @return count of blocks in the cache
249      */
250     public int getCount() {
251       return count;
252     }
253 
254     public int getDataCount() {
255       return dataBlockCount;
256     }
257 
258     /**
259      * @return size of blocks in the cache
260      */
261     public long getSize() {
262       return size;
263     }
264 
265     /**
266      * @return Size of data.
267      */
268     public long getDataSize() {
269       return dataSize;
270     }
271 
272     public AgeSnapshot getAgeInCacheSnapshot() {
273       return new AgeSnapshot(this.hist);
274     }
275 
276     @Override
277     public String toString() {
278       AgeSnapshot snapshot = getAgeInCacheSnapshot();
279       return "count=" + count + ", dataBlockCount=" + dataBlockCount + ", size=" + size +
280           ", dataSize=" + getDataSize() +
281           ", mean age=" + snapshot.getMean() +
282           ", min age=" + snapshot.getMin() +
283           ", max age=" + snapshot.getMax() +
284           ", 75th percentile age="   + snapshot.get75thPercentile() +
285           ", 95th percentile age="   + snapshot.get95thPercentile() +
286           ", 98th percentile age="   + snapshot.get98thPercentile() +
287           ", 99th percentile age="   + snapshot.get99thPercentile() +
288           ", 99.9th percentile age=" + snapshot.get99thPercentile();
289     }
290   }
291 }