@Test public void changeExportedFolderRemotely() throws MalformedURLException, IOException, MalformedObjectNameException, IntrospectionException { // connect through RMI and get the proxy JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:9999/server"); JMXConnector jmxc = JMXConnectorFactory.connect(url, null); MBeanServerConnection mbsc = jmxc.getMBeanServerConnection(); ObjectName agentName = ObjectName.getInstance("myDomain:name=Alice,type=tutorial"); /*DynamicMBean proxy = JMX.newMBeanProxy(mbs, agentName, DynamicMBean.class); */ DynamicProxy proxy = new DynamicProxy(agentName, mbsc); // convert the proxy to standard Folder Folder jmxFolder = new DynamicMBeanToFolderAdapter(proxy); //jmxFolder.getProperty("name").setValue("Cecil Corn"); String newName = "Cecil Corn"; jmxFolder.getFolder("knows").getProperty("name").setValue(newName); //mbsc.setAttribute(agentName, new Attribute("name", "Bob")); // waitForEnterPressed(); assertTrue(person.knows.name.equals(newName)); System.out.println("---/// TEST OK ///---"); }
public AgentJMXProxy(String agentJmxAddress) { // connect through RMI and get the proxy String[] strs = agentJmxAddress.split("\\" + AgentJMXComponents.JMX_SERVER_AGENT_NAME_DELIM); String jmxService = strs[0]; String objectName = strs[1]; try { JMXServiceURL url = new JMXServiceURL(jmxService); JMXConnector jmxc = JMXConnectorFactory.connect(url, null); mbsc = jmxc.getMBeanServerConnection(); agentName = ObjectName.getInstance(objectName); proxy = new DynamicProxy(agentName, mbsc); agentFlag = new FlagJMXProxy<IAgentState>(agentName, mbsc, AgentMBeanAdapter.AGENT_STATE_FLAG_NAME); agentId = new AgentIdJMXProxy(this); } catch (Exception e) { throw new PogamutJMXException("Can't create AgentJMXProxy.", e, this); } }
private static MBeanServerConnection initMBeanServerConnection() { try { String ip = Config.getProperty("jmx_ip"); String port = Config.getProperty("jmx_port"); String jmxURL = "service:jmx:rmi:///jndi/rmi://" + ip + ":" + port + "/jmxrmi"; JMXServiceURL serviceURL = new JMXServiceURL(jmxURL); Map map = new HashMap(); String[] credentials = Config.getProperty("credentials").split(","); map.put("jmx.remote.credentials", credentials); JMXConnector connector = JMXConnectorFactory.connect(serviceURL, map); mbsconnector = connector.getMBeanServerConnection(); } catch (IOException e) { logger.error("get connector error" + e); } return mbsconnector; }
/** * create a new JMX Connection with auth when username and password is set. */ public static MBeanServerConnection createJMXConnection(String url, String host, String port, String username, String password) throws MalformedURLException, IOException { String urlForJMX; if (url != null) urlForJMX = url; else urlForJMX = JMX_SERVICE_PREFIX + host + ":" + port + JMX_SERVICE_SUFFIX; Map<String, String[]> environment = null; if (username != null && password != null) { String[] credentials = new String[2]; credentials[0] = username; credentials[1] = password; environment = new HashMap<String, String[]>(); environment.put(JMXConnector.CREDENTIALS, credentials); } return JMXConnectorFactory.connect(new JMXServiceURL(urlForJMX), environment).getMBeanServerConnection(); }
MBeanWrapper( int jvmPort ) throws MonitorConfigurationException { this.jvmPort = jvmPort; try { JMXConnector connector = JMXConnectorFactory.newJMXConnector(new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:" + this.jvmPort + "/jmxrmi"), null); connector.connect(); this.connection = connector.getMBeanServerConnection(); } catch (Exception e) { final String msg = "Error initializing the JMV monitor. Unable to connect to JVM at port " + this.jvmPort; log.error(msg, e); throw new MonitorConfigurationException(msg, e); } }
/** * Connects to the remote {@code MBeanServer} using the configured {@code JMXServiceURL}: * to the specified JMX service, or to a local MBeanServer if no service URL specified. * @param serviceUrl the JMX service URL to connect to (may be {@code null}) * @param environment the JMX environment for the connector (may be {@code null}) * @param agentId the local JMX MBeanServer's agent id (may be {@code null}) */ public MBeanServerConnection connect(JMXServiceURL serviceUrl, Map<String, ?> environment, String agentId) throws MBeanServerNotFoundException { if (serviceUrl != null) { if (logger.isDebugEnabled()) { logger.debug("Connecting to remote MBeanServer at URL [" + serviceUrl + "]"); } try { this.connector = JMXConnectorFactory.connect(serviceUrl, environment); return this.connector.getMBeanServerConnection(); } catch (IOException ex) { throw new MBeanServerNotFoundException("Could not connect to remote MBeanServer [" + serviceUrl + "]", ex); } } else { logger.debug("Attempting to locate local MBeanServer"); return JmxUtils.locateMBeanServer(agentId); } }
@Test public void test_simple() { MBeanServer mBeanServer = exporter.getServer(); try { ObjectName objectName = new ObjectName("bean:name=otterControllor"); MBeanInfo nodeInfo = mBeanServer.getMBeanInfo(objectName); System.out.println(nodeInfo); Object result = mBeanServer.getAttribute(objectName, "HeapMemoryUsage"); System.out.println(result); JMXServiceURL address = new JMXServiceURL("service:jmx:rmi://127.0.0.1/jndi/rmi://127.0.0.1:1099/mbean"); Map environment = null; JMXConnector cntor = JMXConnectorFactory.connect(address, environment); MBeanServerConnection mbsc = cntor.getMBeanServerConnection(); String domain = mbsc.getDefaultDomain(); System.out.println(domain); result = mbsc.getAttribute(objectName, "HeapMemoryUsage"); System.out.println(result); } catch (Exception e) { want.fail(e.getMessage()); } }
private static void connect(String pid, String address) throws Exception { if (address == null) { throw new RuntimeException("Local connector address for " + pid + " is null"); } System.out.println("Connect to process " + pid + " via: " + address); JMXServiceURL url = new JMXServiceURL(address); JMXConnector c = JMXConnectorFactory.connect(url); MBeanServerConnection server = c.getMBeanServerConnection(); System.out.println("Connected."); RuntimeMXBean rt = newPlatformMXBeanProxy(server, RUNTIME_MXBEAN_NAME, RuntimeMXBean.class); System.out.println(rt.getName()); // close the connection c.close(); }
private static void tryConnect(int port, boolean shouldSucceed) throws Exception { String jmxUrlStr = String.format( "service:jmx:rmi:///jndi/rmi://localhost:%d/jmxrmi", port); JMXServiceURL url = new JMXServiceURL(jmxUrlStr); HashMap<String, ?> env = new HashMap<>(); boolean succeeded; try { JMXConnector c = JMXConnectorFactory.connect(url, env); c.getMBeanServerConnection(); succeeded = true; } catch(Exception ex) { succeeded = false; } if (succeeded && !shouldSucceed) { throw new Exception("Could connect to agent, but should not have been possible"); } if (!succeeded && shouldSucceed) { throw new Exception("Could not connect to agent"); } }
public static void main(String[] args) throws Exception { MBeanServer mbs = MBeanServerFactory.newMBeanServer(); Sender sender = new Sender(); mbs.registerMBean(sender, testObjectName); JMXServiceURL url = new JMXServiceURL("service:jmx:rmi://"); JMXConnectorServer cs = JMXConnectorServerFactory.newJMXConnectorServer(url, null, mbs); cs.start(); JMXServiceURL addr = cs.getAddress(); JMXConnector cc = JMXConnectorFactory.connect(addr); try { test(mbs, cs, cc); } finally { cc.close(); cs.stop(); } }
private static void dotest(JMXServiceURL url, MBeanServer mbs) throws Exception { JMXConnectorServer server = null; JMXConnector client = null; server = JMXConnectorServerFactory.newJMXConnectorServer(url, null, mbs); server.start(); JMXServiceURL outputAddr = server.getAddress(); System.out.println("Server started ["+ outputAddr+ "]"); client = JMXConnectorFactory.newJMXConnector(outputAddr, null); client.connect(); System.out.println("Client connected"); MBeanServerConnection connection = client.getMBeanServerConnection(); System.out.println(connection.getDefaultDomain()); }
@Override public int start() { try { this.mbscConnector = JMXConnectorFactory.connect(this.JMXConnectionURL); this.mbsc = mbscConnector.getMBeanServerConnection(); return 1; } catch (Exception e) { log.err(this, "Worker[" + this.cName + "] Connect to JMXURL[" + this.JMXConnectionURL.toString() + "] FAIL:", e); return -1; } }
public static void main(String[] args) throws Exception { if (Platform.isDebugBuild()) { System.out.println("Running on a debug build. Performance test not applicable. Skipping."); return; } MBeanServer mbs = MBeanServerFactory.newMBeanServer(); Sender sender = new Sender(); mbs.registerMBean(sender, testObjectName); JMXServiceURL url = new JMXServiceURL("service:jmx:rmi://"); JMXConnectorServer cs = JMXConnectorServerFactory.newJMXConnectorServer(url, null, mbs); cs.start(); JMXServiceURL addr = cs.getAddress(); JMXConnector cc = JMXConnectorFactory.connect(addr); try { test(mbs, cs, cc); } finally { cc.close(); cs.stop(); } }
/** * Instantiates a new JMXExecutor targeting the VM indicated by the given host/port combination or a full JMX * Service URL * * @param target a host/port combination on the format "host:port" or a full JMX Service URL of the target VM */ public JMXExecutor(String target) { String urlStr; if (target.matches("^\\w[\\w\\-]*(\\.[\\w\\-]+)*:\\d+$")) { /* Matches "hostname:port" */ urlStr = String.format("service:jmx:rmi:///jndi/rmi://%s/jmxrmi", target); } else if (target.startsWith("service:")) { urlStr = target; } else { throw new IllegalArgumentException("Could not recognize target string: " + target); } try { JMXServiceURL url = new JMXServiceURL(urlStr); JMXConnector c = JMXConnectorFactory.connect(url, new HashMap<>()); mbs = c.getMBeanServerConnection(); } catch (IOException e) { throw new CommandExecutorException("Could not initiate connection to target: " + target, e); } }
private static void fetchKafkaMetrics(String host, String jmxPort, String metric) throws Exception { Map<String, String[]> env = new HashMap<>(); JMXServiceURL address = new JMXServiceURL( "service:jmx:rmi://" + host + "/jndi/rmi://" + host + ":" + jmxPort + "/jmxrmi"); JMXConnector connector = JMXConnectorFactory.connect(address, env); MBeanServerConnection mbs = connector.getMBeanServerConnection(); ObjectName name = ObjectName.getInstance(metric); MBeanInfo beanInfo = mbs.getMBeanInfo(name); for (MBeanAttributeInfo attributeInfo : beanInfo.getAttributes()) { Object obj = mbs.getAttribute(name, attributeInfo.getName()); System.out.println(" attributeName = " + attributeInfo.getName() + " " + obj.toString()); } }
/** * Creates the jmxConnector with passed parameters. * @param host host address * @param port port of the host * @param user username (null possible) * @param pass password (null possible) * @return connected JMXConnector * @throws IOException IOException */ public static JMXConnector buildJmxMPConnector(final String host, final int port, final String user, final String pass) throws IOException { try { final JMXServiceURL serviceURL = new JMXServiceURL("jmxmp", host,port); if("null".equals(user) || "null".equals(pass) || user == null || pass == null){ return JMXConnectorFactory.connect(serviceURL); } final Map<String, Object> environment = new HashMap<>(); environment.put("jmx.remote.credentials", new String[]{user,pass}); environment.put(Context.SECURITY_PRINCIPAL, user); environment.put(Context.SECURITY_CREDENTIALS, pass); return JMXConnectorFactory.connect(serviceURL,environment); } catch (MalformedURLException e) { log.log(Level.WARNING, "Malformed ServiceURL in buildJmxConnector"); return null; } }
private <T> T execute(JmxTemplate<T> template) throws OpsMetricsException { LOG.debug("Connecting to {}:{}", host, port); JMXConnector connector = null; try { JMXServiceURL address = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://" + host + ":" + port + "/jmxrmi"); HashMap<String, String[]> env = getCredentials(); connector = JMXConnectorFactory.connect(address, env); MBeanServerConnection mbs = connector.getMBeanServerConnection(); return template.execute(mbs); } catch (Exception e) { LOG.error("Unabled to execute JMX command", e); throw new OpsMetricsException(e); } finally { close(connector); } }
private void connect() throws IOException, MalformedObjectNameException, InstanceNotFoundException { try { this.connector = JMXConnectorFactory.connect(serviceURL, jmxEnv); mbsc = connector.getMBeanServerConnection(); ObjectName name = new ObjectName(LocalOnlineApplicationMBean.BEAN_NAME); application = MBeanServerInvocationHandler.newProxyInstance(mbsc, name, LocalOnlineApplicationMBean.class, false); mbsc.addNotificationListener(name, this, null, null); connected = true; for (OnlineApplicationListener l : listeners) { l.onConnection(); } } catch (Exception ex) { LOGGER.error("Exception connecting JMX to " + serviceURL + ": " + ex.getMessage(), ex); } }
/** * JMX Connector helper class * * @param host host name * @param port port number * @param service service name * @return the mbean connection */ protected static MBeanServerConnection getMBeanServerConnection( String host, String port, String service ) { try { if ( ( host == null || port == null ) && service == null ) { System.out.println( "Using local JMV connection" ); return ManagementFactory.getPlatformMBeanServer(); } if ( service == null ) { service = "service:jmx:rmi:///jndi/rmi://" + host + ":" + port + "/jmxrmi"; } System.out.println( "Connecting to : " + service ); JMXServiceURL url = new JMXServiceURL( service ); JMXConnector jmx = JMXConnectorFactory.connect( url ); return jmx.getMBeanServerConnection(); } catch ( Throwable e ) { System.out.println( "Unable to connect to JMX Server: " + service + " : " + e.getMessage() ); } System.out.println( "Reverting to local jvm connection" ); return ManagementFactory.getPlatformMBeanServer(); }
@Override public JmxConnection connect() { try { com.sun.tools.attach.VirtualMachine vm = com.sun.tools.attach.VirtualMachine.attach( descriptor ); Stopwatch sw = Stopwatch.createStarted(); // TODO - timeout // https://community.oracle.com/blogs/emcmanus/2007/05/23/making-jmx-connection-timeout JMXServiceURL jmxUrl = JmxUtils.determineServiceUrl( vm ); logger.info( "Connecting to JVM {} via {}", descriptor, jmxUrl ); JMXConnector connector = JMXConnectorFactory.connect( jmxUrl ); final MBeanServerConnection mbeanServerConnection = connector.getMBeanServerConnection(); sw.stop(); logger.info( "Connected to '{}' in {}ms", descriptor, sw.elapsed( TimeUnit.MILLISECONDS ) ); return new JmxConnection( connector, mbeanServerConnection, createConnectionMetaData( vm ) ); } catch( Exception e ) { throw Throwables.propagate( e ); } }
@Override public JmxConnection connect() { try { Stopwatch sw = Stopwatch.createStarted(); // TODO - timeout // https://community.oracle.com/blogs/emcmanus/2007/05/23/making-jmx-connection-timeout JMXServiceURL jmxUrl = new JMXServiceURL( String.format( "service:jmx:rmi:///jndi/rmi://:%d/jmxrmi", jmxPort ) ); logger.info( "Connecting to JVM via {}", jmxUrl ); JMXConnector connector = JMXConnectorFactory.connect( jmxUrl ); final MBeanServerConnection mbeanServerConnection = connector.getMBeanServerConnection(); sw.stop(); logger.info( "Connected to '{}' in {}ms", jmxUrl, sw.elapsed( TimeUnit.MILLISECONDS ) ); return new JmxConnection( connector, mbeanServerConnection, createConnectionMetaData( jmxPort ) ); } catch( Exception e ) { throw Throwables.propagate( e ); } }
private void connect() throws IOException { System.out.println( "JMXConnectorThread: Attempting JMX connection on: " + addr + " on port " + jmxPort); JMXServiceURL url; try { url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://" + addr + ":" + jmxPort + "/jmxrmi"); } catch (MalformedURLException e) { throw new RuntimeException("Test failed.", e); } Map<String, Object> env = new HashMap<>(); if (useSSL) { SslRMIClientSocketFactory csf = new SslRMIClientSocketFactory(); env.put("com.sun.jndi.rmi.factory.socket", csf); env.put(RMIConnectorServer.RMI_CLIENT_SOCKET_FACTORY_ATTRIBUTE, csf); } // connect and immediately close JMXConnector c = JMXConnectorFactory.connect(url, env); c.close(); System.out.println("JMXConnectorThread: connection to JMX worked"); jmxConnectWorked = true; checkRmiSocket(); latch.countDown(); // signal we are done. }
/** * {@inheritDoc} * @see javax.management.remote.JMXConnectorProvider#newJMXConnector(javax.management.remote.JMXServiceURL, java.util.Map) */ @Override public JMXConnector newJMXConnector(final JMXServiceURL serviceURL, final Map<String, ?> env) throws IOException { if (!serviceURL.getProtocol().equals(PROTOCOL_NAME)) { throw new MalformedURLException("Protocol not [" + PROTOCOL_NAME + "]: " + serviceURL.getProtocol()); } final Map<String, ?> environment = env==null ? new HashMap<String, Object>() : env; final String remoteHost = serviceURL.getHost(); final int remotePort = serviceURL.getPort(); final int localPort = SSHTunnelManager.getInstance().getPortForward(remoteHost, remotePort); final String format = environment.containsKey(DELEGATE_PROTOCOL_FORMAT_KEY) ? environment.get(DELEGATE_PROTOCOL_FORMAT_KEY).toString() : DEFAULT_DELEGATE_PROTOCOL_FORMAT; final JMXServiceURL tunneledURL = JMXHelper.serviceUrl(format, "localhost", localPort); final JMXConnector connector = JMXConnectorFactory.newJMXConnector(tunneledURL, environment); final UpdateableJMXConnector ujmx = new UpdateableJMXConnector(connector, serviceURL, environment); connector.addConnectionNotificationListener(this, this, ujmx); return ujmx; }
private MBeanInfo testMBeanForDatasource() throws Exception { Map<String, String[]> env = new HashMap<>(); String[] credentials = { "admin", "admin" }; env.put(JMXConnector.CREDENTIALS, credentials); try { String url = "service:jmx:rmi://localhost:12311/jndi/rmi://localhost:11199/jmxrmi"; JMXServiceURL jmxUrl = new JMXServiceURL(url); JMXConnector jmxConnector = JMXConnectorFactory.connect(jmxUrl, env); MBeanServerConnection mBeanServer = jmxConnector.getMBeanServerConnection(); ObjectName mbeanObject = new ObjectName(dataSourceName + ",-1234:type=DataSource"); MBeanInfo mBeanInfo = mBeanServer.getMBeanInfo(mbeanObject); return mBeanInfo; } catch (MalformedURLException | MalformedObjectNameException | IntrospectionException | ReflectionException e) { throw new AxisFault("Error while connecting to MBean Server " + e.getMessage(), e); } }
/** * @return Connection to a remote MBeanServer * @throws cz.cuni.amis.utils.exception.PogamutException */ public MBeanServerConnection getMBeanServerConnection() throws PogamutException { // connect through RMI and get the proxy try { if (mbsc == null) { JMXServiceURL url = getMBeanServerURL(); JMXConnector jmxc = JMXConnectorFactory.connect(url, null); mbsc = jmxc.getMBeanServerConnection(); } return mbsc; } catch (IOException iOException) { throw new PogamutException("IO exception occured while creating remote MBeanServer connector.", iOException); } }
/** * Creates JMX wrapper for agent on specified adress and adds it to the list * of all connected agents. * @param serviceUrl URL of the JMX service where remote agent resides eg. service:jmx:rmi:///jndi/rmi://localhost:9999/server * @param objectName name of the MBean representing agent eg. myDomain:name=MyAgent1 */ protected void addJMXAgentFromAdress(String serviceUrl, ObjectName objectName) throws IOException { JMXServiceURL url = new JMXServiceURL(serviceUrl); JMXConnector jmxc = JMXConnectorFactory.connect(url, null); MBeanServerConnection mbsc = jmxc.getMBeanServerConnection(); IAgent agent = JMX.newMXBeanProxy(mbsc, objectName, IAgent.class); agents.add(agent); }