Пример #1
0
  /**
   * Get a pointer to the root context of the directory tree under which this server is supposed to
   * register itself. All LDAP DNs will be considered to be relative to that root.
   *
   * <p>Note that this root is not part of the JSR 160 specification, since the actual location
   * where a JMX Agent will register its connectors is left completely open by the specification.
   * The specification only discuss what the JMX Agent must/may put in the directory - but not
   * where.
   *
   * <p>This method assumes that the root of the directory is will be passed in a the {@link
   * Context#PROVIDER_URL Context.PROVIDER_URL} System property.
   *
   * <p>This method will transfer a fixed set of System Properties to the Hashtable given to the
   * JNDI InitialContext:
   *
   * <ul>
   *   <li>{@link Context#INITIAL_CONTEXT_FACTORY Context.INITIAL_CONTEXT_FACTORY} - default is
   *       <code>"com.sun.jndi.ldap.LdapCtxFactory"</code>
   *   <li>{@link Context#PROVIDER_URL Context.PROVIDER_URL}
   *   <li>{@link Context#SECURITY_PRINCIPAL Context.SECURITY_PRINCIPAL} - default is <code>
   *       "cn=Directory Manager"</code>
   *   <li>{@link Context#SECURITY_CREDENTIALS Context.SECURITY_CREDENTIALS}
   * </ul>
   *
   * @return a pointer to the LDAP Directory.
   */
  public static DirContext getRootContext() throws NamingException {
    // Prepare environment
    //
    final Hashtable env = new Hashtable();

    // The Initial Context Factory must be provided, and
    // must point to an LDAP Context Factory
    //
    final String factory =
        System.getProperty(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");

    // The LDAP Provider URL must be provided, and
    // must point to a running LDAP directory server
    //
    final String ldapServerUrl = System.getProperty(Context.PROVIDER_URL);

    // The LDAP user must be provided, and
    // must have write access to the subpart of the directory
    // where the agent will be registered.
    //
    final String ldapUser = System.getProperty(Context.SECURITY_PRINCIPAL, "cn=Directory Manager");

    // Credentials must be provided, so that the user may
    // write to the directory.
    //
    final String ldapPasswd = System.getProperty(Context.SECURITY_CREDENTIALS);

    // Debug info: print provided values:
    //
    debug(Context.PROVIDER_URL + "=" + ldapServerUrl);
    debug(Context.SECURITY_PRINCIPAL + "=" + ldapUser);
    if (debug) {
      System.out.print(Context.SECURITY_CREDENTIALS + "=");
      final int len = (ldapPasswd == null) ? 0 : ldapPasswd.length();
      for (int i = 0; i < len; i++) System.out.print("*");
      System.out.println();
    }

    // Put provided value in the environment table.
    //
    env.put(Context.INITIAL_CONTEXT_FACTORY, factory);
    env.put(Context.SECURITY_PRINCIPAL, ldapUser);
    if (ldapServerUrl != null) env.put(Context.PROVIDER_URL, ldapServerUrl);
    if (ldapPasswd != null) env.put(Context.SECURITY_CREDENTIALS, ldapPasswd);

    // Create initial context
    //
    InitialContext root = new InitialLdapContext(env, null);

    // Now return the root directory context.
    //
    return (DirContext) (root.lookup(""));
  }
Пример #2
0
 /**
  * Get a pointer to the Jini Lookup Service. (See Jini documentation for more info).
  *
  * <p>The Jini Lookup Service URL is determined as follows:
  *
  * <p>If the System property <code>"jini.lookup.url"</code> is provided, its value is the Jini
  * Lookup Service URL.
  *
  * <p>Otherwise, the default URL is assumed to be <code>"jini://localhost"</code>
  *
  * @return a pointer to the Jini Lookup Service.
  */
 public static ServiceRegistrar getRegistrar()
     throws IOException, ClassNotFoundException, MalformedURLException {
   final String jurl = System.getProperty("jini.lookup.url", "jini://localhost");
   final LookupLocator lookup = new LookupLocator(jurl);
   final ServiceRegistrar registrar = lookup.getRegistrar();
   if (registrar instanceof Administrable) debug("Registry is administrable.");
   return registrar;
 }
Пример #3
0
  /**
   * Program Main
   *
   * <p>Creates a server object, gets the JMX Service URL, and calls the method that will create and
   * register the appropriate JMX Connector Server for that URL.
   *
   * <p>You may wish to use the following properties on the Java command line:
   *
   * <ul>
   *   <li><code>-Durl=&lt;jmxServiceURL&gt;</code>: specifies the URL of the JMX Connector Server
   *       you wish to use. See README file for more details
   *   <li><code>-Dagent.name=&lt;AgentName&gt;</code>: specifies an AgentName to register with.
   *   <li><code>-Djini.lookup.url=&lt;jini-url&gt;</code>: the Jini Lookup Service URL (default is
   *       "jini://localhost"), see {@link #getRegistrar()}.
   *   <li><code>-Ddebug="true|false"</code>: switch the Server debug flag on/off (default is
   *       "false").
   * </ul>
   */
  public static void main(String[] args) {
    try {
      // Jini requires a security manager.
      //
      if (System.getSecurityManager() == null) System.setSecurityManager(new RMISecurityManager());

      // Get the value of the debug flag.
      //
      debug = (Boolean.valueOf(System.getProperty("debug", "false"))).booleanValue();

      // Create a new Server object.
      //
      final Server s = new Server();

      // Get the JMXConnector URL
      //
      final String url = System.getProperty("url", "service:jmx:rmi://");

      // Build a JMXServiceURL
      //
      final JMXServiceURL jurl = new JMXServiceURL(url);

      // Creates a JMX Connector Server
      //
      debug("Creating Connector: " + jurl);
      final String p = jurl.getProtocol();
      if (p.equals("rmi")) // Create an RMI Connector
      s.rmi(url);
      else if (p.equals("iiop")) // Create an RMI/IIOP Connector
      s.rmi(url);
      else // Unsupported protocol
      throw new MalformedURLException("Unsupported protocol: " + p);

      System.out.println("\nService URL successfully registered " + "in the Jini Lookup Service");

    } catch (Exception x) {
      // Something went wrong somewhere....
      //
      System.err.println("Unexpected exception caught in main: " + x);
      x.printStackTrace(System.err);
    }
  }
Пример #4
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;
  }
Пример #5
0
class DBPortPool extends SimplePool<DBPort> {

  static class Holder {

    Holder(MongoOptions options) {
      _options = options;
    }

    DBPortPool get(InetSocketAddress addr) {

      DBPortPool p = _pools.get(addr);

      if (p != null) return p;

      synchronized (_pools) {
        p = _pools.get(addr);
        if (p != null) {
          return p;
        }

        p = new DBPortPool(addr, _options);
        _pools.put(addr, p);
        String name = "com.mongodb:type=ConnectionPool,host=" + addr.toString().replace(':', '_');

        try {
          ObjectName on = new ObjectName(name);
          if (_server.isRegistered(on)) {
            _server.unregisterMBean(on);
            Bytes.LOGGER.log(
                Level.INFO, "multiple Mongo instances for same host, jmx numbers might be off");
          }
          _server.registerMBean(p, on);
        } catch (JMException e) {
          Bytes.LOGGER.log(Level.WARNING, "jmx registration error, continuing", e);
        } catch (java.security.AccessControlException e) {
          Bytes.LOGGER.log(Level.WARNING, "jmx registration error, continuing", e);
        }
      }

      return p;
    }

    void close() {
      synchronized (_pools) {
        for (DBPortPool p : _pools.values()) {
          p.close();
        }
      }
    }

    final MongoOptions _options;
    final Map<InetSocketAddress, DBPortPool> _pools =
        Collections.synchronizedMap(new HashMap<InetSocketAddress, DBPortPool>());
    final MBeanServer _server = ManagementFactory.getPlatformMBeanServer();
  }

  // ----

  public static class NoMoreConnection extends MongoInternalException {
    NoMoreConnection(String msg) {
      super(msg);
    }
  }

  public static class SemaphoresOut extends NoMoreConnection {
    SemaphoresOut() {
      super("Out of semaphores to get db connection");
    }
  }

  public static class ConnectionWaitTimeOut extends NoMoreConnection {
    ConnectionWaitTimeOut(int timeout) {
      super("Connection wait timeout after " + timeout + " ms");
    }
  }

  // ----

  DBPortPool(InetSocketAddress addr, MongoOptions options) {
    super("DBPortPool-" + addr.toString(), options.connectionsPerHost, options.connectionsPerHost);
    _options = options;
    _addr = addr;
    _waitingSem =
        new Semaphore(
            _options.connectionsPerHost * _options.threadsAllowedToBlockForConnectionMultiplier);
  }

  protected long memSize(DBPort p) {
    return 0;
  }

  protected int pick(int iThink, boolean couldCreate) {
    final int id = Thread.currentThread().hashCode();
    final int s = _availSafe.size();
    for (int i = 0; i < s; i++) {
      DBPort p = _availSafe.get(i);
      if (p._lastThread == id) return i;
    }

    if (couldCreate) return -1;
    return iThink;
  }

  public DBPort get() {
    DBPort port = null;
    if (!_waitingSem.tryAcquire()) throw new SemaphoresOut();

    try {
      port = get(_options.maxWaitTime);
    } finally {
      _waitingSem.release();
    }

    if (port == null) throw new ConnectionWaitTimeOut(_options.maxWaitTime);

    port._lastThread = Thread.currentThread().hashCode();
    return port;
  }

  void gotError(Exception e) {
    if (e instanceof java.nio.channels.ClosedByInterruptException
        || e instanceof InterruptedException) {
      // this is probably a request that is taking too long
      // so usually doesn't mean there is a real db problem
      return;
    }

    if (e instanceof java.net.SocketTimeoutException && _options.socketTimeout > 0) {
      // we don't want to clear the port pool for 1 connection timing out
      return;
    }

    // We don't want to clear the entire pool for the occasional error.
    if (e instanceof SocketException) {
      if (recentFailures < ALLOWED_ERRORS_BEFORE_CLEAR) {
        return;
      }
    }

    Bytes.LOGGER.log(Level.INFO, "emptying DBPortPool b/c of error", e);
    clear();
  }

  void close() {
    clear();
  }

  public void cleanup(DBPort p) {
    p.close();
  }

  public boolean ok(DBPort t) {
    return _addr.equals(t._addr);
  }

  protected DBPort createNew() throws MongoInternalException {
    try {
      return new DBPort(_addr, this, _options);
    } catch (IOException ioe) {
      throw new MongoInternalException("can't create port to:" + _addr, ioe);
    }
  }

  public int getRecentFailures() {
    return recentFailures;
  }

  public void incrementRecentFailures() {
    _logger.warning("Failure recorded:" + _addr.toString());
    this.recentFailures++;
  }

  public void resetRecentFailures() {
    if (this.recentFailures > 0) {
      _logger.warning("Successful Request. Reseting recent failures:" + _addr.toString());
    }

    this.recentFailures = 0;
  }

  final MongoOptions _options;
  private final Semaphore _waitingSem;
  final InetSocketAddress _addr;
  boolean _everWorked = false;
  public static final Integer ALLOWED_ERRORS_BEFORE_CLEAR =
      Integer.valueOf(System.getProperty("MONGO.ERRORS_BEFORE_CLEAR", "5"));
  private Logger _logger = Logger.getLogger(DBPortPool.class.toString());

  /** The number of failures that this port pool has recently experienced. */
  private int recentFailures = 0;
}
Пример #6
0
  /**
   * Program Main.
   *
   * <p>Lookup all JMX agents in the LDAP Directory and list their MBeans and attributes.
   *
   * <p>You may wish to use the following properties on the Java command line:
   *
   * <ul>
   *   <li><code>-Dagent.name=&lt;AgentName&gt;</code>: specifies an AgentName to lookup (default is
   *       null, meaning any agent).
   *   <li><code>-Dprotocol=&lt;ProtocolType&gt;</code>: restrains the client to lookup for a
   *       specific protocol type (default is null, meaning any type).
   *   <li><code>-Djava.naming.factory.initial=&lt;initial-context-factory&gt;
   *     </code>: The initial context factory to use for accessing the LDAP directory (see {@link
   *       Context#INITIAL_CONTEXT_FACTORY Context.INITIAL_CONTEXT_FACTORY}) - default is <code>
   *       "com.sun.jndi.ldap.LdapCtxFactory"</code>.
   *   <li><code>-Djava.naming.provider.url=&lt;provider-url&gt;</code>: The LDAP Provider URL (see
   *       {@link Context#PROVIDER_URL Context.PROVIDER_URL}).
   *   <li><code>-Djava.naming.security.principal=&lt;ldap-principal&gt;
   *     </code>: The security principal (login) to use to connect with the LDAP directory (see
   *       {@link Context#SECURITY_PRINCIPAL Context.SECURITY_PRINCIPAL} - default is <code>
   *       "cn=Directory Manager"</code>.
   *   <li><code>-Djava.naming.security.credentials=&lt;ldap-credentials&gt;
   *     </code>: The security credentials (password) to use to connect with the LDAP directory (see
   *       {@link Context#SECURITY_CREDENTIALS Context.SECURITY_CREDENTIALS}).
   *   <li><code>-Ddebug="true|false"</code>: switch the Server debug flag on/off (default is
   *       "false")
   * </ul>
   */
  public static void main(String[] args) {
    try {
      // Get the value of the debug flag.
      //
      debug = (Boolean.valueOf(System.getProperty("debug", "false"))).booleanValue();

      // Get a pointer to the LDAP Directory.
      //
      final DirContext root = getRootContext();
      debug("root is: " + root.getNameInNamespace());

      final String protocolType = System.getProperty("protocol");
      final String agentName = System.getProperty("agent.name");

      // Lookup all matching agents in the LDAP Directory.
      //
      List l = lookup(root, protocolType, agentName);

      // Attempt to connect to retrieved agents
      //
      System.out.println("Number of agents found : " + l.size());
      int j = 1;
      for (Iterator i = l.iterator(); i.hasNext(); j++) {
        JMXConnector c1 = (JMXConnector) i.next();
        if (c1 != null) {

          // Connect
          //
          System.out.println("----------------------------------------------------");
          System.out.println("\tConnecting to agent number " + j);
          System.out.println("----------------------------------------------------");
          debug("JMXConnector is: " + c1);

          // Prepare the environment Map
          //
          final HashMap env = new HashMap();
          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);

          try {
            c1.connect(env);
          } catch (IOException x) {
            System.err.println("Connection failed: " + x);
            x.printStackTrace(System.err);
            continue;
          }

          // Get MBeanServerConnection
          //
          MBeanServerConnection conn = c1.getMBeanServerConnection();
          debug("Connection is:" + conn);
          System.out.println("Server domain is: " + conn.getDefaultDomain());

          // List all MBeans
          //
          try {
            listMBeans(conn);
          } catch (IOException x) {
            System.err.println("Failed to list MBeans: " + x);
            x.printStackTrace(System.err);
          }

          // Close connector
          //
          try {
            c1.close();
          } catch (IOException x) {
            System.err.println("Failed to close connection: " + x);
            x.printStackTrace(System.err);
          }
        }
      }
    } catch (Exception x) {
      System.err.println("Unexpected exception caught in main: " + x);
      x.printStackTrace(System.err);
    }
  }
Пример #7
0
  /**
   * Program Main
   *
   * <p>Lookup all JMX agents in the Jini Lookup Service and list their MBeans and attributes.
   *
   * <p>You may wish to use the following properties on the Java command line:
   *
   * <ul>
   *   <li><code>-Dagent.name=&lt;AgentName&gt;</code>: specifies an AgentName to lookup (default is
   *       null, meaning any agent).
   *   <li><code>-Djini.lookup.url=&lt;jini-url&gt;</code>: the Jini Lookup Service URL (default is
   *       "jini://localhost"), see {@link #getRegistrar()}.
   *   <li><code>-Ddebug="true|false"</code>: switch the Client debug flag on/off (default is
   *       "false").
   * </ul>
   */
  public static void main(String[] args) {
    try {
      // Jini requires a security manager.
      //
      if (System.getSecurityManager() == null) System.setSecurityManager(new RMISecurityManager());

      // Get the value of the debug flag.
      //
      debug = (Boolean.valueOf(System.getProperty("debug", "false"))).booleanValue();

      // Get AgentName to lookup. If not defined, all agents
      // are looked up.
      //
      final String agentName = System.getProperty("agent.name");

      // Get a pointer to the Jini Lookup Service.
      //
      final ServiceRegistrar registrar = getRegistrar();
      debug("registrar is: " + registrar);

      // Lookup all matching agents in the Jini Lookup Service.
      //
      List l = lookup(registrar, agentName);

      // Attempt to connect to retrieved agents
      //
      System.out.println("Number of agents found : " + l.size());
      int j = 1;
      for (Iterator i = l.iterator(); i.hasNext(); j++) {
        JMXConnector c1 = (JMXConnector) i.next();
        if (c1 != null) {

          // Connect
          //
          System.out.println("----------------------------------------------------");
          System.out.println("\tConnecting to agent number " + j);
          System.out.println("----------------------------------------------------");
          debug("JMXConnector is: " + c1);

          try {
            c1.connect(null);
          } catch (IOException x) {
            System.err.println("Connection failed: " + x);
            if (debug) x.printStackTrace(System.err);
            continue;
          }

          // Get MBeanServerConnection
          //
          MBeanServerConnection conn = c1.getMBeanServerConnection();
          debug("Connection is:" + conn);
          System.out.println("Server domain is: " + conn.getDefaultDomain());

          // List all MBeans
          //
          try {
            listMBeans(conn);
          } catch (IOException x) {
            System.err.println("Failed to list MBeans: " + x);
            if (debug) x.printStackTrace(System.err);
          }

          // Close connector
          //
          try {
            c1.close();
          } catch (IOException x) {
            System.err.println("Failed to close connection: " + x);
            if (debug) x.printStackTrace(System.err);
          }
        }
      }
    } catch (Exception x) {
      System.err.println("Unexpected exception caught in main: " + x);
      x.printStackTrace(System.err);
    }
  }