Ejemplo n.º 1
0
  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();
  }
Ejemplo n.º 2
0
public class DBPort {

  public static final int PORT = 27017;
  static final boolean USE_NAGLE = false;

  static final long CONN_RETRY_TIME_MS = 15000;

  public DBPort(InetSocketAddress addr) throws IOException {
    this(addr, null, new MongoOptions());
  }

  DBPort(InetSocketAddress addr, DBPortPool pool, MongoOptions options) throws IOException {
    _options = options;
    _addr = addr;
    _pool = pool;

    _hashCode = _addr.hashCode();

    _logger = Logger.getLogger(_rootLogger.getName() + "." + addr.toString());
  }

  /** @param response will get wiped */
  DBMessage call(DBMessage msg, ByteDecoder decoder) throws IOException {
    return go(msg, decoder);
  }

  void say(DBMessage msg) throws IOException {
    go(msg, null);
  }

  private synchronized DBMessage go(DBMessage msg, ByteDecoder decoder) throws IOException {

    if (_sock == null) _open();

    {
      ByteBuffer out = msg.prepare();
      while (out.remaining() > 0) _sock.write(out);
    }

    if (_pool != null) _pool._everWorked = true;

    if (decoder == null) return null;

    ByteBuffer response = decoder._buf;

    if (response.position() != 0) throw new IllegalArgumentException();

    int read = 0;
    while (read < DBMessage.HEADER_LENGTH) read += _read(response);

    int len = response.getInt(0);
    if (len <= DBMessage.HEADER_LENGTH)
      throw new IllegalArgumentException("db sent invalid length: " + len);

    if (len > response.capacity())
      throw new IllegalArgumentException(
          "db message size is too big (" + len + ") " + "max is (" + response.capacity() + ")");

    response.limit(len);
    while (read < len) read += _read(response);

    if (read != len) throw new RuntimeException("something is wrong");

    response.flip();
    return new DBMessage(response);
  }

  public synchronized void ensureOpen() throws IOException {

    if (_sock != null) return;

    _open();
  }

  void _open() throws IOException {

    long sleepTime = 100;

    final long start = System.currentTimeMillis();
    while (true) {

      IOException lastError = null;

      try {
        _sock = SocketChannel.open();
        _socket = _sock.socket();
        _socket.connect(_addr, _options.connectTimeout);

        _socket.setTcpNoDelay(!USE_NAGLE);
        _socket.setSoTimeout(_options.socketTimeout);
        _in = _socket.getInputStream();
        return;
      } catch (IOException ioe) {
        //  TODO  - erh to fix                lastError = new IOException( "couldn't connect to [" +
        // _addr + "] bc:" + lastError , lastError );
        lastError = new IOException("couldn't connect to [" + _addr + "] bc:" + ioe);
        _logger.log(Level.INFO, "connect fail to : " + _addr, ioe);
      }

      if (!_options.autoConnectRetry || (_pool != null && !_pool._everWorked)) throw lastError;

      long sleptSoFar = System.currentTimeMillis() - start;

      if (sleptSoFar >= CONN_RETRY_TIME_MS) throw lastError;

      if (sleepTime + sleptSoFar > CONN_RETRY_TIME_MS) sleepTime = CONN_RETRY_TIME_MS - sleptSoFar;

      _logger.severe(
          "going to sleep and retry.  total sleep time after = "
              + (sleptSoFar + sleptSoFar)
              + "ms  this time:"
              + sleepTime
              + "ms");
      ThreadUtil.sleep(sleepTime);
      sleepTime *= 2;
    }
  }

  public int hashCode() {
    return _hashCode;
  }

  public String host() {
    return _addr.toString();
  }

  public String toString() {
    return "{DBPort  " + host() + "}";
  }

  protected void finalize() {
    if (_sock != null) {
      try {
        _sock.close();
      } catch (Exception e) {
        // don't care
      }

      _in = null;
      _socket = null;
      _sock = null;
    }
  }

  void checkAuth(DB db) {
    if (db._username == null) return;
    if (_authed.containsKey(db)) return;

    if (_inauth) return;

    _inauth = true;
    try {
      if (db.reauth()) {
        _authed.put(db, true);
        return;
      }
    } finally {
      _inauth = false;
    }

    throw new MongoInternalException("can't reauth!");
  }

  private int _read(ByteBuffer buf) throws IOException {
    int x = _in.read(buf.array(), buf.position(), buf.remaining());
    if (x < 0) throw new IOException("connection to server closed unexpectedly");
    buf.position(buf.position() + x);
    return x;
  }

  final int _hashCode;
  final InetSocketAddress _addr;
  final DBPortPool _pool;
  final MongoOptions _options;
  final Logger _logger;

  private SocketChannel _sock;
  private Socket _socket;
  private InputStream _in;

  private boolean _inauth = false;
  private Map<DB, Boolean> _authed = Collections.synchronizedMap(new WeakHashMap<DB, Boolean>());

  private static Logger _rootLogger = Logger.getLogger("com.mongodb.port");
}
Ejemplo n.º 3
0
  // make sure Vects are disposed
  private static class TestVect extends ArrayVect1 {
    private static final long serialVersionUID = 1L;
    /** Visible only for tests. */
    public static int max = 0;
    /** Visible only for tests. */
    public static int total = 0;
    /** Visible only for tests. */
    public static Map<Object, String> undisposed =
        Collections.synchronizedMap(new HashMap<Object, String>());

    /** Visible only for tests. */
    public String identity = "default";

    @Override
    public void add(double scaleThis, double scaleOther, VectConst other) {
      assertSameType(other);
      super.add(scaleThis, scaleOther, other);
    }

    @Override
    public void project(double scaleThis, double scaleOther, VectConst other) {
      TestVect tv = (TestVect) other;
      if (!identity.equals(tv.identity)) {
        projectWasTested = true;
      }
      super.add(scaleThis, scaleOther, other);
    }

    @Override
    public double dot(VectConst other) {
      assertSameType(other);
      return super.dot(other);
    }

    private void assertSameType(VectConst other) {
      TestVect tv = (TestVect) other;
      if (!identity.equals(tv.identity)) {
        throw new IllegalArgumentException("different types");
      }
    }

    /**
     * Constructor.
     *
     * @param data
     * @param variance
     * @param identity
     */
    public TestVect(double[] data, double variance, String identity) {
      super(data, variance);
      this.identity = identity;
      remember(this);
    }

    @Override
    public TestVect clone() {
      TestVect result = (TestVect) super.clone();
      remember(result);
      return result;
    }

    private void remember(Object tv) { // remember where allocated
      synchronized (undisposed) {
        java.io.StringWriter sw = new java.io.StringWriter();
        java.io.PrintWriter pw = new java.io.PrintWriter(sw);
        new Exception("This vector was never disposed").printStackTrace(pw);
        pw.flush();
        undisposed.put(tv, sw.toString());
        // LOG.info("**********************************************");
        // LOG.info(sw.toString());
        max = Math.max(max, undisposed.size());
        total += 1;
        if (undisposed.size() > 12 && !printedUndisposed) {
          LOG.severe("**********************************************");
          LOG.severe(getTraces());
          LOG.severe("**********************************************");
          printedUndisposed = true;
        }
      }
    }

    @Override
    public void dispose() {
      synchronized (undisposed) {
        super.dispose();
        undisposed.remove(this);
      }
    }
    /**
     * View traces for debugging
     *
     * @return printable version of traces
     */
    public static String getTraces() {
      StringBuilder sb = new StringBuilder();
      for (String s : undisposed.values()) {
        sb.append(s);
        sb.append("\n");
      }
      return sb.toString();
    }
  }