Search in sources :

Example 51 with JMXServiceURL

use of javax.management.remote.JMXServiceURL in project felix by apache.

the class RmiConnectorActivator method startRmiConnector.

private void startRmiConnector() throws Exception {
    String profile = bc.getProperty(BundleCache.CACHE_PROFILE_PROP);
    if (profile == null) {
        profile = System.getProperty(BundleCache.CACHE_PROFILE_PROP);
    }
    String rmiPort = bc.getProperty("mosgi.jmxconsole.rmiport." + profile);
    if (rmiPort == null) {
        rmiPort = "1099";
    }
    String url = "service:jmx:rmi:///jndi/rmi://" + InetAddress.getLocalHost().getHostAddress() + ":" + rmiPort + "/" + profile;
    RmiConnectorActivator.log(LogService.LOG_INFO, "jmx connexion string ==> " + url, null);
    RmiConnectorActivator.log(LogService.LOG_INFO, "Starting JMX Rmi Connector " + version, null);
    this.mbs = (MBeanServer) bc.getService(this.mBeanServerSR);
    this.nsi = (NamingServiceIfc) bc.getService(this.namingServiceIfcSR);
    JMXServiceURL address = new JMXServiceURL(url);
    /*
    Map environment = new HashMap();
    environment.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.rmi.registry.RegistryContextFactory");
    environment.put(Context.PROVIDER_URL, "rmi://localhost:"+rmiPort);
    environment.put(JMXConnectorServerFactory.PROTOCOL_PROVIDER_CLASS_LOADER,this.getClass().getClassLoader());
  */
    /* Loggin 
Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader());
java.util.logging.ConsoleHandler ch=new java.util.logging.ConsoleHandler();
ch.setLevel(java.util.logging.Level.FINEST);
java.util.logging.Logger.getLogger("javax.management.remote.misc").setLevel(java.util.logging.Level.FINEST);
java.util.logging.Logger.getLogger("javax.management.remote.rmi").setLevel(java.util.logging.Level.FINEST);
java.util.logging.Logger.getLogger("javax.management.remote.rmi").addHandler(ch);
java.util.logging.Logger.getLogger("javax.management.remote.misc").addHandler(ch);
*/
    /*
		java.util.Map env = new java.util.HashMap();
		env.put(JMXConnectorServerFactory.PROTOCOL_PROVIDER_CLASS_LOADER, this.getClass().getClassLoader());
		env.put("jmx.remote.protocol.provider.pkgs", "mx4j.remote.provider");
		*/
    this.connectorServer = JMXConnectorServerFactory.newJMXConnectorServer(address, null, this.mbs);
    RmiConnectorActivator.log(LogService.LOG_DEBUG, "===> " + this.connectorServer, null);
    RmiConnectorActivator.log(LogService.LOG_DEBUG, "======> " + this.connectorServer.getMBeanServer(), null);
    // this.mbs.registerMBean(this.connectorServer, this.connectorServerName);
    // this.connectorServer = JMXConnectorServerFactory.newJMXConnectorServer(address, null, java.lang.management.ManagementFactory.getPlatformMBeanServer());
    this.connectorServer.start();
    RmiConnectorActivator.log(LogService.LOG_INFO, "JMX Rmi Connector started " + version, null);
}
Also used : JMXServiceURL(javax.management.remote.JMXServiceURL)

Example 52 with JMXServiceURL

use of javax.management.remote.JMXServiceURL in project airlift by airlift.

the class TestJmxAgent method testJava8Agent.

@Test
public void testJava8Agent() throws Exception {
    HostAndPort address = JmxAgent8.getRunningAgentAddress(null, null);
    JmxAgent agent = new JmxAgent8(new JmxConfig());
    if (address == null) {
        // if agent wasn't running, it must have been started by the instantiation of JmxAgent
        address = JmxAgent8.getRunningAgentAddress(null, null);
        assertNotNull(address);
    }
    JMXServiceURL url = agent.getUrl();
    assertEquals(url.toString(), format("service:jmx:rmi:///jndi/rmi://%s:%s/jmxrmi", address.getHost(), address.getPort()));
    JMXConnector connector = JMXConnectorFactory.connect(url);
    connector.connect();
}
Also used : JMXServiceURL(javax.management.remote.JMXServiceURL) HostAndPort(com.google.common.net.HostAndPort) JMXConnector(javax.management.remote.JMXConnector) Test(org.testng.annotations.Test)

Example 53 with JMXServiceURL

use of javax.management.remote.JMXServiceURL in project jdk8u_jdk by JetBrains.

the class ScanDirClient method main.

/**
     * Connects to a secured JMX <i>scandir</i> application.
     * @param args The {@code main} method takes two parameters:
     *        <ul>
     *        <li>args[0] must be the server's host</li>
     *        <li>args[1] must be the rmi port number at which the
     *        JMX <i>scandir</i> daemon is listening for connections
     *        - that is, the port number of its JMX RMI Connector which
     *        was configured in {@code management.properties}
     *        </li>
     *        <ul>
     **/
public static void main(String[] args) {
    try {
        //
        if (args == null || args.length != 2) {
            System.err.println("Bad number of arguments: usage is: \n\t" + USAGE);
            System.exit(1);
        }
        try {
            InetAddress.getByName(args[0]);
        } catch (UnknownHostException x) {
            System.err.println("No such host: " + args[0] + "\n usage is: \n\t" + USAGE);
            System.exit(2);
        } catch (Exception x) {
            System.err.println("Bad address: " + args[0] + "\n usage is: \n\t" + USAGE);
            System.exit(2);
        }
        try {
            if (Integer.parseInt(args[1]) <= 0) {
                System.err.println("Bad port value: " + args[1] + "\n usage is: \n\t" + USAGE);
                System.exit(2);
            }
        } catch (Exception x) {
            System.err.println("Bad argument: " + args[1] + "\n usage is: \n\t" + USAGE);
            System.exit(2);
        }
        // Create an environment map to hold connection properties
        // like credentials etc... We will later pass this map
        // to the JMX Connector.
        //
        System.out.println("\nInitialize the environment map");
        final Map<String, Object> env = new HashMap<String, Object>();
        // Provide the credentials required by the server
        // to successfully perform user authentication
        //
        final String[] credentials = new String[] { "guest", "guestpasswd" };
        env.put("jmx.remote.credentials", credentials);
        // Provide the SSL/TLS-based RMI Client Socket Factory required
        // by the JNDI/RMI Registry Service Provider to communicate with
        // the SSL/TLS-protected RMI Registry
        //
        env.put("com.sun.jndi.rmi.factory.socket", new SslRMIClientSocketFactory());
        // Create the RMI connector client and
        // connect it to the RMI connector server
        // args[0] is the server's host - localhost
        // args[1] is the secure server port - 4545
        //
        System.out.println("\nCreate the RMI connector client and " + "connect it to the RMI connector server");
        final JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://" + args[0] + ":" + args[1] + "/jmxrmi");
        System.out.println("Connecting to: " + url);
        final JMXConnector jmxc = JMXConnectorFactory.connect(url, env);
        // Get an MBeanServerConnection
        //
        System.out.println("\nGet the MBeanServerConnection");
        final MBeanServerConnection mbsc = jmxc.getMBeanServerConnection();
        // Create a proxy for the ScanManager MXBean
        //
        final ScanManagerMXBean proxy = ScanManager.newSingletonProxy(mbsc);
        // Get the ScanDirConfig MXBean from the scan manager
        //
        System.out.println("\nGet ScanDirConfigMXBean from ScanManagerMXBean");
        final ScanDirConfigMXBean configMBean = proxy.getConfigurationMBean();
        // Print the scan dir configuration
        //
        System.out.println("\nGet 'Configuration' attribute on ScanDirConfigMXBean");
        System.out.println("\nConfiguration:\n" + configMBean.getConfiguration());
        // Try to invoke the "close" method on the ScanManager MXBean.
        //
        // Should get a SecurityException as the user "guest" doesn't
        // have readwrite access.
        //
        System.out.println("\nInvoke 'close' on ScanManagerMXBean");
        try {
            proxy.close();
        } catch (SecurityException e) {
            System.out.println("\nGot expected security exception: " + e);
        }
        // Close MBeanServer connection
        //
        System.out.println("\nClose the connection to the server");
        jmxc.close();
        System.out.println("\nBye! Bye!");
    } catch (Exception e) {
        System.out.println("\nGot unexpected exception: " + e);
        e.printStackTrace();
        System.exit(3);
    }
}
Also used : JMXServiceURL(javax.management.remote.JMXServiceURL) UnknownHostException(java.net.UnknownHostException) HashMap(java.util.HashMap) UnknownHostException(java.net.UnknownHostException) SslRMIClientSocketFactory(javax.rmi.ssl.SslRMIClientSocketFactory) JMXConnector(javax.management.remote.JMXConnector) MBeanServerConnection(javax.management.MBeanServerConnection)

Example 54 with JMXServiceURL

use of javax.management.remote.JMXServiceURL in project jdk8u_jdk by JetBrains.

the class ConnectorBootstrap method startLocalConnectorServer.

/*
     * Creates and starts a RMI Connector Server for "local" monitoring
     * and management.
     */
public static JMXConnectorServer startLocalConnectorServer() {
    // Ensure cryptographically strong random number generater used
    // to choose the object number - see java.rmi.server.ObjID
    System.setProperty("java.rmi.server.randomIDs", "true");
    // This RMI server should not keep the VM alive
    Map<String, Object> env = new HashMap<>();
    env.put(RMIExporter.EXPORTER_ATTRIBUTE, new PermanentExporter());
    env.put(EnvHelp.CREDENTIAL_TYPES, new String[] { String[].class.getName(), String.class.getName() });
    // The local connector server need only be available via the
    // loopback connection.
    String localhost = "localhost";
    InetAddress lh = null;
    try {
        lh = InetAddress.getByName(localhost);
        localhost = lh.getHostAddress();
    } catch (UnknownHostException x) {
    }
    // a loopback address.
    if (lh == null || !lh.isLoopbackAddress()) {
        localhost = "127.0.0.1";
    }
    MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
    try {
        JMXServiceURL url = new JMXServiceURL("rmi", localhost, 0);
        // Do we accept connections from local interfaces only?
        Properties props = Agent.getManagementProperties();
        if (props == null) {
            props = new Properties();
        }
        String useLocalOnlyStr = props.getProperty(PropertyNames.USE_LOCAL_ONLY, DefaultValues.USE_LOCAL_ONLY);
        boolean useLocalOnly = Boolean.valueOf(useLocalOnlyStr).booleanValue();
        if (useLocalOnly) {
            env.put(RMIConnectorServer.RMI_SERVER_SOCKET_FACTORY_ATTRIBUTE, new LocalRMIServerSocketFactory());
        }
        JMXConnectorServer server = JMXConnectorServerFactory.newJMXConnectorServer(url, env, mbs);
        server.start();
        return server;
    } catch (Exception e) {
        throw new AgentConfigurationError(AGENT_EXCEPTION, e, e.toString());
    }
}
Also used : JMXServiceURL(javax.management.remote.JMXServiceURL) UnknownHostException(java.net.UnknownHostException) HashMap(java.util.HashMap) Properties(java.util.Properties) RemoteException(java.rmi.RemoteException) NoSuchObjectException(java.rmi.NoSuchObjectException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException) JMXConnectorServer(javax.management.remote.JMXConnectorServer) AgentConfigurationError(sun.management.AgentConfigurationError) UnicastRemoteObject(java.rmi.server.UnicastRemoteObject) RemoteObject(java.rmi.server.RemoteObject) InetAddress(java.net.InetAddress) MBeanServer(javax.management.MBeanServer)

Example 55 with JMXServiceURL

use of javax.management.remote.JMXServiceURL in project bnd by bndtools.

the class JMXBundleDeployer method getLocalConnectorAddress.

/**
	 * 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;
}
Also used : JMXServiceURL(javax.management.remote.JMXServiceURL) Method(java.lang.reflect.Method) Properties(java.util.Properties) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) MalformedObjectNameException(javax.management.MalformedObjectNameException) ObjectName(javax.management.ObjectName) Field(java.lang.reflect.Field) JMXConnector(javax.management.remote.JMXConnector) URLClassLoader(java.net.URLClassLoader) ArrayList(java.util.ArrayList) List(java.util.List) File(java.io.File) Vector(java.util.Vector) MBeanServerConnection(javax.management.MBeanServerConnection)

Aggregations

JMXServiceURL (javax.management.remote.JMXServiceURL)280 JMXConnector (javax.management.remote.JMXConnector)150 MBeanServerConnection (javax.management.MBeanServerConnection)107 ObjectName (javax.management.ObjectName)90 IOException (java.io.IOException)78 HashMap (java.util.HashMap)75 MBeanServer (javax.management.MBeanServer)71 JMXConnectorServer (javax.management.remote.JMXConnectorServer)64 MalformedURLException (java.net.MalformedURLException)45 RemoteException (java.rmi.RemoteException)22 Test (org.junit.Test)22 Map (java.util.Map)16 UnknownHostException (java.net.UnknownHostException)14 Properties (java.util.Properties)14 Notification (javax.management.Notification)14 NotificationListener (javax.management.NotificationListener)14 MalformedObjectNameException (javax.management.MalformedObjectNameException)13 LocateRegistry (java.rmi.registry.LocateRegistry)12 Registry (java.rmi.registry.Registry)12 ArrayList (java.util.ArrayList)11