private static boolean test(String proto, MBeanServer mbs) throws Exception { System.out.println("Testing for proto " + 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(); JMXServiceURL rmiurl = new JMXServiceURL("rmi", null, 0); JMXConnector client = JMXConnectorFactory.connect(addr); MBeanServerConnection mbsc = client.getMBeanServerConnection(); ObjectName on = new ObjectName("x:proto=" + proto + ",ok=yes"); mbsc.createMBean( RMIConnectorServer.class.getName(), on, mletName, new Object[] {rmiurl, null}, new String[] {JMXServiceURL.class.getName(), Map.class.getName()}); System.out.println("Successfully deserialized with " + proto); mbsc.unregisterMBean(on); client.close(); cs.stop(); return true; }
/** Constructs a PrintGCStat object to monitor a remote JVM. */ public PrintGCStat(MBeanServerConnection server) throws IOException { // Create the platform mxbean proxies this.rmbean = newPlatformMXBeanProxy(server, RUNTIME_MXBEAN_NAME, RuntimeMXBean.class); this.mmbean = newPlatformMXBeanProxy(server, MEMORY_MXBEAN_NAME, MemoryMXBean.class); ObjectName poolName = null; ObjectName gcName = null; try { poolName = new ObjectName(MEMORY_POOL_MXBEAN_DOMAIN_TYPE + ",*"); gcName = new ObjectName(GARBAGE_COLLECTOR_MXBEAN_DOMAIN_TYPE + ",*"); } catch (MalformedObjectNameException e) { // should not reach here assert (false); } Set<ObjectName> mbeans = server.queryNames(poolName, null); if (mbeans != null) { pools = new ArrayList<MemoryPoolMXBean>(); for (ObjectName objName : mbeans) { MemoryPoolMXBean p = newPlatformMXBeanProxy(server, objName.getCanonicalName(), MemoryPoolMXBean.class); pools.add(p); } } mbeans = server.queryNames(gcName, null); if (mbeans != null) { gcmbeans = new ArrayList<GarbageCollectorMXBean>(); for (ObjectName objName : mbeans) { GarbageCollectorMXBean gc = newPlatformMXBeanProxy( server, objName.getCanonicalName(), GarbageCollectorMXBean.class); gcmbeans.add(gc); } } }
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 void setProperty(String property, Object value) { try { server.setAttribute(name, new Attribute(property, value)); } catch (MBeanException e) { throwExceptionWithTarget("Could not set property: " + property + ". Reason: ", e); } catch (Exception e) { throwException("Could not set property: " + property + ". Reason: ", e); } }
public Object getProperty(String property) { try { return server.getAttribute(name, property); } catch (MBeanException e) { throwExceptionWithTarget("Could not access property: " + property + ". Reason: ", e); } catch (Exception e) { if (!ignoreErrors) throwException("Could not access property: " + property + ". Reason: ", e); } return null; }
public static void main(String[] args) throws Exception { // TODO Auto-generated method stub if (args.length != 4) { System.err.println("Please provide process id zabbix-host zabbix-port host-guid"); System.exit(-1); } String processPid = args[0]; String zabbixHost = args[1]; String zabbixPort = args[2]; String hostGuid = args[3]; VirtualMachine vm = VirtualMachine.attach(processPid); String connectorAddr = vm.getAgentProperties().getProperty("com.sun.management.jmxremote.localConnectorAddress"); if (connectorAddr == null) { String agent = vm.getSystemProperties().getProperty("java.home") + File.separator + "lib" + File.separator + "management-agent.jar"; vm.loadAgent(agent); connectorAddr = vm.getAgentProperties().getProperty("com.sun.management.jmxremote.localConnectorAddress"); } JMXServiceURL serviceURL = new JMXServiceURL(connectorAddr); JMXConnector connector = JMXConnectorFactory.connect(serviceURL); MBeanServerConnection mbsc = connector.getMBeanServerConnection(); ObjectName objName = new ObjectName(ManagementFactory.THREAD_MXBEAN_NAME); Set<ObjectName> mbeans = mbsc.queryNames(objName, null); for (ObjectName name : mbeans) { ThreadMXBean threadBean; threadBean = ManagementFactory.newPlatformMXBeanProxy(mbsc, name.toString(), ThreadMXBean.class); long threadIds[] = threadBean.getAllThreadIds(); for (long threadId : threadIds) { ThreadInfo threadInfo = threadBean.getThreadInfo(threadId); System.out.println(threadInfo.getThreadName() + " / " + threadInfo.getThreadState()); } } }
private Object getAttribute(ObjectName objName, String attrName) throws MBeanException, InstanceNotFoundException, AttributeNotFoundException, ReflectionException, IOException { final NameValueMap values = getCachedAttributes(objName, Collections.singleton(attrName)); Object value = values.get(attrName); if (value != null || values.containsKey(attrName)) { return value; } // Not in cache, presumably because it was omitted from the // getAttributes result because of an exception. Following // call will probably provoke the same exception. return conn.getAttribute(objName, attrName); }
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); } }
private synchronized NameValueMap getCachedAttributes(ObjectName objName, Set<String> attrNames) throws InstanceNotFoundException, ReflectionException, IOException { NameValueMap values = cachedValues.get(objName); if (values != null && values.keySet().containsAll(attrNames)) { return values; } attrNames = new TreeSet<String>(attrNames); Set<String> oldNames = cachedNames.get(objName); if (oldNames != null) { attrNames.addAll(oldNames); } values = new NameValueMap(); final AttributeList attrs = conn.getAttributes(objName, attrNames.toArray(new String[attrNames.size()])); for (Attribute attr : attrs.asList()) { values.put(attr.getName(), attr.getValue()); } cachedValues.put(objName, values); cachedNames.put(objName, attrNames); return values; }
public Object invokeMethod(String method, Object arguments) { Object[] argArray; if (arguments instanceof Object[]) { argArray = (Object[]) arguments; } else { argArray = new Object[] {arguments}; } // Locate the specific method based on the name and number of parameters String operationKey = createOperationKey(method, argArray.length); String[] signature = operations.get(operationKey); if (signature != null) { try { return server.invoke(name, method, argArray, signature); } catch (MBeanException e) { throwExceptionWithTarget("Could not invoke method: " + method + ". Reason: ", e); } catch (Exception e) { throwException("Could not invoke method: " + method + ". Reason: ", e); } return null; } else { return super.invokeMethod(method, arguments); } }
@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); }
public Map<ObjectName, Result> process(JmxInvokerArguments arguments) throws IOException { String pid = (arguments.pid == null) ? Files2.readFile(arguments.pidFile, "US-ASCII") : arguments.pid; pid = pid.replace("\n", "").trim(); ObjectName on = arguments.objectName; String[] op = arguments.operation; String operationName = op == null || op.length == 0 ? null : op[0]; String[] operationArguments = op == null || op.length < 2 ? new String[0] : Arrays.copyOfRange(op, 1, op.length); String[] attr = arguments.attribute; String attributeName = attr == null || attr.length == 0 ? null : attr[0]; String attributeValue = attr == null || attr.length < 2 ? null : attr[1]; MBeanServerConnection mbeanServer = connectToMbeanServer(pid); Map<ObjectName, Result> results = new TreeMap<ObjectName, Result>(); Set<ObjectName> objectNames = mbeanServer.queryNames(on, null); if (objectNames.isEmpty()) { logger.warn("No mbean found for ObjectName {}", on); } for (ObjectName objectName : objectNames) { Result result; try { if (operationName != null) { result = invokeOperation(mbeanServer, objectName, operationName, operationArguments); } else if (attributeName != null) { result = invokeAttribute(mbeanServer, objectName, attributeName, attributeValue); } else if (arguments.describeMbeans) { result = describeMbean(mbeanServer, objectName); } else if (arguments.listMbeans) { result = new Result(objectName, objectName.toString(), objectName.toString()); } else { throw new CmdLineException( arguments.cmdLineParser, "NO SEARCH_MBEANS OR OPERATION OR ATTRIBUTE DEFINED"); } } catch (Exception e) { StringWriter sw = new StringWriter(); e.printStackTrace(new PrintWriter(sw)); String msg = "## EXCEPTION ##\n" + sw.toString(); result = new Result(objectName, msg, msg); } results.put(objectName, result); } logger.info("INVOCATION RESULT"); logger.info("#################"); logger.info("JVM pid: {}", pid); logger.info("Searched object-name: {}", on); if (operationName != null) { logger.info("Invoke operation {}{}", operationName, Arrays.asList(operationArguments)); } else if (attributeValue == null) { logger.info("Get attribute {}", attributeName); } else { logger.info("Set attribute {}: {}", attributeName, attributeValue); } for (Map.Entry<ObjectName, Result> entry : results.entrySet()) { logger.info("{}", entry.getKey()); logger.info("\t{}", entry.getValue()); } return results; }
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; }