@Override public void run(String... args) throws Exception { // TODO Auto-generated method stub final AttachProvider attachProvider = AttachProvider.providers().get(0); VirtualMachineDescriptor descriptor = null; for (VirtualMachineDescriptor virtualMachineDescriptor : attachProvider.listVirtualMachines()) { if (virtualMachineDescriptor.displayName().equals(applicationName)) { descriptor = virtualMachineDescriptor; } } final VirtualMachine virtualMachine = attachProvider.attachVirtualMachine(descriptor); virtualMachine.loadAgent(managmentAgentJar, "com.sun.management.jmxremote"); final Object portObject = virtualMachine .getAgentProperties() .get("com.sun.management.jmxremote.localConnectorAddress"); final JMXServiceURL target = new JMXServiceURL(portObject + ""); final JMXConnector connector = JMXConnectorFactory.connect(target); final MBeanServerConnection remote = connector.getMBeanServerConnection(); final ObjectName objectName = new ObjectName("Catalina:type=Manager,host=localhost,context=" + context); System.out.println("Start"); System.out.println("ActiveSession = " + remote.getAttribute(objectName, "activeSessions")); System.out.println("End"); }
private void attachAgent() throws IOException, AttachNotSupportedException, AgentLoadException, AgentInitializationException { String name = ManagementFactory.getRuntimeMXBean().getName(); String pid = name.substring(0, name.indexOf("@")); System.out.println(name); final VirtualMachine m = VirtualMachine.attach(pid); m.loadAgent("target/notsoserial-1.0-SNAPSHOT.jar"); }
/** * @param args * @throws Exception */ public static void main(final String[] args) throws Exception { if (args == null || args.length < 1) { throw new IllegalStateException("args"); } final String pid = args[0]; final File thisJar = getJarFile(); final VirtualMachine vm = VirtualMachine.attach(pid); vm.loadAgent(thisJar.getAbsolutePath(), ""); vm.detach(); }
/** * Tests this VirtualMachine for equality with another object. * * <p> * * <p>If the given object is not a VirtualMachine then this method returns <tt>false</tt>. For two * VirtualMachines to be considered equal requires that they both reference the same provider, and * their {@link VirtualMachineDescriptor#id() identifiers} are equal. * * <p> * * <p>This method satisfies the general contract of the {@link java.lang.Object#equals(Object) * Object.equals} method. * * @param ob The object to which this object is to be compared * @return <tt>true</tt> if, and only if, the given object is a VirtualMachine that is equal to * this VirtualMachine. */ public boolean equals(Object ob) { if (ob == this) { return true; } if (!(ob instanceof VirtualMachine)) { return false; } VirtualMachine other = (VirtualMachine) ob; return other.provider() == provider() && other.id().equals(id()); }
@Nonnull protected MBeanServerConnection connectToMbeanServer(@Nonnull String pid) throws IOException { VirtualMachine vm; try { Integer.parseInt(pid); } catch (Exception e) { logger.warn("Exception parsing PID '{}'", pid, e); } try { vm = VirtualMachine.attach(pid); } catch (Exception e) { throw new IllegalStateException("Exception attaching VM with PID '" + pid + "'", e); } logger.trace("VM Agent Properties"); for (String key : new TreeSet<String>(vm.getAgentProperties().stringPropertyNames())) { logger.trace("\t {}: {}", key, vm.getAgentProperties().get(key)); } logger.trace("VM System Properties"); for (String key : new TreeSet<String>(vm.getSystemProperties().stringPropertyNames())) { logger.trace("\t {}: {}", key, vm.getSystemProperties().get(key)); } String connectorAddress = vm.getAgentProperties().getProperty("com.sun.management.jmxremote.localConnectorAddress"); if (connectorAddress == null) { String agent = vm.getSystemProperties().getProperty("java.home") + File.separator + "lib" + File.separator + "management-agent.jar"; try { vm.loadAgent(agent); } catch (Exception e) { throw new IllegalStateException("Exception loading agent " + agent); } connectorAddress = vm.getAgentProperties().getProperty("com.sun.management.jmxremote.localConnectorAddress"); } if (connectorAddress == null) { throw new IllegalStateException( "Could not attach to pid: " + pid + ". No connector available"); } logger.trace("Connect to {} ...", connectorAddress); JMXConnector connector = JMXConnectorFactory.connect(new JMXServiceURL(connectorAddress)); return connector.getMBeanServerConnection(); }
/* * Find the VM instance running Cougar based on COUGARVMNAME1 and COUGARVMNAME2 * fields, and attach, setting the JmxConnector to be used by other methods. * */ private void setJMXConnectionFactory() { String id = null; List<VirtualMachineDescriptor> vms = VirtualMachine.list(); Boolean foundVM = false; for (VirtualMachineDescriptor vmd : vms) { String vmName = cleanCommandLineArgs(vmd.displayName()); id = vmd.id(); JMXConnector jmxConnector = null; try { jmxConnector = createJMXConnector(id); } catch (Exception e) { // Do Nothing move onto next vm continue; } try { if (!makeServerConnection(jmxConnector)) { continue; } } catch (Exception e) { // Do Nothing move onto next vm continue; } // No exceptions thrown so we have our cougar vm jmxc = jmxConnector; foundVM = true; break; } if (!foundVM) { throw new RuntimeException("Unable to find cougar VM"); } }
private JMXConnector initJMXConnector(String svcName) throws IOException, AttachNotSupportedException, AgentLoadException, AgentInitializationException { int pid = PlatformUtils.getServicePid(svcName); log.info("{} service pid {}", svcName, pid); VirtualMachine vm = VirtualMachine.attach(String.valueOf(pid)); try { String connectorAddress = vm.getAgentProperties().getProperty(CONNECTOR_ADDRESS); if (connectorAddress == null) { String agent = Strings.join( File.separator, vm.getSystemProperties().getProperty("java.home"), "lib", "management-agent.jar"); vm.loadAgent(agent); connectorAddress = vm.getAgentProperties().getProperty(CONNECTOR_ADDRESS); } JMXServiceURL serviceURL = new JMXServiceURL(connectorAddress); return JMXConnectorFactory.connect(serviceURL); } finally { vm.detach(); } }
private synchronized void loadManagementAgent() throws IOException { VirtualMachine vm = null; String name = String.valueOf(vmid); try { vm = VirtualMachine.attach(name); } catch (AttachNotSupportedException x) { throw new IOException(x); } // try to enable local JMX via jcmd command if (!loadManagementAgentViaJcmd(vm)) { // load the management agent into the target VM loadManagementAgentViaJar(vm); } // get the connector address Properties agentProps = vm.getAgentProperties(); address = (String) agentProps.get(LOCAL_CONNECTOR_ADDRESS_PROP); vm.detach(); }
private Stream<VirtualMachine> attach(VirtualMachineDescriptor vmDescriptor) { try { com.sun.tools.attach.VirtualMachine vm = com.sun.tools.attach.VirtualMachine.attach(vmDescriptor); String vmArgs = vm.getAgentProperties().getProperty(VM_ARGS); String id = vmDescriptor.id(); String displayName = vmDescriptor.displayName(); boolean agentLoaded = vmArgs.contains(AGENT_NAME); String userDir = getUserDir(vm); return Stream.of(new VirtualMachine(id, displayName, agentLoaded, userDir)); } catch (AttachNotSupportedException e) { logger.warn(e.getMessage()); } catch (IOException e) { if (!noSuchProcess(e)) { logger.warn(e.getMessage(), e); } } return Stream.empty(); }
public JMXConnector createJMXConnector(String id) throws IOException, AgentLoadException, AgentInitializationException, AttachNotSupportedException { // attach to the target application VirtualMachine vm = VirtualMachine.attach(id); // get the connector address String connectorAddress = vm.getAgentProperties().getProperty(CONNECTOR_ADDRESS); // no connector address, so we start the JMX agent if (connectorAddress == null) { String agent = vm.getSystemProperties().getProperty("java.home") + File.separator + "lib" + File.separator + "management-agent.jar"; vm.loadAgent(agent); // agent is started, get the connector address connectorAddress = vm.getAgentProperties().getProperty(CONNECTOR_ADDRESS); } // establish connection to connector server JMXServiceURL url = new JMXServiceURL(connectorAddress); return JMXConnectorFactory.connect(url); }
public void poll() { Set<VirtualMachineDescriptor> current = new HashSet<>(com.sun.tools.attach.VirtualMachine.list()); difference( current, previous, machine -> { ProfileListener profileListener = listener.onNewMachine(machine); if (machine.isAgentLoaded() && profileListener != null) { try { conductor.pipeFile(machine.getLogFile(), machine, profileListener); } catch (IOException e) { logger.error(e.getMessage(), e); } } }); difference(previous, current, listener::onClosedMachine); previous = current; }
private void loadManagementAgentViaJar(VirtualMachine vm) throws IOException { // Normally in ${java.home}/jre/lib/management-agent.jar but might // be in ${java.home}/lib in build environments. String agent = javaHome + File.separator + "jre" + File.separator + // NOI18N "lib" + File.separator + "management-agent.jar"; // NOI18N File f = new File(agent); if (!f.exists()) { agent = javaHome + File.separator + "lib" + File.separator + // NOI18N "management-agent.jar"; // NOI18N f = new File(agent); if (!f.exists()) { throw new IOException("Management agent not found"); // NOI18N } } agent = f.getCanonicalPath(); try { vm.loadAgent(agent, "com.sun.management.jmxremote"); // NOI18N } catch (AgentLoadException x) { throw new IOException(x); } catch (AgentInitializationException x) { throw new IOException(x); } }
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 JMXServiceURL getURLForPid(String pid) throws Exception { // attach to the target application final VirtualMachine vm = VirtualMachine.attach(pid); // get the connector address String connectorAddress = vm.getAgentProperties().getProperty(CONNECTOR_ADDRESS); // no connector address, so we start the JMX agent if (connectorAddress == null) { String agent = vm.getSystemProperties().getProperty("java.home") + File.separator + "lib" + File.separator + "management-agent.jar"; vm.loadAgent(agent); // agent is started, get the connector address connectorAddress = vm.getAgentProperties().getProperty(CONNECTOR_ADDRESS); assert connectorAddress != null; } return new JMXServiceURL(connectorAddress); }
private JMXServiceURL parseArgs(String[] args) { String host = null; int port = 0; String pid = null; JMXServiceURL serviceURL = null; for (int i = 0; i < args.length; i++) { if (args[i].startsWith("-url")) { // The '-url' option will let you specify a JMXServiceURL // on the command line. This is an URL that begins with // service:jmx:<protocol> // if (host != null) throwSyntaxError("-url and -host are mutually exclusive"); if (pid != null) throwSyntaxError("-pid and -url are mutually exclusive"); if (port > 0) throwSyntaxError("-port and -url are mutually exclusive"); if (++i >= args.length) throwSyntaxError("missing JMXServiceURL after -url"); try { serviceURL = new JMXServiceURL(args[i]); } catch (Exception x) { throwSyntaxError("bad JMXServiceURL after -url: " + x); } continue; } else if (args[i].startsWith("-host")) { // The '-host' and '-port' options will let you specify a host // and port, and from that will construct the JMXServiceURL of // the default RMI connector, that is: // service:jmx:rmi:///jndi/rmi://<host>:<port>/jmxrmi" // if (serviceURL != null) throwSyntaxError("-url and -host are mutually exclusive"); if (pid != null) throwSyntaxError("-pid and -host are mutually exclusive"); if (++i >= args.length) throwSyntaxError("missing host after -host"); try { InetAddress.getByName(args[i]); host = args[i]; } catch (Exception x) { throwSyntaxError("bad host after -url: " + x); } } else if (args[i].startsWith("-port")) { // The '-host' and '-port' options will let you specify a host // and port, and from that will construct the JMXServiceURL of // the default RMI connector, that is: // service:jmx:rmi:///jndi/rmi://<host>:<port>/jmxrmi" // if (serviceURL != null) throwSyntaxError("-url and -port are mutually exclusive"); if (pid != null) throwSyntaxError("-pid and -port are mutually exclusive"); if (++i >= args.length) throwSyntaxError("missing port number after -port"); try { port = Integer.parseInt(args[i]); if (port <= 0) throwSyntaxError("bad port number after -port: " + "must be positive"); } catch (Exception x) { throwSyntaxError("bad port number after -port: " + x); } } else if (args[i].startsWith("-pid")) { // The '-pid' and option will let you specify the PID of the // target VM you want to connect to. It will then use the // attach API to dynamically launch the JMX agent in the target // VM (if needed) and to find out the JMXServiceURL of the // the default JMX Connector in that VM. // if (serviceURL != null) throwSyntaxError("-url and -pid are mutually exclusive"); if (port > 0) throwSyntaxError("-port and -pid are mutually exclusive"); if (++i >= args.length) throwSyntaxError("missing pid after -pid"); try { pid = args[i]; } catch (Exception x) { throwSyntaxError("bad pid after -pid: " + x); } } else if (args[i].startsWith("-help")) { final List<String> vmlist = new ArrayList(); for (VirtualMachineDescriptor vd : VirtualMachine.list()) { vmlist.add(vd.id()); } System.err.println(SYNTAX); System.err.println("Running JVMs are: " + vmlist); throw new IllegalArgumentException(SYNTAX); } else { throwSyntaxError("Unknown argument: " + args[i]); } } // A JMXServiceURL was given on the command line, just use this. // if (serviceURL != null) return serviceURL; // A -host -port info was given on the command line. // Construct the default RMI JMXServiceURL from this. // if (port > 0) { if (host == null) host = "localhost"; try { return new JMXServiceURL( "service:jmx:rmi:///jndi/rmi://" + host + ":" + port + "/jmxrmi"); } catch (Exception x) { throwSyntaxError("Bad host or port number: " + x); } } // A PID was given on the command line. // Use the attach API to find the target's connector address, and // start it if needed. // if (pid != null) { try { return getURLForPid(pid); } catch (Exception x) { throwSyntaxError("cannot attach to target vm " + pid + ": " + x); } } final List<String> vmlist = new ArrayList(); for (VirtualMachineDescriptor vd : VirtualMachine.list()) { vmlist.add(vd.id()); } throwSyntaxError( "missing argument: " + "-port | -url | -pid | -list" + "\n\tRunning VMs are: " + vmlist); // Unreachable. return null; }
private String getUserDir(com.sun.tools.attach.VirtualMachine vm) throws IOException { final String userDir = vm.getAgentProperties().getProperty(USER_DIR); if (userDir != null) return userDir; return vm.getSystemProperties().getProperty(USER_DIR); }