Exemplo n.º 1
0
    ServerImpl::ServerImpl(connection::ConnectionPtr const &conn,
                           boost::optional<std::string> const &host,
                           boost::optional<int> const &port)
        : m_conn(conn), m_ctx(make_shared<pluginhost::RegistrationContext>()),
          m_host(host.get_value_or("localhost")),
          m_port(port.get_value_or(util::UseDefaultPort)),
          m_log(util::log::make_logger(util::log::OSVR_SERVER_LOG)) {
        if (!m_conn) {
            throw std::logic_error(
                "Can't pass a null ConnectionPtr into Server constructor!");
        }
        osvr::connection::Connection::storeConnection(*m_ctx, m_conn);

        // Get the underlying VRPN connection, and make sure it's OK.
        auto vrpnConn = getVRPNConnection(m_conn);

        if (!(vrpnConn->doing_okay())) {
            throw ServerCreationFailure();
        }

        // Set up system device/system component
        m_systemDevice = common::createServerDevice(
            common::SystemComponent::deviceName(), vrpnConn);

        m_systemComponent =
            m_systemDevice->addComponent(common::SystemComponent::create());
        m_systemComponent->registerClientRouteUpdateHandler(
            &ServerImpl::m_handleUpdatedRoute, this);

        // Things to do when we get a new incoming connection
        // No longer doing hardware detect unconditionally here - see
        // triggerHardwareDetect()
        m_commonComponent =
            m_systemDevice->addComponent(common::CommonComponent::create());
        m_commonComponent->registerPingHandler([&] { m_queueTreeSend(); });

        // Set up the default display descriptor.
        m_tree.getNodeByPath("/display").value() =
            common::elements::StringElement(util::makeString(display_json));
        // Deal with updated device descriptors.
        m_conn->registerDescriptorHandler([&] { m_handleDeviceDescriptors(); });

        // Set up handlers to enter/exit idle sleep mode.
        // Can't do this with the nice wrappers on the CommonComponent of the
        // system device, I suppose since people aren't really connecting to
        // that device.
        vrpnConn->register_handler(
            vrpnConn->register_message_type(vrpn_got_first_connection),
            &ServerImpl::m_exitIdle, this);
        vrpnConn->register_handler(
            vrpnConn->register_message_type(vrpn_dropped_last_connection),
            &ServerImpl::m_enterIdle, this);
    }
Exemplo n.º 2
0
StatusWith<Shard::QueryResponse> ShardLocal::_exhaustiveFindOnConfig(
    OperationContext* txn,
    const ReadPreferenceSetting& readPref,
    const repl::ReadConcernLevel& readConcernLevel,
    const NamespaceString& nss,
    const BSONObj& query,
    const BSONObj& sort,
    boost::optional<long long> limit) {
    auto replCoord = repl::ReplicationCoordinator::get(txn);

    if (readConcernLevel == repl::ReadConcernLevel::kMajorityReadConcern) {
        // Set up operation context with majority read snapshot so correct optime can be retrieved.
        Status status = txn->recoveryUnit()->setReadFromMajorityCommittedSnapshot();

        // Wait for any writes performed by this ShardLocal instance to be committed and visible.
        Status readConcernStatus = replCoord->waitUntilOpTimeForRead(
            txn, repl::ReadConcernArgs{_getLastOpTime(), readConcernLevel});
        if (!readConcernStatus.isOK()) {
            return readConcernStatus;
        }

        // Inform the storage engine to read from the committed snapshot for the rest of this
        // operation.
        status = txn->recoveryUnit()->setReadFromMajorityCommittedSnapshot();
        if (!status.isOK()) {
            return status;
        }
    } else {
        invariant(readConcernLevel == repl::ReadConcernLevel::kLocalReadConcern);
    }

    DBDirectClient client(txn);
    Query fullQuery(query);
    if (!sort.isEmpty()) {
        fullQuery.sort(sort);
    }
    fullQuery.readPref(readPref.pref, BSONArray());

    try {
        std::unique_ptr<DBClientCursor> cursor =
            client.query(nss.ns().c_str(), fullQuery, limit.get_value_or(0));

        if (!cursor) {
            return {ErrorCodes::OperationFailed,
                    str::stream() << "Failed to establish a cursor for reading " << nss.ns()
                                  << " from local storage"};
        }

        std::vector<BSONObj> documentVector;
        while (cursor->more()) {
            BSONObj document = cursor->nextSafe().getOwned();
            documentVector.push_back(std::move(document));
        }

        return Shard::QueryResponse{std::move(documentVector),
                                    replCoord->getCurrentCommittedSnapshotOpTime()};
    } catch (const DBException& ex) {
        return ex.toStatus();
    }
}
Exemplo n.º 3
0
int binary::last_index_of(
  value byte_, boost::optional<int> start_, boost::optional<int> stop_)
{
  int byte = get_byte(byte_);
  int start = start_.get_value_or(0);
  if (start < 0)
    start = 0;
  int stop = stop_.get_value_or(get_length() - 1);
  if (std::size_t(stop) >= get_length())
    stop = get_length() - 1;

  for (; start <= stop; --stop)
    if (v_data[stop] == byte)
      return stop;
  return -1;
}
Exemplo n.º 4
0
void file::create(char const *name, boost::optional<int> mode) {
  security &sec = security::get();

  if (!sec.check_path(name, security::CREATE))
    throw exception("Could not create file (security)");

  if (creat(name, mode.get_value_or(0666)) < 0)
    throw exception("Could not create file");
}
Exemplo n.º 5
0
 VrpnBasedConnection::VrpnBasedConnection(
     boost::optional<std::string const &> iface, boost::optional<int> port) {
     int myPort = port.get_value_or(0);
     if (iface && !(iface->empty())) {
         m_initConnection(iface->c_str(), myPort);
     } else {
         m_initConnection(nullptr, myPort);
     }
 }
Exemplo n.º 6
0
StatusWith<Shard::QueryResponse> ShardLocal::_exhaustiveFindOnConfig(
    OperationContext* txn,
    const ReadPreferenceSetting& readPref,
    const NamespaceString& nss,
    const BSONObj& query,
    const BSONObj& sort,
    boost::optional<long long> limit) {
    // Set up operation context with majority read snapshot so correct optime can be retrieved.
    Status status = txn->recoveryUnit()->setReadFromMajorityCommittedSnapshot();
    auto replCoord = repl::ReplicationCoordinator::get(txn);

    // Ensure timeout is set on the txn so we don't wait forever for the snapshot.
    // TODO (SERVER-18277): Remove this
    CurOp::get(txn)->ensureStarted();

    // Wait until a snapshot is available.
    while (status == ErrorCodes::ReadConcernMajorityNotAvailableYet) {
        LOG(1) << "Waiting for ReadFromMajorityCommittedSnapshot to become available";
        replCoord->waitUntilSnapshotCommitted(txn, SnapshotName::min());
        status = txn->recoveryUnit()->setReadFromMajorityCommittedSnapshot();
    }

    if (!status.isOK()) {
        return status;
    }

    DBDirectClient client(txn);
    Query fullQuery(query);
    if (!sort.isEmpty()) {
        fullQuery.sort(sort);
    }
    fullQuery.readPref(readPref.pref, BSONArray());

    try {
        std::unique_ptr<DBClientCursor> cursor =
            client.query(nss.ns().c_str(), fullQuery, limit.get_value_or(0));

        if (!cursor) {
            return {ErrorCodes::OperationFailed,
                    str::stream() << "Failed to establish a cursor for reading " << nss.ns()
                                  << " from local storage"};
        }

        std::vector<BSONObj> documentVector;
        while (cursor->more()) {
            BSONObj document = cursor->nextSafe().getOwned();
            documentVector.push_back(std::move(document));
        }

        return Shard::QueryResponse{std::move(documentVector),
                                    replCoord->getCurrentCommittedSnapshotOpTime()};
    } catch (const DBException& ex) {
        return ex.toStatus();
    }
}
Exemplo n.º 7
0
object byte_string::substring(int first, boost::optional<int> last_) {
  if (first < 0)
    first = 0;
  if (std::size_t(first) > get_length())
    first = get_length();
  int last = last_.get_value_or(get_length());
  if (last < 0)
    last = 0;
  if (std::size_t(last) > get_length())
    last = get_length();
  if (last < first)
    std::swap(first, last);
  return create(&get_data()[first], last - first);
}
Exemplo n.º 8
0
std::pair<std::size_t, std::size_t>
binary::length_range(int start, boost::optional<int> length_) {
  if (start < 0)
    start += get_length();
  if (start < 0)
    start = 0;
  if (std::size_t(start) >= get_length())
    start = get_length();
  int length = length_.get_value_or(get_length() - start);
  if (length < 0)
    length = 0;
  if (std::size_t(length) > get_length() - start)
    length = get_length() - start;
  return std::pair<std::size_t, std::size_t>(start, start + length);
}
Exemplo n.º 9
0
void Remote::process(const Coordinate & pos, boost::optional<floatCoordinate> normal) {
    //distance vector
    floatCoordinate deltaPos = pos - state->viewerState->currentPosition;
    const float jumpThreshold = 0.5f * Dataset::current().cubeEdgeLength * state->M * Dataset::current().magnification;//approximately inside sc
    if (deltaPos.length() > jumpThreshold) {
        state->viewer->setPosition(pos);
    } else if (pos != state->viewerState->currentPosition) {
        rotate = normal.is_initialized();
        normal = normal.get_value_or({});
        targetPos = pos;
        recenteringOffset = pos - state->viewerState->currentPosition;
        elapsed.restart();
        timer.start(ms);
        state->viewer->userMoveClear();
        remoteWalk();
    }
}
Exemplo n.º 10
0
Arquivo: Client.cpp Projeto: vcmi/vcmi
void CClient::installNewBattleInterface(std::shared_ptr<CBattleGameInterface> battleInterface, boost::optional<PlayerColor> color, bool needCallback)
{
	boost::unique_lock<boost::recursive_mutex> un(*CPlayerInterface::pim);
	PlayerColor colorUsed = color.get_value_or(PlayerColor::UNFLAGGABLE);

	if(!color)
		privilegedBattleEventReceivers.push_back(battleInterface);

	battleints[colorUsed] = battleInterface;

	if(needCallback)
	{
		logGlobal->trace("\tInitializing the battle interface for player %s", *color);
		auto cbc = std::make_shared<CBattleCallback>(color, this);
		battleCallbacks[colorUsed] = cbc;
		battleInterface->init(cbc);
	}
}
Exemplo n.º 11
0
Arquivo: Client.cpp Projeto: vcmi/vcmi
void CClient::installNewPlayerInterface(std::shared_ptr<CGameInterface> gameInterface, boost::optional<PlayerColor> color, bool battlecb)
{
	boost::unique_lock<boost::recursive_mutex> un(*CPlayerInterface::pim);
	PlayerColor colorUsed = color.get_value_or(PlayerColor::UNFLAGGABLE);

	if(!color)
		privilegedGameEventReceivers.push_back(gameInterface);

	playerint[colorUsed] = gameInterface;

	logGlobal->trace("\tInitializing the interface for player %s", colorUsed);
	auto cb = std::make_shared<CCallback>(gs, color, this);
	callbacks[colorUsed] = cb;
	battleCallbacks[colorUsed] = cb;
	gameInterface->init(cb);

	installNewBattleInterface(gameInterface, color, battlecb);
}
Exemplo n.º 12
0
StatusWith<std::vector<ChunkType>> readShardChunks(OperationContext* opCtx,
                                                   const NamespaceString& nss,
                                                   const BSONObj& query,
                                                   const BSONObj& sort,
                                                   boost::optional<long long> limit,
                                                   const OID& epoch) {
    // Query to retrieve the chunks.
    Query fullQuery(query);
    fullQuery.sort(sort);

    try {
        DBDirectClient client(opCtx);

        std::string chunkMetadataNs = ChunkType::ShardNSPrefix + nss.ns();
        std::unique_ptr<DBClientCursor> cursor =
            client.query(chunkMetadataNs, fullQuery, limit.get_value_or(0));

        if (!cursor) {
            return {ErrorCodes::OperationFailed,
                    str::stream() << "Failed to establish a cursor for reading " << chunkMetadataNs
                                  << " from local storage"};
        }

        std::vector<ChunkType> chunks;
        while (cursor->more()) {
            BSONObj document = cursor->nextSafe().getOwned();
            auto statusWithChunk = ChunkType::fromShardBSON(document, epoch);
            if (!statusWithChunk.isOK()) {
                return {statusWithChunk.getStatus().code(),
                        str::stream() << "Failed to parse chunk '" << document.toString()
                                      << "' due to "
                                      << statusWithChunk.getStatus().reason()};
            }
            chunks.push_back(std::move(statusWithChunk.getValue()));
        }

        return chunks;
    } catch (const DBException& ex) {
        return ex.toStatus();
    }
}
Exemplo n.º 13
0
std::pair<std::size_t, std::size_t>
binary::range(int begin, boost::optional<int> end_) {
  int n = get_length();

  if (begin < 0)
    begin = n + begin;

  int end = end_.get_value_or(n);
  if (end < 0)
    end = n + end;

  if (begin > n)
    begin = n;
  if (end > n)
    end = n;

  if (end < begin)
    end = begin;

  return std::pair<std::size_t, std::size_t>(begin, end);
}