Ejemplo n.º 1
0
  public WriteResult say(DB db, OutMessage m, DB.WriteConcern concern) throws MongoException {
    MyPort mp = _threadPort.get();
    DBPort port = mp.get(true);
    port.checkAuth(db);

    try {
      port.say(m);
      if (concern == DB.WriteConcern.STRICT) {
        return _checkWriteError(mp, port);
      } else {
        mp.done(port);
        return new WriteResult(db, port);
      }
    } catch (IOException ioe) {
      mp.error(ioe);
      _error(ioe);
      if (concern == DB.WriteConcern.NONE) {
        CommandResult res = new CommandResult();
        res.put("ok", false);
        res.put("$err", "NETWORK ERROR");
        return new WriteResult(res);
      }
      throw new MongoException.Network("can't say something", ioe);
    } catch (MongoException me) {
      throw me;
    } catch (RuntimeException re) {
      mp.error(re);
      throw re;
    }
  }
Ejemplo n.º 2
0
 /**
  * Tries to authorize current connection and throws AuthenticationErrorException if not
  * successful.
  *
  * <p>Retrieved token is stored for later use with all commands that need authentication.
  */
 public void login(@NotNull String userName, @NotNull String password)
     throws AuthenticationErrorException, CommandExecutionException, IOException {
   final Login login = new Login(this);
   login.setParameter("login", userName);
   login.setParameter("password", password);
   final CommandResult<String> result = execute(login);
   if (result.success()) {
     authorization = result.getResult();
     this.userName = userName;
     this.password = password;
     timeout = Calendar.getInstance().getTimeInMillis();
   } else throw new AuthenticationErrorException(this, userName, password.replaceAll(".", "*"));
 }
Ejemplo n.º 3
0
  WriteResult _checkWriteError(MyPort mp, DBPort port) throws MongoException {

    CommandResult e = _mongo.getDB("admin").getLastError();
    mp.done(port);

    Object foo = e.get("err");
    if (foo == null) return new WriteResult(e);

    int code = -1;
    if (e.get("code") instanceof Number) code = ((Number) e.get("code")).intValue();
    String s = foo.toString();
    if (code == 11000 || code == 11001 || s.startsWith("E11000") || s.startsWith("E11001"))
      throw new MongoException.DuplicateKey(code, s);
    throw new MongoException(code, s);
  }
Ejemplo n.º 4
0
 /**
  * Executes a YouTrack command and returns a result.
  *
  * @return instance of @link CommandResult containing command execution results.
  */
 <O extends BaseItem, R> CommandResult<R> execute(Command<O, R> command)
     throws CommandExecutionException, IOException {
   final CloseableHttpClient httpClient = getHttpClient();
   try {
     if (command.usesAuthorization()) {
       checkAuthState(command);
     }
     command.run(httpClient, authorization);
     final CommandResult<R> result = command.getResult();
     if (result.getException() != null) throw result.getException();
     if (result.getError() != null)
       throw new CommandExecutionException(command, result.getError());
     return result;
   } catch (CommandExecutionException cee) {
     throw cee;
   } catch (Exception e) {
     throw new CommandExecutionException(command, e);
   } finally {
     command.close();
     httpClient.close();
   }
 }
Ejemplo n.º 5
0
    synchronized void update(Set<Node> seenNodes) {
      try {
        long start = System.currentTimeMillis();
        CommandResult res = _port.runCommand(_mongo.getDB("admin"), _isMasterCmd);
        _lastCheck = System.currentTimeMillis();
        _pingTime = _lastCheck - start;

        if (res == null) {
          _ok = false;
          return;
        }

        _ok = true;
        _isMaster = res.getBoolean("ismaster", false);
        _isSecondary = res.getBoolean("secondary", false);
        _lastPrimarySignal = res.getString("primary");

        if (res.containsField("hosts")) {
          for (Object x : (List) res.get("hosts")) {
            String host = x.toString();
            Node node = _addIfNotHere(host);
            if (node != null && seenNodes != null) seenNodes.add(node);
          }
        }

        if (res.containsField("passives")) {
          for (Object x : (List) res.get("passives")) {
            String host = x.toString();
            Node node = _addIfNotHere(host);
            if (node != null && seenNodes != null) seenNodes.add(node);
          }
        }

        if (_isMaster) {
          // max size was added in 1.8
          if (res.containsField("maxBsonObjectSize"))
            maxBsonObjectSize = ((Integer) res.get("maxBsonObjectSize")).intValue();
          else maxBsonObjectSize = Bytes.MAX_OBJECT_SIZE;
        }

      } catch (MongoException e) {
        Throwable root = e;
        if (e.getCause() != null) root = e.getCause();
        _logger.log(Level.FINE, "node down: " + _addr + " " + root);
        _ok = false;
      } catch (Exception e) {
        _logger.log(Level.SEVERE, "can't update node: " + _addr, e);
        _ok = false;
      }

      if (!_isMaster) return;

      try {
        DB db = _mongo.getDB("local");
        _port.checkAuth(db);
        DBObject config = _port.findOne(db, "system.replset", new BasicDBObject());
        if (config == null) {
          // probably a replica pair
          // TODO: add this in when pairs are really gone
          // _logger.log( Level.SEVERE , "no replset config!" );
        } else if (config.get("$err") != null
            && UNAUTHENTICATED_ERROR_CODE == (Integer) config.get("code")) {
          _logger.log(
              Level.WARNING,
              "Replica Set updater cannot get results, call authenticate on 'local' or 'admin' db");
        } else {

          String setName = config.get("_id").toString();
          if (_setName == null) {
            _setName = setName;
            _logger = Logger.getLogger(_rootLogger.getName() + "." + setName);
          } else if (!_setName.equals(setName)) {
            _logger.log(Level.SEVERE, "mis match set name old: " + _setName + " new: " + setName);
            return;
          }

          // TODO: look at members
        }
      } catch (MongoException e) {
        if (_setName != null) {
          // this probably means the master is busy, so going to ignore
        } else {
          _logger.log(Level.SEVERE, "can't get initial config from node: " + _addr, e);
        }
      } catch (Exception e) {
        _logger.log(Level.SEVERE, "unexpected error getting config from node: " + _addr, e);
      }
    }
    synchronized void update(Set<UpdatableNode> seenNodes) {
      try {
        long start = System.nanoTime();
        CommandResult res = _port.runCommand(_mongo.getDB("admin"), _isMasterCmd);
        long end = System.nanoTime();
        float newPingMS = (end - start) / 1000000F;
        if (!successfullyContacted) _pingTimeMS = newPingMS;
        else _pingTimeMS = _pingTimeMS + ((newPingMS - _pingTimeMS) / latencySmoothFactor);

        _rootLogger.log(
            Level.FINE,
            "Latency to " + _addr + " actual=" + newPingMS + " smoothed=" + _pingTimeMS);

        successfullyContacted = true;

        if (res == null) {
          throw new MongoInternalException("Invalid null value returned from isMaster");
        }

        if (!_ok) {
          _logger.get().log(Level.INFO, "Server seen up: " + _addr);
        }
        _ok = true;
        _isMaster = res.getBoolean("ismaster", false);
        _isSecondary = res.getBoolean("secondary", false);
        _lastPrimarySignal.set(res.getString("primary"));

        if (res.containsField("hosts")) {
          for (Object x : (List) res.get("hosts")) {
            String host = x.toString();
            UpdatableNode node = _addIfNotHere(host);
            if (node != null && seenNodes != null) seenNodes.add(node);
          }
        }

        if (res.containsField("passives")) {
          for (Object x : (List) res.get("passives")) {
            String host = x.toString();
            UpdatableNode node = _addIfNotHere(host);
            if (node != null && seenNodes != null) seenNodes.add(node);
          }
        }

        // Tags were added in 2.0 but may not be present
        if (res.containsField("tags")) {
          DBObject tags = (DBObject) res.get("tags");
          for (String key : tags.keySet()) {
            _tags.put(key, tags.get(key).toString());
          }
        }

        // max size was added in 1.8
        if (res.containsField("maxBsonObjectSize")) {
          _maxBsonObjectSize = (Integer) res.get("maxBsonObjectSize");
        } else {
          _maxBsonObjectSize = Bytes.MAX_OBJECT_SIZE;
        }

        if (res.containsField("setName")) {
          String setName = res.get("setName").toString();
          if (_setName.get() == null) {
            _setName.set(setName);
            _logger.set(Logger.getLogger(_rootLogger.getName() + "." + setName));
          } else if (!_setName.get().equals(setName)) {
            _logger
                .get()
                .log(Level.SEVERE, "mismatch set name old: " + _setName.get() + " new: " + setName);
          }
        }

      } catch (Exception e) {
        if (_ok) {
          _logger.get().log(Level.WARNING, "Server seen down: " + _addr, e);
        } else if (Math.random() < 0.1) {
          _logger.get().log(Level.WARNING, "Server seen down: " + _addr, e);
        }
        _ok = false;
      }
    }