/** * Get full MBean name with given bean name, domain and session * * @param bean Name of bean. It can be NULL so that session#getBean() is returned * @param domain Domain for bean * @param session Current session * @return Full qualified name of MBean * @throws JMException Thrown when given MBean name is malformed * @throws IOException */ public static String getBeanName(String bean, String domain, Session session) throws JMException, IOException { Validate.notNull(session, "Session can't be NULL"); if (bean == null) { return session.getBean(); } if (SyntaxUtils.isNull(bean)) { return null; } MBeanServerConnection con = session.getConnection().getServerConnection(); if (bean.indexOf(':') != -1) { try { ObjectName name = new ObjectName(bean); con.getMBeanInfo(name); return bean; } catch (MalformedObjectNameException e) { } catch (InstanceNotFoundException e) { } } String domainName = DomainCommand.getDomainName(domain, session); if (domainName == null) { throw new IllegalArgumentException( "Please specify domain using either -d option or domain command"); } try { ObjectName name = new ObjectName(domainName + ":" + bean); con.getMBeanInfo(name); return domainName + ":" + bean; } catch (MalformedObjectNameException e) { } catch (InstanceNotFoundException e) { } throw new IllegalArgumentException("Bean name " + bean + " isn't valid"); }
@Override public MBeanInfo getMBeanInfo(ObjectName name) throws InstanceNotFoundException, IntrospectionException, ReflectionException, IOException { try { return connection.getMBeanInfo(name); } catch (IOException e) { checkConnection(); return connection.getMBeanInfo(name); } }
/** List all MBeans and their attributes. */ public static void listMBeans(MBeanServerConnection server) throws IOException { final Set names = server.queryNames(null, null); for (final Iterator i = names.iterator(); i.hasNext(); ) { ObjectName name = (ObjectName) i.next(); System.out.println("Got MBean: " + name); try { MBeanInfo info = server.getMBeanInfo((ObjectName) name); MBeanAttributeInfo[] attrs = info.getAttributes(); if (attrs == null) continue; for (int j = 0; j < attrs.length; j++) { if (attrs[j].isReadable()) { try { Object o = server.getAttribute(name, attrs[j].getName()); System.out.println("\t\t" + attrs[j].getName() + " = " + o); } catch (Exception x) { System.err.println("JmxClient failed to get " + attrs[j].getName()); x.printStackTrace(System.err); } } } } catch (Exception x) { System.err.println("JmxClient failed to get MBeanInfo: " + x); x.printStackTrace(System.err); } } }
protected Result describeMbean( @Nonnull MBeanServerConnection mbeanServer, @Nonnull ObjectName objectName) throws IntrospectionException, ReflectionException, InstanceNotFoundException, IOException { MBeanInfo mbeanInfo = mbeanServer.getMBeanInfo(objectName); StringWriter sw = new StringWriter(); PrintWriter out = new PrintWriter(sw); out.println("# MBEAN"); out.println(objectName.toString()); out.println(); out.println("## OPERATIONS"); List<MBeanOperationInfo> operations = Arrays.asList(mbeanInfo.getOperations()); Collections.sort( operations, new Comparator<MBeanOperationInfo>() { @Override public int compare(MBeanOperationInfo o1, MBeanOperationInfo o2) { return o1.getName().compareTo(o1.getName()); } }); for (MBeanOperationInfo opInfo : operations) { out.print("* " + opInfo.getName() + "("); MBeanParameterInfo[] signature = opInfo.getSignature(); for (int i = 0; i < signature.length; i++) { MBeanParameterInfo paramInfo = signature[i]; out.print(paramInfo.getType() + " " + paramInfo.getName()); if (i < signature.length - 1) { out.print(", "); } } out.print("):" + opInfo.getReturnType() /* + " - " + opInfo.getDescription() */); out.println(); } out.println(); out.println("## ATTRIBUTES"); List<MBeanAttributeInfo> attributes = Arrays.asList(mbeanInfo.getAttributes()); Collections.sort( attributes, new Comparator<MBeanAttributeInfo>() { @Override public int compare(MBeanAttributeInfo o1, MBeanAttributeInfo o2) { return o1.getName().compareTo(o2.getName()); } }); for (MBeanAttributeInfo attrInfo : attributes) { out.println( "* " + attrInfo.getName() + ": " + attrInfo.getType() + " - " + (attrInfo.isReadable() ? "r" : "") + (attrInfo.isWritable() ? "w" : "") /* + " - " + attrInfo.getDescription() */); } String description = sw.getBuffer().toString(); return new Result(objectName, description, description); }
public MBeanInfo getMBeanInfo(ObjectName objectName) throws InstanceNotFoundException, IntrospectionException, IOException { try { return mBeanServerConnection.getMBeanInfo(objectName); } catch (ReflectionException e) { Activator.getDefault().error("Cannot reflect the MBeanInfo:", e); throw new IOException(e); } }
/** Returns the MBeanInfo for the mbean. */ @Name("mbean_info") public MBeanInfo getMbean_info() { try { if (_info == null) _info = _server.getMBeanInfo(_name); return _info; } catch (Exception e) { log.log(Level.FINE, e.toString(), e); return null; } }
public GroovyMBean(MBeanServerConnection server, ObjectName name, boolean ignoreErrors) throws JMException, IOException { this.server = server; this.name = name; this.ignoreErrors = ignoreErrors; this.beanInfo = server.getMBeanInfo(name); MBeanOperationInfo[] operationInfos = beanInfo.getOperations(); for (MBeanOperationInfo info : operationInfos) { String signature[] = createSignature(info); // Construct a simplistic key to support overloaded operations on the MBean. String operationKey = createOperationKey(info.getName(), signature.length); operations.put(operationKey, signature); } }
@SuppressWarnings("unchecked") private void listAll() throws IOException, InstanceNotFoundException, IntrospectionException, ReflectionException { Set<ObjectName> mbeans = connection.queryNames(null, null); for (ObjectName name : mbeans) { MBeanInfo info = connection.getMBeanInfo(name); MBeanAttributeInfo[] attrs = info.getAttributes(); String[] attrNames = new String[attrs.length]; for (int i = 0; i < attrs.length; i++) { attrNames[i] = attrs[i].getName(); } try { List<Attribute> attributes = connection.getAttributes(name, attrNames).asList(); for (Attribute attribute : attributes) { output(name.getCanonicalName() + "%" + attribute.getName(), attribute.getValue()); } } catch (Exception e) { System.err.println("error getting " + name + ":" + e.getMessage()); } } }
public void walkTree(MBeanServerConnection connection, Server server) throws Exception { // key here is null, null returns everything! Set<ObjectName> mbeans = connection.queryNames(null, null); Map<String, String> output = newHashMap(); for (ObjectName name : mbeans) { MBeanInfo info = connection.getMBeanInfo(name); MBeanAttributeInfo[] attrs = info.getAttributes(); Query.Builder queryBuilder = Query.builder().setObj(name.getCanonicalName()); ResultCapture resultCapture = new ResultCapture(); queryBuilder.addOutputWriter(resultCapture); for (MBeanAttributeInfo attrInfo : attrs) { queryBuilder.addAttr(attrInfo.getName()); } Query query = queryBuilder.build(); try { Iterable<Result> results = server.execute(query); query.runOutputWritersForQuery(server, results); } catch (AttributeNotFoundException anfe) { log.error("Error", anfe); } for (Result result : resultCapture.results) { output.put(result.getTypeName(), query.getAttr().toString()); } } for (Entry<String, String> entry : output.entrySet()) { log.debug(entry.getKey()); log.debug(entry.getValue()); log.debug("-----------------------------------------"); } }
/** @inheritDoc */ @Override public void execute() throws IOException, JMException { Session session = getSession(); if (bean == null) { if (session.getBean() == null) { session.output.println(SyntaxUtils.NULL); } else { session.output.println(session.getBean()); } return; } String beanName = getBeanName(bean, domain, session); if (beanName == null) { session.setBean(null); session.output.printMessage("bean is unset"); return; } ObjectName name = new ObjectName(beanName); MBeanServerConnection con = session.getConnection().getServerConnection(); con.getMBeanInfo(name); session.setBean(beanName); session.output.printMessage("bean is set to " + beanName); }
/** * Query the mbean connection and add all metrics that satisfy the filter to the list {@code * metrics}. */ private void getMetrics( MBeanServerConnection con, MetricFilter filter, List<Metric> metrics, ObjectName name) throws JMException, IOException { // Create tags from the object name TagList tags = createTagList(name); MBeanInfo info = con.getMBeanInfo(name); MBeanAttributeInfo[] attrInfos = info.getAttributes(); // Restrict to attributes that match the filter List<String> matchingNames = Lists.newArrayList(); for (MBeanAttributeInfo attrInfo : attrInfos) { String attrName = attrInfo.getName(); if (filter.matches(new MonitorConfig.Builder(attrName).withTags(tags).build())) { matchingNames.add(attrName); } } List<Attribute> attributeList = safelyLoadAttributes(con, name, matchingNames); for (Attribute attr : attributeList) { String attrName = attr.getName(); Object obj = attr.getValue(); if (obj instanceof CompositeData) { Map<String, Object> values = Maps.newHashMap(); extractValues(null, values, (CompositeData) obj); for (Map.Entry<String, Object> e : values.entrySet()) { String key = e.getKey(); TagList newTags = SortedTagList.builder().withTags(tags).withTag(COMPOSITE_PATH_KEY, key).build(); if (filter.matches(MonitorConfig.builder(attrName).withTags(newTags).build())) { addMetric(metrics, attrName, newTags, e.getValue()); } } } else { addMetric(metrics, attrName, tags, obj); } } }
@Nullable public Result invokeOperation( @Nonnull MBeanServerConnection mBeanServer, @Nonnull ObjectName on, @Nonnull String operationName, @Nonnull String... arguments) throws JMException, IOException { logger.debug("invokeOperation({},{}, {}, {})...", on, operationName, Arrays.asList(arguments)); MBeanInfo mbeanInfo = mBeanServer.getMBeanInfo(on); List<MBeanOperationInfo> candidates = new ArrayList<MBeanOperationInfo>(); for (MBeanOperationInfo mbeanOperationInfo : mbeanInfo.getOperations()) { if (mbeanOperationInfo.getName().equals(operationName) && mbeanOperationInfo.getSignature().length == arguments.length) { candidates.add(mbeanOperationInfo); logger.debug("Select matching operation {}", mbeanOperationInfo); } else { logger.trace("Ignore non matching operation {}", mbeanOperationInfo); } } if (candidates.isEmpty()) { throw new IllegalArgumentException( "Operation '" + operationName + "(" + Strings2.join(arguments, ", ") + ")' NOT found on " + on); } else if (candidates.size() > 1) { throw new IllegalArgumentException( "More than 1 (" + candidates.size() + ") operation '" + operationName + "(" + Strings2.join(arguments, ", ") + ")' found on '" + on + "': " + candidates); } MBeanOperationInfo beanOperationInfo = candidates.get(0); MBeanParameterInfo[] mbeanParameterInfos = beanOperationInfo.getSignature(); List<String> signature = new ArrayList<String>(); for (MBeanParameterInfo mbeanParameterInfo : mbeanParameterInfos) { signature.add(mbeanParameterInfo.getType()); } Object[] convertedArguments = convertValues(arguments, signature); logger.debug("Invoke {}:{}({}) ...", on, operationName, Arrays.asList(convertedArguments)); Object result = mBeanServer.invoke(on, operationName, convertedArguments, signature.toArray(new String[0])); if ("void".equals(beanOperationInfo.getReturnType()) && result == null) { result = "void"; } logger.info( "Invoke {}:{}({}): {}", on, operationName, Arrays.asList(convertedArguments), result); String description = "Invoke operation " + on + ":" + operationName + "(" + Strings2.join(convertedArguments, ", ") + "): " + Strings2.toString(result); return new Result(on, result, description); }
/** * @param mbeanServer * @param objectName * @param attributeName * @param attributeValue if <code>null</code>, this is a read access. * @return if this is a read access, the returned value (may be null); if it is a write access, * return <code>void.class</code>. * @throws IOException * @throws JMException */ public Result invokeAttribute( @Nonnull MBeanServerConnection mbeanServer, @Nonnull ObjectName objectName, @Nonnull String attributeName, @Nullable String attributeValue) throws IOException, JMException { MBeanInfo mbeanInfo = mbeanServer.getMBeanInfo(objectName); MBeanAttributeInfo attributeInfo = null; for (MBeanAttributeInfo mai : mbeanInfo.getAttributes()) { if (mai.getName().equals(attributeName)) { attributeInfo = mai; break; } } if (attributeInfo == null) { throw new IllegalArgumentException( "No attribute '" + attributeName + "' found on '" + objectName + "'. Existing attributes: " + Arrays.asList(mbeanInfo.getAttributes())); } String description; Object resultValue; if (attributeValue == null) { if (attributeInfo.isReadable()) { Object attribute = mbeanServer.getAttribute(objectName, attributeName); logger.info("get attribute value {}:{}:{}", objectName, attributeName, attribute); resultValue = attribute; description = "Get attribute value " + objectName + ":" + attributeName + ": " + resultValue; } else { throw new IllegalArgumentException( "Attribute '" + attributeName + "' is not readable on '" + objectName + "': " + attributeInfo); } } else { if (attributeInfo.isWritable()) { Object value = convertValue(attributeValue, attributeInfo.getType()); mbeanServer.setAttribute(objectName, new Attribute(attributeName, value)); logger.info("set attribute value {}:{}:{}", objectName, attributeName, value); description = "Set attribute value " + objectName + ":" + attributeName + ": " + value; resultValue = void.class; } else { throw new IllegalArgumentException( "Attribute '" + attributeName + "' is not writable on '" + objectName + "': " + attributeInfo); } } return new Result(objectName, resultValue, description); }
private static String invokeJmx( String ip, String port, String newPort, String objectName, String methodName, String[] arguments) throws MalformedURLException, IOException, MalformedObjectNameException, InstanceNotFoundException, IntrospectionException, ReflectionException, MBeanException { try { if ("other".equals(port)) { port = newPort; } JMXServiceURL address = new JMXServiceURL( "service:jmx:rmi://" + ip + "/jndi/rmi://" + ip + ":" + port + "/defaultConnector"); JMXConnector connector = JMXConnectorFactory.connect(address); MBeanServerConnection mbs = connector.getMBeanServerConnection(); ObjectName mxbeanName = new ObjectName(objectName); // com.taobao.wlb:id=testJmxMBean,type=mywlb MBeanInfo mbeanInfo = mbs.getMBeanInfo(mxbeanName); MBeanOperationInfo[] opeInfos = mbeanInfo.getOperations(); for (MBeanOperationInfo o : opeInfos) { if (o.getName().equals(methodName)) { int length = o.getSignature().length; Object[] params = new Object[length]; String[] typeNames = new String[length]; for (int i = 0; i < length; i++) { if ("boolean".equals(o.getSignature()[i].getType())) { params[i] = Boolean.valueOf(arguments[i]); } else if ("int".equals(o.getSignature()[i].getType())) { params[i] = Integer.valueOf(arguments[i]); } else if ("java.lang.Integer".equals(o.getSignature()[i].getType())) { params[i] = Integer.valueOf(arguments[i]); } else if ("long".equals(o.getSignature()[i].getType())) { params[i] = Long.valueOf(arguments[i]); } else if ("java.lang.Long".equals(o.getSignature()[i].getType())) { params[i] = Long.valueOf(arguments[i]); } else if ("double".equals(o.getSignature()[i].getType())) { params[i] = Double.valueOf(arguments[i]); } else if ("java.lang.Double".equals(o.getSignature()[i].getType())) { params[i] = Double.valueOf(arguments[i]); } else { params[i] = arguments[i]; } typeNames[i] = o.getSignature()[i].getType(); } Object result = mbs.invoke(mxbeanName, methodName, params, typeNames); if (result == null) return null; return result.toString(); } } return "Jmx对象中没有该方法"; } catch (Exception e) { e.printStackTrace(); return "执行JMX异常:" + e.getMessage(); } }
private static boolean test(String proto, MBeanServer mbs, ObjectName on) throws Exception { System.out.println("Testing for protocol " + proto); JMXConnectorServer cs; JMXServiceURL url = new JMXServiceURL(proto, null, 0); try { cs = JMXConnectorServerFactory.newJMXConnectorServer(url, null, mbs); } catch (MalformedURLException e) { System.out.println("System does not recognize URL: " + url + "; ignoring"); return true; } cs.start(); JMXServiceURL addr = cs.getAddress(); JMXConnector client = JMXConnectorFactory.connect(addr); MBeanServerConnection mbsc = client.getMBeanServerConnection(); Object getAttributeExotic = mbsc.getAttribute(on, "Exotic"); AttributeList getAttrs = mbsc.getAttributes(on, new String[] {"Exotic"}); AttributeList setAttrs = new AttributeList(); setAttrs.add(new Attribute("Exotic", new Exotic())); setAttrs = mbsc.setAttributes(on, setAttrs); Object invokeExotic = mbsc.invoke(on, "anExotic", new Object[] {}, new String[] {}); MBeanInfo exoticMBI = mbsc.getMBeanInfo(on); mbsc.setAttribute(on, new Attribute("Exception", Boolean.TRUE)); Exception getAttributeException, setAttributeException, invokeException; try { try { mbsc.getAttribute(on, "Exotic"); throw noException("getAttribute"); } catch (Exception e) { getAttributeException = e; } try { mbsc.setAttribute(on, new Attribute("Exotic", new Exotic())); throw noException("setAttribute"); } catch (Exception e) { setAttributeException = e; } try { mbsc.invoke(on, "anExotic", new Object[] {}, new String[] {}); throw noException("invoke"); } catch (Exception e) { invokeException = e; } } finally { mbsc.setAttribute(on, new Attribute("Exception", Boolean.FALSE)); } client.close(); cs.stop(); boolean ok = true; ok &= checkAttrs("getAttributes", getAttrs); ok &= checkAttrs("setAttributes", setAttrs); ok &= checkType("getAttribute", getAttributeExotic, Exotic.class); ok &= checkType("getAttributes", attrValue(getAttrs), Exotic.class); ok &= checkType("setAttributes", attrValue(setAttrs), Exotic.class); ok &= checkType("invoke", invokeExotic, Exotic.class); ok &= checkType("getMBeanInfo", exoticMBI, ExoticMBeanInfo.class); ok &= checkExceptionType("getAttribute", getAttributeException, ExoticException.class); ok &= checkExceptionType("setAttribute", setAttributeException, ExoticException.class); ok &= checkExceptionType("invoke", invokeException, ExoticException.class); if (ok) System.out.println("Test passes for protocol " + proto); return ok; }