Exemple #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();
     }
   }
 }
  /**
   * 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 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) {
      }
    }
  }
 private void destroyServer(String serverName, JMXConnectorServer theConnectorServer) {
   if (theConnectorServer != null) {
     try {
       theConnectorServer.stop();
     } catch (IOException e) {
       log.error(sm.getString("jmxRemoteLifecycleListener.destroyServerFailed", serverName), e);
     }
   }
 }
Exemple #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();
  }
    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;
      }
    }
  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.");
    }
  }
  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());
  }
  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();
    }
  }
Exemple #11
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);
    }
  }
  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();
    }
  }
 /** @see org.eclipse.jetty.util.component.AbstractLifeCycle#doStop() */
 @Override
 public void doStop() throws Exception {
   ShutdownThread.deregister(this);
   _connectorServer.stop();
   stopRegistry();
 }
Exemple #14
0
 public void stop() throws IOException {
   if (cs != null && cs.isActive()) {
     cs.stop();
     cs = null;
   }
 }
 @After
 public void tearDown() throws IOException {
   m_connectorServer.stop();
 }
  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 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);
    }
  }
  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) {
      }
    }
  }