예제 #1
0
  protected void createJmxConnector(String host) throws IOException {
    ObjectHelper.notEmpty(serviceUrlPath, "serviceUrlPath");
    ObjectHelper.notNull(registryPort, "registryPort");

    try {
      registry = LocateRegistry.createRegistry(registryPort);
      LOG.debug("Created JMXConnector RMI registry on port {}", registryPort);
    } catch (RemoteException ex) {
      // The registry may had been created, we could get the registry instead
    }

    // must start with leading slash
    String path = serviceUrlPath.startsWith("/") ? serviceUrlPath : "/" + serviceUrlPath;
    // Create an RMI connector and start it
    final JMXServiceURL url;
    if (connectorPort > 0) {
      url =
          new JMXServiceURL(
              "service:jmx:rmi://"
                  + host
                  + ":"
                  + connectorPort
                  + "/jndi/rmi://"
                  + host
                  + ":"
                  + registryPort
                  + path);
    } else {
      url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://" + host + ":" + registryPort + path);
    }

    cs = JMXConnectorServerFactory.newJMXConnectorServer(url, null, server);

    // use async thread for starting the JMX Connector
    // (no need to use a thread pool or enlist in JMX as this thread is terminated when the JMX
    // connector has been started)
    String threadName =
        camelContext.getExecutorServiceManager().resolveThreadName("JMXConnector: " + url);
    Thread thread =
        getCamelContext()
            .getExecutorServiceManager()
            .newThread(
                threadName,
                new Runnable() {
                  public void run() {
                    try {
                      LOG.debug("Staring JMX Connector thread to listen at: {}", url);
                      cs.start();
                      LOG.info("JMX Connector thread started and listening at: {}", url);
                    } catch (IOException ioe) {
                      LOG.warn(
                          "Could not start JMXConnector thread at: "
                              + url
                              + ". JMX Connector not in use.",
                          ioe);
                    }
                  }
                });
    thread.start();
  }
  public void export() {
    try {
      // 创建一个MBeanServer
      MBeanServer mbs = MBeanServerFactory.createMBeanServer(DOMAIN);
      // MBeanServer mbs = MBeanServerFactory.createMBeanServer();//不能在jconsole中使用
      // MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();//可在jconsole中使用
      // 用MBeanServer注册LoginStatsMBean
      // MBeanServer.registerMBean(Object,ObjectName)方法使用的参数有两个:一个是MBean实现的一个实例;另一个是类型ObjectName的一个对象-它用于唯一地标识该MBean
      mbs.registerMBean(new Status(), new ObjectName(MBeanName));

      // 存取该JMX服务的URL:
      JMXServiceURL url =
          new JMXServiceURL("rmi", HOST, JMX_PORT, "/jndi/rmi://" + HOST + ":" + 1099 + "/app");
      // start()和stop()来启动和停止 JMXConnectorServer
      JMXConnectorServer jmxServer =
          JMXConnectorServerFactory.newJMXConnectorServer(url, null, mbs);
      serviceUrl = url.toString();
      // 在RMI上注册
      LocateRegistry.createRegistry(JMX_PORT);
      jmxServer.start();

      // 创建适配器,用于能够通过浏览器访问MBean
      //            HtmlAdaptorServer adapter = new HtmlAdaptorServer();
      //            adapter.setPort(9797);
      //            mbs.registerMBean(adapter, new ObjectName(
      //                    "MyappMBean:name=htmladapter,port=9797"));
      //            adapter.start();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
예제 #3
0
  private static boolean test(String proto, MBeanServer mbs) throws Exception {
    System.out.println("Testing for proto " + proto);

    JMXConnectorServer cs;
    JMXServiceURL url = new JMXServiceURL(proto, null, 0);
    try {
      cs = JMXConnectorServerFactory.newJMXConnectorServer(url, null, mbs);
    } catch (MalformedURLException e) {
      System.out.println("System does not recognize URL: " + url + "; ignoring");
      return true;
    }
    cs.start();
    JMXServiceURL addr = cs.getAddress();
    JMXServiceURL rmiurl = new JMXServiceURL("rmi", null, 0);
    JMXConnector client = JMXConnectorFactory.connect(addr);
    MBeanServerConnection mbsc = client.getMBeanServerConnection();
    ObjectName on = new ObjectName("x:proto=" + proto + ",ok=yes");
    mbsc.createMBean(
        RMIConnectorServer.class.getName(),
        on,
        mletName,
        new Object[] {rmiurl, null},
        new String[] {JMXServiceURL.class.getName(), Map.class.getName()});
    System.out.println("Successfully deserialized with " + proto);
    mbsc.unregisterMBean(on);

    client.close();
    cs.stop();
    return true;
  }
  public static void main(String[] args) throws Exception {
    System.out.println("---RMIConnectorNullSubjectConnTest starting...");

    JMXConnectorServer connectorServer = null;
    JMXConnector connectorClient = null;

    try {
      MBeanServer mserver = ManagementFactory.getPlatformMBeanServer();
      JMXServiceURL serverURL = new JMXServiceURL("rmi", "localhost", 0);
      connectorServer = JMXConnectorServerFactory.newJMXConnectorServer(serverURL, null, mserver);
      connectorServer.start();

      JMXServiceURL serverAddr = connectorServer.getAddress();
      connectorClient = JMXConnectorFactory.connect(serverAddr, null);
      connectorClient.connect();

      Field nullSubjectConnField = RMIConnector.class.getDeclaredField("nullSubjectConnRef");
      nullSubjectConnField.setAccessible(true);

      WeakReference<MBeanServerConnection> weak =
          (WeakReference<MBeanServerConnection>) nullSubjectConnField.get(connectorClient);

      if (weak != null && weak.get() != null) {
        throw new RuntimeException("nullSubjectConnRef must be null at initial time.");
      }

      MBeanServerConnection conn1 = connectorClient.getMBeanServerConnection(null);
      MBeanServerConnection conn2 = connectorClient.getMBeanServerConnection(null);
      if (conn1 == null) {
        throw new RuntimeException("A connection with null subject should not be null.");
      } else if (conn1 != conn2) {
        throw new RuntimeException("The 2 connections with null subject are not equal.");
      }

      conn1 = null;
      conn2 = null;
      int i = 1;
      do {
        System.gc();
        Thread.sleep(100);
        weak = (WeakReference<MBeanServerConnection>) nullSubjectConnField.get(connectorClient);
      } while ((weak != null && weak.get() != null) && i++ < 60);

      System.out.println("---GC times: " + i);

      if (weak != null && weak.get() != null) {
        throw new RuntimeException("Failed to clean RMIConnector's nullSubjectConn");
      } else {
        System.out.println("---RMIConnectorNullSubjectConnTest: PASSED!");
      }
    } finally {
      try {
        connectorClient.close();
        connectorServer.stop();
      } catch (Exception e) {
      }
    }
  }
예제 #5
0
  @Before
  public void setUp() throws IOException {
    MockLogAppender.setupLogging();

    assertNotNull(m_detector);

    JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:9123/server");

    m_connectorServer = JMXConnectorServerFactory.newJMXConnectorServer(url, null, m_beanServer);
    m_connectorServer.start();
  }
예제 #6
0
  private static void test(String proto) throws Exception {
    System.out.println(">>> Test for protocol " + proto);

    JMXServiceURL u = null;
    JMXConnectorServer server = null;

    HashMap env = new HashMap(2);
    // server will close a client connection after 1 second
    env.put("jmx.remote.x.server.connection.timeout", "1000");

    // disable the client ping
    env.put("jmx.remote.x.client.connection.check.period", "0");

    try {
      u = new JMXServiceURL(proto, null, 0);
      server = JMXConnectorServerFactory.newJMXConnectorServer(u, env, mbs);
    } catch (MalformedURLException e) {
      System.out.println(">>> Skipping unsupported URL " + proto);
    }

    server.start();

    JMXServiceURL addr = server.getAddress();

    long st = 2000;
    MyListener myListener;

    // a cycle to make sure that we test the blocking problem.
    do {
      JMXConnector client = JMXConnectorFactory.connect(addr, env);
      MBeanServerConnection conn = client.getMBeanServerConnection();
      myListener = new MyListener(conn);
      client.addConnectionNotificationListener(myListener, null, null);

      // wait the server to close the client connection
      Thread.sleep(st);

      // makes the listener to do a remote request via the connection
      // which should be closed by the server.
      conn.getDefaultDomain();

      // allow the listner to have time to work
      Thread.sleep(100);

      // get a closed notif, should no block.
      client.close();
      Thread.sleep(100);

      st += 2000;

    } while (!myListener.isDone());

    server.stop();
  }
예제 #7
0
  private JMXConnectorServer createServer(
      String serverName,
      int theRmiRegistryPort,
      int theRmiServerPort,
      HashMap<String, Object> theEnv,
      MBeanServer theMBeanServer) {

    // Create the RMI registry
    try {
      LocateRegistry.createRegistry(theRmiRegistryPort);
    } catch (RemoteException e) {
      log.error(
          sm.getString(
              "jmxRemoteLifecycleListener.createRegistryFailed",
              serverName,
              Integer.toString(theRmiRegistryPort)),
          e);
      return null;
    }

    // Build the connection string with fixed ports
    StringBuffer url = new StringBuffer();
    url.append("service:jmx:rmi://localhost:");
    url.append(theRmiServerPort);
    url.append("/jndi/rmi://localhost:");
    url.append(theRmiRegistryPort);
    url.append("/jmxrmi");
    JMXServiceURL serviceUrl;
    try {
      serviceUrl = new JMXServiceURL(url.toString());
    } catch (MalformedURLException e) {
      log.error(
          sm.getString("jmxRemoteLifecycleListener.invalidURL", serverName, url.toString()), e);
      return null;
    }

    // Start the JMX server with the connection string
    JMXConnectorServer cs = null;
    try {
      cs = JMXConnectorServerFactory.newJMXConnectorServer(serviceUrl, theEnv, theMBeanServer);
      cs.start();
      log.info(
          sm.getString(
              "jmxRemoteLifecycleListener.start",
              Integer.toString(theRmiRegistryPort),
              Integer.toString(theRmiServerPort),
              serverName));
    } catch (IOException e) {
      log.error(sm.getString("jmxRemoteLifecycleListener.createServerFailed", serverName), e);
    }
    return cs;
  }
예제 #8
0
  private void createConnectorServer() throws IOException {
    // first create the registry
    createRegistry();

    // Retrieve the PlatformMBeanServer.
    final MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();

    // Environment map.
    HashMap<String, Object> env = new HashMap<String, Object>();

    final JMXServiceURL url = new JMXServiceURL(getServiceURL());

    // Now create the server from the JMXServiceURL
    cs = JMXConnectorServerFactory.newJMXConnectorServer(url, env, mbs);
  }
  /**
   * Start the connector server. If the <code>threaded</code> flag is set to <code>true</code>, the
   * <code>JMXConnectorServer</code> will be started in a separate thread. If the <code>daemon
   * </code> flag is set to <code>true</code>, that thread will be started as a daemon thread.
   *
   * @throws JMException if a problem occured when registering the connector server with the <code>
   *     MBeanServer</code>
   * @throws IOException if there is a problem starting the connector server
   */
  public void afterPropertiesSet() throws JMException, IOException {
    if (this.server == null) {
      this.server = JmxUtils.locateMBeanServer();
    }

    // Create the JMX service URL.
    JMXServiceURL url = new JMXServiceURL(this.serviceUrl);

    // Create the connector server now.
    this.connectorServer =
        JMXConnectorServerFactory.newJMXConnectorServer(url, this.environment, this.server);

    // Do we want to register the connector with the MBean server?
    if (this.objectName != null) {
      this.server.registerMBean(this.connectorServer, this.objectName);
    }

    try {
      if (this.threaded) {
        // Start the connector server asynchronously (in a separate thread).
        Thread connectorThread =
            new Thread() {
              public void run() {
                try {
                  connectorServer.start();
                } catch (IOException ex) {
                  throw new DelayedConnectorStartException(ex);
                }
              }
            };

        connectorThread.setName("JMX Connector Thread [" + this.serviceUrl + "]");
        connectorThread.setDaemon(this.daemon);
        connectorThread.start();
      } else {
        // Start the connector server in the same thread.
        this.connectorServer.start();
      }

      if (logger.isInfoEnabled()) {
        logger.info("JMX connector server started: " + this.connectorServer);
      }
    } catch (IOException ex) {
      // Unregister the connector server if startup failed.
      unregisterConnectorServer();
      throw ex;
    }
  }
예제 #10
0
  public static void main(String[] args) {
    try {
      // Instantiate the MBean server
      //
      System.out.println("\nCreate the MBean server");
      MBeanServer mbs = MBeanServerFactory.createMBeanServer();

      // Environment map
      //
      System.out.println("\nInitialize the environment map");
      HashMap env = new HashMap();

      // Provide SSL-based RMI socket factories.
      //
      SslRMIClientSocketFactory csf = new SslRMIClientSocketFactory();
      SslRMIServerSocketFactory ssf = new SslRMIServerSocketFactory();
      env.put(RMIConnectorServer.RMI_CLIENT_SOCKET_FACTORY_ATTRIBUTE, csf);
      env.put(RMIConnectorServer.RMI_SERVER_SOCKET_FACTORY_ATTRIBUTE, ssf);

      // Provide the password file used by the connector server to
      // perform user authentication. The password file is a properties
      // based text file specifying username/password pairs. This
      // properties based password authenticator has been implemented
      // using the JMXAuthenticator interface and is passed to the
      // connector through the "jmx.remote.authenticator" property
      // in the map.
      //
      // This property is implementation-dependent and might not be
      // supported by all implementations of the JMX Remote API.
      //
      env.put("jmx.remote.x.password.file", "config" + File.separator + "password.properties");

      // Create an RMI connector server
      //
      System.out.println("\nCreate an RMI connector server");
      JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:9999/server");
      JMXConnectorServer cs = JMXConnectorServerFactory.newJMXConnectorServer(url, env, mbs);

      // Start the RMI connector server
      //
      System.out.println("\nStart the RMI connector server");
      cs.start();
      System.out.println("\nRMI connector server successfully started");
      System.out.println("\nWaiting for incoming connections...");
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
예제 #11
0
  private void addJMXConnectors() {

    // This will make the JobExecutor threads in remote JMX idle timeout after 5s (instead of 5
    // minutes)
    try {
      Class c = Class.forName("com.sun.jmx.remote.opt.util.JobExecutor");
      Method method = c.getMethod("setWaitingTime", Long.TYPE);
      method.setAccessible(true);
      method.invoke(null, 5000L);
    } catch (Exception e) {
      logger.warn("cannot adjust job executor timeout", e);
    }

    JMXServiceURL url = null;
    try {
      // LKC-2990 and LKC-3171: Remove the JMX generic optional logging
      java.util.logging.Logger jmxLogger =
          java.util.logging.Logger.getLogger("javax.management.remote.generic");
      jmxLogger.setLevel(java.util.logging.Level.OFF);
    } catch (Throwable t) {
      logger.warn(
          "Unable to disable default logging in Sun's JMX package; when Terracotta clients go"
              + " up/down you may see stack traces printed to the log");
    }
    try {
      final Map environment = new HashMap();
      environment.put("jmx.remote.x.server.connection.timeout", Long.valueOf(Long.MAX_VALUE));
      ProtocolProvider.addTerracottaJmxProvider(environment);
      environment.put(TunnelingMessageConnectionServer.TUNNELING_HANDLER, tunnelingHandler);
      environment.put(EnvHelp.SERVER_CONNECTION_TIMEOUT, String.valueOf(Long.MAX_VALUE));
      url = new JMXServiceURL("terracotta", "localhost", 0);
      // Normally you should NOT do this in the client, but we have a modified version of
      // jmxremote_optional.jar that
      // uses a daemon thread to wait for connections so we don't hang the client
      connServer = JMXConnectorServerFactory.newJMXConnectorServer(url, environment, mBeanServer);
      connServer.start();
      logger.info("Terracotta JMX connector available at[" + url + "]");
    } catch (Exception e) {
      if (url != null) {
        logger.warn("Unable to start embedded JMX connector for url[" + url + "]", e);
      } else {
        logger.warn(
            "Unable to construct embedded JMX connector URL with params (terracotta, localhost, 0)");
      }
    }
  }
예제 #12
0
  private static void test() {
    try {
      JMXServiceURL u = new JMXServiceURL("rmi", null, 0);
      JMXConnectorServer server;
      JMXServiceURL addr;
      JMXConnector client;
      MBeanServerConnection mserver;

      final ObjectName delegateName = new ObjectName("JMImplementation:type=MBeanServerDelegate");
      final NotificationListener dummyListener =
          new NotificationListener() {
            public void handleNotification(Notification n, Object o) {
              // do nothing
              return;
            }
          };

      server = JMXConnectorServerFactory.newJMXConnectorServer(u, null, mbs);
      server.start();

      addr = server.getAddress();
      client = JMXConnectorFactory.newJMXConnector(addr, null);
      client.connect(null);

      mserver = client.getMBeanServerConnection();
      String s1 = "1";
      String s2 = "2";
      String s3 = "3";

      mserver.addNotificationListener(delegateName, dummyListener, null, s1);
      mserver.addNotificationListener(delegateName, dummyListener, null, s2);
      mserver.addNotificationListener(delegateName, dummyListener, null, s3);

      mserver.removeNotificationListener(delegateName, dummyListener, null, s3);
      mserver.removeNotificationListener(delegateName, dummyListener, null, s2);
      mserver.removeNotificationListener(delegateName, dummyListener, null, s1);
      client.close();

      server.stop();
    } catch (Exception e) {
      System.out.println(e);
      e.printStackTrace();
      System.exit(1);
    }
  }
예제 #13
0
 /**
  * Constructs connector server
  *
  * @param svcUrl the address of the new connector server. The actual address of the new connector
  *     server, as returned by its getAddress method, will not necessarily be exactly the same.
  * @param environment a set of attributes to control the new connector server's behavior. This
  *     parameter can be null. Keys in this map must be Strings. The appropriate type of each
  *     associated value depends on the attribute. The contents of environment are not changed by
  *     this call.
  * @param name object name string to be assigned to connector server bean
  * @throws Exception
  */
 public ConnectorServer(JMXServiceURL svcUrl, Map<String, ?> environment, String name)
     throws Exception {
   String urlPath = svcUrl.getURLPath();
   int idx = urlPath.indexOf("rmi://");
   if (idx > 0) {
     String hostPort = urlPath.substring(idx + 6, urlPath.indexOf('/', idx + 6));
     String regHostPort = startRegistry(hostPort);
     if (regHostPort != null) {
       urlPath = urlPath.replace(hostPort, regHostPort);
       svcUrl =
           new JMXServiceURL(svcUrl.getProtocol(), svcUrl.getHost(), svcUrl.getPort(), urlPath);
     }
   }
   MBeanServer mbeanServer = ManagementFactory.getPlatformMBeanServer();
   _connectorServer =
       JMXConnectorServerFactory.newJMXConnectorServer(svcUrl, environment, mbeanServer);
   mbeanServer.registerMBean(_connectorServer, new ObjectName(name));
 }
예제 #14
0
  /**
   * Creates an RMI Connector Server, starts it, and registers it with the Jini Lookup Service.
   *
   * <p>This method will transfer a fixed set of System Properties to the Map given to the
   * RMIConnectorServer constructor. Some JNDI properties, if defined, are transfered to the Map so
   * that they may be used when LDAP is used as external directory to register the RMI Stub (see
   * {@link javax.management.remote.rmi} Javadoc). Note that even if LDAP is used as external
   * directory the {@link Context#INITIAL_CONTEXT_FACTORY Context.INITIAL_CONTEXT_FACTORY} and
   * {@link Context#PROVIDER_URL Context.PROVIDER_URL} properties usually don't need to be passed.
   *
   * <p>The following System properties, if defined, are transfered to the Map given to the
   * RMIConnectorServer constructor.
   *
   * <ul>
   *   <li>{@link Context#INITIAL_CONTEXT_FACTORY Context.INITIAL_CONTEXT_FACTORY}
   *   <li>{@link Context#PROVIDER_URL Context.PROVIDER_URL}
   *   <li>{@link Context#SECURITY_PRINCIPAL Context.SECURITY_PRINCIPAL}
   *   <li>{@link Context#SECURITY_CREDENTIALS Context.SECURITY_CREDENTIALS}
   *   <li>{@link RMIConnectorServer#JNDI_REBIND_ATTRIBUTE RMIConnectorServer.JNDI_REBIND_ATTRIBUTE}
   *       - default is <code>true</code>.
   * </ul>
   *
   * @param url A string representation of the JMXServiceURL.
   * @return the created RMIConnectorServer.
   */
  public JMXConnectorServer rmi(String url)
      throws IOException, JMException, ClassNotFoundException {

    // Make a JMXServiceURL from the url string.
    //
    JMXServiceURL jurl = new JMXServiceURL(url);

    // Prepare the environment Map
    //
    final HashMap env = new HashMap();
    final String rprop = RMIConnectorServer.JNDI_REBIND_ATTRIBUTE;
    final String rebind = System.getProperty(rprop, "true");
    final String factory = System.getProperty(Context.INITIAL_CONTEXT_FACTORY);
    final String ldapServerUrl = System.getProperty(Context.PROVIDER_URL);
    final String ldapUser = System.getProperty(Context.SECURITY_PRINCIPAL);
    final String ldapPasswd = System.getProperty(Context.SECURITY_CREDENTIALS);

    // Transfer some system properties to the Map
    //
    if (factory != null) // this should not be needed
    env.put(Context.INITIAL_CONTEXT_FACTORY, factory);
    if (ldapServerUrl != null) // this should not be needed
    env.put(Context.PROVIDER_URL, ldapServerUrl);
    if (ldapUser != null) // this is needed when LDAP is used
    env.put(Context.SECURITY_PRINCIPAL, ldapUser);
    if (ldapPasswd != null) // this is needed when LDAP is used
    env.put(Context.SECURITY_CREDENTIALS, ldapPasswd);
    env.put(rprop, rebind); // default is true.

    // Create an RMIConnectorServer
    //
    System.out.println("Creating RMI Connector: " + jurl);
    JMXConnectorServer rmis = JMXConnectorServerFactory.newJMXConnectorServer(jurl, env, mbs);

    // Get the AgentName for registering the Connector in the Lookup Service
    //
    final String agentName = System.getProperty("agent.name", "DefaultAgent");

    // Start the connector and register it with Jini Lookup Service.
    //
    start(rmis, env, agentName);

    return rmis;
  }
예제 #15
0
  public static void main(String[] args) throws Exception {
    MBeanServer server = MBeanServerFactory.createMBeanServer();

    ObjectName helloName = new ObjectName("Hello:name=HelloWorld");
    server.registerMBean(new Hello(), helloName);

    ObjectName adapterName = new ObjectName("HelloAgent:name=htmladapter,port=8082");
    HtmlAdaptorServer adapter = new HtmlAdaptorServer();
    server.registerMBean(adapter, adapterName);

    adapter.start();
    System.out.println("start.....");

    int rmiPort = 1099;
    String jmxServerName = "TestJMXServer";
    JMXServiceURL url =
        new JMXServiceURL(
            "service:jmx:rmi:///jndi/rmi://localhost:" + rmiPort + "/" + jmxServerName);
    System.out.println("JMXServiceURL: " + url.toString());
    JMXConnectorServer jmxConnServer =
        JMXConnectorServerFactory.newJMXConnectorServer(url, null, server);
    jmxConnServer.start();
  }
    public void activate() throws Exception {
      if (config.configuration().enabled().get()) {
        // see java.rmi.server.ObjID
        System.setProperty("java.rmi.server.randomIDs", "true");

        int jmxAgentPort = config.configuration().port().get();

        try {
          registry = LocateRegistry.createRegistry(jmxAgentPort);
        } catch (RemoteException e) {
          registry = LocateRegistry.getRegistry(jmxAgentPort);
        }

        String hostName = InetAddress.getLocalHost().getHostName();
        JMXServiceURL url =
            new JMXServiceURL(
                "service:jmx:rmi://"
                    + hostName
                    + ":"
                    + jmxAgentPort
                    + "/jndi/rmi://"
                    + hostName
                    + ":"
                    + jmxAgentPort
                    + "/jmxrmi");
        Map env = new HashMap();
        env.put(JMXConnectorServer.AUTHENTICATOR, new StreamflowJmxAuthenticator());

        try {
          connector = JMXConnectorServerFactory.newJMXConnectorServer(url, env, server);
          connector.start();
        } catch (Exception e) {
          logger.error("Could not start JMX connector", e);
        }
      }
    }
예제 #17
0
  public static void initialize(String MBeanArray[], String MBeanTypeArray[]) {

    try {
      setupTls();

      logger.info("");
      logger.info("############# MBean Server ##################");

      logger.info("Create the MBean server...");
      mbeanServer = MBeanServerFactory.createMBeanServer();

      logger.info("Created !");

      for (int i = 0; i < MBeanArray.length; i++) {
        ObjectName mbeanName = new ObjectName("MBeans:type=" + MBeanTypeArray[i]);
        logger.info(MBeanArray[i] + " MBean is created ...");
        mbeanServer.createMBean(
            JMXServer.class.getPackage().getName() + ".beans." + MBeanArray[i],
            mbeanName,
            null,
            null);
      }

      logger.info(ResourceMapper.SECTION_DIVISON_KARE);
      logger.info("");
      logger.info("######### JMXMP-TLS Connector Server ############");
      logger.info("");

      // Create a JMXMP-TLS connector server
      //
      logger.info("Create a JMXMP-TLS connector server... > ");

      // hardcoded ip : localhost port : 5555
      int port =
          TlosSpaceWide.getSpaceWideRegistry()
              .getTlosSWConfigInfo()
              .getJmxParams()
              .getJmxTlsPort()
              .getPortNumber();
      if (port <= 0) {
        port = 5555;
      }

      logger.info("Using port number : " + port);

      String ipAddress =
          TlosSpaceWide.getSpaceWideRegistry().getServerConfig().getServerParams().getIpAddress();
      if (ipAddress == null || ipAddress.equals("")) {
        ipAddress = null;
      }

      logger.info("Using ip address : " + ipAddress);

      JMXServiceURL url = new JMXServiceURL("jmxmp", ipAddress, port);
      jConnectorServer = JMXConnectorServerFactory.newJMXConnectorServer(url, env, mbeanServer);

      logger.info("Created !");

      // Start the JMXMP-TLS connector server
      //
      logger.info("Start the JMXMP-TLS connector server... > ");
      jConnectorServer.start();

      logger.info("Started !");
      logger.info("Waiting for incoming connections...");
      logger.info("#############################################");
      logger.info("");

      String jmxUserName =
          "" + new Random(new Long(Calendar.getInstance().getTimeInMillis())).nextLong();
      Thread.sleep(10);
      String jmxPassWord =
          "" + new Random(new Long(Calendar.getInstance().getTimeInMillis())).nextLong();

      JmxUser jmxUser = new JmxUser();
      jmxUser.setJmxClientAuthanticationId(jmxUserName);
      jmxUser.setJmxClientAuthanticationKey(jmxPassWord);

      TlosSpaceWide.getSpaceWideRegistry().setJmxUser(jmxUser);

    } catch (MalformedURLException mue) {
      logger.error("### MalformedURLException ###");
      mue.printStackTrace();
      try {
        jConnectorServer.stop();
      } catch (IOException e) {
        e.printStackTrace();
      }
    } catch (SecurityException e) {
      // System.out.println(" ### SecurityException ### ");
      logger.error("### SecurityException ###");
      e.printStackTrace();
      System.exit(-1);
    } catch (BindException e) {
      // System.out.println(" ### BindException ### ");
      logger.error("### BindException ###");
      e.printStackTrace();
      System.exit(-1);
    } catch (Exception e) {
      // System.out.println(" ### Unclassified Error ### ");
      logger.error("### Unclassified Error ###");
      e.printStackTrace();
      System.exit(-1);
    }
  }
예제 #18
0
  private static boolean test(String proto, MBeanServer mbs, ObjectName on) throws Exception {
    System.out.println("Testing for protocol " + proto);

    JMXConnectorServer cs;
    JMXServiceURL url = new JMXServiceURL(proto, null, 0);
    try {
      cs = JMXConnectorServerFactory.newJMXConnectorServer(url, null, mbs);
    } catch (MalformedURLException e) {
      System.out.println("System does not recognize URL: " + url + "; ignoring");
      return true;
    }
    cs.start();
    JMXServiceURL addr = cs.getAddress();
    JMXConnector client = JMXConnectorFactory.connect(addr);
    MBeanServerConnection mbsc = client.getMBeanServerConnection();
    Object getAttributeExotic = mbsc.getAttribute(on, "Exotic");
    AttributeList getAttrs = mbsc.getAttributes(on, new String[] {"Exotic"});
    AttributeList setAttrs = new AttributeList();
    setAttrs.add(new Attribute("Exotic", new Exotic()));
    setAttrs = mbsc.setAttributes(on, setAttrs);
    Object invokeExotic = mbsc.invoke(on, "anExotic", new Object[] {}, new String[] {});
    MBeanInfo exoticMBI = mbsc.getMBeanInfo(on);

    mbsc.setAttribute(on, new Attribute("Exception", Boolean.TRUE));
    Exception getAttributeException, setAttributeException, invokeException;
    try {
      try {
        mbsc.getAttribute(on, "Exotic");
        throw noException("getAttribute");
      } catch (Exception e) {
        getAttributeException = e;
      }
      try {
        mbsc.setAttribute(on, new Attribute("Exotic", new Exotic()));
        throw noException("setAttribute");
      } catch (Exception e) {
        setAttributeException = e;
      }
      try {
        mbsc.invoke(on, "anExotic", new Object[] {}, new String[] {});
        throw noException("invoke");
      } catch (Exception e) {
        invokeException = e;
      }
    } finally {
      mbsc.setAttribute(on, new Attribute("Exception", Boolean.FALSE));
    }
    client.close();
    cs.stop();

    boolean ok = true;

    ok &= checkAttrs("getAttributes", getAttrs);
    ok &= checkAttrs("setAttributes", setAttrs);

    ok &= checkType("getAttribute", getAttributeExotic, Exotic.class);
    ok &= checkType("getAttributes", attrValue(getAttrs), Exotic.class);
    ok &= checkType("setAttributes", attrValue(setAttrs), Exotic.class);
    ok &= checkType("invoke", invokeExotic, Exotic.class);
    ok &= checkType("getMBeanInfo", exoticMBI, ExoticMBeanInfo.class);

    ok &= checkExceptionType("getAttribute", getAttributeException, ExoticException.class);
    ok &= checkExceptionType("setAttribute", setAttributeException, ExoticException.class);
    ok &= checkExceptionType("invoke", invokeException, ExoticException.class);

    if (ok) System.out.println("Test passes for protocol " + proto);
    return ok;
  }
  public JMXConnectorServer startRmiConnector(MBeanServer mbs) {
    try {
      Properties props = getProperties();

      String hostName = props.getProperty("java.rmi.server.hostname");
      int port = Integer.parseInt(props.getProperty("com.sun.management.jmxremote.port"));
      String shouldAuthenticate = props.getProperty("com.sun.management.jmxremote.authenticate");
      String authFileName = props.getProperty("com.sun.management.jmxremote.password.file");
      String accessFileName = props.getProperty("com.sun.management.jmxremote.access.file");
      String shouldUseSSL = props.getProperty("com.sun.management.jmxremote.ssl");

      LocateRegistry.createRegistry(port);

      String remoteJMXConnectionUrl =
          String.format("service:jmx:rmi:///jndi/rmi://%s:%d/jmxrmi", hostName, port);
      System.err.println("JMX URL: " + remoteJMXConnectionUrl);

      JMXServiceURL url = new JMXServiceURL(remoteJMXConnectionUrl);

      if ((shouldAuthenticate != null) && (shouldAuthenticate.equalsIgnoreCase("true"))) {
        String javaHome = System.getProperty("java.home");
        if (authFileName == null) {
          authFileName = javaHome + "/lib/management/jmxremote.password";
        }
        if (accessFileName == null) {
          accessFileName = javaHome + "/lib/management/jmxremote.access";
        }
      }

      Map<String, Object> mapEnv = new HashMap<String, Object>();

      if ((authFileName != null) && (mapEnv.get("jmx.remote.x.password.file") == null)) {
        mapEnv.put("jmx.remote.x.password.file", authFileName);
      }

      if ((accessFileName != null) && (mapEnv.get("jmx.remote.x.access.file") == null)) {
        mapEnv.put("jmx.remote.x.access.file", accessFileName);
      }

      if ((shouldUseSSL != null) && (shouldUseSSL.equalsIgnoreCase("true"))) {
        try {
          if (mapEnv.get("jmx.remote.rmi.client.socket.factory") == null) {
            mapEnv.put(
                "jmx.remote.rmi.client.socket.factory",
                Class.forName("javax.rmi.ssl.SslRMIClientSocketFactory").newInstance());
          }

          if (mapEnv.get("jmx.remote.rmi.server.socket.factory") == null) {
            mapEnv.put(
                "jmx.remote.rmi.server.socket.factory",
                Class.forName("javax.rmi.ssl.SslRMIServerSocketFactory").newInstance());
          }

        } catch (ClassNotFoundException e) {
          String sMsg =
              "JMXConnectorServer not started. SSL security requires the Java Dynamic Management Kit or Java 1.5.";
          throw Base.ensureRuntimeException(e, sMsg);
        }
      }

      JMXConnectorServer connector =
          JMXConnectorServerFactory.newJMXConnectorServer(url, mapEnv, mbs);

      connector.start();
      return connector;
    } catch (Exception e) {
      throw Base.ensureRuntimeException(e, "Could not start JMXConnectorServer");
    }
  }
  public static void main(String[] args) throws Exception {
    System.out.println("---RMIConnectorInternalMapTest starting...");

    JMXConnectorServer connectorServer = null;
    JMXConnector connectorClient = null;

    try {
      MBeanServer mserver = ManagementFactory.getPlatformMBeanServer();
      JMXServiceURL serverURL = new JMXServiceURL("rmi", "localhost", 0);
      connectorServer = JMXConnectorServerFactory.newJMXConnectorServer(serverURL, null, mserver);
      connectorServer.start();

      JMXServiceURL serverAddr = connectorServer.getAddress();
      connectorClient = JMXConnectorFactory.connect(serverAddr, null);
      connectorClient.connect();

      Field rmbscMapField = RMIConnector.class.getDeclaredField("rmbscMap");
      rmbscMapField.setAccessible(true);
      Map<Subject, WeakReference<MBeanServerConnection>> map =
          (Map<Subject, WeakReference<MBeanServerConnection>>) rmbscMapField.get(connectorClient);
      if (map != null && !map.isEmpty()) { // failed
        throw new RuntimeException("RMIConnector's rmbscMap must be empty at the initial time.");
      }

      Subject delegationSubject =
          new Subject(
              true,
              Collections.singleton(new JMXPrincipal("delegate")),
              Collections.EMPTY_SET,
              Collections.EMPTY_SET);
      MBeanServerConnection mbsc1 = connectorClient.getMBeanServerConnection(delegationSubject);
      MBeanServerConnection mbsc2 = connectorClient.getMBeanServerConnection(delegationSubject);

      if (mbsc1 == null) {
        throw new RuntimeException("Got null connection.");
      }
      if (mbsc1 != mbsc2) {
        throw new RuntimeException("Not got same connection with a same subject.");
      }

      map = (Map<Subject, WeakReference<MBeanServerConnection>>) rmbscMapField.get(connectorClient);
      if (map == null || map.isEmpty()) { // failed
        throw new RuntimeException(
            "RMIConnector's rmbscMap has wrong size " + "after creating a delegated connection.");
      }

      delegationSubject = null;
      mbsc1 = null;
      mbsc2 = null;

      int i = 0;
      while (!map.isEmpty() && i++ < 60) {
        System.gc();
        Thread.sleep(100);
      }
      System.out.println("---GC times: " + i);

      if (!map.isEmpty()) {
        throw new RuntimeException("Failed to clean RMIConnector's rmbscMap");
      } else {
        System.out.println("---RMIConnectorInternalMapTest: PASSED!");
      }
    } finally {
      try {
        connectorClient.close();
        connectorServer.stop();
      } catch (Exception e) {
      }
    }
  }