Esempio n. 1
1
 @Override
 public void run() {
   boolean loop = true;
   try {
     while (loop) {
       final Thread[] all = new Thread[Thread.activeCount() + 100];
       final int count = Thread.enumerate(all);
       loop = false;
       for (int i = 0; i < count; i++) {
         final Thread t = all[i];
         // daemon: skip it.
         if (t.isDaemon()) continue;
         // RMI Reaper: skip it.
         if (t.getName().startsWith("RMI Reaper")) continue;
         if (t.getName().startsWith("DestroyJavaVM")) continue;
         // Non daemon, non RMI Reaper: join it, break the for
         // loop, continue in the while loop (loop=true)
         loop = true;
         try {
           // Found a non-daemon thread. Wait for it.
           t.join();
         } catch (Exception ex) {
           ex.printStackTrace();
         }
         break;
       }
     }
     // We went through a whole for-loop without finding any thread
     // to join. We can close cs.
   } catch (Exception ex) {
     ex.printStackTrace();
   } finally {
     try {
       // if we reach here it means the only non-daemon threads
       // that remain are reaper threads - or that we got an
       // unexpected exception/error.
       //
       if (cs != null && cs.isActive()) {
         cs.stop();
       }
     } catch (Exception ex) {
       ex.printStackTrace();
     }
   }
 }
Esempio n. 2
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 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();
    }
  }
Esempio n. 4
0
  /** @see org.eclipse.jetty.util.component.AbstractLifeCycle#doStart() */
  @Override
  public void doStart() throws Exception {
    _connectorServer.start();
    ShutdownThread.register(0, this);

    LOG.info("JMX Remote URL: {}", _connectorServer.getAddress().toString());
  }
  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) {
      }
    }
  }
Esempio n. 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();
  }
Esempio n. 7
0
  /**
   * Closes this connection handler so that it will no longer accept new client connections. It may
   * or may not disconnect existing client connections based on the provided flag.
   *
   * @param stopRegistry Indicates if the RMI registry should be stopped
   */
  public void finalizeConnectionHandler(boolean stopRegistry) {
    try {
      if (jmxRmiConnectorNoClientCertificate != null) {
        jmxRmiConnectorNoClientCertificate.stop();
      }
      if (jmxRmiConnectorClientCertificate != null) {
        jmxRmiConnectorClientCertificate.stop();
      }
    } catch (Exception e) {
      TRACER.debugCaught(DebugLogLevel.ERROR, e);
    }

    jmxRmiConnectorNoClientCertificate = null;
    jmxRmiConnectorClientCertificate = null;

    //
    // Unregister connectors and stop them.
    try {
      ObjectName name = new ObjectName(jmxRmiConnectorNoClientCertificateName);
      if (mbs.isRegistered(name)) {
        mbs.unregisterMBean(name);
      }
      if (jmxRmiConnectorNoClientCertificate != null) {
        jmxRmiConnectorNoClientCertificate.stop();
      }

      // TODO: unregister the connector with SSL client authen
      //      name = new ObjectName(jmxRmiConnectorClientCertificateName);
      //      if (mbs.isRegistered(name))
      //      {
      //        mbs.unregisterMBean(name);
      //      }
      //      jmxRmiConnectorClientCertificate.stop() ;
    } catch (Exception e) {
      // TODO Log an error message
      if (debugEnabled()) {
        TRACER.debugCaught(DebugLogLevel.ERROR, e);
      }
    }

    if (stopRegistry) {
      //
      // Close the socket
      try {
        if (rmiSsf != null) rmiSsf.close();
      } catch (IOException e) {
        // TODO Log an error message
        if (debugEnabled()) {
          TRACER.debugCaught(DebugLogLevel.ERROR, e);
        }
      }
      registry = null;
    }
  }
  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;
  }
Esempio n. 9
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();
    }
  }
Esempio n. 10
0
 public boolean isActive() {
   if (cs == null) {
     return false;
   } else {
     return cs.isActive();
   }
 }
Esempio n. 11
0
  public void start() throws IOException {
    log.infof("Starting JMX Remoting Server %s", Version.getVersionString());

    // Initialise general Remoting - this step would be implemented elsewhere when
    // running within an application server.
    final Xnio xnio = Xnio.getInstance();
    endpoint = Remoting.createEndpoint("JMXRemoting", xnio, OptionMap.EMPTY);
    endpoint.addConnectionProvider(
        "remote", new RemoteConnectionProviderFactory(), OptionMap.EMPTY);

    final NetworkServerProvider nsp =
        endpoint.getConnectionProviderInterface("remote", NetworkServerProvider.class);
    final SocketAddress bindAddress = new InetSocketAddress(host, listenerPort);
    final OptionMap serverOptions = createOptionMap();

    server = nsp.createServer(bindAddress, serverOptions, authenticationProvider, null);

    Map<String, Object> configMap = new HashMap<String, Object>();
    if (excludedVersions != null) {
      configMap.put(EXCLUDED_VERSIONS, excludedVersions);
    }
    // Initialise the components that will provide JMX connectivity.
    if (mbeanServerLocator == null) {
      connectorServer =
          new RemotingConnectorServer(
              mbeanServer, endpoint, configMap, serverMessageEventHandlerFactory);
      connectorServer.start();
    } else {
      delegatingServer =
          new DelegatingRemotingConnectorServer(
              mbeanServerLocator, endpoint, configMap, serverMessageEventHandlerFactory);
      delegatingServer.start();
    }
  }
Esempio n. 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);
    }
  }
Esempio n. 13
0
 private void destroyServer(String serverName, JMXConnectorServer theConnectorServer) {
   if (theConnectorServer != null) {
     try {
       theConnectorServer.stop();
     } catch (IOException e) {
       log.error(sm.getString("jmxRemoteLifecycleListener.destroyServerFailed", serverName), e);
     }
   }
 }
Esempio n. 14
0
  /**
   * Start a JMXConnectorServer and register it with Jini Lookup Service.
   *
   * @param server the JMXConnectorServer to start and register.
   * @param env the environment Map.
   * @param agentName the AgentName with which the proxy must be registered in the Jini Lookup
   *     Service.
   */
  public void start(JMXConnectorServer server, Map env, String agentName)
      throws IOException, ClassNotFoundException {

    // Start the JMXConnectorServer
    //
    server.start();

    // Get a pointer to Jini Lookup Service
    //
    final ServiceRegistrar registrar = getRegistrar();

    // Create a JMXConnector proxy to register with Jini
    //
    final JMXConnector proxy = server.toJMXConnector(env);

    // Register the proxy with Jini Lookup Service.
    //
    register(registrar, proxy, agentName);
  }
Esempio n. 15
0
  public static void disconnect() {
    try {

      logger.info("Closing jmx server...");

      String[] connIdList = jConnectorServer.getConnectionIds();

      logger.info("Current active JMXMP-TLS client count : " + connIdList.length);
      logger.info("Waiting for the connections to be closed...");

      int counter = 0;

      while (true) {
        if (jConnectorServer.getConnectionIds().length == 0 || counter++ == 20) {
          break;
        }
        try {
          Thread.sleep(1000);
          System.out.print(".");
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
      }

      if (counter == 20) {
        logger.info("Client(s) are not disconnected, terminated by server !");
      } else {
        logger.info("Client(s) disconnected !");
      }

      jConnectorServer.stop();

      logger.info("Closed !");
      logger.info("Releasing MBean Server...");

      MBeanServerFactory.releaseMBeanServer(mbeanServer);

      logger.info("Released !");

    } catch (IOException e) {
      e.printStackTrace();
    }
  }
Esempio n. 16
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();
  }
Esempio n. 17
0
  public void start() throws IOException {
    if (cleanthread == null) {
      cleanthread = new CleanThread();
      cleanthread.start();
    }

    if (cs == null) {
      createConnectorServer();
      cs.start();
      cleanthread.setCS(cs);
    }
  }
    public void passivate() throws Exception {
      // Stop connector
      if (connector != null) {
        connector.stop();
        connector = null;
      }

      // Remove registry
      if (registry != null) {
        UnicastRemoteObject.unexportObject(registry, true);
        registry = null;
      }
    }
Esempio n. 19
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();
  }
Esempio n. 20
0
  protected void doStop() throws Exception {
    // close JMX Connector, if it was created
    if (cs != null) {
      try {
        cs.stop();
        LOG.debug("Stopped JMX Connector");
      } catch (IOException e) {
        LOG.debug(
            "Error occurred during stopping JMXConnectorService: "
                + cs
                + ". This exception will be ignored.");
      }
      cs = null;
    }

    // Unexport JMX RMI registry, if it was created
    if (registry != null) {
      try {
        UnicastRemoteObject.unexportObject(registry, true);
        LOG.debug("Unexported JMX RMI Registry");
      } catch (NoSuchObjectException e) {
        LOG.debug(
            "Error occurred while unexporting JMX RMI registry. This exception will be ignored.");
      }
    }

    if (mbeansRegistered.isEmpty()) {
      return;
    }

    // Using the array to hold the busMBeans to avoid the CurrentModificationException
    ObjectName[] mBeans =
        mbeansRegistered.keySet().toArray(new ObjectName[mbeansRegistered.size()]);
    int caught = 0;
    for (ObjectName name : mBeans) {
      try {
        unregister(name);
      } catch (Exception e) {
        LOG.info("Exception unregistering MBean with name " + name, e);
        caught++;
      }
    }
    if (caught > 0) {
      LOG.warn(
          "A number of "
              + caught
              + " exceptions caught while unregistering MBeans during stop operation."
              + " See INFO log for details.");
    }
  }
Esempio n. 21
0
  public synchronized void stop() throws IOException {
    stopped = true;

    if (connServer != null) {
      try {
        connServer.stop();
      } finally {
        connServer = null;
      }
    }

    ManagementResources mr = new ManagementResources();
    unregisterBeans(mr.getInternalMBeanDomain());
    unregisterBeans(mr.getPublicMBeanDomain());
  }
Esempio n. 22
0
  public void stop() throws IOException {
    log.infof("Stopping JMX Remoting Server %s", Version.getVersionString());

    // Services using an existing Remoting installation only need to stop the JMXConnectorServer
    // to disassociate it from Remoting.
    if (connectorServer != null) {
      connectorServer.stop();
    }
    if (server != null) {
      server.close();
    }

    if (endpoint != null) {
      endpoint.close();
    }
  }
Esempio n. 23
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)");
      }
    }
  }
Esempio n. 24
0
  public void start() throws IOException {
    log.infof("Starting JMX Remoting Server %s", Version.getVersionString());

    // Initialise general Remoting - this step would be implemented elsewhere when
    // running within an application server.
    final Xnio xnio = Xnio.getInstance();
    endpoint = Remoting.createEndpoint("JMXRemoting", xnio, OptionMap.EMPTY);
    endpoint.addConnectionProvider(
        "remote", new RemoteConnectionProviderFactory(), OptionMap.EMPTY);

    final NetworkServerProvider nsp =
        endpoint.getConnectionProviderInterface("remote", NetworkServerProvider.class);
    final SocketAddress bindAddress = new InetSocketAddress("localhost", listenerPort);
    final OptionMap serverOptions = createOptionMap();

    server = nsp.createServer(bindAddress, serverOptions, authenticationProvider, null);

    // Initialise the components that will provide JMX connectivity.
    connectorServer = new RemotingConnectorServer(mbeanServer, endpoint);
    connectorServer.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);
        }
      }
    }
Esempio n. 26
0
 /** @see org.eclipse.jetty.util.component.AbstractLifeCycle#doStop() */
 @Override
 public void doStop() throws Exception {
   ShutdownThread.deregister(this);
   _connectorServer.stop();
   stopRegistry();
 }
  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) {
      }
    }
  }
Esempio n. 28
0
 public void stop() throws IOException {
   if (cs != null && cs.isActive()) {
     cs.stop();
     cs = null;
   }
 }
Esempio n. 29
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);
    }
  }
Esempio n. 30
0
 @After
 public void tearDown() throws IOException {
   m_connectorServer.stop();
 }