Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/src/share/classes/sun/tools/jcmd/JCmd.java
38918 views
/*1* Copyright (c) 2011, 2014, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425package sun.tools.jcmd;2627import java.io.InputStream;28import java.io.IOException;29import java.io.UnsupportedEncodingException;30import java.util.List;31import java.util.ArrayList;32import java.util.Comparator;33import java.net.URISyntaxException;3435import com.sun.tools.attach.AttachOperationFailedException;36import com.sun.tools.attach.VirtualMachine;37import com.sun.tools.attach.VirtualMachineDescriptor;38import com.sun.tools.attach.AgentLoadException;39import com.sun.tools.attach.AttachNotSupportedException;4041import sun.tools.attach.HotSpotVirtualMachine;42import sun.tools.jstat.JStatLogger;43import sun.jvmstat.monitor.Monitor;44import sun.jvmstat.monitor.MonitoredHost;45import sun.jvmstat.monitor.MonitoredVm;46import sun.jvmstat.monitor.MonitoredVmUtil;47import sun.jvmstat.monitor.MonitorException;48import sun.jvmstat.monitor.VmIdentifier;4950public class JCmd {51public static void main(String[] args) {52Arguments arg = null;53try {54arg = new Arguments(args);55} catch (IllegalArgumentException ex) {56System.err.println("Error parsing arguments: " + ex.getMessage()57+ "\n");58Arguments.usage();59System.exit(1);60}6162if (arg.isShowUsage()) {63Arguments.usage();64System.exit(1);65}6667if (arg.isListProcesses()) {68List<VirtualMachineDescriptor> vmds = VirtualMachine.list();69for (VirtualMachineDescriptor vmd : vmds) {70System.out.println(vmd.id() + " " + vmd.displayName());71}72System.exit(0);73}7475List<String> pids = new ArrayList<String>();76if (arg.getPid() == 0) {77// find all VMs78List<VirtualMachineDescriptor> vmds = VirtualMachine.list();79for (VirtualMachineDescriptor vmd : vmds) {80if (!isJCmdProcess(vmd)) {81pids.add(vmd.id());82}83}84} else if (arg.getProcessSubstring() != null) {85// use the partial class-name match86List<VirtualMachineDescriptor> vmds = VirtualMachine.list();87for (VirtualMachineDescriptor vmd : vmds) {88if (isJCmdProcess(vmd)) {89continue;90}91try {92String mainClass = getMainClass(vmd);93if (mainClass != null94&& mainClass.indexOf(arg.getProcessSubstring()) != -1) {95pids.add(vmd.id());96}97} catch (MonitorException|URISyntaxException e) {98if (e.getMessage() != null) {99System.err.println(e.getMessage());100} else {101Throwable cause = e.getCause();102if ((cause != null) && (cause.getMessage() != null)) {103System.err.println(cause.getMessage());104} else {105e.printStackTrace();106}107}108}109}110if (pids.isEmpty()) {111System.err.println("Could not find any processes matching : '"112+ arg.getProcessSubstring() + "'");113System.exit(1);114}115} else if (arg.getPid() == -1) {116System.err.println("Invalid pid specified");117System.exit(1);118} else {119// Use the found pid120pids.add(arg.getPid() + "");121}122123boolean success = true;124for (String pid : pids) {125System.out.println(pid + ":");126if (arg.isListCounters()) {127listCounters(pid);128} else {129try {130executeCommandForPid(pid, arg.getCommand());131} catch(AttachOperationFailedException ex) {132System.err.println(ex.getMessage());133success = false;134} catch(Exception ex) {135ex.printStackTrace();136success = false;137}138}139}140System.exit(success ? 0 : 1);141}142143private static void executeCommandForPid(String pid, String command)144throws AttachNotSupportedException, IOException,145UnsupportedEncodingException {146VirtualMachine vm = VirtualMachine.attach(pid);147148// Cast to HotSpotVirtualMachine as this is an149// implementation specific method.150HotSpotVirtualMachine hvm = (HotSpotVirtualMachine) vm;151String lines[] = command.split("\\n");152for (String line : lines) {153if (line.trim().equals("stop")) {154break;155}156try (InputStream in = hvm.executeJCmd(line);) {157// read to EOF and just print output158byte b[] = new byte[256];159int n;160boolean messagePrinted = false;161do {162n = in.read(b);163if (n > 0) {164String s = new String(b, 0, n, "UTF-8");165System.out.print(s);166messagePrinted = true;167}168} while (n > 0);169if (!messagePrinted) {170System.out.println("Command executed successfully");171}172}173}174vm.detach();175}176177private static void listCounters(String pid) {178// Code from JStat (can't call it directly since it does System.exit)179VmIdentifier vmId = null;180try {181vmId = new VmIdentifier(pid);182} catch (URISyntaxException e) {183System.err.println("Malformed VM Identifier: " + pid);184return;185}186try {187MonitoredHost monitoredHost = MonitoredHost.getMonitoredHost(vmId);188MonitoredVm monitoredVm = monitoredHost.getMonitoredVm(vmId, -1);189JStatLogger logger = new JStatLogger(monitoredVm);190logger.printSnapShot("\\w*", // all names191new AscendingMonitorComparator(), // comparator192false, // not verbose193true, // show unsupported194System.out);195monitoredHost.detach(monitoredVm);196} catch (MonitorException ex) {197ex.printStackTrace();198}199}200201private static boolean isJCmdProcess(VirtualMachineDescriptor vmd) {202try {203String mainClass = getMainClass(vmd);204return mainClass != null && mainClass.equals(JCmd.class.getName());205} catch (URISyntaxException|MonitorException ex) {206return false;207}208}209210private static String getMainClass(VirtualMachineDescriptor vmd)211throws URISyntaxException, MonitorException {212try {213String mainClass = null;214VmIdentifier vmId = new VmIdentifier(vmd.id());215MonitoredHost monitoredHost = MonitoredHost.getMonitoredHost(vmId);216MonitoredVm monitoredVm = monitoredHost.getMonitoredVm(vmId, -1);217mainClass = MonitoredVmUtil.mainClass(monitoredVm, true);218monitoredHost.detach(monitoredVm);219return mainClass;220} catch(NullPointerException e) {221// There is a potential race, where a running java app is being222// queried, unfortunately the java app has shutdown after this223// method is started but before getMonitoredVM is called.224// If this is the case, then the /tmp/hsperfdata_xxx/pid file225// will have disappeared and we will get a NullPointerException.226// Handle this gracefully....227return null;228}229}230231/**232* Class to compare two Monitor objects by name in ascending order.233* (from jstat)234*/235static class AscendingMonitorComparator implements Comparator<Monitor> {236237public int compare(Monitor m1, Monitor m2) {238String name1 = m1.getName();239String name2 = m2.getName();240return name1.compareTo(name2);241}242}243}244245246