Java Code Examples for com.sun.tools.attach.VirtualMachine#attach()

The following examples show how to use com.sun.tools.attach.VirtualMachine#attach() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AttachSelf.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {

        String value = System.getProperty("jdk.attach.allowAttachSelf");
        boolean canAttachSelf = (value != null) && !value.equals("false");

        String vmid = "" + ProcessHandle.current().pid();

        VirtualMachine vm = null;
        try {
            vm = VirtualMachine.attach(vmid);
            if (!canAttachSelf)
                throw new RuntimeException("Attached to self not expected");
        } catch (IOException ioe) {
            if (canAttachSelf)
                throw ioe;
        } finally {
            if (vm != null) vm.detach();
        }

    }
 
Example 2
Source File: JMap.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
private static VirtualMachine attach(String pid) {
    try {
        return VirtualMachine.attach(pid);
    } catch (Exception x) {
        String msg = x.getMessage();
        if (msg != null) {
            System.err.println(pid + ": " + msg);
        } else {
            x.printStackTrace();
        }
        if ((x instanceof AttachNotSupportedException) && haveSA()) {
            System.err.println("The -F option can be used when the " +
              "target process is not responding");
        }
        System.exit(1);
        return null; // keep compiler happy
    }
}
 
Example 3
Source File: JMap.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
private static VirtualMachine attach(String pid) {
    try {
        return VirtualMachine.attach(pid);
    } catch (Exception x) {
        String msg = x.getMessage();
        if (msg != null) {
            System.err.println(pid + ": " + msg);
        } else {
            x.printStackTrace();
        }
        if ((x instanceof AttachNotSupportedException) && haveSA()) {
            System.err.println("The -F option can be used when the " +
              "target process is not responding");
        }
        System.exit(1);
        return null; // keep compiler happy
    }
}
 
Example 4
Source File: LocalVirtualMachine.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
private void loadManagementAgent() throws IOException {
    VirtualMachine vm = null;
    String name = String.valueOf(vmid);
    try {
        vm = VirtualMachine.attach(name);
    } catch (AttachNotSupportedException x) {
        IOException ioe = new IOException(x.getMessage());
        ioe.initCause(x);
        throw ioe;
    }

    vm.startLocalManagementAgent();

    // get the connector address
    Properties agentProps = vm.getAgentProperties();
    address = (String) agentProps.get(LOCAL_CONNECTOR_ADDRESS_PROP);

    vm.detach();
}
 
Example 5
Source File: JCmd.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
private static void executeCommandForPid(String pid, String command)
    throws AttachNotSupportedException, IOException,
           UnsupportedEncodingException {
    VirtualMachine vm = VirtualMachine.attach(pid);

    // Cast to HotSpotVirtualMachine as this is an
    // implementation specific method.
    HotSpotVirtualMachine hvm = (HotSpotVirtualMachine) vm;
    String lines[] = command.split("\\n");
    for (String line : lines) {
        if (line.trim().equals("stop")) {
            break;
        }
        try (InputStream in = hvm.executeJCmd(line);) {
            // read to EOF and just print output
            byte b[] = new byte[256];
            int n;
            boolean messagePrinted = false;
            do {
                n = in.read(b);
                if (n > 0) {
                    String s = new String(b, 0, n, "UTF-8");
                    System.out.print(s);
                    messagePrinted = true;
                }
            } while (n > 0);
            if (!messagePrinted) {
                System.out.println("Command executed successfully");
            }
        }
    }
    vm.detach();
}
 
Example 6
Source File: TestManager.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    String pid = args[0]; // pid as a string
    System.out.println("Starting TestManager for PID = " + pid);
    System.out.flush();
    VirtualMachine vm = VirtualMachine.attach(pid);

    String agentPropLocalConnectorAddress = (String)
        vm.getAgentProperties().get(LOCAL_CONNECTOR_ADDRESS_PROP);

    int vmid = Integer.parseInt(pid);
    String jvmstatLocalConnectorAddress =
        ConnectorAddressLink.importFrom(vmid);

    if (agentPropLocalConnectorAddress == null &&
        jvmstatLocalConnectorAddress == null) {
        // No JMX Connector address so attach to VM, and start local agent
        startManagementAgent(pid);
        agentPropLocalConnectorAddress = (String)
            vm.getAgentProperties().get(LOCAL_CONNECTOR_ADDRESS_PROP);
        jvmstatLocalConnectorAddress =
            ConnectorAddressLink.importFrom(vmid);
    }


    // Test address obtained from agent properties
    System.out.println("Testing the connector address from agent properties");
    connect(pid, agentPropLocalConnectorAddress);

    // Test address obtained from jvmstat buffer
    System.out.println("Testing the connector address from jvmstat buffer");
    connect(pid, jvmstatLocalConnectorAddress);

    // Shutdown application
    int port = Integer.parseInt(args[1]);
    System.out.println("Shutdown process via TCP port: " + port);
    Socket s = new Socket();
    s.connect(new InetSocketAddress(port));
    s.close();
}
 
Example 7
Source File: JCozClient.java    From JCoz with GNU General Public License v3.0 5 votes vote down vote up
public JCozClient(VirtualMachineDescriptor vmDesc) throws
AttachNotSupportedException,
IOException {
    this.vm = VirtualMachine.attach(vmDesc);
    this.vm.startLocalManagementAgent();
    this.connectToProfiler();
}
 
Example 8
Source File: StartManagementAgent.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
public static void runTests(int pid) throws Exception {
    VirtualMachine vm = VirtualMachine.attach(""+pid);
    try {

        basicTests(vm);

        testLocalAgent(vm);

        // we retry the remote case several times in case the error
        // was caused by a port conflict
        int i = 0;
        boolean success = false;
        do {
            try {
                System.err.println("Trying remote agent. Try #" + i);
                testRemoteAgent(vm);
                success = true;
            } catch(Exception ex) {
                System.err.println("testRemoteAgent failed with exception:");
                ex.printStackTrace();
                System.err.println("Retrying.");
            }
            i++;
        } while(!success && i < MAX_RETRIES);
        if (!success) {
            throw new Exception("testRemoteAgent failed after " + MAX_RETRIES + " tries");
        }
    } finally {
        vm.detach();
    }
}
 
Example 9
Source File: AttachWithStalePidFile.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
public static boolean runTest() throws Exception {
  ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(
    "-XX:+UnlockDiagnosticVMOptions", "-XX:+PauseAtStartup", "AttachWithStalePidFileTarget");
  Process target = pb.start();
  Path pidFile = null;

  try {
    int pid = getUnixProcessId(target);

    // create the stale .java_pid file. use hard-coded /tmp path as in th VM
    pidFile = createJavaPidFile(pid);
    if(pidFile == null) {
      return false;
    }

    // wait for vm.paused file to be created and delete it once we find it.
    waitForAndResumeVM(pid);

    // unfortunately there's no reliable way to know the VM is ready to receive the
    // attach request so we have to do an arbitrary sleep.
    Thread.sleep(5000);

    HotSpotVirtualMachine vm = (HotSpotVirtualMachine)VirtualMachine.attach(((Integer)pid).toString());
    BufferedReader remoteDataReader = new BufferedReader(new InputStreamReader(vm.remoteDataDump()));
    String line = null;
    while((line = remoteDataReader.readLine()) != null);

    vm.detach();
    return true;
  }
  finally {
    target.destroy();
    target.waitFor();

    if(pidFile != null && Files.exists(pidFile)) {
      Files.delete(pidFile);
    }
  }
}
 
Example 10
Source File: StartManagementAgent.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
public static void runTests(int pid) throws Exception {
    VirtualMachine vm = VirtualMachine.attach(""+pid);
    try {

        basicTests(vm);

        testLocalAgent(vm);

        // we retry the remote case several times in case the error
        // was caused by a port conflict
        int i = 0;
        boolean success = false;
        do {
            try {
                System.err.println("Trying remote agent. Try #" + i);
                testRemoteAgent(vm);
                success = true;
            } catch(Exception ex) {
                System.err.println("testRemoteAgent failed with exception:");
                ex.printStackTrace();
                System.err.println("Retrying.");
            }
            i++;
        } while(!success && i < MAX_RETRIES);
        if (!success) {
            throw new Exception("testRemoteAgent failed after " + MAX_RETRIES + " tries");
        }
    } finally {
        vm.detach();
    }
}
 
Example 11
Source File: HeapDump.java    From java-svc with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static void main(String[] args) throws AttachNotSupportedException, IOException {
	AttachUtils.printJVMVersion();
	String outFileStr = "dump.hprof";
	if (args.length >= 2) {
		outFileStr = args[1];
	}
	System.out.println("Using dump file: " + outFileStr);
	String pid = AttachUtils.checkPid(args);
	VirtualMachine vm = VirtualMachine.attach(pid);
	HotSpotVirtualMachine hsvm = (HotSpotVirtualMachine) vm;
	String result = AttachUtils.readFromStream(hsvm.dumpHeap(outFileStr));
	System.out.println(result);
	vm.detach();
}
 
Example 12
Source File: JCmd.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
private static void executeCommandForPid(String pid, String command)
    throws AttachNotSupportedException, IOException,
           UnsupportedEncodingException {
    VirtualMachine vm = VirtualMachine.attach(pid);

    // Cast to HotSpotVirtualMachine as this is an
    // implementation specific method.
    HotSpotVirtualMachine hvm = (HotSpotVirtualMachine) vm;
    String lines[] = command.split("\\n");
    for (String line : lines) {
        if (line.trim().equals("stop")) {
            break;
        }
        try (InputStream in = hvm.executeJCmd(line);) {
            // read to EOF and just print output
            byte b[] = new byte[256];
            int n;
            boolean messagePrinted = false;
            do {
                n = in.read(b);
                if (n > 0) {
                    String s = new String(b, 0, n, "UTF-8");
                    System.out.print(s);
                    messagePrinted = true;
                }
            } while (n > 0);
            if (!messagePrinted) {
                System.out.println("Command executed successfully");
            }
        }
    }
    vm.detach();
}
 
Example 13
Source File: JStack.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
private static void runThreadDump(String pid, String args[]) throws Exception {
    VirtualMachine vm = null;
    try {
        vm = VirtualMachine.attach(pid);
    } catch (Exception x) {
        String msg = x.getMessage();
        if (msg != null) {
            System.err.println(pid + ": " + msg);
        } else {
            x.printStackTrace();
        }
        if ((x instanceof AttachNotSupportedException) &&
            (loadSAClass() != null)) {
            System.err.println("The -F option can be used when the target " +
                "process is not responding");
        }
        System.exit(1);
    }

    // Cast to HotSpotVirtualMachine as this is implementation specific
    // method.
    InputStream in = ((HotSpotVirtualMachine)vm).remoteDataDump((Object[])args);

    // read to EOF and just print output
    byte b[] = new byte[256];
    int n;
    do {
        n = in.read(b);
        if (n > 0) {
            String s = new String(b, 0, n, "UTF-8");
            System.out.print(s);
        }
    } while (n > 0);
    in.close();
    vm.detach();
}
 
Example 14
Source File: TestManager.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    String pid = args[0]; // pid as a string
    System.out.println("Starting TestManager for PID = " + pid);
    System.out.flush();
    VirtualMachine vm = VirtualMachine.attach(pid);

    String agentPropLocalConnectorAddress = (String)
        vm.getAgentProperties().get(LOCAL_CONNECTOR_ADDRESS_PROP);

    int vmid = Integer.parseInt(pid);
    String jvmstatLocalConnectorAddress =
        ConnectorAddressLink.importFrom(vmid);

    if (agentPropLocalConnectorAddress == null &&
        jvmstatLocalConnectorAddress == null) {
        // No JMX Connector address so attach to VM, and start local agent
        startManagementAgent(pid);
        agentPropLocalConnectorAddress = (String)
            vm.getAgentProperties().get(LOCAL_CONNECTOR_ADDRESS_PROP);
        jvmstatLocalConnectorAddress =
            ConnectorAddressLink.importFrom(vmid);
    }


    // Test address obtained from agent properties
    System.out.println("Testing the connector address from agent properties");
    connect(pid, agentPropLocalConnectorAddress);

    // Test address obtained from jvmstat buffer
    System.out.println("Testing the connector address from jvmstat buffer");
    connect(pid, jvmstatLocalConnectorAddress);

    // Shutdown application
    int port = Integer.parseInt(args[1]);
    System.out.println("Shutdown process via TCP port: " + port);
    Socket s = new Socket();
    s.connect(new InetSocketAddress(port));
    s.close();
}
 
Example 15
Source File: TestManager.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    String pid = args[0]; // pid as a string
    System.out.println("Starting TestManager for PID = " + pid);
    System.out.flush();
    VirtualMachine vm = VirtualMachine.attach(pid);

    String agentPropLocalConnectorAddress = (String)
        vm.getAgentProperties().get(LOCAL_CONNECTOR_ADDRESS_PROP);

    int vmid = Integer.parseInt(pid);
    String jvmstatLocalConnectorAddress =
        ConnectorAddressLink.importFrom(vmid);

    if (agentPropLocalConnectorAddress == null &&
        jvmstatLocalConnectorAddress == null) {
        // No JMX Connector address so attach to VM, and start local agent
        startManagementAgent(pid);
        agentPropLocalConnectorAddress = (String)
            vm.getAgentProperties().get(LOCAL_CONNECTOR_ADDRESS_PROP);
        jvmstatLocalConnectorAddress =
            ConnectorAddressLink.importFrom(vmid);
    }


    // Test address obtained from agent properties
    System.out.println("Testing the connector address from agent properties");
    connect(pid, agentPropLocalConnectorAddress);

    // Test address obtained from jvmstat buffer
    System.out.println("Testing the connector address from jvmstat buffer");
    connect(pid, jvmstatLocalConnectorAddress);

    // Shutdown application
    int port = Integer.parseInt(args[1]);
    System.out.println("Shutdown process via TCP port: " + port);
    Socket s = new Socket();
    s.connect(new InetSocketAddress(port));
    s.close();
}
 
Example 16
Source File: ColaTestAttach.java    From COLA with GNU Lesser General Public License v2.1 5 votes vote down vote up
public static VirtualMachine attach(AgentArgs config)
    throws Exception {
    curClassLoader = Thread.currentThread().getContextClassLoader();
    VirtualMachine virtualMachine = VirtualMachine.attach(getPid2());
    virtualMachine.loadAgent(getAgentJar(), JSON.toJSONString(config));
    ColaTestAttach.virtualMachine = virtualMachine;
    return virtualMachine;
}
 
Example 17
Source File: AttachWithStalePidFile.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
public static boolean runTest() throws Exception {
  ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(
    "-XX:+UnlockDiagnosticVMOptions", "-XX:+PauseAtStartup", "AttachWithStalePidFileTarget");
  Process target = pb.start();
  Path pidFile = null;

  try {
    int pid = getUnixProcessId(target);

    // create the stale .java_pid file. use hard-coded /tmp path as in th VM
    pidFile = createJavaPidFile(pid);
    if(pidFile == null) {
      return false;
    }

    // wait for vm.paused file to be created and delete it once we find it.
    waitForAndResumeVM(pid);

    // unfortunately there's no reliable way to know the VM is ready to receive the
    // attach request so we have to do an arbitrary sleep.
    Thread.sleep(5000);

    HotSpotVirtualMachine vm = (HotSpotVirtualMachine)VirtualMachine.attach(((Integer)pid).toString());
    BufferedReader remoteDataReader = new BufferedReader(new InputStreamReader(vm.remoteDataDump()));
    String line = null;
    while((line = remoteDataReader.readLine()) != null);

    vm.detach();
    return true;
  }
  finally {
    target.destroy();
    target.waitFor();

    if(pidFile != null && Files.exists(pidFile)) {
      Files.delete(pidFile);
    }
  }
}
 
Example 18
Source File: AttachWithStalePidFile.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public static boolean runTest() throws Exception {
  ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(
    "-XX:+UnlockDiagnosticVMOptions", "-XX:+PauseAtStartup", "AttachWithStalePidFileTarget");
  Process target = pb.start();
  Path pidFile = null;

  try {
    int pid = getUnixProcessId(target);

    // create the stale .java_pid file. use hard-coded /tmp path as in th VM
    pidFile = createJavaPidFile(pid);
    if(pidFile == null) {
      return false;
    }

    // wait for vm.paused file to be created and delete it once we find it.
    waitForAndResumeVM(pid);

    waitForTargetReady(target);

    HotSpotVirtualMachine vm = (HotSpotVirtualMachine)VirtualMachine.attach(((Integer)pid).toString());
    BufferedReader remoteDataReader = new BufferedReader(new InputStreamReader(vm.remoteDataDump()));
    String line = null;
    while((line = remoteDataReader.readLine()) != null);

    vm.detach();
    return true;
  }
  finally {
    target.destroy();
    target.waitFor();

    if(pidFile != null && Files.exists(pidFile)) {
      Files.delete(pidFile);
    }
  }
}
 
Example 19
Source File: JCmd.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
private static void executeCommandForPid(String pid, String command)
    throws AttachNotSupportedException, IOException,
           UnsupportedEncodingException {
    VirtualMachine vm = VirtualMachine.attach(pid);

    // Cast to HotSpotVirtualMachine as this is an
    // implementation specific method.
    HotSpotVirtualMachine hvm = (HotSpotVirtualMachine) vm;
    String lines[] = command.split("\\n");
    for (String line : lines) {
        if (line.trim().equals("stop")) {
            break;
        }
        try (InputStream in = hvm.executeJCmd(line);) {
            // read to EOF and just print output
            byte b[] = new byte[256];
            int n;
            boolean messagePrinted = false;
            do {
                n = in.read(b);
                if (n > 0) {
                    String s = new String(b, 0, n, "UTF-8");
                    System.out.print(s);
                    messagePrinted = true;
                }
            } while (n > 0);
            if (!messagePrinted) {
                System.out.println("Command executed successfully");
            }
        }
    }
    vm.detach();
}
 
Example 20
Source File: ArthasStarter.java    From bistoury with GNU General Public License v3.0 4 votes vote down vote up
private static void attachAgent(Configure configure) throws Exception {
    logger.info("start attach to arthas agent");
    VirtualMachineDescriptor virtualMachineDescriptor = null;
    for (VirtualMachineDescriptor descriptor : VirtualMachine.list()) {
        String pid = descriptor.id();
        if (pid.equals(String.valueOf(configure.getJavaPid()))) {
            virtualMachineDescriptor = descriptor;
        }
    }
    VirtualMachine virtualMachine = null;
    try {
        if (virtualMachineDescriptor == null) {
            virtualMachine = VirtualMachine.attach(String.valueOf(configure.getJavaPid()));
        } else {
            virtualMachine = VirtualMachine.attach(virtualMachineDescriptor);
        }

        Properties targetSystemProperties = virtualMachine.getSystemProperties();
        String targetJavaVersion = targetSystemProperties.getProperty("java.specification.version");
        String currentJavaVersion = System.getProperty("java.specification.version");
        if (targetJavaVersion != null && currentJavaVersion != null) {
            if (!targetJavaVersion.equals(currentJavaVersion)) {
                logger.warn("Current VM java version: {} do not match target VM java version: {}, attach may fail.",
                        currentJavaVersion, targetJavaVersion);
                logger.warn("Target VM JAVA_HOME is {}, try to set the same JAVA_HOME.",
                        targetSystemProperties.getProperty("java.home"));
            }
        }

        String arthasAgent = configure.getArthasAgent();
        File agentFile = new File(arthasAgent);
        String name = agentFile.getName();
        String prefix = name.substring(0, name.indexOf('.'));
        File dir = agentFile.getParentFile();
        File realAgentFile = getFileWithPrefix(dir, prefix);

        logger.info("start load arthas agent, input {}, load {}", arthasAgent, realAgentFile.getCanonicalPath());
        final String delimiter = "$|$";
        virtualMachine.loadAgent(realAgentFile.getCanonicalPath(),
                configure.getArthasCore() + delimiter + ";;" + configure.toString() + delimiter + System.getProperty("bistoury.app.lib.class"));
    } finally {
        if (virtualMachine != null) {
            virtualMachine.detach();
        }
    }
}