View Javadoc

1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    *
9    *      http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  package org.apache.hadoop.hbase.util;
18  
19  import java.io.BufferedWriter;
20  import java.io.Closeable;
21  import java.io.IOException;
22  import java.io.PrintWriter;
23  import java.io.StringWriter;
24  import java.lang.management.ManagementFactory;
25  import java.lang.reflect.Array;
26  import java.util.Iterator;
27  import java.util.Set;
28  
29  import javax.management.AttributeNotFoundException;
30  import javax.management.InstanceNotFoundException;
31  import javax.management.IntrospectionException;
32  import javax.management.MBeanAttributeInfo;
33  import javax.management.MBeanException;
34  import javax.management.MBeanInfo;
35  import javax.management.MBeanServer;
36  import javax.management.MalformedObjectNameException;
37  import javax.management.ObjectName;
38  import javax.management.ReflectionException;
39  import javax.management.RuntimeErrorException;
40  import javax.management.RuntimeMBeanException;
41  import javax.management.openmbean.CompositeData;
42  import javax.management.openmbean.CompositeType;
43  import javax.management.openmbean.TabularData;
44  
45  import org.apache.commons.logging.Log;
46  import org.apache.commons.logging.LogFactory;
47  import org.apache.hbase.thirdparty.com.google.gson.Gson;
48  import org.apache.hbase.thirdparty.com.google.gson.stream.JsonWriter;
49  
50  /**
51   * Utility for doing JSON and MBeans.
52   */
53  public class JSONBean {
54    private static final Log LOG = LogFactory.getLog(JSONBean.class);
55    private static final Gson GSON = GsonUtil.createGson().create();
56  
57    /**
58     * Use dumping out mbeans as JSON.
59     */
60    public interface Writer extends Closeable {
61  
62      void write(final String key, final String value) throws IOException;
63  
64      int write(final MBeanServer mBeanServer, final ObjectName qry, final String attribute,
65        final boolean description) throws IOException;
66  
67      void flush() throws IOException;
68    }
69  
70    /**
71     * Notice that, closing the return {@link Writer} will not close the {@code writer} passed in, you
72     * still need to close the {@code writer} by yourself.
73     * <p/>
74     * This is because that, we can only finish the json after you call {@link Writer#close()}. So if
75     * we just close the {@code writer}, you can write nothing after finished the json.
76     */
77    public Writer open(final PrintWriter writer) throws IOException {
78      final JsonWriter jsonWriter = GSON.newJsonWriter(new java.io.Writer() {
79  
80        @Override
81        public void write(char[] cbuf, int off, int len) throws IOException {
82          writer.write(cbuf, off, len);
83        }
84  
85        @Override
86        public void flush() throws IOException {
87          writer.flush();
88        }
89  
90        @Override
91        public void close() throws IOException {
92          // do nothing
93        }
94      });
95      jsonWriter.setIndent("  ");
96      jsonWriter.beginObject();
97      return new Writer() {
98        @Override
99        public void flush() throws IOException {
100         jsonWriter.flush();
101       }
102 
103       @Override
104       public void close() throws IOException {
105         jsonWriter.endObject();
106         jsonWriter.close();
107       }
108 
109       @Override
110       public void write(String key, String value) throws IOException {
111         jsonWriter.name(key).value(value);
112       }
113 
114       @Override
115       public int write(MBeanServer mBeanServer, ObjectName qry, String attribute,
116           boolean description) throws IOException {
117         return JSONBean.write(jsonWriter, mBeanServer, qry, attribute, description);
118       }
119     };
120   }
121 
122   /**
123    * @param mBeanServer
124    * @param qry
125    * @param attribute
126    * @param description
127    * @return Return non-zero if failed to find bean. 0
128    * @throws IOException
129    */
130   private static int write(final JsonWriter writer, final MBeanServer mBeanServer,
131       final ObjectName qry, final String attribute, final boolean description) throws IOException {
132 
133     LOG.trace("Listing beans for " + qry);
134     Set<ObjectName> names = null;
135     names = mBeanServer.queryNames(qry, null);
136     writer.name("beans").beginArray();
137     Iterator<ObjectName> it = names.iterator();
138     while (it.hasNext()) {
139       ObjectName oname = it.next();
140       MBeanInfo minfo;
141       String code = "";
142       String descriptionStr = null;
143       Object attributeinfo = null;
144       try {
145         minfo = mBeanServer.getMBeanInfo(oname);
146         code = minfo.getClassName();
147         if (description) {
148           descriptionStr = minfo.getDescription();
149         }
150         String prs = "";
151         try {
152           if ("org.apache.commons.modeler.BaseModelMBean".equals(code)) {
153             prs = "modelerType";
154             code = (String) mBeanServer.getAttribute(oname, prs);
155           }
156           if (attribute != null) {
157             prs = attribute;
158             attributeinfo = mBeanServer.getAttribute(oname, prs);
159           }
160         } catch (RuntimeMBeanException e) {
161           // UnsupportedOperationExceptions happen in the normal course of business,
162           // so no need to log them as errors all the time.
163           if (e.getCause() instanceof UnsupportedOperationException) {
164             if (LOG.isTraceEnabled()) {
165               LOG.trace("Getting attribute " + prs + " of " + oname + " threw " + e);
166             }
167           } else {
168             LOG.error("Getting attribute " + prs + " of " + oname + " threw an exception", e);
169           }
170           return 0;
171         } catch (AttributeNotFoundException e) {
172           // If the modelerType attribute was not found, the class name is used
173           // instead.
174           LOG.error("getting attribute " + prs + " of " + oname
175               + " threw an exception", e);
176         } catch (MBeanException e) {
177           // The code inside the attribute getter threw an exception so log it,
178           // and fall back on the class name
179           LOG.error("getting attribute " + prs + " of " + oname
180               + " threw an exception", e);
181         } catch (RuntimeException e) {
182           // For some reason even with an MBeanException available to them
183           // Runtime exceptionscan still find their way through, so treat them
184           // the same as MBeanException
185           LOG.error("getting attribute " + prs + " of " + oname
186               + " threw an exception", e);
187         } catch (ReflectionException e) {
188           // This happens when the code inside the JMX bean (setter?? from the
189           // java docs) threw an exception, so log it and fall back on the
190           // class name
191           LOG.error("getting attribute " + prs + " of " + oname
192               + " threw an exception", e);
193         }
194       } catch (InstanceNotFoundException e) {
195         //Ignored for some reason the bean was not found so don't output it
196         continue;
197       } catch (IntrospectionException e) {
198         // This is an internal error, something odd happened with reflection so
199         // log it and don't output the bean.
200         LOG.error("Problem while trying to process JMX query: " + qry
201             + " with MBean " + oname, e);
202         continue;
203       } catch (ReflectionException e) {
204         // This happens when the code inside the JMX bean threw an exception, so
205         // log it and don't output the bean.
206         LOG.error("Problem while trying to process JMX query: " + qry
207             + " with MBean " + oname, e);
208         continue;
209       }
210 
211       writer.beginObject();
212       writer.name("name").value(oname.toString());
213       if (description && descriptionStr != null && descriptionStr.length() > 0) {
214         writer.name("description").value(descriptionStr);
215       }
216       writer.name("modelerType").value(code);
217       if (attribute != null && attributeinfo == null) {
218         writer.name("result").value("ERROR");
219         writer.name("message").value("No attribute with name " + attribute + " was found.");
220         writer.endObject();
221         writer.endArray();
222         writer.close();
223         return -1;
224       }
225 
226       if (attribute != null) {
227         writeAttribute(writer, attribute, descriptionStr, attributeinfo);
228       } else {
229         MBeanAttributeInfo[] attrs = minfo.getAttributes();
230         for (int i = 0; i < attrs.length; i++) {
231           writeAttribute(writer, mBeanServer, oname, description, attrs[i]);
232         }
233       }
234       writer.endObject();
235     }
236     writer.endArray();
237     return 0;
238   }
239 
240   private static void writeAttribute(final JsonWriter writer, final MBeanServer mBeanServer,
241       final ObjectName oname, final boolean description, final MBeanAttributeInfo attr)
242       throws IOException {
243     if (!attr.isReadable()) {
244       return;
245     }
246     String attName = attr.getName();
247     if ("modelerType".equals(attName)) {
248       return;
249     }
250     if (attName.indexOf("=") >= 0 || attName.indexOf(":") >= 0 || attName.indexOf(" ") >= 0) {
251       return;
252     }
253     String descriptionStr = description? attr.getDescription(): null;
254     Object value = null;
255     try {
256       value = mBeanServer.getAttribute(oname, attName);
257     } catch (RuntimeMBeanException e) {
258       // UnsupportedOperationExceptions happen in the normal course of business,
259       // so no need to log them as errors all the time.
260       if (e.getCause() instanceof UnsupportedOperationException) {
261         if (LOG.isTraceEnabled()) {
262           LOG.trace("Getting attribute " + attName + " of " + oname + " threw " + e);
263         }
264       } else {
265         LOG.error("getting attribute "+attName+" of "+oname+" threw an exception", e);
266       }
267       return;
268     } catch (RuntimeErrorException e) {
269       // RuntimeErrorException happens when an unexpected failure occurs in getAttribute
270       // for example https://issues.apache.org/jira/browse/DAEMON-120
271       LOG.debug("getting attribute "+attName+" of "+oname+" threw an exception", e);
272       return;
273     } catch (AttributeNotFoundException e) {
274       //Ignored the attribute was not found, which should never happen because the bean
275       //just told us that it has this attribute, but if this happens just don't output
276       //the attribute.
277       return;
278     } catch (MBeanException e) {
279       //The code inside the attribute getter threw an exception so log it, and
280       // skip outputting the attribute
281       LOG.error("getting attribute "+attName+" of "+oname+" threw an exception", e);
282       return;
283     } catch (RuntimeException e) {
284       //For some reason even with an MBeanException available to them Runtime exceptions
285       //can still find their way through, so treat them the same as MBeanException
286       LOG.error("getting attribute "+attName+" of "+oname+" threw an exception", e);
287       return;
288     } catch (ReflectionException e) {
289       //This happens when the code inside the JMX bean (setter?? from the java docs)
290       //threw an exception, so log it and skip outputting the attribute
291       LOG.error("getting attribute "+attName+" of "+oname+" threw an exception", e);
292       return;
293     } catch (InstanceNotFoundException e) {
294       //Ignored the mbean itself was not found, which should never happen because we
295       //just accessed it (perhaps something unregistered in-between) but if this
296       //happens just don't output the attribute.
297       return;
298     }
299 
300     writeAttribute(writer, attName, descriptionStr, value);
301   }
302 
303   private static void writeAttribute(JsonWriter writer, String attName, String descriptionStr,
304     Object value) throws IOException {
305     boolean description = false;
306     if (descriptionStr != null && descriptionStr.length() > 0 && !attName.equals(descriptionStr)) {
307       writer.name(attName);
308       writer.beginObject();
309       writer.name("description").value(descriptionStr);
310       writer.name("value");
311       writeObject(writer, value);
312       writer.endObject();
313     } else {
314       writer.name(attName);
315       writeObject(writer, value);
316     }
317   }
318 
319   private static void writeObject(final JsonWriter writer, final Object value) throws IOException {
320     if (value == null) {
321       writer.nullValue();
322     } else {
323       Class<?> c = value.getClass();
324       if (c.isArray()) {
325         writer.beginArray();
326         int len = Array.getLength(value);
327         for (int j = 0; j < len; j++) {
328           Object item = Array.get(value, j);
329           writeObject(writer, item);
330         }
331         writer.endArray();
332       } else if(value instanceof Number) {
333         Number n = (Number)value;
334         double doubleValue = n.doubleValue();
335         if (Double.isNaN(doubleValue) || Double.isInfinite(doubleValue)) {
336           writer.value(n);
337         } else {
338           writer.value(n.toString());
339         }
340       } else if(value instanceof Boolean) {
341         Boolean b = (Boolean)value;
342         writer.value(b);
343       } else if(value instanceof CompositeData) {
344         CompositeData cds = (CompositeData)value;
345         CompositeType comp = cds.getCompositeType();
346         Set<String> keys = comp.keySet();
347         writer.beginObject();
348         for (String key : keys) {
349           writeAttribute(writer, key, null, cds.get(key));
350         }
351         writer.endObject();
352       } else if(value instanceof TabularData) {
353         TabularData tds = (TabularData)value;
354         writer.beginArray();
355         for (Object entry : tds.values()) {
356           writeObject(writer, entry);
357         }
358         writer.endArray();
359       } else {
360         writer.value(value.toString());
361       }
362     }
363   }
364 
365   /**
366    * Dump out a subset of regionserver mbeans only, not all of them, as json on System.out.
367    * @throws MalformedObjectNameException
368    * @throws IOException
369    */
370   public static String dumpRegionServerMetrics() throws MalformedObjectNameException, IOException {
371     StringWriter sw = new StringWriter(1024 * 100); // Guess this size
372     try (PrintWriter writer = new PrintWriter(sw)) {
373       JSONBean dumper = new JSONBean();
374       try (JSONBean.Writer jsonBeanWriter = dumper.open(writer)) {
375         MBeanServer mbeanServer = ManagementFactory.getPlatformMBeanServer();
376         jsonBeanWriter.write(mbeanServer,
377           new ObjectName("java.lang:type=Memory"), null, false);
378         jsonBeanWriter.write(mbeanServer,
379           new ObjectName("Hadoop:service=HBase,name=RegionServer,sub=IPC"), null, false);
380         jsonBeanWriter.write(mbeanServer,
381           new ObjectName("Hadoop:service=HBase,name=RegionServer,sub=Replication"), null, false);
382         jsonBeanWriter.write(mbeanServer,
383           new ObjectName("Hadoop:service=HBase,name=RegionServer,sub=Server"), null, false);
384       }
385     }
386     sw.close();
387     return sw.toString();
388   }
389 
390   /**
391    * Dump out all registered mbeans as json on System.out.
392    * @throws IOException
393    * @throws MalformedObjectNameException
394    */
395   public static void dumpAllBeans() throws IOException, MalformedObjectNameException {
396     try (PrintWriter writer = new PrintWriter(System.out)) {
397       JSONBean dumper = new JSONBean();
398       try (JSONBean.Writer jsonBeanWriter = dumper.open(writer)) {
399         MBeanServer mbeanServer = ManagementFactory.getPlatformMBeanServer();
400         jsonBeanWriter.write(mbeanServer, new ObjectName("*:*"), null, false);
401       }
402     }
403   }
404 
405   public static void main(String[] args) throws IOException, MalformedObjectNameException {
406     String str = dumpRegionServerMetrics();
407     System.out.println(str);
408   }
409 }