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

The following examples show how to use com.sun.tools.attach.VirtualMachine#list() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: JMXConnection.java    From OpenFalcon-SuitAgent with Apache License 2.0 6 votes vote down vote up
/**
 * 获取指定服务名的本地JMX VM 描述对象
 * @param serverName
 * @return
 */
public static List<VirtualMachineDescriptor> getVmDescByServerName(String serverName){
    List<VirtualMachineDescriptor> vmDescList = new ArrayList<>();
    List<VirtualMachineDescriptor> vms = VirtualMachine.list();
    for (VirtualMachineDescriptor desc : vms) {
        File file = new File(desc.displayName());
        if(file.exists()){
            //java -jar 形式启动的Java应用
            if(file.toPath().getFileName().toString().equals(serverName)){
                vmDescList.add(desc);
            }
        }else if(desc.displayName().contains(serverName)){
            vmDescList.add(desc);
        }
    }
    return vmDescList;
}
 
Example 2
Source File: JMXUtil.java    From SuitAgent with Apache License 2.0 6 votes vote down vote up
/**
 * 获取指定服务名的本地JMX VM 描述对象
 * @param serverName
 * @return
 */
public static List<VirtualMachineDescriptor> getVmDescByServerName(String serverName){
    List<VirtualMachineDescriptor> vmDescList = new ArrayList<>();
    if (StringUtils.isEmpty(serverName)){
        return vmDescList;
    }
    List<VirtualMachineDescriptor> vms = VirtualMachine.list();
    for (VirtualMachineDescriptor desc : vms) {
        //java -jar 形式启动的Java应用
        if(desc.displayName().matches(".*\\.jar(\\s*-*.*)*") && desc.displayName().contains(serverName)){
            vmDescList.add(desc);
        }else if(hasContainsServerName(desc.displayName(),serverName)){
            vmDescList.add(desc);
        }else if (isJSVC(desc.id(),serverName)){
            VirtualMachineDescriptor descriptor = new VirtualMachineDescriptor(desc.provider(),desc.id(),serverName);
            vmDescList.add(descriptor);
        }
    }
    return vmDescList;
}
 
Example 3
Source File: LauncherLifecycleCommands.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
protected boolean isVmWithProcessIdRunning(final Integer pid) {
  for (final VirtualMachineDescriptor vm : VirtualMachine.list()) {
    if (String.valueOf(pid).equals(vm.id())) {
      return true;
    }
  }

  return false;
}
 
Example 4
Source File: AttachHelper.java    From extract-tls-secrets with Apache License 2.0 5 votes vote down vote up
private static String list() {
    StringBuilder msg = new StringBuilder();
    for (VirtualMachineDescriptor vm : VirtualMachine.list()) {
        msg.append("  ").append(vm.id()).append(" ").append(vm.displayName()).append("\n");
    }
    return msg.toString();
}
 
Example 5
Source File: LauncherLifecycleCommands.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
protected boolean isVmWithProcessIdRunning(final Integer pid) {
  for (final VirtualMachineDescriptor vm : VirtualMachine.list()) {
    if (String.valueOf(pid).equals(vm.id())) {
      return true;
    }
  }

  return false;
}
 
Example 6
Source File: AttachModelProvider.java    From visualvm with GNU General Public License v2.0 5 votes vote down vote up
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 7
Source File: JCozServiceImpl.java    From JCoz with GNU General Public License v3.0 5 votes vote down vote up
@Override
public int attachToProcess(int localProcessId) throws RemoteException {
    logger.info("Attaching to process {}", localProcessId);
    try {
        for (VirtualMachineDescriptor desc : VirtualMachine.list()) {
            if (Integer.parseInt(desc.id()) == localProcessId) {
                VirtualMachine vm = VirtualMachine.attach(desc);
                vm.startLocalManagementAgent();
                Properties props = vm.getAgentProperties();
                String connectorAddress = props
                    .getProperty(CONNECTOR_ADDRESS_PROPERTY_KEY);
                JMXServiceURL url = new JMXServiceURL(connectorAddress);
                JMXConnector connector = JMXConnectorFactory.connect(url);
                MBeanServerConnection mbeanConn = connector
                    .getMBeanServerConnection();
                attachedVMs.put(localProcessId, JMX.newMXBeanProxy(mbeanConn,
                            JCozProfiler.getMBeanName(),
                            JCozProfilerMBean.class));
                return JCozProfilingErrorCodes.NORMAL_RETURN;
            }
        }
    } catch (IOException | NumberFormatException
            | AttachNotSupportedException e) {
        StringWriter stringWriter = new StringWriter();
        e.printStackTrace(new PrintWriter(stringWriter));
        logger.error("Got an exception during attachToProcess, stacktrace: {}", stringWriter);
        throw new RemoteException("", e);

            }
    return JCozProfilingErrorCodes.INVALID_JAVA_PROCESS;
}
 
Example 8
Source File: JCozServiceImpl.java    From JCoz with GNU General Public License v3.0 5 votes vote down vote up
@Override
public List<JCozVMDescriptor> getJavaProcessDescriptions() throws RemoteException {
    logger.info("Getting Java Process Descriptions");
    ArrayList<JCozVMDescriptor> stringDesc = new ArrayList<>();
    for (VirtualMachineDescriptor desc : VirtualMachine.list()) {
        logger.debug("Adding description {} with id {}", desc.displayName(), desc.id());
        stringDesc.add(new JCozVMDescriptor(Integer.parseInt(desc.id()), desc.displayName()));
    }
    return stringDesc;
}
 
Example 9
Source File: JCozClient.java    From JCoz with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Search through the list of running VMs on the localhost
 * and attach to a JCoz Profiler instance.
 *
 * @return Map<String, VirtualMachineDescriptor> A list of the VirtualMachines that
 * should be queried for being profilable.
 */
public static Map<String, VirtualMachineDescriptor> getJCozVMList() {
    Map<String, VirtualMachineDescriptor> jcozVMs = new HashMap<>();
    for (VirtualMachineDescriptor vmDesc : VirtualMachine.list()) {
        if (vmDesc.displayName().endsWith("JCozProfiler")) {
            jcozVMs.put(vmDesc.displayName(), vmDesc);
        }
    }

    return jcozVMs;
}
 
Example 10
Source File: AbstractLauncherDUnitTestCase.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
protected boolean isPidAlive(int pid) {
  for (VirtualMachineDescriptor vm : VirtualMachine.list()) {
    if (vm.id().equals(String.valueOf(pid))) {
      return true; // found the vm
    }
  }

  return false;
}
 
Example 11
Source File: AttachProcessUtils.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
@Override
public boolean isProcessAlive(final int pid) {
  for (VirtualMachineDescriptor vm : VirtualMachine.list()) {
    if (vm.id().equals(String.valueOf(pid))) {
      return true; // found the vm
    }
  }
  return false;
}
 
Example 12
Source File: DremioAttach.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
static String getVmIdForProcess(String dremioProcess) throws Exception {
  int dremioCount = 0;
  String vmid = null;
  for (VirtualMachineDescriptor descriptor : VirtualMachine.list()) {
    if (descriptor.toString().contains(dremioProcess)) {
      vmid = descriptor.id();
      dremioCount++;
    }
  }

  if (dremioCount != 1) {
    throw new UnsupportedOperationException("Failed to attach: couldn't find Dremio process to attach");
  }
  return vmid;
}
 
Example 13
Source File: ProcessArgumentMatcher.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private static Collection<VirtualMachineDescriptor> getVMDs(Class<?> excludeClass, String partialMatch) {
    String excludeCls = getExcludeStringFrom(excludeClass);
    Collection<VirtualMachineDescriptor> vids = new ArrayList<>();
    List<VirtualMachineDescriptor> vmds = VirtualMachine.list();
    for (VirtualMachineDescriptor vmd : vmds) {
        if (check(vmd, excludeCls, partialMatch)) {
            vids.add(vmd);
        }
    }
    return vids;
}
 
Example 14
Source File: ProcessArgumentMatcher.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private static Collection<VirtualMachineDescriptor> getSingleVMD(String pid) {
    Collection<VirtualMachineDescriptor> vids = new ArrayList<>();
    List<VirtualMachineDescriptor> vmds = VirtualMachine.list();
    for (VirtualMachineDescriptor vmd : vmds) {
        if (check(vmd, null, null)) {
            if (pid.equals(vmd.id())) {
                vids.add(vmd);
            }
        }
    }
    return vids;
}
 
Example 15
Source File: PromagentLoader.java    From promagent with Apache License 2.0 5 votes vote down vote up
private static VirtualMachineDescriptor findVirtualMachine(String pid) {
    for (VirtualMachineDescriptor vmd : VirtualMachine.list()) {
        if (vmd.id().equalsIgnoreCase(pid)) {
            return vmd;
        }
    }
    return null;
}
 
Example 16
Source File: AbstractLauncherDUnitTestCase.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
protected boolean isPidAlive(int pid) {
  for (VirtualMachineDescriptor vm : VirtualMachine.list()) {
    if (vm.id().equals(String.valueOf(pid))) {
      return true; // found the vm
    }
  }

  return false;
}
 
Example 17
Source File: AttachHelper.java    From extract-tls-secrets with Apache License 2.0 5 votes vote down vote up
private static boolean pidExists(String pid) {
    for (VirtualMachineDescriptor vm : VirtualMachine.list()) {
        if (vm.id().equals(pid)) {
            return true;
        }
    }
    return false;
}
 
Example 18
Source File: ArthasStarter.java    From bistoury with GNU General Public License v3.0 4 votes vote down vote up
private static void attachAgent(Configure configure) throws Exception {
    logger.info("start attach to arthas agent");
    VirtualMachineDescriptor virtualMachineDescriptor = null;
    for (VirtualMachineDescriptor descriptor : VirtualMachine.list()) {
        String pid = descriptor.id();
        if (pid.equals(String.valueOf(configure.getJavaPid()))) {
            virtualMachineDescriptor = descriptor;
        }
    }
    VirtualMachine virtualMachine = null;
    try {
        if (virtualMachineDescriptor == null) {
            virtualMachine = VirtualMachine.attach(String.valueOf(configure.getJavaPid()));
        } else {
            virtualMachine = VirtualMachine.attach(virtualMachineDescriptor);
        }

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

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

        logger.info("start load arthas agent, input {}, load {}", arthasAgent, realAgentFile.getCanonicalPath());
        final String delimiter = "$|$";
        virtualMachine.loadAgent(realAgentFile.getCanonicalPath(),
                configure.getArthasCore() + delimiter + ";;" + configure.toString() + delimiter + System.getProperty("bistoury.app.lib.class"));
    } finally {
        if (virtualMachine != null) {
            virtualMachine.detach();
        }
    }
}
 
Example 19
Source File: Attacher.java    From openjdk-systemtest with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {
	
	if (args.length < 2)
	{
		logOut("Not enough arguments given. This code requires, in this order:");
		logOut("1) The PID of JVM to attach to.");
		logOut("1) The absolute location of the agent jar to be attached.");
		logOut("3) (optional) Any arguments to be passed to the java agent.");
		System.exit(1);
	}
	String vmPidArg = args[0];
	Integer.parseInt(vmPidArg); //Just to make sure it's a number.
	logOut("Will attempt to attach to JVM with pid " + vmPidArg);

	String agentPathString = args[1];

	logOut("Attach will be done using agent jar file: " + agentPathString);
	
	// This may cause a compiler error in eclipse, as it is not a java.* class
	// It can be fixed by editing the access rules for the JRE system library
	// attach to target VM
	
	//First we wait for the target VM to become available
	boolean foundTarget = false;
	while (!foundTarget) {
		List<VirtualMachineDescriptor> allVMs = VirtualMachine.list();
		for (VirtualMachineDescriptor oneVM : allVMs) {
			if (oneVM.id().equals(vmPidArg)) {
				foundTarget = true;
			}
		}
		if (!foundTarget) {
			Thread.sleep(1000);
		}
	}
	
	//Then we attach to it.
	VirtualMachine vm = VirtualMachine.attach(vmPidArg);
	
	// load agent into target VM
	try {
		if (args.length > 2) {
			vm.loadAgent(agentPathString, args[2]);
		} else {
			vm.loadAgent(agentPathString);
		}
	} catch (java.io.IOException e) {
		//This exception is thrown if the test process terminates before the agent does. 
		//We don't mind if this happens.
	}
	
	// detach
	vm.detach();
}
 
Example 20
Source File: Arthas.java    From arthas with Apache License 2.0 4 votes vote down vote up
private void attachAgent(Configure configure) throws Exception {
    VirtualMachineDescriptor virtualMachineDescriptor = null;
    for (VirtualMachineDescriptor descriptor : VirtualMachine.list()) {
        String pid = descriptor.id();
        if (pid.equals(Long.toString(configure.getJavaPid()))) {
            virtualMachineDescriptor = descriptor;
            break;
        }
    }
    VirtualMachine virtualMachine = null;
    try {
        if (null == virtualMachineDescriptor) { // 使用 attach(String pid) 这种方式
            virtualMachine = VirtualMachine.attach("" + configure.getJavaPid());
        } else {
            virtualMachine = VirtualMachine.attach(virtualMachineDescriptor);
        }

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

        String arthasAgentPath = configure.getArthasAgent();
        //convert jar path to unicode string
        configure.setArthasAgent(encodeArg(arthasAgentPath));
        configure.setArthasCore(encodeArg(configure.getArthasCore()));
        virtualMachine.loadAgent(arthasAgentPath,
                configure.getArthasCore() + ";" + configure.toString());
    } finally {
        if (null != virtualMachine) {
            virtualMachine.detach();
        }
    }
}