Java Examples for com.sun.tools.attach.VirtualMachine
The following java examples will help you to understand the usage of com.sun.tools.attach.VirtualMachine. These source code samples are taken from different open source projects.
Example 1
| Project: activejpa-master File: ActiveJpaAgentLoaderImpl.java View source code |
public static void loadAgent() {
String nameOfRunningVM = ManagementFactory.getRuntimeMXBean().getName();
int p = nameOfRunningVM.indexOf('@');
String pid = nameOfRunningVM.substring(0, p);
try {
VirtualMachine vm = VirtualMachine.attach(pid);
CodeSource codeSource = ActiveJpaAgent.class.getProtectionDomain().getCodeSource();
vm.loadAgent(codeSource.getLocation().toURI().getPath(), "");
vm.detach();
} catch (Exception e) {
throw new RuntimeException(e);
}
}Example 2
| Project: jmxfetch-master File: App.java View source code |
/**
* Main entry of JMXFetch
* <p/>
* See AppConfig class for more details on the args
*/
public static void main(String[] args) {
// Load the config from the args
AppConfig config = new AppConfig();
JCommander jCommander = null;
try {
// Try to parse the args using JCommander
jCommander = new JCommander(config, args);
} catch (ParameterException e) {
System.out.println(e.getMessage());
System.exit(1);
}
// Display the help and quit
if (config.isHelp() || config.getAction().equals(AppConfig.ACTION_HELP)) {
jCommander.usage();
System.exit(0);
}
// Set up the logger to add file handler
CustomLogger.setup(Level.toLevel(config.getLogLevel()), config.getLogLocation());
// The specified action is unknown
if (!AppConfig.ACTIONS.contains(config.getAction())) {
LOGGER.fatal(config.getAction() + " is not in " + AppConfig.ACTIONS + ". Exiting.");
System.exit(1);
}
// The "list_*" actions can only be used with the reporter
if (!config.getAction().equals(AppConfig.ACTION_COLLECT) && !config.isConsoleReporter()) {
LOGGER.fatal(config.getAction() + " argument can only be used with the console reporter. Exiting.");
System.exit(1);
}
if (config.getAction().equals(AppConfig.ACTION_LIST_JVMS)) {
List<com.sun.tools.attach.VirtualMachineDescriptor> descriptors = com.sun.tools.attach.VirtualMachine.list();
System.out.println("List of JVMs for user " + System.getProperty("user.name"));
for (com.sun.tools.attach.VirtualMachineDescriptor descriptor : descriptors) {
System.out.println("\tJVM id " + descriptor.id() + ": '" + descriptor.displayName() + "'");
}
System.exit(0);
}
// Set up the shutdown hook to properly close resources
attachShutdownHook();
LOGGER.info("JMX Fetch has started");
App app = new App(config);
// Initiate JMX Connections, get attributes that match the yaml configuration
app.init(false);
// We don't want to loop if the action is list_* as it's just used for display information about what will be collected
if (config.getAction().equals(AppConfig.ACTION_COLLECT)) {
// Start the main loop
app.start();
}
}Example 3
| Project: perftrace-master File: PerftraceAttachMain.java View source code |
/**
* @param args
*/
public static void main(String[] args) {
if (args.length != 3) {
throw new IllegalArgumentException("Args num should be 3.");
}
String pid = args[0];
String agentJarPath = args[1];
String perftraceConfigFile = args[2];
VirtualMachine vm = null;
try {
vm = VirtualMachine.attach(pid);
vm.loadAgent(agentJarPath, perftraceConfigFile);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
vm.detach();
} catch (IOException e) {
e.printStackTrace();
}
}
}Example 4
| Project: enumerable-master File: LambdaAgentAttach.java View source code |
/**
* Attempts to attach the Enumerable.java jar to the running process.
* $JAVA_HOME/lib/tools.jar with com.sun.tools.attach.VirtualMachine must be present.
*/
public static void attachAgent(String pathToEnumerableJavaJar) {
try {
if (!toolsJar().isFile())
throw new IllegalStateException("Cannot find tools jar in " + System.getProperty("java.home"));
Class<?> vmClass = classLoaderWithToolsJar().loadClass("com.sun.tools.attach.VirtualMachine");
Object vm = vmClass.getMethod("attach", String.class).invoke(null, pidOfRunningVM());
vmClass.getMethod("loadAgent", String.class).invoke(vm, pathToEnumerableJavaJar);
vmClass.getMethod("detach").invoke(vm);
} catch (Exception e) {
throw new RuntimeException(e);
}
}Example 5
| Project: gcexplorer-master File: LocalJavaProcessFinder.java View source code |
public static List<String> getLocalJavaProcesses() {
List<String> localProcesses = new LinkedList<>();
List<VirtualMachineDescriptor> vms = VirtualMachine.list();
for (VirtualMachineDescriptor vmd : vms) {
if (!vmd.displayName().contains(GarbageGeneratorApp.class.getSimpleName())) {
localProcesses.add(vmd.id() + " " + vmd.displayName());
}
}
return localProcesses;
}Example 6
| Project: jconfig-master File: ConfigLoaderJvm.java View source code |
/**
* Attach to the ConfigLoader VM
*
* @throws @VirtualMachineException
*/
@Override
public void attach() throws VirtualMachineException {
// Iterate through the running vms ...
List<VirtualMachineDescriptor> vms = com.sun.tools.attach.VirtualMachine.list();
for (VirtualMachineDescriptor vmd : vms) {
JMXConnector jmxc = null;
try {
ObjectName mbeanName = new ObjectName(CONFIG_LOADER_MBEAN_NAME);
jmxc = connect(vmd);
MBeanServerConnection mbsc = jmxc.getMBeanServerConnection();
// Look for one that has the ConfigLoader MBean registered
if (!mbsc.isRegistered(mbeanName)) {
jmxc.close();
continue;
} else {
// Set the JMXConnector and the MBeanServerConnection
setJMXConnector(jmxc);
return;
}
} catch (MalformedObjectNameException e) {
} catch (IOException e) {
if (jmxc != null) {
try {
jmxc.close();
} catch (IOException e1) {
}
}
}
}
throw new VirtualMachineException("Unable to find config loader jvm.");
}Example 7
| Project: Bias-master File: LocalMachineSource.java View source code |
private VirtualMachine attach(VirtualMachineDescriptor descriptor) { try { com.sun.tools.attach.VirtualMachine vm = com.sun.tools.attach.VirtualMachine.attach(descriptor); String vmArgs = vm.getAgentProperties().getProperty(VM_ARGS); String id = descriptor.id(); String displayName = descriptor.displayName(); boolean agentLoaded = vmArgs.contains(AGENT_NAME); String userDir = getUserDir(vm); return new VirtualMachine(id, displayName, agentLoaded, userDir, vmArgs); } catch (AttachNotSupportedException e) { logger.warn(e.getMessage()); } catch (IOException e) { if (!noSuchProcess(e)) { logger.warn(e.getMessage(), e); } } return null; }
Example 8
| Project: excalibur-master File: Util.java View source code |
public static List<JVMFlagItem> parseFlags(String pid) {
try {
VirtualMachine vm = VirtualMachine.attach(pid);
HotSpotVirtualMachine hvm = (HotSpotVirtualMachine) vm;
InputStream in = hvm.executeJCmd("VM.flags -all");
byte buffer[] = new byte[256];
StringBuilder sbd = new StringBuilder(100000);
int n;
do {
n = in.read(buffer);
if (n > 0) {
String s = new String(buffer, 0, n, "UTF-8");
sbd.append(s);
}
} while (n > 0);
in.close();
vm.detach();
String[] flags = sbd.toString().split("\n");
List<JVMFlagItem> result = Lists.newArrayListWithCapacity(128);
Pattern ptn = Pattern.compile("\\s*([^\\s]+)\\s+([^\\s]+)\\s+(=|:=)([^\\{]+)\\{(.*)\\}");
for (int i = 1; i < flags.length; i++) {
Matcher m = ptn.matcher(flags[i]);
if (m.find()) {
result.add(JVMFlagItem.builder().flagName(m.group(2)).original(m.group(3).equals("=")).value(m.group(4).trim()).type(m.group(5)).build());
}
}
return result;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}Example 9
| Project: honest-profiler-master File: LocalMachineSource.java View source code |
private VirtualMachine attach(VirtualMachineDescriptor descriptor) { try { com.sun.tools.attach.VirtualMachine vm = com.sun.tools.attach.VirtualMachine.attach(descriptor); String vmArgs = vm.getAgentProperties().getProperty(VM_ARGS); String id = descriptor.id(); String displayName = descriptor.displayName(); boolean agentLoaded = vmArgs.contains(AGENT_NAME); String userDir = getUserDir(vm); return new VirtualMachine(id, displayName, agentLoaded, userDir, vmArgs); } catch (AttachNotSupportedException e) { logger.warn(e.getMessage()); } catch (IOException e) { if (!noSuchProcess(e)) { logger.warn(e.getMessage(), e); } } return null; }
Example 10
| Project: analytica-agent-master File: VirtualMachineAgentLoader.java View source code |
/**
* Charge un agent à chaud.
* @param agentPath Chemin vers le jar de l'agent
* @param option option de l'agent
*/
public static void loadAgent(final String agentPath, final String option) {
LOG.info("dynamically loading javaagent: " + agentPath + "=" + option);
final String nameOfRunningVM = ManagementFactory.getRuntimeMXBean().getName();
final int p = nameOfRunningVM.indexOf('@');
final String pid = nameOfRunningVM.substring(0, p);
try {
//on check, pour indiquer où trouver ce jar
VirtualMachineAgentLoader.class.getClassLoader().loadClass(VIRTUAL_MACHINE_CLASS_NAME);
} catch (final ClassNotFoundException e) {
throw new RuntimeException("La class " + VIRTUAL_MACHINE_CLASS_NAME + " est utilisée pour ajout l'agent à la VM. Ajouter le tools.jar du jdk 1.6+ dans le classpath", e);
}
try {
final com.sun.tools.attach.VirtualMachine vm = com.sun.tools.attach.VirtualMachine.attach(pid);
vm.loadAgent(agentPath, option);
vm.detach();
} catch (final Exception e) {
throw new RuntimeException(e);
}
}Example 11
| Project: classlib6-master File: LocalVirtualMachine.java View source code |
private static void getAttachableVMs(Map<Integer, LocalVirtualMachine> map) {
List<VirtualMachineDescriptor> vms = VirtualMachine.list();
for (VirtualMachineDescriptor vmd : vms) {
try {
Integer vmid = Integer.valueOf(vmd.id());
if (!map.containsKey(vmid)) {
boolean attachable = false;
String address = null;
try {
VirtualMachine vm = VirtualMachine.attach(vmd);
attachable = true;
Properties agentProps = vm.getAgentProperties();
address = (String) agentProps.get(LOCAL_CONNECTOR_ADDRESS_PROP);
vm.detach();
} catch (AttachNotSupportedException x) {
} catch (IOException x) {
}
map.put(vmid, new LocalVirtualMachine(vmid.intValue(), vmd.displayName(), attachable, address));
}
} catch (NumberFormatException e) {
}
}
}Example 12
| Project: ikvm-openjdk-master File: JMap.java View source code |
private static void dump(String pid, String options) throws IOException {
// parse the options to get the dump filename
String filename = parseDumpOptions(options);
if (filename == null) {
// invalid options or no filename
usage();
}
// get the canonical path - important to avoid just passing
// a "heap.bin" and having the dump created in the target VM
// working directory rather than the directory where jmap
// is executed.
filename = new File(filename).getCanonicalPath();
// dump live objects only or not
boolean live = isDumpLiveObjects(options);
VirtualMachine vm = attach(pid);
System.out.println("Dumping heap to " + filename + " ...");
InputStream in = ((HotSpotVirtualMachine) vm).dumpHeap((Object) filename, (live ? LIVE_OBJECTS_OPTION : ALL_OBJECTS_OPTION));
drain(vm, in);
}Example 13
| Project: jdk7u-jdk-master File: JMap.java View source code |
private static void dump(String pid, String options) throws IOException {
// parse the options to get the dump filename
String filename = parseDumpOptions(options);
if (filename == null) {
// invalid options or no filename
usage();
}
// get the canonical path - important to avoid just passing
// a "heap.bin" and having the dump created in the target VM
// working directory rather than the directory where jmap
// is executed.
filename = new File(filename).getCanonicalPath();
// dump live objects only or not
boolean live = isDumpLiveObjects(options);
VirtualMachine vm = attach(pid);
System.out.println("Dumping heap to " + filename + " ...");
InputStream in = ((HotSpotVirtualMachine) vm).dumpHeap((Object) filename, (live ? LIVE_OBJECTS_OPTION : ALL_OBJECTS_OPTION));
drain(vm, in);
}Example 14
| Project: ManagedRuntimeInitiative-master File: JMap.java View source code |
private static void dump(String pid, String options) throws IOException {
// parse the options to get the dump filename
String filename = parseDumpOptions(options);
if (filename == null) {
// invalid options or no filename
usage();
}
// get the canonical path - important to avoid just passing
// a "heap.bin" and having the dump created in the target VM
// working directory rather than the directory where jmap
// is executed.
filename = new File(filename).getCanonicalPath();
// dump live objects only or not
boolean live = isDumpLiveObjects(options);
VirtualMachine vm = attach(pid);
System.out.println("Dumping heap to " + filename + " ...");
InputStream in = ((HotSpotVirtualMachine) vm).dumpHeap((Object) filename, (live ? LIVE_OBJECTS_OPTION : ALL_OBJECTS_OPTION));
drain(vm, in);
}Example 15
| Project: openjdk-master File: DefineClass.java View source code |
private static void loadInstrumentationAgent(String myName, byte[] buf) throws Exception {
// Create agent jar file on the fly
Manifest m = new Manifest();
m.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
m.getMainAttributes().put(new Attributes.Name("Agent-Class"), myName);
m.getMainAttributes().put(new Attributes.Name("Can-Redefine-Classes"), "true");
File jarFile = File.createTempFile("agent", ".jar");
jarFile.deleteOnExit();
JarOutputStream jar = new JarOutputStream(new FileOutputStream(jarFile), m);
jar.putNextEntry(new JarEntry(myName.replace('.', '/') + ".class"));
jar.write(buf);
jar.close();
String pid = Long.toString(ProcessTools.getProcessId());
System.out.println("Our pid is = " + pid);
VirtualMachine vm = VirtualMachine.attach(pid);
vm.loadAgent(jarFile.getAbsolutePath());
}Example 16
| Project: openjdk8-jdk-master File: JMap.java View source code |
private static void dump(String pid, String options) throws IOException {
// parse the options to get the dump filename
String filename = parseDumpOptions(options);
if (filename == null) {
// invalid options or no filename
usage();
}
// get the canonical path - important to avoid just passing
// a "heap.bin" and having the dump created in the target VM
// working directory rather than the directory where jmap
// is executed.
filename = new File(filename).getCanonicalPath();
// dump live objects only or not
boolean live = isDumpLiveObjects(options);
VirtualMachine vm = attach(pid);
System.out.println("Dumping heap to " + filename + " ...");
InputStream in = ((HotSpotVirtualMachine) vm).dumpHeap((Object) filename, (live ? LIVE_OBJECTS_OPTION : ALL_OBJECTS_OPTION));
drain(vm, in);
}Example 17
| Project: Rio-master File: JMXConnectionUtil.java View source code |
/**
* Using the <a
* href="http://java.sun.com/javase/6/docs/technotes/guides/attach/index.html">
* JMX Attach API </a>, connect to a local Java Virtual Machine.
*
* <p>This utility requires Java 6 or greater.
*
* @param id The identifier used to connect to the Java Virtual Machine
* @return An MBeanServerConnection to the platform MBeanServer of the
* Java Virtual Machine identified, or null if the connection cannot be
* created.
*
* @throws Exception if the following occurs:
* <ul>
* <li>MBeanServerConnection cannot be created</li>
* <li>If the underlying provider either does not exist, or if the provider attempts to attach to a
* Java virtual machine with which it is not compatible.</li>
* <li>If an agent fails to initialize in the target Java virtual machine.</li>
* <li>If an agent cannot be loaded into the target Java virtual machine.</li>
* </ul>
*/
public static MBeanServerConnection attach(final String id) throws Exception {
String jvmVersion = System.getProperty("java.version");
if (jvmVersion.contains("1.5")) {
logger.info("The JMX Attach APIs require Java 6 or above. You are running Java {}", jvmVersion);
return null;
}
VirtualMachine vm = VirtualMachine.attach(id);
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");
}
MBeanServerConnection mbs = null;
if (connectorAddr != null) {
JMXServiceURL serviceURL = new JMXServiceURL(connectorAddr);
JMXConnector connector = JMXConnectorFactory.connect(serviceURL);
mbs = connector.getMBeanServerConnection();
}
return mbs;
}Example 18
| Project: btrace-master File: Client.java View source code |
/**
* Attach the BTrace client to the given Java process.
* Loads BTrace agent on the target process if not loaded
* already. Accepts the full path of the btrace agent jar.
* Also, accepts system classpath and boot classpath optionally.
*/
public void attach(String pid, String agentPath, String sysCp, String bootCp) throws IOException {
try {
VirtualMachine vm = null;
if (debug) {
debugPrint("attaching to " + pid);
}
vm = VirtualMachine.attach(pid);
if (debug) {
debugPrint("checking port availability: " + port);
}
Properties serverVmProps = vm.getSystemProperties();
int serverPort = Integer.parseInt(serverVmProps.getProperty("btrace.port", "-1"));
if (serverPort != -1) {
if (serverPort != port) {
throw new IOException("Can not attach to PID " + pid + " on port " + port + ". There is already a BTrace server active on port " + serverPort + "!");
}
} else {
if (!isPortAvailable(port)) {
throw new IOException("Port " + port + " unavailable.");
}
}
if (debug) {
debugPrint("attached to " + pid);
}
if (debug) {
debugPrint("loading " + agentPath);
}
String agentArgs = "port=" + port;
if (statsdDef != null) {
agentArgs += ",statsd=" + statsdDef;
}
if (debug) {
agentArgs += ",debug=true";
}
if (trusted) {
agentArgs += ",trusted=true";
}
if (dumpClasses) {
agentArgs += ",dumpClasses=true";
agentArgs += ",dumpDir=" + dumpDir;
}
if (trackRetransforms) {
agentArgs += ",trackRetransforms=true";
}
if (bootCp != null) {
agentArgs += ",bootClassPath=" + bootCp;
}
String toolsPath = getToolsJarPath(serverVmProps.getProperty("java.class.path"), serverVmProps.getProperty("java.home"));
if (sysCp == null) {
sysCp = toolsPath;
} else {
sysCp = sysCp + File.pathSeparator + toolsPath;
}
agentArgs += ",systemClassPath=" + sysCp;
String cmdQueueLimit = System.getProperty(BTraceRuntime.CMD_QUEUE_LIMIT_KEY, null);
if (cmdQueueLimit != null) {
agentArgs += ",cmdQueueLimit=" + cmdQueueLimit;
}
agentArgs += ",probeDescPath=" + probeDescPath;
if (debug) {
debugPrint("agent args: " + agentArgs);
}
vm.loadAgent(agentPath, agentArgs);
if (debug) {
debugPrint("loaded " + agentPath);
}
} catch (RuntimeException re) {
throw re;
} catch (IOException ioexp) {
throw ioexp;
} catch (Exception exp) {
throw new IOException(exp.getMessage());
}
}Example 19
| Project: hiccup-master File: HiccupMeterAttacher.java View source code |
public static void main(final String[] args) {
HiccupMeter.HiccupMeterConfiguration config = new HiccupMeter.HiccupMeterConfiguration(args, HiccupMeter.defaultHiccupLogFileName);
if (config.error) {
System.exit(1);
}
if (!config.attachToProcess) {
System.err.println("HiccupMeterAttacher: must be used with -p option.");
System.exit(1);
}
try {
// We are supposed to attach to another process and launch a jHiccup agent there, not here.
if (config.verbose) {
System.out.println("Attaching to process " + config.pidOfProcessToAttachTo + " and launching jHiccup agent from jar " + config.pidOfProcessToAttachTo + " with args: " + config.agentArgs);
}
VirtualMachine vm = VirtualMachine.attach(config.pidOfProcessToAttachTo);
vm.loadAgent(config.agentJarFileName, config.agentArgs);
vm.detach();
System.exit(0);
} catch (IOException ex) {
System.out.println(ex);
System.exit(1);
} catch (AttachNotSupportedException ex) {
System.out.println(ex);
System.exit(1);
} catch (AgentInitializationException ex) {
System.out.println(ex);
System.exit(1);
} catch (AgentLoadException ex) {
System.out.println(ex);
System.exit(1);
}
}Example 20
| Project: Java-threadTop-master File: JMXConnection.java View source code |
public static Class addToolsJar() {
try {
return com.sun.tools.attach.VirtualMachine.class;
} catch (Throwable t) {
System.out.println("tools.jar not in class path from" + System.getProperty("java.home"));
File toolsJar = new File(System.getProperty("java.home") + "/lib/tools.jar");
System.out.println("try:" + toolsJar);
if (toolsJar.exists()) {
addURL(toolsJar);
System.out.println(toolsJar);
} else {
toolsJar = new File(System.getProperty("java.home") + "/../lib/tools.jar");
System.out.println("try:" + toolsJar);
if (toolsJar.exists()) {
addURL(toolsJar);
System.out.println("Found:" + toolsJar);
} else {
System.out.println("Unable to locate tools.jar pls add it to classpath");
}
}
}
return com.sun.tools.attach.VirtualMachine.class;
}Example 21
| Project: JDave-master File: Unfinalizer.java View source code |
/**
* Removes final from classes and methods loaded <strong>after</strong> this
* is called.
* <p>
* Removing finals after a class has been loaded is not supported by the
* JVM. In a serial environment, such as running within your build tool, you
* currently have to use something silly like what I did in sample project
* if another test uses the classes you want to unfinalize before
* unfinalizer first runs.
*
*/
public static synchronized void unfinalize() {
if (!initialized) {
try {
final Filter filter = new Filter();
final VirtualMachine jvm = VirtualMachine.attach(filter.getCurrentJvm(new JVMHelper()));
jvm.loadAgent(filter.getUnfinalizerJarPath(jvm.getSystemProperties()));
jvm.detach();
} catch (final Exception e) {
throw new RuntimeException(e);
}
}
initialized = true;
}Example 22
| Project: jmx-agent-master File: DynamicallyAgentAttacher.java View source code |
public static void main(String[] args) {
if (args.length != 3) {
printUsage();
System.exit(1);
}
String agentJarPath = args[0];
String targetJvmPid = args[1];
String configurationFile = args[2];
logger.info("Dynamically loading jmxtrans-agent");
logger.info("Agent path: " + agentJarPath);
logger.info("Target JVM PID: " + targetJvmPid);
logger.info("XML configuration file: " + configurationFile);
try {
VirtualMachine vm = VirtualMachine.attach(targetJvmPid);
vm.loadAgent(agentJarPath, configurationFile);
vm.detach();
} catch (Exception e) {
e.printStackTrace();
}
}Example 23
| Project: mjprof-master File: JstackDataSourcePlugin.java View source code |
private static String runThreadDump(String pid, String args[]) throws Exception {
StringBuilder sb = new StringBuilder();
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");
sb.append(s);
}
} while (n > 0);
in.close();
vm.detach();
return sb.toString();
}Example 24
| Project: one-nio-master File: ThreadDumperImpl.java View source code |
public static void dump(OutputStream out) throws IOException {
HotSpotVirtualMachine vm;
try {
vm = (HotSpotVirtualMachine) VirtualMachine.attach(PID);
} catch (AttachNotSupportedException e) {
throw new IOException(e);
}
try {
if (out == null) {
vm.localDataDump();
} else {
InputStream in = vm.remoteDataDump();
try {
copy(in, out);
} finally {
in.close();
}
}
} finally {
vm.detach();
}
}Example 25
| Project: org.intrace-master File: InTraceLoader.java View source code |
public static void loadAgent(Application app, StatusHandler handler) {
Jvm jvm = JvmFactory.getJVMFor(app);
if (app.isLocalApplication() && jvm.isAttachable() && jvm.isGetSystemPropertiesSupported()) {
try {
VirtualMachine vm = VirtualMachine.attach(String.valueOf(app.getPid()));
handler.handleStatus("Attached to JVM (PID: " + app.getPid() + ")");
vm.loadAgent(Locator.agentPath, "");
handler.handleStatus("InTrace Agent loaded");
} catch (Exception ex) {
handler.handleStatus("Exception thrown:\n" + throwableToString(ex));
Exceptions.printStackTrace(ex);
}
}
}Example 26
| Project: perf-workshop-master File: HiccupMeterAttacher.java View source code |
public static void main(final String[] args) {
HiccupMeter.HiccupMeterConfiguration config = new HiccupMeter.HiccupMeterConfiguration(args, HiccupMeter.defaultHiccupLogFileName);
if (config.error) {
System.exit(1);
}
if (!config.attachToProcess) {
System.err.println("HiccupMeterAttacher: must be used with -p option.");
System.exit(1);
}
try {
// We are supposed to attach to another process and launch a jHiccup agent there, not here.
if (config.verbose) {
System.out.println("Attaching to process " + config.pidOfProcessToAttachTo + " and launching jHiccup agent from jar " + config.pidOfProcessToAttachTo + " with args: " + config.agentArgs);
}
VirtualMachine vm = VirtualMachine.attach(config.pidOfProcessToAttachTo);
vm.loadAgent(config.agentJarFileName, config.agentArgs);
vm.detach();
System.exit(0);
} catch (IOException ex) {
System.out.println(ex);
System.exit(1);
} catch (AttachNotSupportedException ex) {
System.out.println(ex);
System.exit(1);
} catch (AgentInitializationException ex) {
System.out.println(ex);
System.exit(1);
} catch (AgentLoadException ex) {
System.out.println(ex);
System.exit(1);
}
}Example 27
| Project: samurai-master File: ThreadDumpUtil.java View source code |
public static byte[] getThreadDump(int pid) throws AttachNotSupportedException, IOException {
HotSpotVirtualMachine virtualMachine = null;
try {
virtualMachine = (HotSpotVirtualMachine) VirtualMachine.attach(String.valueOf(pid));
try (InputStream in = virtualMachine.remoteDataDump()) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int count;
byte[] buf = new byte[256];
while ((count = in.read(buf)) != -1) {
baos.write(buf, 0, count);
}
return baos.toByteArray();
}
} finally {
if (virtualMachine != null) {
try {
virtualMachine.detach();
} catch (IOException ignore) {
}
}
}
}Example 28
| Project: sizeof4j-master File: HotSpotHistogram.java View source code |
public static Map<String, HistogramEntry> heapHistogram() {
String processId = JvmUtil.processId();
VirtualMachine vm = null;
try {
vm = VirtualMachine.attach(processId);
final InputStream in = ((HotSpotVirtualMachine) vm).heapHisto();
final String histo = IOUtil.read(in);
return parse(histo);
} catch (AttachNotSupportedExceptionIOException | e) {
throw new SizeOfException(e);
} finally {
if (vm != null) {
try {
vm.detach();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}Example 29
| Project: tomee-master File: Agent.java View source code |
private static void dynamicLoadAgent() throws Exception {
if (instrumentation != null) {
return;
}
try {
final Class<?> vmClass = Class.forName("com.sun.tools.attach.VirtualMachine");
final Method attachMethod = vmClass.getMethod("attach", String.class);
final Method loadAgentMethod = vmClass.getMethod("loadAgent", String.class);
// find the agentJar
final String agentPath = getAgentJar();
// get the pid of the current process (for attach command)
final String pid = getPid();
// attach to the vm
final Object vm = attachMethod.invoke(null, new String[] { pid });
// load our agent
loadAgentMethod.invoke(vm, agentPath);
// The AgentJar is loaded into the system classpath, and this class could
// be in a child classloader, so we need to double check the system classpath
checkSystemClassPath();
} catch (final ClassNotFoundExceptionNoSuchMethodException | e) {
}
}Example 30
| Project: hudson_plugins-master File: JavaProcInfo.java View source code |
public Properties call() throws Exception {
super.call();
VirtualMachine vm = null;
try {
vm = VirtualMachine.attach(pid);
return vm.getSystemProperties();
} finally {
if (vm != null) {
try {
vm.detach();
} catch (Exception e) {
}
}
}
}Example 31
| Project: cyrille-leclerc-master File: AttachProcessTest.java View source code |
@Test
public void test() throws Exception {
final String CONNECTOR_ADDRESS = "com.sun.management.jmxremote.localConnectorAddress";
// attach to the target application
VirtualMachine vm = VirtualMachine.attach("1028");
// 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
System.out.println("Connect to " + connectorAddress);
JMXServiceURL url = new JMXServiceURL(connectorAddress);
JMXConnector connector = JMXConnectorFactory.connect(url);
MBeanServerConnection mbeanServerConnection = connector.getMBeanServerConnection();
Set<ObjectInstance> objectInstances = mbeanServerConnection.queryMBeans(new ObjectName("*:*"), null);
for (ObjectInstance objectInstance : objectInstances) {
ObjectName objectName = objectInstance.getObjectName();
System.out.println(objectName);
}
}Example 32
| Project: fabric8-master File: ApmAgentLauncher.java View source code |
public static void loadAgent(String pid, String args) throws IOException {
VirtualMachine vm;
try {
vm = VirtualMachine.attach(pid);
} catch (AttachNotSupportedException x) {
IOException ioe = new IOException(x.getMessage());
ioe.initCause(x);
throw ioe;
}
try {
String agent = ApmAgentLauncher.class.getProtectionDomain().getCodeSource().getLocation().getPath();
System.err.println("Trying to load agent " + agent);
vm.loadAgent(agent, args);
System.out.println("Agent successfully loaded");
} catch (AgentLoadException x) {
IOException ioe = new IOException(x.getMessage());
ioe.initCause(x);
throw ioe;
} catch (AgentInitializationException x) {
IOException ioe = new IOException(x.getMessage());
ioe.initCause(x);
throw ioe;
} finally {
if (vm != null) {
vm.detach();
}
}
}Example 33
| Project: instrumentj-master File: Main.java View source code |
/**
*
* @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();
}Example 34
| Project: jboss-libra-master File: LibraAttacher.java View source code |
static void attach() {
for (VirtualMachineDescriptor virtualMachineDescriptor : VirtualMachine.list()) {
try {
VirtualMachine virtualMachine = virtualMachineDescriptor.provider().attachVirtualMachine(virtualMachineDescriptor);
try {
String propertyName = Libra.class.getName() + ".installed";
Properties systemProperties = virtualMachine.getSystemProperties();
Properties agentProperties = virtualMachine.getAgentProperties();
String installed = agentProperties.getProperty(propertyName, systemProperties.getProperty(propertyName));
if (installed == null || Boolean.valueOf(installed) == false) {
String javaClassPath = systemProperties.getProperty("java.class.path");
String location = Libra.class.getProtectionDomain().getCodeSource().getLocation().getFile();
if (javaClassPath.contains(location)) {
virtualMachine.loadAgent(location, propertyName + "=true");
log.info("Libra installed in " + virtualMachineDescriptor);
}
} else {
log.info("Libra already installed in " + virtualMachineDescriptor);
}
} finally {
virtualMachine.detach();
}
} catch (Exception e) {
log.warning("Failed to install Libra into " + virtualMachineDescriptor + ": " + e.getMessage());
}
}
}Example 35
| Project: jRT-master File: Attachermain.java View source code |
public static void main(String[] args) {
//TODO: Exclude CLI option Xbootclasspath/a=...../tools.jar
// try {
// Method method = URLClassLoader.class.getDeclaredMethod("addURL", new Class[]{URL.class});
// method.setAccessible(true);
// method.invoke(ClassLoader.getSystemClassLoader(), new Object[]{new File("/usr/lib/jvm/java-1.7.0-openjdk-amd64/lib/tools.jar").toURI().toURL()});
// } catch (Exception e) {
// }
boolean needHelp = false;
String pid = null;
String agentArguments = "";
for (String s : args) {
if (s.startsWith("-pid")) {
String[] p = s.split("=");
if (p.length == 2) {
pid = p[1];
} else {
needHelp = true;
}
} else if (s.startsWith("-agentargs")) {
String[] p = s.split("=", 2);
if (p.length == 2) {
agentArguments = p[1];
} else {
needHelp = true;
}
} else if (s.startsWith("-h") || s.startsWith("--help") || s.startsWith("-help")) {
needHelp = true;
} else {
needHelp = true;
}
}
//validate agent arguments
//print help message and exit if something is wrong
{
(new JRT()).parseArguments(agentArguments);
}
if (needHelp || null == pid) {
System.err.println("please, to attach jRT to already running application rerun it in next manner:\n\n" + "\tjava -jar jRT.jar -pid=<PID of java VM> -agentargs='<args>' \n\n");
JRT.printHelpParameters();
System.exit(1);
}
try {
VirtualMachine vm = VirtualMachine.attach(pid);
vm.loadAgent(Agentmain.class.getProtectionDomain().getCodeSource().getLocation().getPath(), agentArguments);
vm.detach();
System.exit(0);
} catch (IOException e) {
System.err.println("Seems like java process with pid=" + pid + " doesn't exist or not permit to instrument. \nPlease ensure that pid is correct.");
} catch (AgentInitializationException e) {
System.err.println("Failed to initialize agent: " + e);
} catch (AgentLoadException e) {
System.err.println("Failed to load agent: " + e);
} catch (AttachNotSupportedException e) {
System.err.println("Seems like attach isn't supported: " + e);
}
}Example 36
| Project: moonshine-master File: JmxUtils.java View source code |
public static JMXServiceURL attachToJMX(Long pid) {
String CONNECTOR_ADDRESS = "com.sun.management.jmxremote.localConnectorAddress";
VirtualMachine vm;
try {
vm = VirtualMachine.attach(pid.toString());
} catch (AttachNotSupportedExceptionIOException | e) {
throw new RuntimeException(e);
}
try {
String connectorAddress = vm.getAgentProperties().getProperty(CONNECTOR_ADDRESS);
if (connectorAddress == null) {
String agent = vm.getSystemProperties().getProperty("java.home") + File.separator + "lib" + File.separator + "management-agent.jar";
vm.loadAgent(agent);
connectorAddress = vm.getAgentProperties().getProperty(CONNECTOR_ADDRESS);
}
return new JMXServiceURL(connectorAddress);
} catch (IOExceptionAgentLoadException | AgentInitializationException | e) {
throw new RuntimeException(e);
} finally {
try {
vm.detach();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}Example 37
| Project: javamelody-master File: VirtualMachine.java View source code |
private static // NOPMD
Class<?> findVirtualMachineClass() throws // NOPMD
Exception {
// méthode inspirée de javax.tools.ToolProvider.Lazy.findClass
// http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b27/javax/tools/ToolProvider.java#ToolProvider.Lazy.findClass%28%29
final String virtualMachineClassName = "com.sun.tools.attach.VirtualMachine";
try {
// try loading class directly, in case tools.jar is in the classpath
return Class.forName(virtualMachineClassName);
} catch (final ClassNotFoundException e) {
File file = new File(System.getProperty("java.home"));
if ("jre".equalsIgnoreCase(file.getName())) {
file = file.getParentFile();
}
final String[] defaultToolsLocation = { "lib", "tools.jar" };
for (final String name : defaultToolsLocation) {
file = new File(file, name);
}
if (!file.exists()) {
throw e;
}
final URL url = file.toURI().toURL();
final ClassLoader cl;
final URL[] urls = { url };
cl = URLClassLoader.newInstance(urls);
return Class.forName(virtualMachineClassName, true, cl);
}
}Example 38
| Project: javamelody-mirror-backup-master File: VirtualMachine.java View source code |
private static // NOPMD
Class<?> findVirtualMachineClass() throws // NOPMD
Exception {
// méthode inspirée de javax.tools.ToolProvider.Lazy.findClass
// http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b27/javax/tools/ToolProvider.java#ToolProvider.Lazy.findClass%28%29
final String virtualMachineClassName = "com.sun.tools.attach.VirtualMachine";
try {
// try loading class directly, in case tools.jar is in the classpath
return Class.forName(virtualMachineClassName);
} catch (final ClassNotFoundException e) {
File file = new File(System.getProperty("java.home"));
if ("jre".equalsIgnoreCase(file.getName())) {
file = file.getParentFile();
}
final String[] defaultToolsLocation = { "lib", "tools.jar" };
for (final String name : defaultToolsLocation) {
file = new File(file, name);
}
if (!file.exists()) {
throw e;
}
final URL url = file.toURI().toURL();
final ClassLoader cl;
final URL[] urls = { url };
cl = URLClassLoader.newInstance(urls);
return Class.forName(virtualMachineClassName, true, cl);
}
}Example 39
| Project: agentsmith-master File: SmithLoader.java View source code |
/**
* Asks the jvm to load the Smith agent specified by the absolute path
* parameter and telling the agent to monitor the specified folder. This class
* is experimental as it needs a sort of low-level interaction with the
* operating system. The following assumptions are done:
* <ul>
* <li>The Process Identifier (PID of the target jvm) is a integer </li>
* <li>The latest started jvm is the one we want to plug the agent into and
* it has the greatest PID</li>
* </ul>
* If any of these assumptions are NOT valid for your operating system, please
* report is ASAP and contribute to the project
*
* @param pathToSmithJar
* the absolute path to the Smith jar
* @param args
* the SmithArgs instance
* @throws Exception
* if something goes wrong
*/
public static void hotStart(String pathToSmithJar, SmithArgs args) throws Exception {
List<VirtualMachineDescriptor> vmds = new LinkedList<VirtualMachineDescriptor>(VirtualMachine.list());
Collections.sort(vmds, new Comparator<VirtualMachineDescriptor>() {
public int compare(VirtualMachineDescriptor one, VirtualMachineDescriptor two) {
return Integer.valueOf(two.id()).compareTo(Integer.valueOf(one.id()));
}
});
VirtualMachine vm = VirtualMachine.attach(vmds.get(0));
vm.loadAgent(pathToSmithJar, args.toString());
}Example 40
| Project: geode-master File: LocalProcessController.java View source code |
/**
* 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);
}Example 41
| Project: greys-anatomy-master File: GreysLauncher.java View source code |
/*
* åŠ è½½Agent
*/
private void attachAgent(Configure configure) throws Exception {
final ClassLoader loader = Thread.currentThread().getContextClassLoader();
final Class<?> vmdClass = loader.loadClass("com.sun.tools.attach.VirtualMachineDescriptor");
final Class<?> vmClass = loader.loadClass("com.sun.tools.attach.VirtualMachine");
Object attachVmdObj = null;
for (Object obj : (List<?>) vmClass.getMethod("list", (Class<?>[]) null).invoke(null, (Object[]) null)) {
if ((vmdClass.getMethod("id", (Class<?>[]) null).invoke(obj, (Object[]) null)).equals(Integer.toString(configure.getJavaPid()))) {
attachVmdObj = obj;
}
}
// if (null == attachVmdObj) {
// // throw new IllegalArgumentException("pid:" + configure.getJavaPid() + " not existed.");
// }
Object vmObj = null;
try {
if (null == attachVmdObj) {
// 使用 attach(String pid) 这�方�
vmObj = vmClass.getMethod("attach", String.class).invoke(null, "" + configure.getJavaPid());
} else {
vmObj = vmClass.getMethod("attach", vmdClass).invoke(null, attachVmdObj);
}
vmClass.getMethod("loadAgent", String.class, String.class).invoke(vmObj, configure.getGreysAgent(), configure.getGreysCore() + ";" + configure.toString());
} finally {
if (null != vmObj) {
vmClass.getMethod("detach", (Class<?>[]) null).invoke(vmObj, (Object[]) null);
}
}
}Example 42
| Project: jillegal-agent-master File: JillegalAgent.java View source code |
private static void loadAgent(String arguments) throws Exception {
VirtualMachine vm = VirtualMachine.attach(getPidFromRuntimeMBean());
String agentPath = null;
String classPath = getClassPath();
LogUtil.info("OS Name: " + OsUtil.OS);
LogUtil.info("Class Path: " + classPath);
for (String entry : classPath.split(File.pathSeparator)) {
File f = new File(entry);
if (f.exists() && f.getName().startsWith(INSTR_JAR_PREFIX)) {
agentPath = entry;
break;
}
}
LogUtil.info("Agent path: " + agentPath);
if (agentPath == null) {
throw new RuntimeException("Profiler agent is not in classpath ...");
}
if (arguments != null) {
vm.loadAgent(agentPath, arguments);
} else {
vm.loadAgent(agentPath);
}
vm.detach();
}Example 43
| Project: liverepl-master File: Main.java View source code |
private static void listPids() {
System.out.println();
System.out.println("liverepl");
System.out.println("Usage: liverepl <pid>");
System.out.println();
System.out.println("List of Java processes");
System.out.format("%1$-6s %2$.60s%n", "pid", "Details");
for (VirtualMachineDescriptor vmd : VirtualMachine.list()) {
System.out.format("%1$-6s %2$.60s%n", vmd.id(), vmd.displayName());
}
}Example 44
| Project: Maven-JMX-Plugin-master File: AbstractJmxMojo.java View source code |
public final void interactWithAllLocalMBeanServers(MBeanServerCallback callback) throws IOException, MojoExecutionException {
for (VirtualMachineDescriptor desc : VirtualMachine.list()) {
VirtualMachine vm = attach(desc);
if (vm != null) {
JMXServiceURL connectorAddress = getConnectorAddress(desc, vm);
if (connectorAddress != null) {
getLog().info("About to interact with " + desc.displayName());
interact(connectorAddress, callback);
}
}
}
}Example 45
| Project: visualvm-master File: AttachModelProvider.java View source code |
public AttachModel createModelFor(Application app) {
if (Host.LOCALHOST.equals(app.getHost())) {
JvmJvmstatModel jvmstat = JvmJvmstatModelFactory.getJvmstatModelFor(app);
if (jvmstat != null && jvmstat.isAttachable()) {
if (Utilities.isWindows()) {
// on Windows Attach API can only attach to the process of the same
// architecture ( 32bit / 64bit )
Boolean this64bitArch = is64BitArchitecture();
Boolean app64bitArch = is64BitArchitecture(jvmstat);
if (this64bitArch != null && app64bitArch != null) {
if (!this64bitArch.equals(app64bitArch)) {
return null;
}
}
}
// check that application is running under the same user as VisualVM
String pid = String.valueOf(app.getPid());
for (VirtualMachineDescriptor descr : VirtualMachine.list()) {
if (pid.equals(descr.id())) {
String vmName = jvmstat.getVmName();
if (vmName != null) {
if ("BEA JRockit(R)".equals(vmName)) {
// NOI18N
return new JRockitAttachModelImpl(app);
}
if ("Oracle JRockit(R)".equals(vmName)) {
// NOI18N
return new OracleJRockitAttachModelImpl(app);
}
}
return new AttachModelImpl(app);
}
}
}
}
return null;
}Example 46
| Project: graal-core-master File: RedefineIntrinsicTest.java View source code |
public static void loadAgent(Path agent) throws Exception {
String vmName = ManagementFactory.getRuntimeMXBean().getName();
int p = vmName.indexOf('@');
assumeTrue("VM name not in <pid>@<host> format: " + vmName, p != -1);
String pid = vmName.substring(0, p);
Class<?> c;
if (Java8OrEarlier) {
ClassLoader cl = ToolProvider.getSystemToolClassLoader();
c = Class.forName("com.sun.tools.attach.VirtualMachine", true, cl);
} else {
// I don't know what changed to make this necessary...
c = Class.forName("com.sun.tools.attach.VirtualMachine", true, RedefineIntrinsicTest.class.getClassLoader());
}
Method attach = c.getDeclaredMethod("attach", String.class);
Method loadAgent = c.getDeclaredMethod("loadAgent", String.class, String.class);
Method detach = c.getDeclaredMethod("detach");
Object vm = attach.invoke(null, pid);
loadAgent.invoke(vm, agent.toString(), "");
detach.invoke(vm);
}Example 47
| Project: graal-master File: RedefineIntrinsicTest.java View source code |
public static void loadAgent(Path agent) throws Exception {
String vmName = ManagementFactory.getRuntimeMXBean().getName();
int p = vmName.indexOf('@');
assumeTrue("VM name not in <pid>@<host> format: " + vmName, p != -1);
String pid = vmName.substring(0, p);
Class<?> c;
if (Java8OrEarlier) {
ClassLoader cl = ToolProvider.getSystemToolClassLoader();
c = Class.forName("com.sun.tools.attach.VirtualMachine", true, cl);
} else {
// I don't know what changed to make this necessary...
c = Class.forName("com.sun.tools.attach.VirtualMachine", true, RedefineIntrinsicTest.class.getClassLoader());
}
Method attach = c.getDeclaredMethod("attach", String.class);
Method loadAgent = c.getDeclaredMethod("loadAgent", String.class, String.class);
Method detach = c.getDeclaredMethod("detach");
Object vm = attach.invoke(null, pid);
loadAgent.invoke(vm, agent.toString(), "");
detach.invoke(vm);
}Example 48
| Project: jolokia-master File: VirtualMachineHandler.java View source code |
// lookup virtual machine class
private Class lookupVirtualMachineClass() {
try {
return ToolsClassFinder.lookupClass("com.sun.tools.attach.VirtualMachine");
} catch (ClassNotFoundException exp) {
throw new ProcessingException("Cannot find classes from tools.jar. The heuristics for loading tools.jar which contains\n" + "essential classes for attaching to a running JVM could locate the necessary jar file.\n" + "\n" + "Please call this launcher with a qualified classpath on the command line like\n" + "\n" + " java -cp path/to/tools.jar:" + options.getJarFileName() + " org.jolokia.jvmagent.client.AgentLauncher [options] <command> <ppid>\n", exp, options);
}
}Example 49
| Project: lombok-intellij-plugin-master File: LiveInjector.java View source code |
private void injectInternal(String jarFile, String options) throws IllegalStateException {
String ownPidS = ManagementFactory.getRuntimeMXBean().getName();
ownPidS = ownPidS.substring(0, ownPidS.indexOf('@'));
int ownPid = Integer.parseInt(ownPidS);
try {
VirtualMachine vm = VirtualMachine.attach(String.valueOf(ownPid));
vm.loadAgent(jarFile, options);
} catch (Throwable exception) {
throw new IllegalStateException("agent injection not supported on this platform due to unknown reason", exception);
}
}Example 50
| Project: rhq-master File: JvmUtility.java View source code |
/**
* TODO
*
* @param process a java process
* @return the JMX service URL that can be used to obtain the java process' MBeanServer, or null if connecting to
* the process is not possible
*/
public static JMXServiceURL extractJMXServiceURL(ProcessInfo process) {
if (!attachApiAvailable) {
LOG.debug("Returning null, since the Attach API is not available...");
return null;
}
JMXServiceURL url;
try {
VirtualMachine vm = attachToVirtualMachine(process);
if (vm == null) {
return null;
}
String jmxConnectorAddress = getJmxConnectorAddress(vm);
try {
vm.detach();
} catch (Exception e) {
LOG.error("Failed to detach from JVM [" + vm + "].", e);
}
url = new JMXServiceURL(jmxConnectorAddress);
} catch (Exception e) {
throw new RuntimeException("Failed to extract JMX service URL for process with PID [" + process.getPid() + "].", e);
}
LOG.debug("JMX service URL for java process with PID [" + process.getPid() + "]: " + url);
return url;
}Example 51
| Project: Truffle-master File: RedefineIntrinsicTest.java View source code |
public static void loadAgent(Path agent) throws Exception {
String vmName = ManagementFactory.getRuntimeMXBean().getName();
int p = vmName.indexOf('@');
assumeTrue("VM name not in <pid>@<host> format: " + vmName, p != -1);
String pid = vmName.substring(0, p);
Class<?> c;
if (Java8OrEarlier) {
ClassLoader cl = ToolProvider.getSystemToolClassLoader();
c = Class.forName("com.sun.tools.attach.VirtualMachine", true, cl);
} else {
// I don't know what changed to make this necessary...
c = Class.forName("com.sun.tools.attach.VirtualMachine", true, RedefineIntrinsicTest.class.getClassLoader());
}
Method attach = c.getDeclaredMethod("attach", String.class);
Method loadAgent = c.getDeclaredMethod("loadAgent", String.class, String.class);
Method detach = c.getDeclaredMethod("detach");
Object vm = attach.invoke(null, pid);
loadAgent.invoke(vm, agent.toString(), "");
detach.invoke(vm);
}Example 52
| Project: blade.tools-master File: JMXBundleDeployer.java View source code |
/**
* Uses Oracle JDK's Attach API to try to search VMs on this machine looking
* for the osgi.core MBeans. This will stop searching for VMs once the
* MBeans are found. Beware if you have multiple JVMs with osgi.core MBeans
* published.
*
* @return
*/
@SuppressWarnings("unchecked")
static String getLocalConnectorAddress() {
ClassLoader cl = Thread.currentThread().getContextClassLoader();
ClassLoader toolsClassloader = null;
try {
toolsClassloader = getToolsClassLoader(cl);
if (toolsClassloader != null) {
Thread.currentThread().setContextClassLoader(toolsClassloader);
Class<?> vmClass = toolsClassloader.loadClass("com.sun.tools.attach.VirtualMachine");
Method listMethod = vmClass.getMethod("list");
List<Object> vmds = (List<Object>) listMethod.invoke(null);
for (Object vmd : vmds) {
try {
Class<?> vmdClass = toolsClassloader.loadClass("com.sun.tools.attach.VirtualMachineDescriptor");
Method idMethod = vmdClass.getMethod("id");
String id = (String) idMethod.invoke(vmd);
Method attachMethod = vmClass.getMethod("attach", String.class);
Object vm = attachMethod.invoke(null, id);
try {
Method getAgentPropertiesMethod = vmClass.getMethod("getAgentProperties");
Properties agentProperties = (Properties) getAgentPropertiesMethod.invoke(vm);
String localConnectorAddress = agentProperties.getProperty("com.sun.management.jmxremote.localConnectorAddress");
if (localConnectorAddress == null) {
File agentJar = findJdkJar("management-agent.jar");
if (agentJar != null) {
Method loadAgent = vmClass.getMethod("loadAgent", String.class);
loadAgent.invoke(vm, agentJar.getCanonicalPath());
agentProperties = (Properties) getAgentPropertiesMethod.invoke(vm);
localConnectorAddress = agentProperties.getProperty("com.sun.management.jmxremote.localConnectorAddress");
}
}
if (localConnectorAddress != null) {
final JMXServiceURL jmxServiceUrl = new JMXServiceURL(localConnectorAddress);
final JMXConnector jmxConnector = JMXConnectorFactory.connect(jmxServiceUrl, null);
final MBeanServerConnection mBeanServerConnection = jmxConnector.getMBeanServerConnection();
if (mBeanServerConnection != null) {
final ObjectName framework = getFramework(mBeanServerConnection);
if (framework != null) {
return localConnectorAddress;
}
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
Method detachMethod = vmClass.getMethod("detach");
detachMethod.invoke(vm);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
Thread.currentThread().setContextClassLoader(cl);
// try to get custom classloader to unload native libs
try {
if (toolsClassloader != null) {
Field nl = ClassLoader.class.getDeclaredField("nativeLibraries");
nl.setAccessible(true);
Vector<?> nativeLibs = (Vector<?>) nl.get(toolsClassloader);
for (Object nativeLib : nativeLibs) {
Field nameField = nativeLib.getClass().getDeclaredField("name");
nameField.setAccessible(true);
String name = (String) nameField.get(nativeLib);
if (new File(name).getName().contains("attach")) {
Method f = nativeLib.getClass().getDeclaredMethod("finalize");
f.setAccessible(true);
f.invoke(nativeLib);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}Example 53
| Project: CAPS-master File: ProcessUtil.java View source code |
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);
}
}Example 54
| Project: capsule-master File: ProcessUtil.java View source code |
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);
}
}Example 55
| Project: coprhd-controller-master File: DbManagerOps.java View source code |
private JMXConnector initJMXConnector(String svcName) throws IOException, AttachNotSupportedException, AgentLoadException, AgentInitializationException {
int pid = PlatformUtils.getServicePid(svcName);
log.info("Connecting to JMX of {} service with pid {}", svcName, pid);
VirtualMachine vm = VirtualMachine.attach(String.valueOf(pid));
try {
String connectorAddress = vm.getAgentProperties().getProperty(CONNECTOR_ADDRESS);
if (connectorAddress == null) {
String javaHome = vm.getSystemProperties().getProperty("java.home");
String agent = StringUtils.join(new String[] { javaHome, "lib", "management-agent.jar" }, File.separator);
vm.loadAgent(agent);
connectorAddress = vm.getAgentProperties().getProperty(CONNECTOR_ADDRESS);
}
JMXServiceURL serviceURL = new JMXServiceURL(connectorAddress);
return JMXConnectorFactory.connect(serviceURL);
} finally {
vm.detach();
}
}Example 56
| Project: druid-master File: DruidStat.java View source code |
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;
}Example 57
| Project: eguan-master File: JmxTestHelper.java View source code |
/**
* Gets the set of server URLs for all detected local MBean servers that have a registered MBeans of a given class
* and/or a provided ObjectName.
*
* @param objName
* the {@link ObjectName} to search for or <code>null</code>
* @param className
* the target class' canonical name or <code>null</code>
* @return a possibly empty {@link Set} of valid server URLs
* @throws NullPointerException
* if the provided {@link ObjectName} is <code>null</code>
*/
public static final Set<String> getLocalMBeanServerUrls(final ObjectName objName, final String className) throws NullPointerException {
final HashSet<String> result = new HashSet<String>();
final List<VirtualMachineDescriptor> javaVms = VirtualMachine.list();
final String mgmtAgentPath = System.getProperty("java.home") + String.format("%slib%smanagement-agent.jar", File.separator, File.separator);
for (final VirtualMachineDescriptor currDescriptor : javaVms) {
VirtualMachine currVm;
try {
currVm = VirtualMachine.attach(currDescriptor.id());
String connectorAddress = currVm.getAgentProperties().getProperty("com.sun.management.jmxremote.localConnectorAddress");
if (connectorAddress == null) {
try {
currVm.loadAgent(mgmtAgentPath);
connectorAddress = currVm.getAgentProperties().getProperty("com.sun.management.jmxremote.localConnectorAddress");
} catch (AgentLoadExceptionAgentInitializationException | e) {
LOGGER.warn("Failed to load Management Agent on process " + currVm.id(), e);
}
}
LOGGER.info("Connector address for PID=" + currDescriptor.id() + ": " + connectorAddress);
if (connectorAddress == null) {
continue;
}
final MBeanServerConnection conn = JmxClientConnectionFactory.newConnection(connectorAddress);
final Set<ObjectInstance> response = conn.queryMBeans(objName, Strings.isNullOrEmpty(className) ? null : Query.isInstanceOf(Query.value(className)));
if (response.size() > 0) {
result.add(connectorAddress);
}
} catch (AttachNotSupportedExceptionIOException | e) {
LOGGER.error("Exception", e);
}
}
return result;
}Example 58
| Project: glassfish-main-master File: AgentAttacherInternal.java View source code |
static boolean attachAgent(int pid, String options) {
try {
if (isAttached)
return true;
if (pid < 0)
pid = ProcessUtils.getPid();
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;
}
return isAttached;
}Example 59
| Project: glassfish-master File: AgentAttacherInternal.java View source code |
static boolean attachAgent(int pid, String options) {
try {
if (isAttached)
return true;
if (pid < 0)
pid = ProcessUtils.getPid();
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;
}
return isAttached;
}Example 60
| Project: java-dns-cache-manipulator-master File: DcmTool.java View source code |
public static void main(String[] args) throws Exception {
final String tmpFile = getConfig(DCM_TOOLS_TMP_FILE);
final String agentJar = getConfig(DCM_TOOLS_AGENT_JAR);
if (tmpFile == null || tmpFile.trim().isEmpty() || agentJar == null || agentJar.trim().isEmpty()) {
throw new IllegalStateException("blank tmp file " + tmpFile + ", or blank agent jar file " + agentJar);
}
final Options options = new Options();
options.addOption("p", "pid", true, "java process id to attach");
options.addOption("h", "help", false, "show help");
CommandLineParser parser = new DefaultParser();
CommandLine cmd = parser.parse(options, args);
if (cmd.hasOption('h')) {
HelpFormatter hf = new HelpFormatter();
hf.printHelp("Options", options);
return;
}
final String[] arguments = cmd.getArgs();
if (arguments.length < 1) {
System.out.println("No Action! Available action: " + actionList);
exit(2);
}
final String action = arguments[0].trim();
if (!actionList.contains(action)) {
throw new IllegalStateException("Unknown action " + action + ". Available action: " + actionList);
}
final String pid;
if (cmd.hasOption('p')) {
pid = cmd.getOptionValue('p');
} else {
pid = selectProcess();
}
StringBuilder agentArgument = new StringBuilder();
agentArgument.append(action);
for (int i = 1; i < arguments.length; i++) {
String s = arguments[i];
agentArgument.append(' ').append(s);
}
agentArgument.append(" file ").append(tmpFile);
// target java process pid
VirtualMachine vm = null;
boolean actionSuccess = false;
try {
vm = VirtualMachine.attach(pid);
// loadAgent method will wait to agentmain finished.
vm.loadAgent(agentJar, agentArgument.toString());
final List<String> lines = FileUtils.readLines(new File(tmpFile), "UTF-8");
final int lastIdx = lines.size() - 1;
final String lastLine = lines.get(lastIdx);
if (DCM_AGENT_SUCCESS_MARK_LINE.equals(lastLine)) {
lines.remove(lastIdx);
actionSuccess = true;
}
for (String line : lines) {
System.out.println(line);
}
} finally {
if (null != vm) {
vm.detach();
}
}
if (!actionSuccess) {
exit(1);
}
}Example 61
| Project: jmx-cli-master File: Management.java View source code |
/**
* This method returns the Connector address exported by the agent.
* @param vm process id
*/
public static String getLocalVmAddress(VirtualMachine vm) throws Exception {
// load management-agent.jar from java_home/lib/
String homeDir = vm.getSystemProperties().getProperty("java.home");
String agentPath = homeDir + Management.VALUE_FILE_SEP + "lib" + Management.VALUE_FILE_SEP + Management.VALUE_AGENT_JAR;
File agentFile = new File(agentPath);
if (!agentFile.exists() || !agentFile.isFile()) {
throw new Exception("Unable to find management agent file.");
}
vm.loadAgent(agentFile.getAbsolutePath(), Management.VALUE_AGENT_INIT_PROP);
Properties agentProps = vm.getAgentProperties();
String address = (String) agentProps.get(Management.VALUE_AGENT_CONNECTOR_PROP);
return address;
}Example 62
| Project: kune-master File: JMXUtils.java View source code |
public static Object doOperation(final String objectName, final String operation) {
final List<VirtualMachineDescriptor> vms = VirtualMachine.list();
try {
for (final VirtualMachineDescriptor vmd : vms) {
final String id = vmd.id();
LOG.debug("VM id: " + id);
final JMXServiceURL url = getURLForPid(id.trim());
final JMXConnector jmxc = JMXConnectorFactory.connect(url, null);
final MBeanServerConnection mbsc = jmxc.getMBeanServerConnection();
final ObjectName mbeanName = new ObjectName(objectName);
MBeanInfo beanInfo;
try {
beanInfo = mbsc.getMBeanInfo(mbeanName);
for (final MBeanOperationInfo currentOp : beanInfo.getOperations()) {
if (currentOp.getName().equals(operation)) {
LOG.debug("Doing operation '" + operation + "' over mbean: '" + objectName + "' with id: '" + id + "'.");
final Object invoke = mbsc.invoke(mbeanName, currentOp.getName(), new Object[] {}, new String[] {});
return invoke;
}
}
} catch (final InstanceNotFoundException e) {
}
}
throw new RuntimeException("JMX operation not found");
} catch (final Exception e) {
LOG.error("Error in jmx connection", e);
}
throw new RuntimeException("JMX operation failed");
}Example 63
| Project: novelang-master File: ShutdownTools.java View source code |
private static void shutdownAllTattooedVirtualMachines(final File shutdownAgentJar) {
final List<VirtualMachineDescriptor> descriptors = VirtualMachine.list();
for (final VirtualMachineDescriptor descriptor : descriptors) {
try {
final VirtualMachine virtualMachine = VirtualMachine.attach(descriptor);
try {
final Properties properties = virtualMachine.getSystemProperties();
if (properties.containsKey(SHUTDOWN_TATTOO_PROPERTYNAME)) {
shutdown(virtualMachine, shutdownAgentJar);
}
} finally {
virtualMachine.detach();
}
} catch (AttachNotSupportedException e) {
if (!e.getMessage().startsWith("no such process")) {
LOGGER.warn("Counldn't attach, may be normal if other VM did shut down", e.getMessage());
}
} catch (IOException e) {
if (!e.getMessage().startsWith("no such process")) {
LOGGER.warn("Counldn't attach, may be normal if other VM did shut down", e.getMessage());
}
}
}
}Example 64
| Project: Payara-master File: AgentAttacherInternal.java View source code |
static boolean attachAgent(int pid, String options) {
try {
if (isAttached)
return true;
if (pid < 0)
pid = ProcessUtils.getPid();
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;
}
return isAttached;
}Example 65
| Project: radargun-master File: JavaProcessService.java View source code |
@Override
public JMXConnector getConnector() {
String pid = getJavaPIDs();
if (pid == null)
return null;
try {
VirtualMachine vm;
try {
vm = VirtualMachine.attach(pid);
} catch (AttachNotSupportedException e) {
log.error("Cannot attach to machine " + pid, e);
return null;
}
String connectorAddress = vm.getAgentProperties().getProperty(CONNECTOR_ADDRESS);
if (connectorAddress == null) {
String agent = vm.getSystemProperties().getProperty("java.home") + File.separator + "lib" + File.separator + "management-agent.jar";
try {
vm.loadAgent(agent);
connectorAddress = vm.getAgentProperties().getProperty(CONNECTOR_ADDRESS);
} catch (Exception e) {
log.error("Cannot load management agent into target VM.");
}
}
if (connectorAddress == null) {
log.error("Failed to retrieve connector address.");
return null;
}
return JMXConnectorFactory.connect(new JMXServiceURL(connectorAddress));
} catch (NumberFormatException e) {
log.error("Failed to parse service JVM PID");
return null;
} catch (IOException e) {
log.error("Failed to connect JVM", e);
return null;
}
}Example 66
| Project: railo-master File: InstrumentationFactory.java View source code |
public static synchronized Instrumentation getInstance() {
if (doInit) {
doInit = false;
Class agent = ClassUtil.loadClass("railo.runtime.instrumentation.Agent", null);
if (agent == null) {
SystemOut.printDate("missing class railo.runtime.instrumentation.Agent");
return null;
}
// if Agent was loaded at startup there is already a Instrumentation
inst = getInstrumentation(agent);
// try to load Agent
if (inst == null) {
SystemOut.printDate("class railo.runtime.instrumentation.Agent.getInstrumentation() is not returning an Instrumentation");
try {
String id = getPid();
String path = getResourcFromLib().getAbsolutePath();
Class vmClass = ClassUtil.loadClass("com.sun.tools.attach.VirtualMachine");
Object vmObj = attach(vmClass, id);
loadAgent(vmClass, vmObj, path);
detach(vmClass, vmObj);
} catch (Throwable t) {
return null;
}
inst = getInstrumentation(agent);
}
if (inst != null)
SystemOut.printDate("java.lang.instrument.Instrumentation is used to reload class files");
}
return inst;
}Example 67
| Project: tnt4j-stream-jmx-master File: VMUtils.java View source code |
/**
* Attaches to running JVMs process.
*
* @param vmDescr
* JVM descriptor: display name fragment or pid
* @param agentPath
* agent library path
* @param agentOptions
* agent options
* @throws Exception
* if any exception occurs while attaching to JVM
*
* @see #findVMs(String)
*/
public static void attachVM(String vmDescr, String agentPath, String agentOptions) throws Exception {
Collection<VirtualMachineDescriptor> descriptors = findVMs(vmDescr);
for (VirtualMachineDescriptor descriptor : descriptors) {
System.out.println("SamplingAgent.attach: attaching agent " + agentPath + " to " + descriptor + "");
VirtualMachine virtualMachine = VirtualMachine.attach(descriptor.id());
try {
System.out.println("SamplingAgent.attach: VM loading agent agent.path=" + agentPath + ", agent.options=" + agentOptions);
virtualMachine.loadAgent(agentPath, agentOptions);
System.out.println("SamplingAgent.attach: attached and loaded...");
} finally {
virtualMachine.detach();
}
}
}Example 68
| Project: cache2k-benchmark-master File: ForcedGcMemoryProfiler.java View source code |
/** * Loads java VirtualMachine, expects that tools.jar is reachable via JAVA_HOME environment * variable. */ private static Class<?> findAttachVmClass() { final String virtualMachineClassName = "com.sun.tools.attach.VirtualMachine"; try { return Class.forName(virtualMachineClassName); } catch (ClassNotFoundException ignore) { } String _javaHome = System.getenv("JAVA_HOME"); if (_javaHome == null) { System.err.println("ForcedGcMemoryProfiler: tools.jar missing? Add JAVA_HOME."); return null; } File f = new File(new File(_javaHome, "lib"), "tools.jar"); if (!f.exists()) { System.err.println("ForcedGcMemoryProfiler: tools.jar not found in JAVA_HOME/lib/tools.jar."); return null; } try { final URL url = f.toURI().toURL(); ClassLoader cl = URLClassLoader.newInstance(new URL[] { url }); return Class.forName(virtualMachineClassName, true, cl); } catch (Exception ex) { System.err.println("ForcedGcMemoryProfiler: Cannot load " + virtualMachineClassName + " from " + f); ex.printStackTrace(); return null; } }
Example 69
| Project: activemq-master File: AbstractJmxCommand.java View source code |
/**
* Finds the JMX Url for a VM by its process id
*
* @param pid
* The process id value of the VM to search for.
*
* @return the JMX Url of the VM with the given pid or null if not found.
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
protected String findJMXUrlByProcessId(int pid) {
if (isSunJVM()) {
try {
// Classes are all dynamically loaded, since they are specific to Sun VM
// if it fails for any reason default jmx url will be used
// tools.jar are not always included used by default class loader, so we
// will try to use custom loader that will try to load tools.jar
String javaHome = System.getProperty("java.home");
String tools = javaHome + File.separator + ".." + File.separator + "lib" + File.separator + "tools.jar";
URLClassLoader loader = new URLClassLoader(new URL[] { new File(tools).toURI().toURL() });
Class virtualMachine = Class.forName("com.sun.tools.attach.VirtualMachine", true, loader);
Class virtualMachineDescriptor = Class.forName("com.sun.tools.attach.VirtualMachineDescriptor", true, loader);
Method getVMList = virtualMachine.getMethod("list", (Class[]) null);
Method attachToVM = virtualMachine.getMethod("attach", String.class);
Method getAgentProperties = virtualMachine.getMethod("getAgentProperties", (Class[]) null);
Method getVMId = virtualMachineDescriptor.getMethod("id", (Class[]) null);
List allVMs = (List) getVMList.invoke(null, (Object[]) null);
for (Object vmInstance : allVMs) {
String id = (String) getVMId.invoke(vmInstance, (Object[]) null);
if (id.equals(Integer.toString(pid))) {
Object vm = attachToVM.invoke(null, id);
Properties agentProperties = (Properties) getAgentProperties.invoke(vm, (Object[]) null);
String connectorAddress = agentProperties.getProperty(CONNECTOR_ADDRESS);
if (connectorAddress != null) {
return connectorAddress;
} else {
break;
}
}
}
} catch (Exception ignore) {
}
}
return null;
}Example 70
| Project: dumpling-master File: JmxLocalProcessConnector.java View source code |
private static String connectorAddress(int pid) throws IOException {
VirtualMachine vm = getVm(pid);
String address = vm.getAgentProperties().getProperty(CONNECTOR_ADDRESS);
if (address != null)
return address;
final Properties systemProperties = vm.getSystemProperties();
List<String> diag = new ArrayList<String>(3);
try {
// Java 8+, using reflection so it compiles for older releases.
Method method = VirtualMachine.class.getMethod("startLocalManagementAgent");
return (String) method.invoke(vm);
} catch (NoSuchMethodException ex) {
diag.add("VirtualMachine.startLocalManagementAgent not supported");
} catch (InvocationTargetException ex) {
throw new AssertionError(ex);
} catch (IllegalAccessException ex) {
throw new AssertionError(ex);
}
// jcmd - Hotspot && Java 7+
try {
Class<?> hsvm = Class.forName("sun.tools.attach.HotSpotVirtualMachine");
if (hsvm.isInstance(vm)) {
Method method = hsvm.getMethod("executeJCmd", String.class);
InputStream in = (InputStream) method.invoke(vm, "ManagementAgent.start_local");
// Is there anything interesting?
in.close();
address = vm.getAgentProperties().getProperty(CONNECTOR_ADDRESS);
if (address != null)
return address;
diag.add("jcmd ManagementAgent.start_local succeeded");
}
} catch (ClassNotFoundException e) {
diag.add("not a HotSpot VM - jcmd likely unsupported");
} catch (NoSuchMethodException e) {
diag.add("HotSpot VM with no jcmd support");
} catch (InvocationTargetException e) {
throw new AssertionError(e);
} catch (IllegalAccessException e) {
throw new AssertionError(e);
}
// If the JVM is not able to listen to JMX connections, it is necessary to have the agent loaded.
// There does not seem to be a portable way to do so. This mostly works for hotspot:
// Java 6: The management-agent.jar needs to be loaded
// Try management-agent.jar
String agentPath = systemProperties.getProperty("java.home") + File.separator + "lib" + File.separator + "management-agent.jar";
if (new File(agentPath).exists()) {
try {
vm.loadAgent(agentPath);
} catch (AgentLoadException ex) {
throw failed("Unable to load agent", ex);
} catch (AgentInitializationException ex) {
throw failed("Unable to initialize agent", ex);
}
address = vm.getAgentProperties().getProperty(CONNECTOR_ADDRESS);
if (address != null)
return address;
diag.add("management-agent.jar loaded successfully");
} else {
diag.add("management-agent.jar not found");
}
// Note this require both JVMs are IBM ones
try {
Class<?> ibmVmClass = Class.forName("com.ibm.tools.attach.VirtualMachine");
Method attach = ibmVmClass.getMethod("attach", String.class);
Object ibmVm = attach.invoke(null, String.valueOf(pid));
Method method = ibmVm.getClass().getMethod("getSystemProperties");
// the class is likely package protected
method.setAccessible(true);
Properties props = (Properties) method.invoke(ibmVm);
address = props.getProperty(CONNECTOR_ADDRESS);
if (address != null)
return address;
diag.add("IBM JDK attach successful - no address provided");
} catch (ClassNotFoundException e) {
diag.add("not an IBM JDK - unable to create local JMX connection; try HOSTNAME:PORT instead");
} catch (NoSuchMethodException e) {
diag.add("IBM JDK does not seem to support attach: " + e.getMessage());
} catch (InvocationTargetException e) {
throw new AssertionError(e);
} catch (IllegalAccessException e) {
throw new AssertionError(e);
}
throw failedUnsupported("Unable to connect to JVM: " + diag.toString(), systemProperties);
}Example 71
| Project: h-store-master File: JSamplerAttach.java View source code |
public static void main(String[] args) {
if (args.length != 5) {
System.err.println("Usage: JSamplerAttach <jvmpid> <duration> <interval> <port> <output file>");
System.exit(1);
}
// Search the classpath for the jar
File jarPath = null;
for (File path : classPathParts()) {
if (path.isDirectory()) {
File jar = new File(path, JAR_NAME);
if (jar.canRead()) {
jarPath = jar;
break;
}
} else if (path.getName().equals(JAR_NAME) && path.canRead()) {
jarPath = path;
break;
}
}
if (jarPath == null) {
System.err.println("Error: Could not find " + JAR_NAME + " by searching the classpath");
System.err.println("CLASSPATH = " + System.getProperty(CLASSPATH_PROPERTY));
System.err.println("Searched:");
for (File path : classPathParts()) {
System.err.println("\t" + path.getAbsolutePath());
}
System.exit(1);
}
String pid = args[0];
String duration = args[1];
String interval = args[2];
String port = args[3];
String output = args[4];
try {
// Test if we can write to the file by opening it for writing, then
// deleting it
FileOutputStream out = new FileOutputStream(output);
out.close();
File outFile = new File(output);
outFile.delete();
// We need an absolute path to pass to the other JVM
output = outFile.getAbsolutePath();
} catch (java.io.FileNotFoundException e) {
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) {
throw new RuntimeException(e);
}
}Example 72
| Project: javassist-master File: HotSwapAgent.java View source code |
/**
* Ensures that the agent is ready.
* It attempts to dynamically start the agent if necessary.
*/
private static void startAgent() throws NotFoundException {
if (instrumentation != null)
return;
try {
File agentJar = createJarFile();
String nameOfRunningVM = ManagementFactory.getRuntimeMXBean().getName();
String pid = nameOfRunningVM.substring(0, nameOfRunningVM.indexOf('@'));
VirtualMachine vm = VirtualMachine.attach(pid);
vm.loadAgent(agentJar.getAbsolutePath(), "");
vm.detach();
} catch (Exception e) {
throw new NotFoundException("hotswap agent", e);
}
for (int sec = 0; sec < 10; /* sec */
sec++) {
if (instrumentation != null)
return;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
break;
}
}
throw new NotFoundException("hotswap agent (timeout)");
}Example 73
| Project: lombok.patcher-master File: LiveInjector.java View source code |
private void slowInject(String jarFile) throws IllegalStateException {
String ownPidS = ManagementFactory.getRuntimeMXBean().getName();
ownPidS = ownPidS.substring(0, ownPidS.indexOf('@'));
int ownPid = Integer.parseInt(ownPidS);
boolean unsupportedEnvironment = false;
Throwable exception = null;
try {
Class<?> vmClass = Class.forName("com.sun.tools.attach.VirtualMachine");
Object vm = vmClass.getMethod("attach", String.class).invoke(null, String.valueOf(ownPid));
vmClass.getMethod("loadAgent", String.class).invoke(vm, jarFile);
} catch (ClassNotFoundException e) {
unsupportedEnvironment = true;
} catch (NoSuchMethodException e) {
unsupportedEnvironment = true;
} catch (InvocationTargetException e) {
exception = e.getCause();
if (exception == null)
exception = e;
} catch (Throwable t) {
exception = t;
}
if (unsupportedEnvironment)
throw new IllegalStateException("agent injection only works on a sun-derived 1.6 or higher VM");
if (exception != null)
throw new IllegalStateException("agent injection not supported on this platform due to unknown reason", exception);
}Example 74
| Project: MBeanSelector-master File: LocalVirtualMachine.java View source code |
private static void getAttachableVMs(Map<Integer, LocalVirtualMachine> map) {
List<VirtualMachineDescriptor> vms = VirtualMachine.list();
for (VirtualMachineDescriptor vmd : vms) {
try {
Integer vmid = Integer.valueOf(vmd.id());
if (!map.containsKey(vmid)) {
boolean attachable = false;
String address = null;
try {
VirtualMachine vm = VirtualMachine.attach(vmd);
attachable = true;
Properties agentProps = vm.getAgentProperties();
address = (String) agentProps.get(LOCAL_CONNECTOR_ADDRESS_PROP);
vm.detach();
} catch (AttachNotSupportedException x) {
} catch (IOException x) {
}
map.put(vmid, new LocalVirtualMachine(vmid.intValue(), vmd.displayName(), attachable, address));
}
} catch (NumberFormatException e) {
}
}
}Example 75
| Project: misc_hookons_avec_javasnoop-master File: AttachUtil.java View source code |
public static void loadAgentInOtherVM(String agentJarPath, String pid) throws AttachNotSupportedException, IOException, AgentLoadException, AgentInitializationException, AgentCommunicationException {
VirtualMachine vm = VirtualMachine.attach(pid);
/*
* Agent is expecting arguments in the form of:
* <javasnoop install dir>|number|[LookAndFeelClass]
* Where number represents the number of seconds to wait before
* loading the JavaSnoop GUI. Attaching to an existing process
* requires no waiting, so we hardcode to 0.
*/
vm.loadAgent(agentJarPath, new File(".").getAbsolutePath() + "|0|");
vm.detach();
}Example 76
| Project: PerfCake-master File: PerfCakeDebug.java View source code |
/**
* Gets the current process PID. Based on org.jboss.byteman.contrib.bmunit.BMUnitConfigState by Andrew Dinn.
*
* @return The PID of the current process.
*/
private static String getPid() {
String id = null;
// if we can get a proper pid on Linux we use it
int pid = getLinuxPid();
if (pid > 0) {
id = Integer.toString(pid);
} else {
// alternative strategy which will work everywhere
// set a unique system property and then check each available VM until we find it
String prop = "org.jboss.byteman.contrib.bmunit.agent.unique";
String unique = Long.toHexString(System.currentTimeMillis());
System.setProperty(prop, unique);
final List<VirtualMachineDescriptor> vmds = VirtualMachine.list();
for (VirtualMachineDescriptor vmd : vmds) {
String value = getProperty(vmd.id(), prop);
if (unique.equals(value)) {
id = vmd.id();
break;
}
}
// last ditch effort to obtain pid on Windows where the availableVMs list may be empty
if (id == null) {
// last ditch effort to obtain pid on Windows where the availableVMs list may be empty
String processName = ManagementFactory.getRuntimeMXBean().getName();
if (processName != null && processName.contains("@")) {
id = processName.substring(0, processName.indexOf("@"));
// check we actually have an integer
try {
Integer.parseInt(id);
// well, it's a number so now check it identifies the current VM
String value = getProperty(id, prop);
if (!unique.equals(value)) {
// nope, not the right process
id = null;
}
} catch (NumberFormatException e) {
id = null;
}
}
}
}
return id;
}Example 77
| Project: storm-deploy-alternative-master File: MemoryMonitor.java View source code |
private static void GCExternalProcess(String pid) {
System.out.println("Asked process with pid " + pid + " to do GC");
VirtualMachine vm = null;
JMXConnector connector = null;
try {
// Attach to JVM process with pid
vm = VirtualMachine.attach(pid);
// Load management agent
vm.loadAgent(vm.getSystemProperties().getProperty("java.home") + "/lib/management-agent.jar");
// Connect using JMX
JMXServiceURL url = new JMXServiceURL(vm.getAgentProperties().getProperty("com.sun.management.jmxremote.localConnectorAddress"));
connector = JMXConnectorFactory.newJMXConnector(url, null);
connector.connect();
// Do GC
ManagementFactory.newPlatformMXBeanProxy(connector.getMBeanServerConnection(), ManagementFactory.MEMORY_MXBEAN_NAME, MemoryMXBean.class).gc();
} catch (Exception ex) {
log.error("Problem", ex);
} finally {
// Detach from JVM process
try {
if (connector != null)
connector.close();
if (vm != null)
vm.detach();
} catch (Exception ex) {
log.error("Problem", ex);
}
}
}Example 78
| Project: typhon-master File: DebugScriptManager.java View source code |
private void loadAgent() {
try {
String pid = ManagementFactory.getRuntimeMXBean().getName().split("@")[0];
VirtualMachine vm = VirtualMachine.attach(pid);
vm.loadAgent(Typhons.getProperty(Constants.AGENT_JAR_PATH), OBJECT_NAME.toString());
vm.detach();
} catch (Exception ex) {
throw new RuntimeException("æ— æ³•åŠ è½½ä»£ç?†JAR文件[" + Typhons.getProperty(Constants.AGENT_JAR_PATH) + "]", ex);
}
}Example 79
| Project: glowroot-master File: LiveJvmServiceImpl.java View source code |
@Override
public String getJstack(String agentId) throws Exception {
if (AppServerDetection.isIbmJvm()) {
throw new UnavailableDueToRunningInIbmJvmException();
}
if (ToolProvider.getSystemJavaCompiler() == null) {
throw new UnavailableDueToRunningInJreException();
}
ClassLoader systemToolClassLoader = ToolProvider.getSystemToolClassLoader();
Class<?> vmClass = Class.forName("com.sun.tools.attach.VirtualMachine", true, systemToolClassLoader);
Method attachMethod = vmClass.getMethod("attach", String.class);
Method detachMethod = vmClass.getMethod("detach");
Class<?> hotSpotVmClass = Class.forName("sun.tools.attach.HotSpotVirtualMachine", true, systemToolClassLoader);
Method remoteDataDumpMethod = hotSpotVmClass.getMethod("remoteDataDump", Object[].class);
long pid = checkNotNull(LiveJvmServiceImpl.getProcessId());
Object vm = attachMethod.invoke(null, Long.toString(pid));
try {
InputStream in = (InputStream) remoteDataDumpMethod.invoke(vm, (Object) new Object[0]);
checkNotNull(in);
// Closer is used to simulate Java 7 try-with-resources
Closer closer = Closer.create();
try {
BufferedReader reader = closer.register(new BufferedReader(new InputStreamReader(in)));
return CharStreams.toString(reader).trim();
} catch (Throwable t) {
throw closer.rethrow(t);
} finally {
closer.close();
}
} finally {
detachMethod.invoke(vm);
}
}Example 80
| Project: apmrouter-master File: VirtualMachineBootstrap.java View source code |
public static void main(String[] args) {
findAttachAPI();
log("VMBoot:" + inClassPath());
VirtualMachineBootstrap vmb = getInstance();
// for(VirtualMachineDescriptor vmd: VirtualMachine.list()) {
// try {
// VirtualMachine vm = VirtualMachine.attach(vmd);
// log("\tVM:" + vm.toString());
// } catch (Exception e) {
// log("Unable to attach to VM [" + vmd.toString() + "]:" + e);
// }
// }
// for(VirtualMachineDescriptor vmd: VirtualMachineDescriptor.getVirtualMachineDescriptors()) {
// try {
// VirtualMachine vm = VirtualMachine.attach(vmd);
// log("\tVM:" + vm.toString());
// } catch (Exception e) {
// log("Unable to attach to VM [" + vmd.toString() + "]:" + e);
// }
// }
// AttachProvider ap = AttachProvider.getAttachProviders().iterator().next();
// String id = ManagementFactory.getRuntimeMXBean().getName().split("@")[0];
// VirtualMachine vm = ap.attachVirtualMachine(id);
// log("This VM:" + vm.toString());
AttachProvider ap = AttachProvider.getAttachProviders().iterator().next();
String id = ManagementFactory.getRuntimeMXBean().getName().split("@")[0];
for (VirtualMachineDescriptor vmd : ap.listVirtualMachines()) {
log("Testing VMD (" + vmd.id() + ") [" + vmd.displayName() + "] Name:" + vmd.provider().name() + " Type:" + vmd.provider().type());
if (id.equals(vmd.id())) {
VirtualMachine vm = ap.attachVirtualMachine(vmd);
log("This VM:" + vm.toString());
Properties agentProps = vm.getAgentProperties();
for (Map.Entry<Object, Object> p : agentProps.entrySet()) {
log("\t\t" + p.getKey() + ":" + p.getValue());
}
}
if (vmd.id().equals("15684")) {
// log("============== System Props ==============");
// Properties sysProps = ap.attachVirtualMachine(vmd).getSystemProperties();
// for(Map.Entry<Object, Object> p: sysProps.entrySet()) {
// log("\t\t" + p.getKey() + ":" + p.getValue());
// }
log("============== Agent Props ==============");
Properties agentProps = ap.attachVirtualMachine(vmd).getAgentProperties();
for (Map.Entry<Object, Object> p : agentProps.entrySet()) {
log("\t\t" + p.getKey() + ":" + p.getValue());
}
}
}
// BaseWrappedClass.getMethodMapping(vmb.classCache.get(VM_CLASS));
// for(VirtualMachineDescriptor vmd: VirtualMachine.list()) {
// log(vmd.toString());
// }
}Example 81
| Project: avaje-agentloader-master File: AgentLoader.java View source code |
/**
* Load an agent providing the full file path with parameters.
*/
public static void loadAgent(String jarFilePath, String params) {
log.info("dynamically loading javaagent for " + jarFilePath);
try {
String pid = discoverPid();
VirtualMachine vm;
if (AttachProvider.providers().isEmpty()) {
vm = getVirtualMachineImplementationFromEmbeddedOnes(pid);
} else {
vm = VirtualMachine.attach(pid);
}
vm.loadAgent(jarFilePath, params);
vm.detach();
} catch (Exception e) {
throw new RuntimeException(e);
}
}Example 82
| Project: bnd-master File: JMXBundleDeployer.java View source code |
/**
* Uses Oracle JDK's Attach API to try to search VMs on this machine looking
* for the osgi.core MBeans. This will stop searching for VMs once the
* MBeans are found. Beware if you have multiple JVMs with osgi.core MBeans
* published.
*
*/
@SuppressWarnings("unchecked")
static String getLocalConnectorAddress() {
ClassLoader cl = Thread.currentThread().getContextClassLoader();
ClassLoader toolsClassloader = null;
try {
toolsClassloader = getToolsClassLoader(cl);
if (toolsClassloader != null) {
Thread.currentThread().setContextClassLoader(toolsClassloader);
Class<?> vmClass = toolsClassloader.loadClass("com.sun.tools.attach.VirtualMachine");
Method listMethod = vmClass.getMethod("list");
List<Object> vmds = (List<Object>) listMethod.invoke(null);
for (Object vmd : vmds) {
try {
Class<?> vmdClass = toolsClassloader.loadClass("com.sun.tools.attach.VirtualMachineDescriptor");
Method idMethod = vmdClass.getMethod("id");
String id = (String) idMethod.invoke(vmd);
Method attachMethod = vmClass.getMethod("attach", String.class);
Object vm = attachMethod.invoke(null, id);
try {
Method getAgentPropertiesMethod = vmClass.getMethod("getAgentProperties");
Properties agentProperties = (Properties) getAgentPropertiesMethod.invoke(vm);
String localConnectorAddress = agentProperties.getProperty("com.sun.management.jmxremote.localConnectorAddress");
if (localConnectorAddress == null) {
File agentJar = findJdkJar("management-agent.jar");
if (agentJar != null) {
Method loadAgent = vmClass.getMethod("loadAgent", String.class);
loadAgent.invoke(vm, agentJar.getCanonicalPath());
agentProperties = (Properties) getAgentPropertiesMethod.invoke(vm);
localConnectorAddress = agentProperties.getProperty("com.sun.management.jmxremote.localConnectorAddress");
}
}
if (localConnectorAddress != null) {
final JMXServiceURL jmxServiceUrl = new JMXServiceURL(localConnectorAddress);
final JMXConnector jmxConnector = JMXConnectorFactory.connect(jmxServiceUrl, null);
final MBeanServerConnection mBeanServerConnection = jmxConnector.getMBeanServerConnection();
if (mBeanServerConnection != null) {
final ObjectName framework = getFramework(mBeanServerConnection);
if (framework != null) {
return localConnectorAddress;
}
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
Method detachMethod = vmClass.getMethod("detach");
detachMethod.invoke(vm);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
Thread.currentThread().setContextClassLoader(cl);
// try to get custom classloader to unload native libs
try {
if (toolsClassloader != null) {
Field nl = ClassLoader.class.getDeclaredField("nativeLibraries");
nl.setAccessible(true);
Vector<?> nativeLibs = (Vector<?>) nl.get(toolsClassloader);
for (Object nativeLib : nativeLibs) {
Field nameField = nativeLib.getClass().getDeclaredField("name");
nameField.setAccessible(true);
String name = (String) nameField.get(nativeLib);
if (new File(name).getName().contains("attach")) {
Method f = nativeLib.getClass().getDeclaredMethod("finalize");
f.setAccessible(true);
f.invoke(nativeLib);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}Example 83
| Project: evosuite-master File: AgentLoader.java View source code |
private static void attachAgent(String pid, String jarFilePath, ClassLoader toolLoader) throws Exception {
Class<?> string = toolLoader.loadClass("java.lang.String");
Class<?> provider = toolLoader.loadClass("com.sun.tools.attach.spi.AttachProvider");
Method getProviders = provider.getDeclaredMethod("providers");
List<?> list = (List<?>) getProviders.invoke(null);
if (list == null || list.isEmpty()) {
String msg = "AttachProvider.providers() failed to return any provider. Tool classloader: " + toolLoader;
throw new RuntimeException(msg);
}
if (list.stream().anyMatch( k -> k == null)) {
throw new RuntimeException("AttachProvider.providers() returned null values");
}
Class<?> clazz = toolLoader.loadClass("com.sun.tools.attach.VirtualMachine");
Method attach = clazz.getMethod("attach", string);
Object instance = null;
try {
instance = attach.invoke(null, pid);
} catch (Exception e) {
throw new RuntimeException("Failed to attach Java Agent. Tool classloader: " + toolLoader, e);
}
Method loadAgent = clazz.getMethod("loadAgent", string, string);
loadAgent.invoke(instance, jarFilePath, "");
Method detach = clazz.getMethod("detach");
detach.invoke(instance);
}Example 84
| Project: felinx-master File: FrameworkRunner.java View source code |
public static String loadJMXAgent(int port) throws IOException, AttachNotSupportedException, AgentLoadException, AgentInitializationException {
System.setProperty("com.sun.management.jmxremote.port", Integer.toString(port));
String name = ManagementFactory.getRuntimeMXBean().getName();
VirtualMachine vm = VirtualMachine.attach(name.substring(0, name.indexOf('@')));
String lca = vm.getAgentProperties().getProperty("com.sun.management.jmxremote.localConnectorAddress");
if (lca == null) {
Path p = Paths.get(System.getProperty("java.home")).normalize();
if (!"jre".equals(p.getName(p.getNameCount() - 1).toString().toLowerCase()))
p = p.resolve("jre");
File f = p.resolve("lib").resolve("management-agent.jar").toFile();
if (!f.exists())
throw new IOException("Management agent not found");
vm.loadAgent(f.getCanonicalPath(), "com.sun.management.jmxremote");
lca = vm.getAgentProperties().getProperty("com.sun.management.jmxremote.localConnectorAddress");
}
vm.detach();
return lca;
}Example 85
| Project: GroovyMX-master File: VirtualMachineBootstrap.java View source code |
public static void main(String[] args) {
findAttachAPI();
log("VMBoot:" + inClassPath());
VirtualMachineBootstrap vmb = getInstance();
// for(VirtualMachineDescriptor vmd: VirtualMachine.list()) {
// try {
// VirtualMachine vm = VirtualMachine.attach(vmd);
// log("\tVM:" + vm.toString());
// } catch (Exception e) {
// log("Unable to attach to VM [" + vmd.toString() + "]:" + e);
// }
// }
// for(VirtualMachineDescriptor vmd: VirtualMachineDescriptor.getVirtualMachineDescriptors()) {
// try {
// VirtualMachine vm = VirtualMachine.attach(vmd);
// log("\tVM:" + vm.toString());
// } catch (Exception e) {
// log("Unable to attach to VM [" + vmd.toString() + "]:" + e);
// }
// }
// AttachProvider ap = AttachProvider.getAttachProviders().iterator().next();
// String id = ManagementFactory.getRuntimeMXBean().getName().split("@")[0];
// VirtualMachine vm = ap.attachVirtualMachine(id);
// log("This VM:" + vm.toString());
AttachProvider ap = AttachProvider.getAttachProviders().iterator().next();
String id = ManagementFactory.getRuntimeMXBean().getName().split("@")[0];
for (VirtualMachineDescriptor vmd : ap.listVirtualMachines()) {
log("Testing VMD (" + vmd.id() + ") [" + vmd.displayName() + "] Name:" + vmd.provider().name() + " Type:" + vmd.provider().type());
if (id.equals(vmd.id())) {
VirtualMachine vm = ap.attachVirtualMachine(vmd);
log("This VM:" + vm.toString());
Properties agentProps = vm.getAgentProperties();
for (Map.Entry<Object, Object> p : agentProps.entrySet()) {
log("\t\t" + p.getKey() + ":" + p.getValue());
}
}
if (vmd.id().equals("15684")) {
// log("============== System Props ==============");
// Properties sysProps = ap.attachVirtualMachine(vmd).getSystemProperties();
// for(Map.Entry<Object, Object> p: sysProps.entrySet()) {
// log("\t\t" + p.getKey() + ":" + p.getValue());
// }
log("============== Agent Props ==============");
Properties agentProps = ap.attachVirtualMachine(vmd).getAgentProperties();
for (Map.Entry<Object, Object> p : agentProps.entrySet()) {
log("\t\t" + p.getKey() + ":" + p.getValue());
}
}
}
// BaseWrappedClass.getMethodMapping(vmb.classCache.get(VM_CLASS));
// for(VirtualMachineDescriptor vmd: VirtualMachine.list()) {
// log(vmd.toString());
// }
}Example 86
| Project: JMXMiniProbe-master File: JVMRuntimeClient.java View source code |
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")) {
//
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")) {
//
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")) {
//
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")) {
//
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<String>();
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]);
}
}
//
if (serviceURL != null)
return serviceURL;
//
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);
}
}
//
if (pid != null) {
JMXServiceURL retVal = null;
try {
retVal = getURLForPid(pid);
if (retVal == null) {
retVal = extractJMXServiceURL(pid);
}
} catch (Exception x) {
}
if (retVal == null) {
try {
retVal = extractJMXServiceURL(pid);
} catch (Exception x) {
}
}
if (retVal == null) {
throwSyntaxError("cannot attach to target vm " + pid);
}
return retVal;
}
final List<String> vmlist = new ArrayList<String>();
for (VirtualMachineDescriptor vd : VirtualMachine.list()) {
vmlist.add(vd.id());
}
throwSyntaxError("missing argument: " + "-port | -url | -pid | -list" + "\\n\\tRunning VMs are: " + vmlist);
// Unreachable.
return null;
}Example 87
| Project: jvmtop-master File: LocalVirtualMachine.java View source code |
private static void getAttachableVMs(Map<Integer, LocalVirtualMachine> map, Map<Integer, LocalVirtualMachine> existingVmMap) {
List<VirtualMachineDescriptor> vms = VirtualMachine.list();
for (VirtualMachineDescriptor vmd : vms) {
try {
Integer vmid = Integer.valueOf(vmd.id());
if (!map.containsKey(vmid) && !existingVmMap.containsKey(vmid)) {
boolean attachable = false;
String address = null;
try {
VirtualMachine vm = VirtualMachine.attach(vmd);
attachable = true;
Properties agentProps = vm.getAgentProperties();
address = (String) agentProps.get(LOCAL_CONNECTOR_ADDRESS_PROP);
vm.detach();
} catch (AttachNotSupportedException x) {
x.printStackTrace(System.err);
} catch (NullPointerException e) {
e.printStackTrace(System.err);
} catch (IOException x) {
}
map.put(vmid, new LocalVirtualMachine(vmid.intValue(), vmd.displayName(), attachable, address));
}
} catch (NumberFormatException e) {
}
}
}Example 88
| Project: liferay-ide-master File: JMXBundleDeployer.java View source code |
/**
* Uses Oracle JDK's Attach API to try to search VMs on this machine looking
* for the osgi.core MBeans. This will stop searching for VMs once the
* MBeans are found. Beware if you have multiple JVMs with osgi.core MBeans
* published.
*
* @return
*/
@SuppressWarnings("unchecked")
static String getLocalConnectorAddress() {
ClassLoader cl = Thread.currentThread().getContextClassLoader();
ClassLoader toolsClassloader = null;
try {
toolsClassloader = getToolsClassLoader(cl);
if (toolsClassloader != null) {
Thread.currentThread().setContextClassLoader(toolsClassloader);
Class<?> vmClass = toolsClassloader.loadClass("com.sun.tools.attach.VirtualMachine");
Method listMethod = vmClass.getMethod("list");
List<Object> vmds = (List<Object>) listMethod.invoke(null);
for (Object vmd : vmds) {
try {
Class<?> vmdClass = toolsClassloader.loadClass("com.sun.tools.attach.VirtualMachineDescriptor");
Method idMethod = vmdClass.getMethod("id");
String id = (String) idMethod.invoke(vmd);
Method attachMethod = vmClass.getMethod("attach", String.class);
Object vm = attachMethod.invoke(null, id);
try {
Method getAgentPropertiesMethod = vmClass.getMethod("getAgentProperties");
Properties agentProperties = (Properties) getAgentPropertiesMethod.invoke(vm);
String localConnectorAddress = agentProperties.getProperty("com.sun.management.jmxremote.localConnectorAddress");
if (localConnectorAddress == null) {
File agentJar = findJdkJar("management-agent.jar");
if (agentJar != null) {
Method loadAgent = vmClass.getMethod("loadAgent", String.class);
loadAgent.invoke(vm, agentJar.getCanonicalPath());
agentProperties = (Properties) getAgentPropertiesMethod.invoke(vm);
localConnectorAddress = agentProperties.getProperty("com.sun.management.jmxremote.localConnectorAddress");
}
}
if (localConnectorAddress != null) {
final JMXServiceURL jmxServiceUrl = new JMXServiceURL(localConnectorAddress);
final JMXConnector jmxConnector = JMXConnectorFactory.connect(jmxServiceUrl, null);
final MBeanServerConnection mBeanServerConnection = jmxConnector.getMBeanServerConnection();
if (mBeanServerConnection != null) {
final ObjectName framework = getFramework(mBeanServerConnection);
if (framework != null) {
return localConnectorAddress;
}
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
Method detachMethod = vmClass.getMethod("detach");
detachMethod.invoke(vm);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
Thread.currentThread().setContextClassLoader(cl);
// try to get custom classloader to unload native libs
try {
if (toolsClassloader != null) {
Field nl = ClassLoader.class.getDeclaredField("nativeLibraries");
nl.setAccessible(true);
Vector<?> nativeLibs = (Vector<?>) nl.get(toolsClassloader);
for (Object nativeLib : nativeLibs) {
Field nameField = nativeLib.getClass().getDeclaredField("name");
nameField.setAccessible(true);
String name = (String) nameField.get(nativeLib);
if (new File(name).getName().contains("attach")) {
Method f = nativeLib.getClass().getDeclaredMethod("finalize");
f.setAccessible(true);
f.invoke(nativeLib);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}Example 89
| Project: acs-master File: RemoteThreadsClient.java View source code |
private void getServiceURL(int pid) throws IOException, AgentLoadException, RemoteThreadsException, AttachNotSupportedException, AgentInitializationException {
// attach to the target application
final VirtualMachine vm = VirtualMachine.attach(String.valueOf(pid));
// get the connector address
String connectorAddress = vm.getAgentProperties().getProperty(LOCAL_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(LOCAL_CONNECTOR_ADDRESS);
if (connectorAddress == null)
throw new RemoteThreadsException("Can't get the remote JVM connector address");
}
remoteURL = new JMXServiceURL(connectorAddress);
}Example 90
| Project: bagri-master File: BagriMainPanel.java View source code |
private static MBeanServerConnection getMBeanServerConnection() throws Exception {
final AttachProvider attachProvider = AttachProvider.providers().get(0);
VirtualMachineDescriptor descriptor = null;
for (VirtualMachineDescriptor virtualMachineDescriptor : attachProvider.listVirtualMachines()) {
if (pickThisOne(virtualMachineDescriptor)) {
descriptor = virtualMachineDescriptor;
final VirtualMachine virtualMachine = attachProvider.attachVirtualMachine(descriptor);
final JMXServiceURL target = getURLForVM(virtualMachine);
final JMXConnector connector = JMXConnectorFactory.connect(target);
final MBeanServerConnection remote = connector.getMBeanServerConnection();
try {
Object o = remote.getObjectInstance(new ObjectName("com.bagri.db:type=Management,name=ClusterManagement"));
if (null != o) {
break;
}
} catch (Exception e) {
}
}
}
if (descriptor == null)
throw new RuntimeException("Bagri VM not found");
final VirtualMachine virtualMachine = attachProvider.attachVirtualMachine(descriptor);
final JMXServiceURL target = getURLForVM(virtualMachine);
final JMXConnector connector = JMXConnectorFactory.connect(target);
final MBeanServerConnection remote = connector.getMBeanServerConnection();
return remote;
}Example 91
| Project: crash-master File: CRaSH.java View source code |
@Command
public void main(@Option(names = { "non-interactive" }) @Usage("non interactive mode, the JVM io will not be used") Boolean nonInteractive, @Option(names = { "c", "cmd" }) @Usage("the command mounts") String cmd, @Option(names = { "conf" }) @Usage("the conf mounts") String conf, @Option(names = { "p", "property" }) @Usage("set a property of the form a=b") List<String> properties, @Option(names = { "cmd-folder" }) @Usage("a folder in which commands should be extracted") String cmdFolder, @Option(names = { "conf-folder" }) @Usage("a folder in which configuration should be extracted") String confFolder, @Argument(name = "pid") @Usage("the optional list of JVM process id to attach to") List<Integer> pids) throws Exception {
//
boolean interactive = nonInteractive == null || !nonInteractive;
//
if (conf == null) {
conf = "classpath:/crash/";
}
FS.Builder confBuilder = createBuilder().mount(conf);
if (confFolder != null) {
File dst = new File(confFolder);
if (!dst.isDirectory()) {
throw new Exception("Directory " + dst.getAbsolutePath() + " does not exist");
}
org.crsh.vfs.File f = confBuilder.build().get(Path.get("/"));
log.info("Extracting conf resources to " + dst.getAbsolutePath());
for (org.crsh.vfs.File child : f.children()) {
if (!child.hasChildren()) {
copyConf(child, new File(dst, child.getName()));
}
}
confBuilder = createBuilder().mount("file", Path.get(dst));
}
//
if (cmd == null) {
cmd = "classpath:/crash/commands/";
}
FS.Builder cmdBuilder = createBuilder().mount(cmd);
if (cmdFolder != null) {
File dst = new File(cmdFolder);
if (!dst.isDirectory()) {
throw new Exception("Directory " + dst.getAbsolutePath() + " does not exist");
}
org.crsh.vfs.File f = cmdBuilder.build().get(Path.get("/"));
log.info("Extracting command resources to " + dst.getAbsolutePath());
copyCmd(f, dst);
cmdBuilder = createBuilder().mount("file", Path.get(dst));
}
//
log.log(Level.INFO, "conf mounts: " + confBuilder.toString());
log.log(Level.INFO, "cmd mounts: " + cmdBuilder.toString());
//
CloseableList closeable = new CloseableList();
Shell shell;
if (pids != null && pids.size() > 0) {
//
if (interactive && pids.size() > 1) {
throw new Exception("Cannot attach to more than one JVM in interactive mode");
}
// Compute classpath
String classpath = System.getProperty("java.class.path");
String sep = System.getProperty("path.separator");
StringBuilder buffer = new StringBuilder();
for (String path : classpath.split(Pattern.quote(sep))) {
File file = new File(path);
if (file.exists()) {
if (buffer.length() > 0) {
buffer.append(' ');
}
String fileName = file.getCanonicalPath();
if (fileName.charAt(0) != '/' && fileName.charAt(1) == ':') {
// On window, the value of Class-Path in Manifest file must in form: /C:/path/lib/abc.jar
fileName = fileName.replace(File.separatorChar, '/');
buffer.append("/").append(fileName);
} else {
buffer.append(file.getCanonicalPath());
}
}
}
// Create manifest
Manifest manifest = new Manifest();
Attributes attributes = manifest.getMainAttributes();
attributes.putValue("Agent-Class", Agent.class.getName());
attributes.put(Attributes.Name.MANIFEST_VERSION, "1.0");
attributes.put(Attributes.Name.CLASS_PATH, buffer.toString());
// Create jar file
File agentFile = File.createTempFile("agent", ".jar");
agentFile.deleteOnExit();
JarOutputStream out = new JarOutputStream(new FileOutputStream(agentFile), manifest);
out.close();
log.log(Level.INFO, "Created agent jar " + agentFile.getCanonicalPath());
// Build the options
StringBuilder sb = new StringBuilder();
// Path configuration
sb.append("--cmd ");
Delimiter.EMPTY.escape(toString(cmdBuilder), sb);
sb.append(' ');
sb.append("--conf ");
Delimiter.EMPTY.escape(toString(confBuilder), sb);
sb.append(' ');
// Propagate canonical config
if (properties != null) {
for (String property : properties) {
sb.append("--property ");
Delimiter.EMPTY.escape(property, sb);
sb.append(' ');
}
}
//
if (interactive) {
RemoteServer server = new RemoteServer(0);
int port = server.bind();
log.log(Level.INFO, "Callback server set on port " + port);
sb.append(port);
String options = sb.toString();
Integer pid = pids.get(0);
final VirtualMachine vm = VirtualMachine.attach("" + pid);
log.log(Level.INFO, "Loading agent with command " + options + " as agent " + agentFile.getCanonicalPath());
vm.loadAgent(agentFile.getCanonicalPath(), options);
server.accept();
shell = server.getShell();
closeable.add(new Closeable() {
public void close() throws IOException {
vm.detach();
}
});
} else {
for (Integer pid : pids) {
log.log(Level.INFO, "Attaching to remote process " + pid);
VirtualMachine vm = VirtualMachine.attach("" + pid);
String options = sb.toString();
log.log(Level.INFO, "Loading agent with command " + options + " as agent " + agentFile.getCanonicalPath());
vm.loadAgent(agentFile.getCanonicalPath(), options);
}
shell = null;
}
} else {
final Bootstrap bootstrap = new Bootstrap(Thread.currentThread().getContextClassLoader(), confBuilder.build(), cmdBuilder.build());
//
if (properties != null) {
Properties config = new Properties();
for (String property : properties) {
int index = property.indexOf('=');
if (index == -1) {
config.setProperty(property, "");
} else {
config.setProperty(property.substring(0, index), property.substring(index + 1));
}
}
bootstrap.setConfig(config);
}
// Register shutdown hook
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
// Should trigger some kind of run interruption
}
});
// Do bootstrap
bootstrap.bootstrap();
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
bootstrap.shutdown();
}
});
//
if (interactive) {
ShellFactory factory = bootstrap.getContext().getPlugin(ShellFactory.class);
shell = factory.create(null);
} else {
shell = null;
}
closeable = null;
}
//
if (shell != null) {
//
final Terminal term = TerminalFactory.create();
//
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
try {
term.restore();
} catch (Exception ignore) {
}
}
});
//
String encoding = Configuration.getEncoding();
// Use AnsiConsole only if term doesn't support Ansi
PrintStream out;
PrintStream err;
boolean ansi;
if (term.isAnsiSupported()) {
out = new PrintStream(new BufferedOutputStream(term.wrapOutIfNeeded(new FileOutputStream(FileDescriptor.out)), 16384), false, encoding);
err = new PrintStream(new BufferedOutputStream(term.wrapOutIfNeeded(new FileOutputStream(FileDescriptor.err)), 16384), false, encoding);
ansi = true;
} else {
out = AnsiConsole.out;
err = AnsiConsole.err;
ansi = false;
}
//
FileInputStream in = new FileInputStream(FileDescriptor.in);
ConsoleReader reader = new ConsoleReader(null, in, out, term);
//
final JLineProcessor processor = new JLineProcessor(ansi, shell, reader, out);
//
InterruptHandler interruptHandler = new InterruptHandler(new Runnable() {
@Override
public void run() {
processor.interrupt();
}
});
interruptHandler.install();
//
Thread thread = new Thread(processor);
thread.setDaemon(true);
thread.start();
//
try {
processor.closed();
} catch (Throwable t) {
t.printStackTrace();
} finally {
//
if (closeable != null) {
Utils.close(closeable);
}
// Force exit
System.exit(0);
}
}
}Example 92
| Project: heapaudit-master File: HeapAudit.java View source code |
// The following is the wrapper that instructs JVM to load the java agent
// into the designated target process.
public static void main(String[] args) throws Exception {
String id = null;
StringBuffer s = new StringBuffer("-Xconditional");
File file = null;
boolean hasOutput = false;
boolean hasTimeout = false;
boolean hasInject = false;
if (args.length > 0) {
for (int i = 0; i < args.length; ++i) {
String arg = args[i].toLowerCase();
if (arg.equals("?") || arg.equals("-?") || arg.equals("/?") || arg.equals("-h") || arg.equals("--help")) {
System.out.println("HeapAudit command line syntax\n\n" + "> java -jar heapaudit.jar [ <pid> [options] ]\n");
help();
return;
}
}
id = args[0];
} else {
for (VirtualMachineDescriptor vm : VirtualMachine.list()) {
System.out.println(vm.id() + '\t' + vm.displayName());
}
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 {
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");
}
if (!hasOutput) {
file = File.createTempFile("heapaudit", ".out");
s.append(" -Xoutput=" + file.getAbsolutePath());
}
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) {
System.out.println(" terminated");
}
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();
}
}
}Example 93
| Project: jss7-master File: SimpleAlarmListenerForm.java View source code |
private void createLocalProcessesList() {
ArrayList<BeanProcess> lst = new ArrayList<BeanProcess>();
List<VirtualMachineDescriptor> list = VirtualMachine.list();
for (VirtualMachineDescriptor vmd : list) {
String desc = vmd.toString();
try {
BeanProcess bp = new BeanProcess();
bp.vm = VirtualMachine.attach(vmd);
int i2 = desc.indexOf(":");
if (i2 > 0)
desc = desc.substring(i2 + 1);
bp.name = desc;
lst.add(bp);
} catch (IOException e) {
e.printStackTrace();
} catch (AttachNotSupportedException e) {
e.printStackTrace();
}
}
beanList = new BeanProcess[lst.size()];
lst.toArray(beanList);
}Example 94
| Project: Lucee-master File: InstrumentationFactory.java View source code |
@Override
public Object run() {
ClassLoader ccl = Thread.currentThread().getContextClassLoader();
Thread.currentThread().setContextClassLoader(ClassLoader.getSystemClassLoader());
try {
JavaVendor vendor = JavaVendor.getCurrentVendor();
Resource toolsJar = null;
// When running on IBM, the attach api classes are packaged in vm.jar which is a part
// of the default vm classpath.
RefBoolean useOurOwn = new RefBooleanImpl(true);
//if (!vendor.isIBM()) {
// If we can't find the tools.jar and we're not on IBM we can't load the agent.
toolsJar = findToolsJar(config, log, useOurOwn);
if (toolsJar == null) {
return null;
}
//}
log.info("Instrumentation", "tools.jar used:" + toolsJar);
// add the attach native library
if (useOurOwn.toBooleanValue())
addAttachIfNecessary(config, log);
Class<?> vmClass = loadVMClass(toolsJar, log, vendor);
log.info("Instrumentation", "loaded VirtualMachine class:" + (vmClass == null ? "null" : vmClass.getName()));
if (vmClass == null) {
return null;
}
String agentPath = createAgentJar(log, config).getAbsolutePath();
if (agentPath == null) {
return null;
}
log.info("Instrumentation", "try to load agent (path:" + agentPath + ")");
loadAgent(config, log, agentPath, vmClass);
//log.info("Instrumentation","agent loaded (path:"+agentPath+")");
} catch (IOException ioe) {
log.log(Log.LEVEL_INFO, "Instrumentation", ioe);
} finally {
Thread.currentThread().setContextClassLoader(ccl);
}
return null;
}Example 95
| Project: openjpa-master File: InstrumentationFactory.java View source code |
/**
* If <b>ibm</b> is false, this private method will create a new URLClassLoader and attempt to load the
* com.sun.tools.attach.VirtualMachine class from the provided toolsJar file.
*
* <p>
* If <b>ibm</b> is true, this private method will ignore the toolsJar parameter and load the
* com.ibm.tools.attach.VirtualMachine class.
*
*
* @return The AttachAPI VirtualMachine class <br>
* or null if something unexpected happened.
*/
private static Class<?> loadVMClass(File toolsJar, Log log, JavaVendors vendor) {
try {
ClassLoader loader = Thread.currentThread().getContextClassLoader();
String cls = vendor.getVirtualMachineClassName();
if (vendor.isIBM() == false) {
loader = new URLClassLoader(new URL[] { toolsJar.toURI().toURL() }, loader);
}
return loader.loadClass(cls);
} catch (Exception e) {
if (log.isTraceEnabled()) {
log.trace(_name + ".loadVMClass() failed to load the VirtualMachine class");
}
}
return null;
}Example 96
| Project: Vader-master File: JavaProcessImpl.java View source code |
/**
* @throws ConnectException
*/
@Override
public JMXConnector getLocalJmxConnector(String connectorName) throws ConnectException, NoLocalJmxConnectionException {
if (jmxc != null) {
return jmxc;
}
if (!process.isActive()) {
throw new ConnectException("Cannot establish local JMX connection as process is not active: " + this);
}
String address;
try {
VirtualMachine vm = VirtualMachine.attach("" + process.getPid());
Properties props = vm.getSystemProperties();
address = props.getProperty(connectorName);
if (address == null) {
throw new ConnectException("Unable to find address for remote JMX connection with name = " + connectorName);
}
} catch (IOException e) {
ConnectException cex = new ConnectException("Cannot obtain local JMX connector address of: " + this);
cex.initCause(e);
throw cex;
} catch (AttachNotSupportedException e) {
throw new RuntimeException(e);
}
JMXServiceURL jmxUrl;
try {
jmxUrl = new JMXServiceURL(address);
} catch (MalformedURLException e) {
ConnectException cex = new ConnectException("Invalid local JMX URL for " + this + " : " + address);
cex.initCause(e);
throw cex;
}
try {
jmxc = JMXConnectorFactory.connect(jmxUrl);
} catch (java.rmi.ConnectException e) {
if (e.getMessage().startsWith("Connection refused")) {
throw new NoLocalJmxConnectionException("Local JMX connector address does not exist for: " + this);
}
ConnectException cex = new ConnectException("Underlying RMI communications exception");
cex.initCause(e);
throw cex;
} catch (IOException e) {
ConnectException cex = new ConnectException("Cannot establish local JMX connection to: " + this);
cex.initCause(e);
throw cex;
}
try {
jmxc.connect();
} catch (IOException e) {
ConnectException cex = new ConnectException("Cannot establish local JMX connection to: " + this);
cex.initCause(e);
throw cex;
}
return jmxc;
}Example 97
| Project: BeanBagger-master File: BeanBagger.java View source code |
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws Exception {
//Get the MBean server
MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
//register the MBean
BBConfig mBean = new BBConfig();
ObjectName name = new ObjectName("com.stiv.jmx:type=BBConfig");
mbs.registerMBean(mBean, name);
for (int x = 0; x < args.length; x++) {
String disarg = args[x];
switch(disarg) {
case "-p":
if (x == args.length && !args[x + 1].startsWith("-"))
Usage();
mBean.setTargetJVM(args[x + 1]);
x++;
break;
case "-pp":
mBean.setprettyprint(true);
break;
case "-j":
mBean.setoutJSON(true);
if (//If next item on line exists and is not an option
args.length - 1 > x && !args[x + 1].startsWith("-")) {
mBean.setJSONFile(args[x + 1]);
x++;
}
break;
case "-b":
if (args.length - 1 > x && !args[x + 1].startsWith("-")) {
mBean.setTARGETBEAN(args[x + 1]);
x++;
}
break;
case "-r":
mBean.setignoreunreadable(true);
break;
case "-q":
mBean.setconsoleout(false);
break;
case "-u":
mBean.setsuppresscomplex(true);
break;
case "-m":
mBean.setsupressSun(true);
break;
case "-x":
mBean.setExactMatchRequired(true);
break;
case "-log":
if (//If next item on line exists and is not an option
args.length - 1 > x && !args[x + 1].startsWith("-")) {
mBean.setLogDir(args[x + 1]);
try {
File theDir = new File(mBean.getLogDir());
// if the directory does not exist, create it
if (!theDir.exists()) {
if (mBean.getconsoleout())
System.out.println("creating directory: " + mBean.getLogDir());
theDir.mkdir();
}
} catch (Exception ex) {
System.out.println("Error creating directory: " + mBean.getLogDir());
System.exit(1);
}
// Write a readme file to the directory as a test
try {
String rmf = mBean.getLogDir() + "/BeanBaggerreadme.txt";
try (PrintWriter out = new PrintWriter(rmf)) {
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
out.println("Beanbagger started " + dateFormat.format(date));
//consider adding options outlining the arguments started with.
out.close();
}
} catch (Exception ex) {
System.out.println("Error creating files in: " + mBean.getLogDir());
}
x++;
}
break;
case "-l":
mBean.setLoop(true);
if (args.length - 1 > x && !args[x + 1].startsWith("-")) {
try {
mBean.setLoopDelaySeconds(Integer.parseInt(args[x + 1]));
} catch (Exception ex) {
System.out.println("You call " + args[x + 1] + " an integer" + mBean.getInsult() + "?");
Usage();
}
x++;
} else {
mBean.setLoopDelaySeconds(30);
}
break;
case "-c":
mBean.setLoop(true);
if (args.length - 1 > x && !args[x + 1].startsWith("-")) {
try {
mBean.setIterations(Integer.parseInt(args[x + 1]));
} catch (Exception ex) {
System.out.println("You call " + args[x + 1] + " an integer" + mBean.getInsult() + "?");
Usage();
}
x++;
} else {
mBean.setIterations(5);
}
break;
default:
Usage();
}
//End switch
}
//Variables have been set. We are done with intitial config
Boolean loopagain = false;
do {
try {
//The following code grabs a list of running VMs and sees if they match our target--------------------------------------
Map<String, VirtualMachine> result = new HashMap<>();
List<VirtualMachineDescriptor> list = VirtualMachine.list();
List<VirtualMachineDescriptor> MATCHINGLIST = new ArrayList<VirtualMachineDescriptor>();
Boolean gotit = false;
String listofjvs = "";
if (mBean.getconsoleout())
System.out.println("Searching for matching VM instances");
for (VirtualMachineDescriptor vmd : list) {
String desc = vmd.toString();
try {
result.put(desc, VirtualMachine.attach(vmd));
String DN = vmd.displayName();
if (DN.contains(mBean.getTargetJVM()) || mBean.getTargetJVM().equalsIgnoreCase("*")) {
if (DN.equals("")) {
if (mBean.getconsoleout())
System.out.println(" Skipping unnamed JVM");
} else if (!mBean.getTargetJVM().startsWith("BeanBagger") && DN.contains("BeanBagger")) {
if (mBean.getconsoleout())
System.out.println(" Skipping BeanBagger JVM");
} else {
if (mBean.getconsoleout())
System.out.println(" Matching JVM instance found: " + DN);
TARGETDESCRIPTOR = vmd;
gotit = true;
MATCHINGLIST.add(vmd);
}
} else {
listofjvs += DN + " \n";
}
} catch (IOExceptionAttachNotSupportedException | e) {
}
}
if (//If we dont find the instance.
!gotit) {
System.out.println("No JVM Processes matching " + mBean.getTargetJVM() + " were found.");
System.out.println("Found instances: " + listofjvs);
System.exit(1);
}
System.out.println("");
///-------------If we get here, we have identified at least one instance matching our criteria
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Contains Hosts
org.json.JSONObject Jinfrascan = new org.json.JSONObject();
org.json.JSONArray Hosts = new org.json.JSONArray();
org.json.JSONObject Host = new org.json.JSONObject();
//JVMs on host
org.json.JSONArray JVMs = new org.json.JSONArray();
for (VirtualMachineDescriptor avmd : MATCHINGLIST) {
// Connects to the process containing our beans
myJMXconnector = getLocalConnection(VirtualMachine.attach(avmd));
//Connects to the MBean server for that process.
MBeanServerConnection myJMXConnection = myJMXconnector.getMBeanServerConnection();
if (mBean.getconsoleout())
System.out.println("Number of beans found in " + ANSI_CYAN + avmd.displayName() + ANSI_RESET + ": " + myJMXConnection.getMBeanCount());
String getDefaultDomain = myJMXConnection.getDefaultDomain();
String[] getDomains = myJMXConnection.getDomains();
Set<ObjectInstance> beans = myJMXConnection.queryMBeans(null, null);
org.json.JSONObject JVM = new org.json.JSONObject();
org.json.JSONArray JBeans = new org.json.JSONArray();
for (ObjectInstance instance : beans) {
String daclassname = instance.getClassName();
ObjectName oname = instance.getObjectName();
String BeanName = oname.getCanonicalName();
Hashtable<String, String> harry = oname.getKeyPropertyList();
if (mBean.getsupressSun() & (daclassname.startsWith("sun.") | daclassname.startsWith("com.sun."))) {
continue;
}
if (daclassname.contains(mBean.getTARGETBEAN()) || mBean.getTARGETBEAN().contentEquals("*")) {
MBeanAttributeInfo[] myAttributeArray = null;
org.json.JSONObject Beanboy = new org.json.JSONObject();
org.json.JSONArray BeanieButes = new org.json.JSONArray();
try {
MBeanInfo info = myJMXConnection.getMBeanInfo(instance.getObjectName());
myAttributeArray = info.getAttributes();
if (mBean.getconsoleout())
System.out.println(" Processing bean: " + ANSI_GREEN + BeanName + ANSI_RESET);
} catch (UnsupportedOperationExceptionRuntimeMBeanException | IllegalStateException | ex) {
if (mBean.getconsoleout())
System.out.println(" Error processing bean: " + BeanName);
}
for (MBeanAttributeInfo thisAttributeInfo : myAttributeArray) {
String attvalue = "";
String myname = "";
String mytype = "";
String mydesc = "";
boolean myread = false;
boolean mywrite = false;
try {
myname = thisAttributeInfo.getName();
mydesc = thisAttributeInfo.getDescription();
mytype = thisAttributeInfo.getType();
myread = thisAttributeInfo.isReadable();
mywrite = thisAttributeInfo.isWritable();
if (myread) {
switch(mytype) {
case "String":
attvalue = (String) myJMXConnection.getAttribute(instance.getObjectName(), myname);
break;
case "java.lang.String":
attvalue = (String) myJMXConnection.getAttribute(instance.getObjectName(), myname);
break;
case "boolean":
attvalue = myJMXConnection.getAttribute(instance.getObjectName(), myname).toString();
break;
case "int":
attvalue = myJMXConnection.getAttribute(instance.getObjectName(), myname).toString();
break;
case "long":
attvalue = myJMXConnection.getAttribute(instance.getObjectName(), myname).toString();
break;
case "double":
attvalue = myJMXConnection.getAttribute(instance.getObjectName(), myname).toString();
break;
default:
attvalue = "*-Unsupported: complex type-*";
break;
}
//end switch
} else //end if
{
attvalue = "";
}
} catch (Exception ex) {
attvalue = "*-Exception: Unavailable-*";
}
//THis section is where we determine if we are going to record the value or not.
boolean dooutput = false;
if (!mBean.getsuppresscomplex()) {
dooutput = true;
} else {
try {
if (!attvalue.startsWith("*-")) {
dooutput = true;
}
} catch (//For attributes with no values.
Exception //For attributes with no values.
ex) {
attvalue = "*-Unavailable-*";
if (!mBean.getsuppresscomplex())
dooutput = true;
}
}
if (mBean.getignoreunreadable() && !myread) {
dooutput = false;
}
if (dooutput) {
// Create the list of attributes and values into an object.
org.json.JSONObject AtDatas = new org.json.JSONObject();
AtDatas.put("Name", myname);
AtDatas.put("Type", mytype);
String attvaluecolor = "";
if (attvalue == null)
attvalue = "*-NULL-*";
if (attvalue.startsWith("*-U")) {
attvaluecolor = ANSI_PURPLE + attvalue + ANSI_RESET;
} else if (attvalue.startsWith("*-E")) {
attvaluecolor = ANSI_RED + attvalue + ANSI_RESET;
} else
attvaluecolor = attvalue;
if (attvalue.equals("")) {
attvaluecolor = ANSI_YELLOW + "\"\"" + ANSI_RESET;
}
if (myread) {
AtDatas.put("Value", attvalue);
if (mBean.getconsoleout())
System.out.println(" Name:" + myname + " Type:" + mytype + " Writeable:" + mywrite + " Readable:" + myread + " Value:" + attvaluecolor);
} else {
if (mBean.getconsoleout())
System.out.println(" Name:" + myname + " Type:" + mytype + " Writeable:" + mywrite + " Readable:" + myread);
AtDatas.put("Readable", myread);
}
AtDatas.put("Desc", mydesc);
if (mywrite) {
AtDatas.put("Writable", mywrite);
}
BeanieButes.put(AtDatas);
}
}
//End processing Bean Attributes, add attributes to bean array.
//add attributes to the bean
Beanboy.put(BeanName, BeanieButes);
//add bean to VM
JBeans.put(Beanboy);
}
//End if this bean was skipped.
}
//End of process JVM instance beans
JVM.put(avmd.displayName(), JBeans);
JVMs.put(JVM);
}
//End JVM iteration
java.net.InetAddress addr = java.net.InetAddress.getLocalHost();
String mename = addr.getHostName();
Host.put(mename, JVMs);
//add vms to host
Hosts.put(Host);
//add server(s) to infra
String time = String.valueOf(System.currentTimeMillis());
Jinfrascan.put(time, Hosts);
mBean.setLastJSON(Jinfrascan.toString());
if (!mBean.getJSONFile().equals("")) {
try {
PrintWriter writer = new PrintWriter(mBean.getJSONFile(), "UTF-8");
if (mBean.getprettyprint()) {
writer.println(Jinfrascan.toString(4));
} else {
writer.println(Jinfrascan);
}
writer.close();
} catch (Exception ex) {
System.out.print("Error processing file!");
System.out.print(ex);
}
}
if (mBean.getoutJSON()) {
System.out.println("JSON Output:");
if (mBean.getprettyprint()) {
System.out.print(Jinfrascan.toString(4));
} else {
System.out.print(Jinfrascan);
}
}
if (mBean.getDoLogging()) {
String rmf = mBean.getLogDir() + "/BeanBagger" + time + ".txt";
PrintWriter writer = new PrintWriter(rmf, "UTF-8");
if (mBean.getprettyprint()) {
writer.println(Jinfrascan.toString(4));
} else {
writer.println(Jinfrascan);
}
writer.close();
}
} catch (Exception exception) {
System.out.println("Error:" + exception);
System.out.println(" " + exception);
}
loopagain = false;
mBean.setIterationsCount(mBean.getIterationsCount() + 1);
if (mBean.getLoop())
loopagain = true;
if (mBean.getIterations() > 0 && mBean.getIterationsCount() < mBean.getIterations()) {
//If we are counting and havent reached limit
loopagain = true;
}
if (mBean.getIterations() > 0 && mBean.getIterationsCount() >= mBean.getIterations()) {
//If we are counting and havent reached limit
loopagain = false;
}
//If mBean says stop looping, stop it!
if (!mBean.getLoop())
loopagain = false;
if (loopagain) {
System.out.println("Sleeping " + mBean.getLoopDelaySeconds() + " seconds. This was run " + mBean.getIterationsCount());
for (int x = 0; x < mBean.getLoopDelaySeconds(); x++) {
TimeUnit.SECONDS.sleep(1);
if (!mBean.getLoop()) {
loopagain = false;
break;
}
}
}
} while (loopagain);
System.out.println("");
System.out.println("Stiv's Beanbagger Finished: " + mBean.getIterationsCount() + " iterations.");
}Example 98
| Project: jmxtrans-master File: Server.java View source code |
public static JMXServiceURL extractJMXServiceURLFromPid(String pid) throws IOException {
try {
VirtualMachine vm = VirtualMachine.attach(pid);
try {
String connectorAddress = vm.getAgentProperties().getProperty(CONNECTOR_ADDRESS);
if (connectorAddress == null) {
String agent = vm.getSystemProperties().getProperty("java.home") + File.separator + "lib" + File.separator + "management-agent.jar";
vm.loadAgent(agent);
connectorAddress = vm.getAgentProperties().getProperty(CONNECTOR_ADDRESS);
}
return new JMXServiceURL(connectorAddress);
} finally {
vm.detach();
}
} catch (Exception e) {
throw new IOException(e);
}
}Example 99
| Project: rest.li-master File: LoadBalancerClientCli.java View source code |
public static void resetTogglingStores(String host, boolean enabled) throws Exception {
MonitoredHost _host = MonitoredHost.getMonitoredHost(new HostIdentifier(host));
for (Object pidObj : _host.activeVms()) {
int pid = (Integer) pidObj;
System.out.println("checking pid: " + pid);
JMXServiceURL jmxUrl = null;
com.sun.tools.attach.VirtualMachine vm = com.sun.tools.attach.VirtualMachine.attach(pid + "");
try {
// get the connector address
String connectorAddress = vm.getAgentProperties().getProperty(CONNECTOR_ADDRESS);
// establish connection to connector server
if (connectorAddress != null) {
jmxUrl = new JMXServiceURL(connectorAddress);
}
} finally {
vm.detach();
}
if (jmxUrl != null) {
System.out.println("got jmx url: " + jmxUrl);
// connect to jmx
JMXConnector connector = JMXConnectorFactory.connect(jmxUrl);
connector.connect();
MBeanServerConnection mbeanServer = connector.getMBeanServerConnection();
// look for all beans in the d2 name space
Set<ObjectInstance> objectInstances = mbeanServer.queryMBeans(new ObjectName("com.linkedin.d2:*"), null);
for (ObjectInstance objectInstance : objectInstances) {
System.err.println("checking object: " + objectInstance.getObjectName());
// if we've found a toggling store, then toggle it
if (objectInstance.getObjectName().toString().endsWith("TogglingStore")) {
System.out.println("found toggling zk store, so toggling to: " + enabled);
mbeanServer.invoke(objectInstance.getObjectName(), "setEnabled", new Object[] { enabled }, new String[] { "boolean" });
}
}
} else {
System.out.println("pid is not a jmx process: " + pid);
}
}
}Example 100
| Project: arquillian-container-was-master File: WLPManagedContainer.java View source code |
// This method includes parts heavily based on the ManagedDeployableContainer.java in the jboss-as
// managed container implementation as written by Thomas.Diesler@jboss.com
public void start() throws LifecycleException {
if (log.isLoggable(Level.FINER)) {
log.entering(className, "start");
}
// Find WebSphere Liberty Profile VMs by looking for ws-launch.jar and the name of the server
String vmid;
VirtualMachine wlpvm = null;
String serviceURL = null;
try {
vmid = findVirtualMachineIdByName(containerConfiguration.getServerName());
// If it has already been started, throw exception unless we explicitly allow connecting to a running server
if (vmid != null) {
if (!containerConfiguration.isAllowConnectingToRunningServer())
throw new LifecycleException("Connecting to an already running server is not allowed");
wlpvm = VirtualMachine.attach(vmid);
serviceURL = getVMLocalConnectorAddress(wlpvm);
if (serviceURL == null)
throw new LifecycleException("Unable to retrieve connector address for localConnector");
} else {
if (containerConfiguration.isAddLocalConnector()) {
// Get path to server.xml
String serverXML = getServerXML();
if ("defaultServer".equals(containerConfiguration.getServerName()) && !new File(serverXML).exists()) {
// If server.xml doesn't exist for the default server, we may be dealing with a new
// installation where the server will be created at first
// startup. Get the default template server.xml instead. The server.xml for "defaultServer"
// will be created from this.
serverXML = getDefaultServerXML();
}
// Read server.xml file into Memory
Document document = readServerXML(serverXML);
addFeatures(document, "localConnector-1.0");
writeServerXML(document, serverXML);
}
// Start the WebSphere Liberty Profile VM
List<String> cmd = new ArrayList<String>();
String javaVmArguments = containerConfiguration.getJavaVmArguments();
cmd.add(System.getProperty("java.home") + "/bin/java");
cmd.add("-Dcom.ibm.ws.logging.console.log.level=INFO");
if (!javaVmArguments.equals(""))
cmd.add(javaVmArguments);
cmd.add("-javaagent:lib/bootstrap-agent.jar");
cmd.add("-jar");
cmd.add("lib/ws-launch.jar");
cmd.add(containerConfiguration.getServerName());
log.finer("Starting server with command: " + cmd.toString());
ProcessBuilder pb = new ProcessBuilder(cmd);
pb.directory(new File(containerConfiguration.getWlpHome()));
pb.redirectErrorStream(true);
wlpProcess = pb.start();
new Thread(new ConsoleConsumer()).start();
final Process proc = wlpProcess;
shutdownThread = new Thread(new Runnable() {
@Override
public void run() {
if (proc != null) {
proc.destroy();
try {
proc.waitFor();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
});
Runtime.getRuntime().addShutdownHook(shutdownThread);
// Wait up to 30s for the server to start
int startupTimeout = containerConfiguration.getServerStartTimeout() * 1000;
while (startupTimeout > 0 && serviceURL == null) {
startupTimeout -= 500;
Thread.sleep(500);
// Verify that the process we're looking for is actually running
// exit value of the process
int ev = Integer.MIN_VALUE;
// Will be thrown when process is still running
IllegalThreadStateException itse = null;
try {
ev = wlpProcess.exitValue();
} catch (IllegalThreadStateException e) {
itse = e;
}
if (itse == null)
throw new LifecycleException("Process terminated prematurely; ev = " + ev);
if (vmid == null)
// Find WebSphere Liberty Profile VMs by looking for ws-launch.jar and the name of the server
vmid = findVirtualMachineIdByName(containerConfiguration.getServerName());
if (wlpvm == null && vmid != null)
wlpvm = VirtualMachine.attach(vmid);
if (serviceURL == null && wlpvm != null)
serviceURL = getVMLocalConnectorAddress(wlpvm);
}
// If serviceURL is still null, we were unable to start the virtual machine
if (serviceURL == null)
throw new LifecycleException("Unable to retrieve connector address for localConnector of started VM");
log.finer("vmid: " + vmid);
}
} catch (Exception e) {
throw new LifecycleException("Could not start container", e);
}
try {
JMXServiceURL url = new JMXServiceURL(serviceURL);
jmxConnector = JMXConnectorFactory.connect(url);
mbsc = jmxConnector.getMBeanServerConnection();
} catch (IOException e) {
throw new LifecycleException("Connecting to the JMX MBean Server failed", e);
}
if (log.isLoggable(Level.FINER)) {
log.exiting(className, "start");
}
}Example 101
| Project: cougar-master File: CougarHelpers.java View source code |
/*
* 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 (//Do Nothing move onto next vm
Exception //Do Nothing move onto next vm
e) {
continue;
}
try {
if (!makeServerConnection(jmxConnector)) {
continue;
}
} catch (//Do Nothing move onto next vm
Exception //Do Nothing move onto next vm
e) {
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");
}
}