Search in sources :

Example 6 with VirtualMachine

use of com.sun.tools.attach.VirtualMachine in project jdk8u_jdk by JetBrains.

the class LocalVirtualMachine method getLocalVirtualMachine.

public static LocalVirtualMachine getLocalVirtualMachine(int vmid) {
    Map<Integer, LocalVirtualMachine> map = getAllVirtualMachines();
    LocalVirtualMachine lvm = map.get(vmid);
    if (lvm == null) {
        // Check if the VM is attachable but not included in the list
        // if it's running with a different security context.
        // For example, Windows services running
        // local SYSTEM account are attachable if you have Adminstrator
        // privileges.
        boolean attachable = false;
        String address = null;
        // default display name to pid
        String name = String.valueOf(vmid);
        try {
            VirtualMachine vm = VirtualMachine.attach(name);
            attachable = true;
            Properties agentProps = vm.getAgentProperties();
            address = (String) agentProps.get(LOCAL_CONNECTOR_ADDRESS_PROP);
            vm.detach();
            lvm = new LocalVirtualMachine(vmid, name, attachable, address);
        } catch (AttachNotSupportedException x) {
            // not attachable
            if (JConsole.isDebug()) {
                x.printStackTrace();
            }
        } catch (IOException x) {
            // ignore
            if (JConsole.isDebug()) {
                x.printStackTrace();
            }
        }
    }
    return lvm;
}
Also used : IOException(java.io.IOException) AttachNotSupportedException(com.sun.tools.attach.AttachNotSupportedException) VirtualMachine(com.sun.tools.attach.VirtualMachine)

Example 7 with VirtualMachine

use of com.sun.tools.attach.VirtualMachine in project opennms by OpenNMS.

the class Controller method getJmxUrl.

/**
 * This method uses the Java Attach API to connect to a running OpenNMS JVM
 * and fetch the dynamically assigned local JMX agent URL.
 *
 * @see https://docs.oracle.com/javase/8/docs/jdk/api/attach/spec/index.html
 * @see https://docs.oracle.com/javase/8/docs/technotes/guides/management/agent.html
 *
 * @return a {@link java.lang.String} object.
 */
public String getJmxUrl() {
    try {
        // Check to see if the com.sun.tools.attach classes are loadable in
        // this JVM
        Class<?> clazz;
        clazz = Class.forName("com.sun.tools.attach.VirtualMachine");
        clazz = Class.forName("com.sun.tools.attach.VirtualMachineDescriptor");
        clazz = Class.forName("com.sun.tools.attach.AttachNotSupportedException");
    } catch (ClassNotFoundException e) {
        LOG.info("The Attach API is not available in this JVM, falling back to JMX over RMI");
        return m_jmxUrl;
    }
    VirtualMachine vm = null;
    final StringBuilder vmNames = new StringBuilder();
    boolean first = true;
    // Use the Attach API to enumerate all of the JVMs that are running as the same
    // user on this machine
    VirtualMachineDescriptor foundVm = null;
    for (VirtualMachineDescriptor vmDescr : VirtualMachine.list()) {
        if (!first) {
            vmNames.append(", ");
        }
        vmNames.append("\"" + vmDescr.displayName() + "\"");
        first = false;
        if (vmDescr.displayName().contains(OPENNMS_JVM_DISPLAY_NAME_SUBSTRING)) {
            foundVm = vmDescr;
        }
    }
    if (foundVm == null) {
        LOG.debug("Could not find OpenNMS JVM (\"" + OPENNMS_JVM_DISPLAY_NAME_SUBSTRING + "\") among JVMs (" + vmNames + ")");
    } else {
        try {
            vm = VirtualMachine.attach(foundVm);
            LOG.debug("Attached to OpenNMS JVM: " + foundVm.id() + " (" + foundVm.displayName() + ")");
        } catch (AttachNotSupportedException e) {
            // This exception is unexpected so log a warning
            LOG.warn("Cannot attach to OpenNMS JVM", e);
        } catch (IOException e) {
            // This exception is unexpected so log a warning
            LOG.warn("IOException when attaching to OpenNMS JVM", e);
        }
    }
    if (vm == null) {
        if (m_pid == null) {
            LOG.debug("No PID specified for OpenNMS JVM");
        } else {
            try {
                vm = VirtualMachine.attach(m_pid);
                LOG.debug("Attached to OpenNMS JVM with PID: " + m_pid);
            } catch (AttachNotSupportedException e) {
                // This exception is unexpected so log a warning
                LOG.warn("Cannot attach to OpenNMS JVM at PID: " + m_pid, e);
            } catch (IOException e) {
                // This exception will occur if the PID cannot be found
                // because the process has been terminated
                LOG.debug("IOException when attaching to OpenNMS JVM at PID: " + m_pid + ": " + e.getMessage());
            }
        }
    }
    if (vm == null) {
        LOG.debug("Could not attach to JVM, falling back to JMX over RMI");
        return m_jmxUrl;
    } else {
        return getJmxUriFromVirtualMachine(vm);
    }
}
Also used : VirtualMachineDescriptor(com.sun.tools.attach.VirtualMachineDescriptor) IOException(java.io.IOException) AttachNotSupportedException(com.sun.tools.attach.AttachNotSupportedException) VirtualMachine(com.sun.tools.attach.VirtualMachine)

Example 8 with VirtualMachine

use of com.sun.tools.attach.VirtualMachine in project geode by apache.

the class MBeanProcessController method getJMXServiceURL.

/**
   * Uses the Attach API to connect to the local process and ensures that it has loaded the JMX
   * management agent. The JMXServiceURL identifying the local connector address for the JMX agent
   * in the process is returned.
   * 
   * @return the address of the JMX API connector server for connecting to the local process
   * 
   * @throws AttachNotSupportedException if unable to use the Attach API to connect to the process
   * @throws IOException if the JDK management agent cannot be found and loaded
   */
private JMXServiceURL getJMXServiceURL() throws AttachNotSupportedException, IOException {
    String connectorAddress = null;
    final VirtualMachine vm = VirtualMachine.attach(String.valueOf(this.pid));
    try {
        Properties agentProps = vm.getAgentProperties();
        connectorAddress = (String) agentProps.get(LOCAL_CONNECTOR_ADDRESS_PROP);
        if (connectorAddress == null) {
            // need to load the management-agent and get the address
            final String javaHome = vm.getSystemProperties().getProperty("java.home");
            // assume java.home is JDK and look in JRE for agent
            String managementAgentPath = javaHome + File.separator + "jre" + File.separator + "lib" + File.separator + "management-agent.jar";
            File managementAgent = new File(managementAgentPath);
            if (!managementAgent.exists()) {
                // assume java.home is JRE and look in lib for agent
                managementAgentPath = javaHome + File.separator + "lib" + File.separator + "management-agent.jar";
                managementAgent = new File(managementAgentPath);
                if (!managementAgent.exists()) {
                    throw new IOException("JDK management agent not found");
                }
            }
            // attempt to load the management agent
            managementAgentPath = managementAgent.getCanonicalPath();
            try {
                vm.loadAgent(managementAgentPath, "com.sun.management.jmxremote");
            } catch (AgentLoadException e) {
                IOException ioe = new IOException(e.getMessage());
                ioe.initCause(e);
                throw ioe;
            } catch (AgentInitializationException e) {
                IOException ioe = new IOException(e.getMessage());
                ioe.initCause(e);
                throw ioe;
            }
            // get the connector address
            agentProps = vm.getAgentProperties();
            connectorAddress = (String) agentProps.get(LOCAL_CONNECTOR_ADDRESS_PROP);
        }
    } finally {
        vm.detach();
    }
    if (connectorAddress == null) {
        // should never reach here
        throw new IOException("Failed to find address to attach to process");
    }
    return new JMXServiceURL(connectorAddress);
}
Also used : JMXServiceURL(javax.management.remote.JMXServiceURL) AgentLoadException(com.sun.tools.attach.AgentLoadException) IOException(java.io.IOException) Properties(java.util.Properties) File(java.io.File) AgentInitializationException(com.sun.tools.attach.AgentInitializationException) VirtualMachine(com.sun.tools.attach.VirtualMachine)

Example 9 with VirtualMachine

use of com.sun.tools.attach.VirtualMachine in project geode by apache.

the class LocalProcessController method getJMXServiceURL.

/**
   * Uses the Attach API to connect to the local process and ensures that it has loaded the JMX
   * management agent. The JMXServiceURL identifying the local connector address for the JMX agent
   * in the process is returned.
   * 
   * @return the address of the JMX API connector server for connecting to the local process
   * 
   * @throws AttachNotSupportedException if unable to use the Attach API to connect to the process
   * @throws IOException if the JDK management agent cannot be found and loaded
   */
private JMXServiceURL getJMXServiceURL() throws AttachNotSupportedException, IOException {
    String connectorAddress = null;
    final VirtualMachine vm = VirtualMachine.attach(String.valueOf(this.pid));
    try {
        Properties agentProps = vm.getAgentProperties();
        connectorAddress = (String) agentProps.get(LOCAL_CONNECTOR_ADDRESS_PROP);
        if (connectorAddress == null) {
            // need to load the management-agent and get the address
            final String javaHome = vm.getSystemProperties().getProperty("java.home");
            // assume java.home is JDK and look in JRE for agent
            String managementAgentPath = javaHome + File.separator + "jre" + File.separator + "lib" + File.separator + "management-agent.jar";
            File managementAgent = new File(managementAgentPath);
            if (!managementAgent.exists()) {
                // assume java.home is JRE and look in lib for agent
                managementAgentPath = javaHome + File.separator + "lib" + File.separator + "management-agent.jar";
                managementAgent = new File(managementAgentPath);
                if (!managementAgent.exists()) {
                    throw new IOException("JDK management agent not found");
                }
            }
            // attempt to load the management agent
            managementAgentPath = managementAgent.getCanonicalPath();
            try {
                vm.loadAgent(managementAgentPath, "com.sun.management.jmxremote");
            } catch (AgentLoadException e) {
                IOException ioe = new IOException(e.getMessage());
                ioe.initCause(e);
                throw ioe;
            } catch (AgentInitializationException e) {
                IOException ioe = new IOException(e.getMessage());
                ioe.initCause(e);
                throw ioe;
            }
            // get the connector address
            agentProps = vm.getAgentProperties();
            connectorAddress = (String) agentProps.get(LOCAL_CONNECTOR_ADDRESS_PROP);
        }
    } finally {
        vm.detach();
    }
    if (connectorAddress == null) {
        // should never reach here
        throw new IOException("Failed to find address to attach to process");
    }
    return new JMXServiceURL(connectorAddress);
}
Also used : JMXServiceURL(javax.management.remote.JMXServiceURL) AgentLoadException(com.sun.tools.attach.AgentLoadException) IOException(java.io.IOException) Properties(java.util.Properties) File(java.io.File) AgentInitializationException(com.sun.tools.attach.AgentInitializationException) VirtualMachine(com.sun.tools.attach.VirtualMachine)

Example 10 with VirtualMachine

use of com.sun.tools.attach.VirtualMachine in project warn-report by saaavsaaa.

the class TestAgentVMAttacher method test.

// consult: http://ayufox.iteye.com/blog/653214
/*
    * HotSpotDiagnosticMXBean
    * ClassLoadingMXBean
    * CompilationMXBean
    * GarbageCollectorMXBean
    * MemoryManagerMXBean
    * MemoryPoolMXBean
    * OperatingSystemMXBean
    * RuntimeMXBean
    * ThreadMXBeanisolatering
    * */
@Test
public void test() throws IOException, AttachNotSupportedException, AgentLoadException, AgentInitializationException {
    // args[0]传入的是某个jvm进程的pid
    String targetPid = "9527";
    VirtualMachine virtualmachine = VirtualMachine.attach(targetPid);
    // 让JVM加载jmx Agent
    String javaHome = virtualmachine.getSystemProperties().getProperty("java.home");
    String jmxAgent = javaHome + File.separator + "lib" + File.separator + "management-agent.jar";
    virtualmachine.loadAgent(jmxAgent, "com.sun.management.jmxremote");
    // 获得连接地址
    Properties properties = virtualmachine.getAgentProperties();
    String address = (String) properties.get("com.sun.management.jmxremote.localConnectorAddress");
    // Detach
    virtualmachine.detach();
    // 通过jxm address来获取RuntimeMXBean对象,从而得到虚拟机运行时相关信息
    JMXServiceURL url = new JMXServiceURL(address);
    JMXConnector connector = JMXConnectorFactory.connect(url);
    RuntimeMXBean rmxb = ManagementFactory.newPlatformMXBeanProxy(connector.getMBeanServerConnection(), "java.lang:type=Runtime", RuntimeMXBean.class);
    // 得到目标虚拟机占用cpu时间
    System.out.println(rmxb.getInputArguments());
}
Also used : JMXServiceURL(javax.management.remote.JMXServiceURL) JMXConnector(javax.management.remote.JMXConnector) RuntimeMXBean(java.lang.management.RuntimeMXBean) Properties(java.util.Properties) VirtualMachine(com.sun.tools.attach.VirtualMachine) Test(org.junit.Test)

Aggregations

VirtualMachine (com.sun.tools.attach.VirtualMachine)20 IOException (java.io.IOException)8 AttachNotSupportedException (com.sun.tools.attach.AttachNotSupportedException)6 File (java.io.File)5 InputStream (java.io.InputStream)5 HotSpotVirtualMachine (sun.tools.attach.HotSpotVirtualMachine)5 Properties (java.util.Properties)4 JMXServiceURL (javax.management.remote.JMXServiceURL)4 AgentInitializationException (com.sun.tools.attach.AgentInitializationException)3 AgentLoadException (com.sun.tools.attach.AgentLoadException)3 VirtualMachineDescriptor (com.sun.tools.attach.VirtualMachineDescriptor)3 Test (org.junit.Test)2 SmartFile (com.sun.enterprise.universal.io.SmartFile)1 AttachOperationFailedException (com.sun.tools.attach.AttachOperationFailedException)1 RuntimeMXBean (java.lang.management.RuntimeMXBean)1 InetSocketAddress (java.net.InetSocketAddress)1 Socket (java.net.Socket)1 JMXConnector (javax.management.remote.JMXConnector)1