Package com.sun.tools.attach

Examples of com.sun.tools.attach.VirtualMachine


        } catch (Exception x)  { }
        return null;
    }

    private static void flag(String pid, String option) throws IOException {
        VirtualMachine vm = attach(pid);
        String flag;
        InputStream in;
        int index = option.indexOf('=');
        if (index != -1) {
            flag = option.substring(0, index);
View Full Code Here


        return null;
    }

    // Attach to pid and perform a thread dump
    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();
    }
View Full Code Here

 
  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);
View Full Code Here

        System.err.println("WarmRoast");
        System.err.println("http://github.com/sk89q/warmroast");
        System.err.println(SEPARATOR);
        System.err.println("");
       
        VirtualMachine vm = null;
       
        if (opt.pid != null) {
            try {
                vm = VirtualMachine.attach(String.valueOf(opt.pid));
                System.err.println("Attaching to PID " + opt.pid + "...");
View Full Code Here

            perrorQuit("Cannot write to output file", e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        VirtualMachine vm;
        try {
            vm = VirtualMachine.attach(pid);
        } catch (com.sun.tools.attach.AttachNotSupportedException e) {
            perrorQuit("Attach to pid " + pid + " failed", e);
            throw new RuntimeException("should not get here");
        } catch (IOException e) {
            perrorQuit("Attach to pid " + pid + " failed", e);
            throw new RuntimeException("should not get here");
        }

        try {
            vm.loadAgent(jarPath.getAbsolutePath(), duration + ";" + interval + ";" + port + ";" + output);
        } catch (com.sun.tools.attach.AgentLoadException e) {
            throw new RuntimeException(e);
        } catch (com.sun.tools.attach.AgentInitializationException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
View Full Code Here

            id = System.console().readLine("PID: ");

        }

        VirtualMachine vm = null;

        try {

            vm = VirtualMachine.attach(id);

            String[] options = null;

            int start = 0;

            if (args.length > 1) {

                options = args;

                start = 1;

            }
            else {

                // Show interactive menu for specifying instrumentation options.

                do {

                    if (options != null) {

                        help();

                    }

                    options = System.console().readLine("OPTIONS[?]: ").split(" ");

                } while (options[0].equals(""));

            }

            for (int i = start; i < options.length; ++i) {

                s.append(' ');

                s.append(options[i]);

                if (options[i].startsWith("-Xoutput=")) {

                    file = new File(options[i].substring(9));

                    hasOutput = true;

                }
                else if (options[i].startsWith("-Xtimeout=")) {

                    hasTimeout = true;

                }
                else if (options[i].startsWith("-I")) {

                    hasInject = true;

                }

            }

            if (!hasInject) {

                help();

                throw new IllegalArgumentException("Missing -I option");

            }

            // The following instructs the java agent to write to a temporary
            // file if an output file has not already been specified. This is
            // necessary because the java agent runs in the injectee's JVM while
            // the injector runs in a separate JVM. The injectee will not be
            // able to directly write the output to the injector's console.

            if (!hasOutput) {

                file = File.createTempFile("heapaudit",
                                           ".out");

                s.append(" -Xoutput=" + file.getAbsolutePath());

            }

            // The following attaches to the specified process and dynamically
            // injects recorders to collect heap allocation activities. The
            // collection continues until the user presses enter at the command
            // line. Because we are dealing with two separate JVM instances, the
            // following logic relies on a file lock to signal when the
            // collection should terminate.

            if (!hasTimeout) {

                final FileLock lock = (new FileOutputStream(file)).getChannel().lock();

                (new Thread(new Runnable() {

                    public void run() {

                        try {

                            System.console().readLine("Press <enter> to exit HeapAudit...");

                            // Unblock agentmain barrier.

                            lock.release();

                        }
                        catch (Exception e) {

                        }

                    }

                })).start();

            }

            try {

                // Locate the current jar file path and inject itself into the
                // target JVM process. NOTE: The heapaudit.jar file is intended
                // to be multi-purposed. It acts as the java agent for the
                // static use case, the java agent for the dynamic use case and
                // also the command line utility to perform injecting the agent
                // for the dynamic use case.

                vm.loadAgent(HeapAudit.class.getProtectionDomain().getCodeSource().getLocation().getPath(),
                             s.toString());

            }
            catch (IOException e) {

                // There is nothing wrong here. If the targeting app exits
                // before agentmain exits, then an IOException will be thrown.
                // The cleanup logic in agentmain is also registered as a
                // shutdown hook. No need to worry about the non-terminated
                // agentmain behavior.

                System.out.println(" terminated");

            }

            // If the output file was not explicitly specified, display content
            // of the temporary file generated by the injectee to the injector's
            // console.

            if (!hasOutput) {

                BufferedReader input = new BufferedReader(new FileReader(file.getAbsolutePath()));

                char[] buffer = new char[4096];

                int length = 0;

                while ((length = input.read(buffer)) != -1) {

                    System.out.println(String.valueOf(buffer,
                                                      0,
                                                      length));

                }

                file.delete();

            }

        }
        catch (AttachNotSupportedException e) {

            help();

            throw e;

        }
        finally {

            if (vm != null) {

                vm.detach();

            }

        }
View Full Code Here

            List<Map<String, Object>> content = (List<Map<String, Object>>) o.get("Content");
            return content;
    }

    private static String loadManagementAgentAndGetAddress(int vmid) throws IOException {
        VirtualMachine vm = null;
        String name = String.valueOf(vmid);
        try {
            vm = VirtualMachine.attach(name);
        } catch (AttachNotSupportedException x) {
            throw new IOException(x.getMessage(), x);
        }

        String home = vm.getSystemProperties().getProperty("java.home");

        // Normally in ${java.home}/jre/lib/management-agent.jar but might
        // be in ${java.home}/lib in build environments.

        String agent = home + File.separator + "jre" + File.separator + "lib" + File.separator + "management-agent.jar";
        File f = new File(agent);
        if (!f.exists()) {
            agent = home + File.separator + "lib" + File.separator + "management-agent.jar";
            f = new File(agent);
            if (!f.exists()) {
                throw new IOException("Management agent not found");
            }
        }

        agent = f.getCanonicalPath();
        try {
            vm.loadAgent(agent, "com.sun.management.jmxremote");
        } catch (AgentLoadException x) {
            throw new IOException(x.getMessage(), x);
        } catch (AgentInitializationException x) {
            throw new IOException(x.getMessage(), x);
        }

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

        return address;
    }
View Full Code Here

            throw new AssertionError(e);
        }
    }

    private static JMXServiceURL getLocalConnectorAddress(String id, boolean startAgent) {
        VirtualMachine vm = null;
        try {
            try {
                vm = VirtualMachine.attach(id);
                String connectorAddr = vm.getAgentProperties().getProperty(PROP_LOCAL_CONNECTOR_ADDRESS);
                if (connectorAddr == null && startAgent) {
                    final String agent = Paths.get(vm.getSystemProperties().getProperty(PROP_JAVA_HOME)).resolve(MANAGEMENT_AGENT).toString();
                    vm.loadAgent(agent);
                    connectorAddr = vm.getAgentProperties().getProperty(PROP_LOCAL_CONNECTOR_ADDRESS);
                }
                vm.detach();
                final JMXServiceURL url = connectorAddr != null ? new JMXServiceURL(connectorAddr) : null;
                return url;
            } catch (AttachNotSupportedException e) {
                throw new UnsupportedOperationException(e);
            }
        } catch (Throwable e) {
            try {
                if (vm != null)
                    vm.detach();
            } catch (IOException ex) {
                e.addSuppressed(ex);
            }
            throw e instanceof RuntimeException ? (RuntimeException) e : new RuntimeException(e);
        }
View Full Code Here

            if (pid < 0) {
                logger.log(Level.WARNING, INVALID_PID);
                return false;
            }

            VirtualMachine vm = VirtualMachine.attach(String.valueOf(pid));
            String ir = System.getProperty(INSTALL_ROOT_PROPERTY);
            File dir = new File(ir, "lib" + File.separator + "monitor");

            if (!dir.isDirectory()) {
                logger.log(Level.WARNING, MISSING_AGENT_JAR_DIR, dir);
                return false;
            }

            File agentJar = new File(dir, "flashlight-agent.jar");

            if (!agentJar.isFile()) {
                logger.log(Level.WARNING, MISSING_AGENT_JAR, dir);
                return false;
            }

            vm.loadAgent(SmartFile.sanitize(agentJar.getPath()), options);
            isAttached = true;
        }
        catch (Throwable t) {
            logger.log(Level.WARNING, ATTACH_AGENT_EXCEPTION, t.getMessage());
            isAttached = false;
View Full Code Here

            File bytemanJar = new File(bytemanLib, BytemanConfiguration.BYTEMAN_JAR);

            GenerateScriptUtil.copy(bytemanInputJar, new FileOutputStream(bytemanJar));

            VirtualMachine vm = VirtualMachine.attach(pid);
            String agentProperties = config.agentProperties();
            vm.loadAgent(bytemanJar.getAbsolutePath(), "listener:true,port:" + config.containerAgentPort() + (agentProperties != null ? ",prop:" +  agentProperties:""));
            vm.detach();
        }
        catch (IOException e)
        {
            throw new RuntimeException("Could not write byteman.jar to disk", e);
        }
View Full Code Here

TOP

Related Classes of com.sun.tools.attach.VirtualMachine

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.