Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/src/share/classes/sun/management/Agent.java
38827 views
/*1* Copyright (c) 2003, 2017, 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*/24package sun.management;2526import java.io.BufferedInputStream;27import java.io.File;28import java.io.FileInputStream;29import java.io.FileNotFoundException;30import java.io.IOException;31import java.io.InputStream;32import java.lang.management.ManagementFactory;33import java.lang.reflect.InvocationTargetException;34import java.lang.reflect.Method;35import java.net.InetAddress;36import java.net.UnknownHostException;37import java.text.MessageFormat;38import java.util.MissingResourceException;39import java.util.Properties;40import java.util.ResourceBundle;4142import javax.management.remote.JMXConnectorServer;43import javax.management.remote.JMXServiceURL;4445import static sun.management.AgentConfigurationError.*;46import sun.management.jmxremote.ConnectorBootstrap;47import sun.management.jdp.JdpController;48import sun.management.jdp.JdpException;49import sun.misc.VMSupport;5051/**52* This Agent is started by the VM when -Dcom.sun.management.snmp or53* -Dcom.sun.management.jmxremote is set. This class will be loaded by the54* system class loader. Also jmx framework could be started by jcmd55*/56public class Agent {57// management properties5859private static Properties mgmtProps;60private static ResourceBundle messageRB;61private static final String CONFIG_FILE =62"com.sun.management.config.file";63private static final String SNMP_PORT =64"com.sun.management.snmp.port";65private static final String JMXREMOTE =66"com.sun.management.jmxremote";67private static final String JMXREMOTE_PORT =68"com.sun.management.jmxremote.port";69private static final String RMI_PORT =70"com.sun.management.jmxremote.rmi.port";71private static final String ENABLE_THREAD_CONTENTION_MONITORING =72"com.sun.management.enableThreadContentionMonitoring";73private static final String LOCAL_CONNECTOR_ADDRESS_PROP =74"com.sun.management.jmxremote.localConnectorAddress";75private static final String SNMP_ADAPTOR_BOOTSTRAP_CLASS_NAME =76"sun.management.snmp.AdaptorBootstrap";7778private static final String JDP_DEFAULT_ADDRESS = "224.0.23.178";79private static final int JDP_DEFAULT_PORT = 7095;8081// The only active agent allowed82private static JMXConnectorServer jmxServer = null;8384// Parse string com.sun.management.prop=xxx,com.sun.management.prop=yyyy85// and return property set if args is null or empty86// return empty property set87private static Properties parseString(String args) {88Properties argProps = new Properties();89if (args != null && !args.trim().equals("")) {90for (String option : args.split(",")) {91String s[] = option.split("=", 2);92String name = s[0].trim();93String value = (s.length > 1) ? s[1].trim() : "";9495if (!name.startsWith("com.sun.management.")) {96error(INVALID_OPTION, name);97}9899argProps.setProperty(name, value);100}101}102103return argProps;104}105106// invoked by -javaagent or -Dcom.sun.management.agent.class107public static void premain(String args) throws Exception {108agentmain(args);109}110111// invoked by attach mechanism112public static void agentmain(String args) throws Exception {113if (args == null || args.length() == 0) {114args = JMXREMOTE; // default to local management115}116117Properties arg_props = parseString(args);118119// Read properties from the config file120Properties config_props = new Properties();121String fname = arg_props.getProperty(CONFIG_FILE);122readConfiguration(fname, config_props);123124// Arguments override config file125config_props.putAll(arg_props);126startAgent(config_props);127}128129// jcmd ManagementAgent.start_local entry point130// Also called due to command-line via startAgent()131private static synchronized void startLocalManagementAgent() {132Properties agentProps = VMSupport.getAgentProperties();133134// start local connector if not started135if (agentProps.get(LOCAL_CONNECTOR_ADDRESS_PROP) == null) {136JMXConnectorServer cs = ConnectorBootstrap.startLocalConnectorServer();137String address = cs.getAddress().toString();138// Add the local connector address to the agent properties139agentProps.put(LOCAL_CONNECTOR_ADDRESS_PROP, address);140141try {142// export the address to the instrumentation buffer143ConnectorAddressLink.export(address);144} catch (Exception x) {145// Connector server started but unable to export address146// to instrumentation buffer - non-fatal error.147warning(EXPORT_ADDRESS_FAILED, x.getMessage());148}149}150}151152// jcmd ManagementAgent.start entry point153// This method starts the remote JMX agent and starts neither154// the local JMX agent nor the SNMP agent155// @see #startLocalManagementAgent and also @see #startAgent.156private static synchronized void startRemoteManagementAgent(String args) throws Exception {157if (jmxServer != null) {158throw new RuntimeException(getText(INVALID_STATE, "Agent already started"));159}160161try {162Properties argProps = parseString(args);163Properties configProps = new Properties();164165// Load the management properties from the config file166// if config file is not specified readConfiguration implicitly167// reads <java.home>/lib/management/management.properties168169String fname = System.getProperty(CONFIG_FILE);170readConfiguration(fname, configProps);171172// management properties can be overridden by system properties173// which take precedence174Properties sysProps = System.getProperties();175synchronized (sysProps) {176configProps.putAll(sysProps);177}178179// if user specifies config file into command line for either180// jcmd utilities or attach command it overrides properties set in181// command line at the time of VM start182String fnameUser = argProps.getProperty(CONFIG_FILE);183if (fnameUser != null) {184readConfiguration(fnameUser, configProps);185}186187// arguments specified in command line of jcmd utilities188// override both system properties and one set by config file189// specified in jcmd command line190configProps.putAll(argProps);191192// jcmd doesn't allow to change ThreadContentionMonitoring, but user193// can specify this property inside config file, so enable optional194// monitoring functionality if this property is set195final String enableThreadContentionMonitoring =196configProps.getProperty(ENABLE_THREAD_CONTENTION_MONITORING);197198if (enableThreadContentionMonitoring != null) {199ManagementFactory.getThreadMXBean().200setThreadContentionMonitoringEnabled(true);201}202203String jmxremotePort = configProps.getProperty(JMXREMOTE_PORT);204if (jmxremotePort != null) {205jmxServer = ConnectorBootstrap.206startRemoteConnectorServer(jmxremotePort, configProps);207208startDiscoveryService(configProps);209} else {210throw new AgentConfigurationError(INVALID_JMXREMOTE_PORT, "No port specified");211}212} catch (AgentConfigurationError err) {213error(err);214}215}216217private static synchronized void stopRemoteManagementAgent() throws Exception {218219JdpController.stopDiscoveryService();220221if (jmxServer != null) {222ConnectorBootstrap.unexportRegistry();223224// Attempt to stop already stopped agent225// Don't cause any errors.226jmxServer.stop();227jmxServer = null;228}229}230231private static void startAgent(Properties props) throws Exception {232String snmpPort = props.getProperty(SNMP_PORT);233String jmxremote = props.getProperty(JMXREMOTE);234String jmxremotePort = props.getProperty(JMXREMOTE_PORT);235236// Enable optional monitoring functionality if requested237final String enableThreadContentionMonitoring =238props.getProperty(ENABLE_THREAD_CONTENTION_MONITORING);239if (enableThreadContentionMonitoring != null) {240ManagementFactory.getThreadMXBean().241setThreadContentionMonitoringEnabled(true);242}243244try {245if (snmpPort != null) {246loadSnmpAgent(snmpPort, props);247}248249/*250* If the jmxremote.port property is set then we start the251* RMIConnectorServer for remote M&M.252*253* If the jmxremote or jmxremote.port properties are set then254* we start a RMIConnectorServer for local M&M. The address255* of this "local" server is exported as a counter to the jstat256* instrumentation buffer.257*/258if (jmxremote != null || jmxremotePort != null) {259if (jmxremotePort != null) {260jmxServer = ConnectorBootstrap.261startRemoteConnectorServer(jmxremotePort, props);262startDiscoveryService(props);263}264startLocalManagementAgent();265}266267} catch (AgentConfigurationError e) {268error(e);269} catch (Exception e) {270error(e);271}272}273274private static void startDiscoveryService(Properties props)275throws IOException {276// Start discovery service if requested277String discoveryPort = props.getProperty("com.sun.management.jdp.port");278String discoveryAddress = props.getProperty("com.sun.management.jdp.address");279String discoveryShouldStart = props.getProperty("com.sun.management.jmxremote.autodiscovery");280281// Decide whether we should start autodicovery service.282// To start autodiscovery following conditions should be met:283// autodiscovery==true OR (autodicovery==null AND jdp.port != NULL)284285boolean shouldStart = false;286if (discoveryShouldStart == null){287shouldStart = (discoveryPort != null);288}289else{290try{291shouldStart = Boolean.parseBoolean(discoveryShouldStart);292} catch (NumberFormatException e) {293throw new AgentConfigurationError("Couldn't parse autodiscovery argument");294}295}296297if (shouldStart) {298// port and address are required arguments and have no default values299InetAddress address;300try {301address = (discoveryAddress == null) ?302InetAddress.getByName(JDP_DEFAULT_ADDRESS) : InetAddress.getByName(discoveryAddress);303} catch (UnknownHostException e) {304throw new AgentConfigurationError("Unable to broadcast to requested address", e);305}306307int port = JDP_DEFAULT_PORT;308if (discoveryPort != null) {309try {310port = Integer.parseInt(discoveryPort);311} catch (NumberFormatException e) {312throw new AgentConfigurationError("Couldn't parse JDP port argument");313}314}315316// Rebuilding service URL to broadcast it317String jmxremotePort = props.getProperty(JMXREMOTE_PORT);318String rmiPort = props.getProperty(RMI_PORT);319320JMXServiceURL url = jmxServer.getAddress();321String hostname = url.getHost();322323String jmxUrlStr = (rmiPort != null)324? String.format(325"service:jmx:rmi://%s:%s/jndi/rmi://%s:%s/jmxrmi",326hostname, rmiPort, hostname, jmxremotePort)327: String.format(328"service:jmx:rmi:///jndi/rmi://%s:%s/jmxrmi", hostname, jmxremotePort);329330String instanceName = props.getProperty("com.sun.management.jdp.name");331332try{333JdpController.startDiscoveryService(address, port, instanceName, jmxUrlStr);334}335catch(JdpException e){336throw new AgentConfigurationError("Couldn't start JDP service", e);337}338}339}340341public static Properties loadManagementProperties() {342Properties props = new Properties();343344// Load the management properties from the config file345346String fname = System.getProperty(CONFIG_FILE);347readConfiguration(fname, props);348349// management properties can be overridden by system properties350// which take precedence351Properties sysProps = System.getProperties();352synchronized (sysProps) {353props.putAll(sysProps);354}355356return props;357}358359public static synchronized Properties getManagementProperties() {360if (mgmtProps == null) {361String configFile = System.getProperty(CONFIG_FILE);362String snmpPort = System.getProperty(SNMP_PORT);363String jmxremote = System.getProperty(JMXREMOTE);364String jmxremotePort = System.getProperty(JMXREMOTE_PORT);365366if (configFile == null && snmpPort == null367&& jmxremote == null && jmxremotePort == null) {368// return if out-of-the-management option is not specified369return null;370}371mgmtProps = loadManagementProperties();372}373return mgmtProps;374}375376private static void loadSnmpAgent(String snmpPort, Properties props) {377try {378// invoke the following through reflection:379// AdaptorBootstrap.initialize(snmpPort, props);380final Class<?> adaptorClass =381Class.forName(SNMP_ADAPTOR_BOOTSTRAP_CLASS_NAME, true, null);382final Method initializeMethod =383adaptorClass.getMethod("initialize",384String.class, Properties.class);385initializeMethod.invoke(null, snmpPort, props);386} catch (ClassNotFoundException | NoSuchMethodException | IllegalAccessException x) {387// snmp runtime doesn't exist - initialization fails388throw new UnsupportedOperationException("Unsupported management property: " + SNMP_PORT, x);389} catch (InvocationTargetException x) {390final Throwable cause = x.getCause();391if (cause instanceof RuntimeException) {392throw (RuntimeException) cause;393} else if (cause instanceof Error) {394throw (Error) cause;395}396// should not happen...397throw new UnsupportedOperationException("Unsupported management property: " + SNMP_PORT, cause);398}399}400401// read config file and initialize the properties402private static void readConfiguration(String fname, Properties p) {403if (fname == null) {404String home = System.getProperty("java.home");405if (home == null) {406throw new Error("Can't find java.home ??");407}408StringBuffer defaultFileName = new StringBuffer(home);409defaultFileName.append(File.separator).append("lib");410defaultFileName.append(File.separator).append("management");411defaultFileName.append(File.separator).append("management.properties");412// Set file name413fname = defaultFileName.toString();414}415final File configFile = new File(fname);416if (!configFile.exists()) {417error(CONFIG_FILE_NOT_FOUND, fname);418}419420InputStream in = null;421try {422in = new FileInputStream(configFile);423BufferedInputStream bin = new BufferedInputStream(in);424p.load(bin);425} catch (FileNotFoundException e) {426error(CONFIG_FILE_OPEN_FAILED, e.getMessage());427} catch (IOException e) {428error(CONFIG_FILE_OPEN_FAILED, e.getMessage());429} catch (SecurityException e) {430error(CONFIG_FILE_ACCESS_DENIED, fname);431} finally {432if (in != null) {433try {434in.close();435} catch (IOException e) {436error(CONFIG_FILE_CLOSE_FAILED, fname);437}438}439}440}441442public static void startAgent() throws Exception {443String prop = System.getProperty("com.sun.management.agent.class");444445// -Dcom.sun.management.agent.class not set so read management446// properties and start agent447if (prop == null) {448// initialize management properties449Properties props = getManagementProperties();450if (props != null) {451startAgent(props);452}453return;454}455456// -Dcom.sun.management.agent.class=<agent classname>:<agent args>457String[] values = prop.split(":");458if (values.length < 1 || values.length > 2) {459error(AGENT_CLASS_INVALID, "\"" + prop + "\"");460}461String cname = values[0];462String args = (values.length == 2 ? values[1] : null);463464if (cname == null || cname.length() == 0) {465error(AGENT_CLASS_INVALID, "\"" + prop + "\"");466}467468if (cname != null) {469try {470// Instantiate the named class.471// invoke the premain(String args) method472Class<?> clz = ClassLoader.getSystemClassLoader().loadClass(cname);473Method premain = clz.getMethod("premain",474new Class<?>[]{String.class});475premain.invoke(null, /* static */476new Object[]{args});477} catch (ClassNotFoundException ex) {478error(AGENT_CLASS_NOT_FOUND, "\"" + cname + "\"");479} catch (NoSuchMethodException ex) {480error(AGENT_CLASS_PREMAIN_NOT_FOUND, "\"" + cname + "\"");481} catch (SecurityException ex) {482error(AGENT_CLASS_ACCESS_DENIED);483} catch (Exception ex) {484String msg = (ex.getCause() == null485? ex.getMessage()486: ex.getCause().getMessage());487error(AGENT_CLASS_FAILED, msg);488}489}490}491492public static void error(String key) {493String keyText = getText(key);494System.err.print(getText("agent.err.error") + ": " + keyText);495throw new RuntimeException(keyText);496}497498public static void error(String key, String message) {499String keyText = getText(key);500System.err.print(getText("agent.err.error") + ": " + keyText);501System.err.println(": " + message);502throw new RuntimeException(keyText + ": " + message);503}504505public static void error(Exception e) {506e.printStackTrace();507System.err.println(getText(AGENT_EXCEPTION) + ": " + e.toString());508throw new RuntimeException(e);509}510511public static void error(AgentConfigurationError e) {512String keyText = getText(e.getError());513String[] params = e.getParams();514515System.err.print(getText("agent.err.error") + ": " + keyText);516517if (params != null && params.length != 0) {518StringBuffer message = new StringBuffer(params[0]);519for (int i = 1; i < params.length; i++) {520message.append(" " + params[i]);521}522System.err.println(": " + message);523}524e.printStackTrace();525throw new RuntimeException(e);526}527528public static void warning(String key, String message) {529System.err.print(getText("agent.err.warning") + ": " + getText(key));530System.err.println(": " + message);531}532533private static void initResource() {534try {535messageRB =536ResourceBundle.getBundle("sun.management.resources.agent");537} catch (MissingResourceException e) {538throw new Error("Fatal: Resource for management agent is missing");539}540}541542public static String getText(String key) {543if (messageRB == null) {544initResource();545}546try {547return messageRB.getString(key);548} catch (MissingResourceException e) {549return "Missing management agent resource bundle: key = \"" + key + "\"";550}551}552553public static String getText(String key, String... args) {554if (messageRB == null) {555initResource();556}557String format = messageRB.getString(key);558if (format == null) {559format = "missing resource key: key = \"" + key + "\", "560+ "arguments = \"{0}\", \"{1}\", \"{2}\"";561}562return MessageFormat.format(format, (Object[]) args);563}564}565566567