コード例 #1
0
ファイル: zm_thread.cpp プロジェクト: schumi-chu/zm_nvr
bool Condition::wait( int secs )
{
    // Locking done outside of this function
    Debug( 8, "Waiting for %d seconds", secs );
    struct timespec timeout = getTimeout( secs );
    if ( pthread_cond_timedwait( &mCondition, mMutex.getMutex(), &timeout ) < 0 && errno != ETIMEDOUT )
        throw ThreadException( stringtf( "Unable to timedwait pthread condition: %s", strerror(errno) ) );
    return( errno != ETIMEDOUT );
}
コード例 #2
0
StreamSocket HTTPClientSession::proxyConnect() {
    HTTPClientSession proxySession(getProxyHost(), getProxyPort());
    proxySession.setTimeout(getTimeout());

    std::string targetAddress(_host);
    targetAddress.append(":");
    NumberFormatter::append(targetAddress, _port);

    throw NotImplementedException("HTTPClientSession::proxyConnect() not implement");
}
コード例 #3
0
ファイル: config.cpp プロジェクト: hernando/Equalizer
bool Config::_cmdCheckFrame( co::ICommand& cmd )
{
    const int64_t lastInterval = getServer()->getTime() - _lastCheck;
    _lastCheck = getServer()->getTime();

    co::ObjectICommand command( cmd );
    LBVERB << "Check nodes for frame finish " << command << std::endl;

    const uint32_t frameNumber = command.read< uint32_t >();
    const uint32_t timeout = getTimeout();

    bool retry = false;
    const Nodes& nodes = getNodes();
    for( Nodes::const_iterator i = nodes.begin(); i != nodes.end(); ++i )
    {
        Node* node = *i;
        if( node->isRunning() && node->isActive() )
        {
            co::NodePtr netNode = node->getNode();
            if ( netNode->isClosed() )
                continue;

            if ( node->getFinishedFrame() >= frameNumber )
                continue;

            const int64_t interval = getServer()->getTime() -
                                     netNode->getLastReceiveTime();
            getLocalNode()->ping( netNode );

            // TODO?: handle timed out nodes.
            // currently we get a false positive due to lack of communication
            // from client to server. we do not get ping responses in time.
            // running clients should inform the server about their status with
            // a timeout/2 period.

            if ( interval > timeout && lastInterval <= timeout )
                continue;

            // retry
            LBINFO << "Retry waiting for node " << node->getName()
                   << " to finish frame " << frameNumber << " last seen "
                   << interval << " ms ago" << " last run " << lastInterval
                   << std::endl;
            retry = true;
            // else node timeout
        }
    }

    if( retry )
        return true;

    send( command.getRemoteNode(), fabric::CMD_CONFIG_FRAME_FINISH )
        << _currentFrame;
    return true;
}
コード例 #4
0
ファイル: openssl.cpp プロジェクト: mwuehrer/tntnet
  void OpensslStream::shutdown() const
  {
    cxxtools::MutexLock lock(mutex);

    int n, err;

    do
    {
      log_debug("SSL_shutdown(" << _ssl << ')');
      n = ::SSL_shutdown(_ssl);
      log_debug("ssl-shutdown => " << n);
    } while (n == 0);

    if (n == 1)
      return;

    if (n == -1)
    {
      log_debug("SSL_get_error(" << _ssl << ", " << n << ')');

      err = SSL_get_error(_ssl, n);

      if (err != SSL_ERROR_WANT_READ
       && err != SSL_ERROR_WANT_WRITE)
        checkSslError();

      if (getTimeout() == 0)
      {
        log_debug("shutdown-timeout");
        throw cxxtools::IOTimeout();
      }
    }

    do
    {
      log_debug("poll " << (err == SSL_ERROR_WANT_WRITE ? "POLLIN|POLLOUT" : "POLLIN"));
      poll(err == SSL_ERROR_WANT_WRITE ? POLLIN|POLLOUT : POLLIN);

      log_debug("SSL_shutdown(" << _ssl << ')');
      n = ::SSL_shutdown(_ssl);
      log_debug("SSL_shutdown returns " << n);

      if (n == 1)
        return;

      if (n == 0)
        continue;

      checkSslError();
      err = SSL_get_error(_ssl, n);

    } while (err == SSL_ERROR_WANT_READ
          || err == SSL_ERROR_WANT_WRITE);
  }
コード例 #5
0
ファイル: config.cpp プロジェクト: yarda/Equalizer
uint32_t Config::finishFrame()
{
    ClientPtr client = getClient();
    const uint32_t latency = getLatency();
    const uint32_t frameToFinish = (_currentFrame >= latency) ? 
                                       _currentFrame - latency : 0;

    ConfigStatistics stat( Statistic::CONFIG_FINISH_FRAME, this );
    stat.event.data.statistic.frameNumber = frameToFinish;
    {
        ConfigStatistics waitStat( Statistic::CONFIG_WAIT_FINISH_FRAME, this );
        waitStat.event.data.statistic.frameNumber = frameToFinish;
        
        // local draw sync
        if( _needsLocalSync( ))
            while( _unlockedFrame < _currentFrame )
                client->processCommand();

        // local node finish (frame-latency) sync
        const Nodes& nodes = getNodes();
        if( !nodes.empty( ))
        {
            EQASSERT( nodes.size() == 1 );
            const Node* node = nodes.front();

            while( node->getFinishedFrame() < frameToFinish )
                client->processCommand();
        }

        // global sync
        const uint32_t timeout = getTimeout();
        co::base::Clock time;
        const int64_t pingTimeout = co::Global::getKeepaliveTimeout();

        while( !_finishedFrame.timedWaitGE( frameToFinish, pingTimeout ))
        {
            if( time.getTime64() >= timeout || !getLocalNode()->pingIdleNodes())
            {
                EQWARN << "Timeout waiting for nodes to finish frame " 
                       << frameToFinish << std::endl;
                break;
            }
        }
    }

    handleEvents();
    _updateStatistics( frameToFinish );
    _releaseObjects();

    EQLOG( co::base::LOG_ANY ) << "---- Finished Frame --- " << frameToFinish
                               << " (" << _currentFrame << ')' << std::endl;
    return frameToFinish;
}
コード例 #6
0
ファイル: Wind_API.cpp プロジェクト: Rolandklyuan/q_Wind
WIND_API K K_DECL setTimeout(K timeout) {
	if (timeout == K_NIL) {
		return q::error2q("nil timeout");
	}
	try {
		Wind::ASYNC_TIMEOUT = std::chrono::milliseconds(1) * q::q2Dec(timeout);
	}
	catch (std::string const& error) {
		return q::error2q(error);
	}
	return getTimeout(K_NIL);
}
コード例 #7
0
ファイル: openssl.cpp プロジェクト: mwuehrer/tntnet
  int OpensslStream::sslRead(char* buffer, int bufsize) const
  {
    // I had crashes without this (and the lock in sslWrite) lock:
    // openssl should be thread-safe, with the installed callbacks, but I did not
    // get it working
    cxxtools::MutexLock lock(mutex);

    log_debug("read");

    int n;
    int err;

    // non-blocking/with timeout

    // try read
    log_debug("SSL_read(" << _ssl << ", buffer, " << bufsize << ')');
    n = ::SSL_read(_ssl, buffer, bufsize);
    log_debug("ssl-read => " << n);

    if (n > 0)
      return n;

    log_debug("SSL_get_error(" << _ssl << ", " << n << ')');
    if ((err = SSL_get_error(_ssl, n)) != SSL_ERROR_WANT_READ
     && err != SSL_ERROR_WANT_WRITE)
      checkSslError();

    if (getTimeout() == 0)
    {
      log_debug("read-timeout");
      throw cxxtools::IOTimeout();
    }

    // no read, timeout > 0 - poll
    do
    {
      poll(SSL_get_error(_ssl, n) == SSL_ERROR_WANT_WRITE
                  ? POLLIN|POLLOUT : POLLIN);

      log_debug("SSL_read(" << _ssl << ", buffer, " << bufsize << ')');
      n = ::SSL_read(_ssl, buffer, bufsize);
      log_debug("SSL_read returns " << n);
      checkSslError();

    } while (n < 0
       && ((err = SSL_get_error(_ssl, n)) == SSL_ERROR_WANT_READ
        || err == SSL_ERROR_WANT_WRITE
        || (err == SSL_ERROR_SYSCALL && errno == EAGAIN)));

    return n;
  }
コード例 #8
0
bool WaitingList::clientLogin(const Player* player)
{
	if (player->hasFlag(PlayerFlag_CanAlwaysLogin) || player->getAccountType() >= ACCOUNT_TYPE_GAMEMASTER) {
		return true;
	}

	uint32_t maxPlayers = static_cast<uint32_t>(g_config.getNumber(ConfigManager::MAX_PLAYERS));
	if (maxPlayers == 0 || (priorityWaitList.empty() && waitList.empty() && g_game.getPlayersOnline() < maxPlayers)) {
		return true;
	}

	WaitingList::cleanupList(priorityWaitList);
	WaitingList::cleanupList(waitList);

	uint32_t slot;

	WaitListIterator it = findClient(player, slot);
	if (it != waitList.end()) {
		if ((g_game.getPlayersOnline() + slot) <= maxPlayers) {
			//should be able to login now
			waitList.erase(it);
			return true;
		}

		//let them wait a bit longer
		it->timeout = OTSYS_TIME() + (getTimeout(slot) * 1000);
		return false;
	}

	slot = priorityWaitList.size();
	if (player->isPremium()) {
		priorityWaitList.emplace_back(OTSYS_TIME() + (getTimeout(slot + 1) * 1000), player->getGUID());
	} else {
		slot += waitList.size();
		waitList.emplace_back(OTSYS_TIME() + (getTimeout(slot + 1) * 1000), player->getGUID());
	}
	return false;
}
コード例 #9
0
ファイル: Driver.hpp プロジェクト: retlaw84/dune
    //! Read the contents of the MT SBD message buffer.
    //! @param[in] data buffer to hold binary data.
    //! @param[in] data_size size of binary data buffer.
    //! @return number of bytes read.
    unsigned
    readBufferMT(uint8_t* data, unsigned data_size)
    {
        ReadMode saved_read_mode = getReadMode();
        Counter<double> timer(getTimeout());
        uint8_t bfr[2] = {0};
        uint8_t ccsum[2] = {0};
        unsigned length = 0;

        try
        {
            // Prepare to read raw data.
            setReadMode(READ_MODE_RAW);

            // Send command.
            sendAT("+SBDRB");

            // Read incoming data length.
            length = getBufferSizeMT(timer);
            getTask()->spew("reading %u bytes of SBD binary data", length);

            // Read data.
            if (length > data_size)
                throw BufferTooSmall(data_size, length);

            if (length > 0)
            {
                readRaw(timer, data, length);
                computeChecksum(data, length, ccsum);
            }

            // Read and validate.
            readRaw(timer, bfr, 2);
            if ((bfr[0] != ccsum[0]) || (bfr[1] != ccsum[1]))
                throw Hardware::InvalidChecksum(bfr, ccsum);

            setReadMode(saved_read_mode);
            expectOK();
        }
        catch (...)
        {
            setReadMode(saved_read_mode);
            throw;
        }

        return length;
    }
コード例 #10
0
ファイル: HTTPClientSession.cpp プロジェクト: Adoni/WiEngine
StreamSocket HTTPClientSession::proxyConnect()
{
	HTTPClientSession proxySession(getProxyHost(), getProxyPort());
	proxySession.setTimeout(getTimeout());
	SocketAddress targetAddress(getHost(), getPort());
	HTTPRequest proxyRequest(HTTPRequest::HTTP_CONNECT, targetAddress.toString(), HTTPMessage::HTTP_1_1);
	HTTPResponse proxyResponse;
	proxyRequest.set("Proxy-Connection", "keep-alive");
	proxyRequest.set("Host", getHost());
	proxyAuthenticateImpl(proxyRequest);
	proxySession.setKeepAlive(true);
	proxySession.sendRequest(proxyRequest);
	proxySession.receiveResponse(proxyResponse);
	if (proxyResponse.getStatus() != HTTPResponse::HTTP_OK)
		throw HTTPException("Cannot establish proxy connection", proxyResponse.getReason());
	return proxySession.detachSocket();
}
コード例 #11
0
ファイル: socket.cpp プロジェクト: maekitalo/cxxtools
void Socket::postAccept()
{
    log_trace("post accept");
    if (!_certificateFile.empty())
    {
        cxxtools::Timespan t = getTimeout();
        setTimeout(cxxtools::Seconds(10));
        endSslAccept();
        setTimeout(t);
    }

    _accepted = true;

    _stream.buffer().beginRead();

    log_debug("accepted");
}
コード例 #12
0
ファイル: Channel.440.cpp プロジェクト: pheest/pvaPy
void Channel::stopMonitor()
{
    epics::pvData::Lock lock(monitorThreadMutex);
    if (monitorThreadDone) {
        logger.debug("Monitor thread is not running");
        return;
    }
    monitorThreadDone = true;
    logger.debug("Stopping monitor");
    monitor->stop();
    logger.debug("Monitor stopped, waiting for thread exit");
    ChannelMonitorRequesterImpl* monitorRequester = getMonitorRequester();
    monitorRequester->cancelGetQueuedPvObject();
    monitorThreadExitEvent.wait(getTimeout());
    logger.debug("Clearing requester queue");
    monitorRequester->clearPvObjectQueue();
}
コード例 #13
0
ULXR_API_IMPL0
  TcpIpConnection::TcpIpConnection(bool I_am_server, const CppString &dom, unsigned prt)
  : Connection()
  , pimpl(new PImpl)
{
  ULXR_TRACE(ULXR_PCHAR("TcpIpConnection(bool, string, uint)") << dom << ULXR_PCHAR(" ") << pimpl->port);
  init(prt);

  pimpl->remote_name = dom;

  struct hostent *hp = getHostAdress(dom);
  if (hp == 0)
    throw ConnectionException(SystemError,
                              ulxr_i18n(ULXR_PCHAR("Host adress not found: ")) + pimpl->serverdomain, 500);
  memcpy(&(pimpl->hostdata.sin_addr), hp->h_addr_list[0], hp->h_length);

  if (I_am_server)
  {
    pimpl->server_data = new ServerSocketData(socket(AF_INET, SOCK_STREAM, IPPROTO_TCP));
    if (getServerHandle() < 0)
      throw ConnectionException(SystemError,
                                ulxr_i18n(ULXR_PCHAR("Could not create socket: "))
                                     + ULXR_GET_STRING(getErrorString(getLastError())), 500);
#ifdef ULXR_REUSE_SOCKET
    int sockOpt = 1;
    if (::setsockopt(getServerHandle(), SOL_SOCKET, SO_REUSEADDR,
                     (const char*)&sockOpt, sizeof(sockOpt)) < 0)
      throw ConnectionException(SystemError,
                                ulxr_i18n(ULXR_PCHAR("Could not set reuse flag for socket: "))
                                     + ULXR_GET_STRING(getErrorString(getLastError())), 500);
#endif

    int iOptVal = getTimeout() * 1000;
    int iOptLen = sizeof(int);
    ::setsockopt(getServerHandle(), SOL_SOCKET, SO_RCVTIMEO, (char*)&iOptVal, iOptLen);
    ::setsockopt(getServerHandle(), SOL_SOCKET, SO_SNDTIMEO, (char*)&iOptVal, iOptLen);

    if((::bind(getServerHandle(), (sockaddr*) &pimpl->hostdata, sizeof(pimpl->hostdata))) < 0)
      throw ConnectionException(SystemError,
                                ulxr_i18n(ULXR_PCHAR("Could not bind adress: "))
                                     + ULXR_GET_STRING(getErrorString(getLastError())), 500);

    listen(getServerHandle(), 5);
  }
}
コード例 #14
0
ULXR_API_IMPL(void) TcpIpConnection::open()
{
  ULXR_TRACE(ULXR_PCHAR("open"));
  if (isOpen() )
    throw RuntimeException(ApplicationError,
                           ulxr_i18n(ULXR_PCHAR("Attempt to open an already open connection")));

  if (pimpl->server_data != 0)
    throw ConnectionException(SystemError,
                              ulxr_i18n(ULXR_PCHAR("Connection is NOT prepared for client mode")), 500);
//  resetConnection();

  setHandle(socket(AF_INET, SOCK_STREAM, IPPROTO_TCP));
  if (getHandle() < 0)
    throw ConnectionException(SystemError,
                              ulxr_i18n(ULXR_PCHAR("Could not create socket: "))
                                   + ULXR_GET_STRING(getErrorString(getLastError())), 500);

  int iOptVal = getTimeout() * 1000;
  int iOptLen = sizeof(int);
  ::setsockopt(getHandle(), SOL_SOCKET, SO_RCVTIMEO, (char*)&iOptVal, iOptLen);
  ::setsockopt(getHandle(), SOL_SOCKET, SO_SNDTIMEO, (char*)&iOptVal, iOptLen);
  doTcpNoDelay();

  if(connect(getHandle(), (struct sockaddr *)&pimpl->hostdata, sizeof(pimpl->hostdata)) < 0)
    throw ConnectionException(SystemError,
                              ulxr_i18n(ULXR_PCHAR("Could not connect: "))
                                   + ULXR_GET_STRING(getErrorString(getLastError())), 500);

  ULXR_TRACE(ULXR_PCHAR("/open.peername"));
#ifdef ULXR_ENABLE_GET_PEERNAME
  pimpl->remotedata_len = sizeof(pimpl->remotedata);
  if(getpeername(getHandle(),
                 (struct sockaddr *)&pimpl->remotedata,
                 &pimpl->remotedata_len)<0)
    throw ConnectionException(SystemError,
                              ulxr_i18n(ULXR_PCHAR("Could not get peer data: "))
                                   + ULXR_GET_STRING(getErrorString(getLastError())), 500);
#ifdef __BORLANDC__
  pimpl->remote_name = ULXR_PCHAR("<remote-host>");  // FIXME, not working
  host = 0;
  host;
#else
  else
  {
コード例 #15
0
ファイル: HTTPServerSession.cpp プロジェクト: Adoni/WiEngine
bool HTTPServerSession::hasMoreRequests()
{
	if (!socket().impl()->initialized()) return false;

	if (_firstRequest)
	{
		_firstRequest = false;
		--_maxKeepAliveRequests;
		return socket().poll(getTimeout(), Socket::SELECT_READ);
	}
	else if (_maxKeepAliveRequests != 0 && getKeepAlive())
	{
		if (_maxKeepAliveRequests > 0) 
			--_maxKeepAliveRequests;
		return buffered() > 0 || socket().poll(_keepAliveTimeout, Socket::SELECT_READ);
	}
	else return false;
}
コード例 #16
0
ファイル: Strategy.cpp プロジェクト: el-bart/ACARM-ng
void Strategy::processImpl(Node               n,
                           NodesTimeoutQueue &ntq,
                           BackendProxy      &bp)
{
  // get host from this node.
  HostPtr h=getReportedHost(n);
  // if there are no interesting entries, simply skip it.
  if( h.get()==NULL )
    return;
  // prepare entry to compare with
  const NodeEntry thisEntry(n, Data(h) );

  // check if it can be correlated with other nodes
  for(NodesTimeoutQueue::iterator it=ntq.begin(); it!=ntq.end(); ++it)
  {
    try
    {
      // stop after first successful correlation.
      if( tryCorrelate(ntq, bp, thisEntry, it) )
        return;
    }
    catch(const Commons::Exception &ex)
    {
      LOGMSG_INFO_S(log_) << "exception ("
                          << ex.getTypeName()
                          << ") has been thrown: '"
                          << ex.what()
                          << "' - proceeding with processing next element";
      // on error, continue with next element...
    }
    catch(const std::exception &ex)
    {
      LOGMSG_INFO_S(log_) << "exception (std::exception) has been thrown: '"
                          << ex.what()
                          << "' - proceeding with processing next element";
      // on error, continue with next element...
    }
  } // for(nodes in timeout queue)

  // if element cannot be correlated at the moment, add it to queue - maybe
  // we'll have better luck next time...
  ntq.update(thisEntry, getTimeout() );
}
コード例 #17
0
void HTTPSClientSession::connect(const SocketAddress& address)
{
	if (getProxyHost().empty())
	{
		SecureStreamSocket sss(socket());
		if (_pContext->sessionCacheEnabled())
		{
			sss.useSession(_pSession);
		}
		HTTPSession::connect(address);
		if (_pContext->sessionCacheEnabled())
		{
			_pSession = sss.currentSession();
		}
	}
	else
	{
		HTTPClientSession proxySession(address);
		proxySession.setHost(getProxyHost());
		proxySession.setPort(getProxyPort());
		proxySession.setTimeout(getTimeout());
		SocketAddress targetAddress(getHost(), getPort());
		HTTPRequest proxyRequest(HTTPRequest::HTTP_CONNECT, targetAddress.toString(), HTTPMessage::HTTP_1_1);
		HTTPResponse proxyResponse;
		proxyRequest.set("Proxy-Connection", "keep-alive");
		proxyRequest.set("Host", getHost());
		proxyAuthenticateImpl(proxyRequest);
		proxySession.setKeepAlive(true);
		proxySession.sendRequest(proxyRequest);
		proxySession.receiveResponse(proxyResponse);
		if (proxyResponse.getStatus() != HTTPResponse::HTTP_OK)
			throw HTTPException("Cannot establish proxy connection", proxyResponse.getReason());
		
		StreamSocket proxySocket(proxySession.detachSocket());
		SecureStreamSocket secureSocket = SecureStreamSocket::attach(proxySocket, getHost(), _pContext, _pSession);
		attachSocket(secureSocket);
		if (_pContext->sessionCacheEnabled())
		{
			_pSession = secureSocket.currentSession();
		}
	}
}
コード例 #18
0
  void Stream::connect(const std::string& ipaddr, unsigned short int port)
  {
    log_debug("connect to " << ipaddr << " port " << port);

    Addrinfo ai(ipaddr, port);

    log_debug("do connect");
    for (Addrinfo::const_iterator it = ai.begin(); it != ai.end(); ++it)
    {
      try
      {
        Socket::create(it->ai_family, SOCK_STREAM, 0);
      }
      catch (const Exception&)
      {
        continue;
      }

      if (::connect(getFd(), it->ai_addr, it->ai_addrlen) == 0)
      {
        // save our information
        memmove(&peeraddr, it->ai_addr, it->ai_addrlen);
        return;
      }

      if (errno == EINPROGRESS && getTimeout() > 0)
      {
        poll(POLLOUT);

        if (::connect(getFd(), it->ai_addr, it->ai_addrlen) == 0)
        {
          // save our information
          memmove(&peeraddr, it->ai_addr, it->ai_addrlen);
          return;
        }
      }

    }

    throw Exception("connect");
  }
コード例 #19
0
void IntervalThread::run()
{
	VirtualMachine &vm = VirtualMachine::getInstance();
	myReset = false;
	bool localReset = myReset;

	while (true)
	{
		usleep(getTimeout()*1000);

		myResetMutex.lock();
		localReset = myReset;
		myReset = false;
		myResetMutex.unlock();
		
		if (!localReset)
		{
			vm.queueExpression("Interval.triggerIntervalCallback(" + itos(myId) + ");");
		}
	}
}
コード例 #20
0
ファイル: Channel.440.cpp プロジェクト: pheest/pvaPy
bool Channel::processMonitorElement() 
{
    //epics::pvData::Lock lock(monitorElementProcessingMutex);
    if (monitorThreadDone) {
        return true;
    }

    // Handle possible exceptions while retrieving data from empty queue.
    try {
        PvObject pvObject = getMonitorRequester()->getQueuedPvObject(getTimeout());
        callSubscribers(pvObject);
    }
    catch (const ChannelTimeout& ex) {
        // Ignore, no changes received.
    }
    catch (const std::exception& ex) {
        // Not good.
        logger.error("Exception caught in monitor thread: %s", ex.what());
    }
    return false;
}
コード例 #21
0
ULXR_API_IMPL0 TcpIpConnection::TcpIpConnection(bool I_am_server, long adr, unsigned prt)
  : Connection()
  , pimpl(new PImpl)
{
  ULXR_TRACE(ULXR_PCHAR("TcpIpConnection(bool, long, uint)") << adr << ULXR_PCHAR(" ") << pimpl->port);
  init(prt);

  pimpl->hostdata.sin_addr.s_addr = htonl(adr);

  if (I_am_server)
  {
    pimpl->server_data = new ServerSocketData(socket(AF_INET, SOCK_STREAM, IPPROTO_TCP));
    if (getServerHandle() < 0)
      throw ConnectionException(SystemError,
                                ulxr_i18n(ULXR_PCHAR("Could not create socket: "))
                                     + ULXR_GET_STRING(getErrorString(getLastError())), 500);

#ifdef ULXR_REUSE_SOCKET
    int sockOpt = 1;
    if (::setsockopt(getServerHandle(), SOL_SOCKET, SO_REUSEADDR,
                     (const char*)&sockOpt, sizeof(sockOpt)) < 0)
      throw ConnectionException(SystemError,
                                      ulxr_i18n(ULXR_PCHAR("Could not set reuse flag for socket: "))
                                     + ULXR_GET_STRING(getErrorString(getLastError())), 500);
#endif

    int iOptVal = getTimeout() * 1000;
    int iOptLen = sizeof(int);
    ::setsockopt(getServerHandle(), SOL_SOCKET, SO_RCVTIMEO, (char*)&iOptVal, iOptLen);
    ::setsockopt(getServerHandle(), SOL_SOCKET, SO_SNDTIMEO, (char*)&iOptVal, iOptLen);

    if((::bind(getServerHandle(), (sockaddr*) &pimpl->hostdata, sizeof(pimpl->hostdata))) < 0)
      throw ConnectionException(SystemError,
                                ulxr_i18n(ULXR_PCHAR("Could not bind adress: "))
                                     + ULXR_GET_STRING(getErrorString(getLastError())), 500);

    ::listen(getServerHandle(), 5);
  }
}
コード例 #22
0
ファイル: Strategy.cpp プロジェクト: el-bart/ACARM-ng
bool Strategy::tryCorrelate(NodesTimeoutQueue           &ntq,
                            BackendProxy                &bp,
                            const NodeEntry             &thisEntry,
                            NodesTimeoutQueue::iterator  it)
{
  // skip self
  if( *it==thisEntry )
    return false;
  // check if node represents report on the same host (by IP address)
  if( thisEntry.t_.host_->getIP()!=it->t_.host_->getIP() )
    return false;

  // ok - we've got a match!

  // if node's leaf, create new node and correlate leafs there.
  if( it->node_->isLeaf() )
  {
    const BackendProxy::ChildrenVector cv(it->node_, thisEntry.node_);
    const MetaAlertPtrNN ma( new MetaAlert( getMetaAlertName(thisEntry.t_.host_),
                                            MetaAlert::SeverityDelta(0),
                                            MetaAlert::CertaintyDelta(0),
                                            ReferenceURLPtr(),
                                            Timestamp() ) );
    ntq.dismiss(it);                                // mark source element as already used
    GraphNodePtrNN  newNode=bp.correlate(ma, cv);   // add new, correlated element
    const NodeEntry newEntry(newNode, thisEntry.t_);// use the same reported host entry
    ntq.update(newEntry, getTimeout() );            // add newly correlated entry
  }
  else
    bp.addChild(it->node_, thisEntry.node_);  // add new alert to already
                                              // correlated in one set

  // if we're here, it means that we were able to correlate and may exit
  // in glory now.
  // NOTE: we intentionaly skip adding new entry to queue, since it has
  //       been already correlated, therefore will not be used anymore.
  return true;
}
コード例 #23
0
   INT32 _coordCMDListLobs::execute( MsgHeader *pMsg,
                                     pmdEDUCB *cb,
                                     INT64 &contextID,
                                     rtnContextBuf *buf )
   {
      INT32 rc = SDB_OK ;
      SDB_RTNCB *pRtncb = pmdGetKRCB()->getRTNCB() ;

      CHAR *pQuery = NULL ;
      BSONObj query ;

      rtnContextCoord *context = NULL ;
      coordQueryOperator queryOpr( TRUE ) ;
      coordQueryConf queryConf ;
      coordSendOptions sendOpt ;

      contextID = -1 ;

      rc = msgExtractQuery( (CHAR*)pMsg, NULL, NULL,
                            NULL, NULL, &pQuery,
                            NULL, NULL, NULL ) ;

      PD_RC_CHECK( rc, PDERROR, "Parse message failed, rc: %d", rc ) ;

      try
      {
         query = BSONObj( pQuery ) ;
         BSONElement ele = query.getField( FIELD_NAME_COLLECTION ) ;
         if ( String != ele.type() )
         {
            PD_LOG( PDERROR, "invalid obj of list lob:%s",
                    query.toString( FALSE, TRUE ).c_str() ) ;
            rc = SDB_INVALIDARG ;
            goto error ;
         }
         queryConf._realCLName = ele.valuestr() ;
      }
      catch ( std::exception &e )
      {
         PD_LOG( PDERROR, "unexpected err happened:%s", e.what() ) ;
         rc = SDB_SYS ;
         goto error ;
      }

      rc = queryOpr.init( _pResource, cb, getTimeout() ) ;
      if ( rc )
      {
         PD_LOG( PDERROR, "Init query operator failed, rc: %d", rc ) ;
         goto error ;
      }

      queryConf._openEmptyContext = TRUE ;
      queryConf._allCataGroups = TRUE ;
      rc = queryOpr.queryOrDoOnCL( pMsg, cb, &context,
                                   sendOpt, &queryConf, buf ) ;
      PD_RC_CHECK( rc, PDERROR, "List lobs[%s] on groups failed, rc: %d",
                   queryConf._realCLName.c_str(), rc ) ;

      contextID = context->contextID() ;

   done:
      return rc ;
   error:
      if ( context )
      {
         pRtncb->contextDelete( context->contextID(), cb ) ;
      }
      goto done ;
   }
コード例 #24
0
  Stream::size_type Stream::read(char* buffer, Stream::size_type bufsize) const
  {
    ssize_t n;

    if (getTimeout() < 0)
    {
      // blocking read
      do
      {
        log_debug("blocking read");
        n = ::read(getFd(), buffer, bufsize);
        log_debug("blocking read ready, return " << n);
      } while (n < 0 && errno == EINTR);

      if (n < 0 && errno != ECONNRESET)
        throw Exception(errno, "read");
    }
    else
    {
      // non-blocking read

      // try reading without timeout
      do
      {
        log_debug("non blocking read fd=" << getFd());
        n = ::read(getFd(), buffer, bufsize);
        log_debug("non blocking read returns " << n);
      } while (n < 0 && errno == EINTR);

      if (n < 0)
      {
        // no data available

        if (errno == EAGAIN)
        {
          if (getTimeout() == 0)
          {
            log_debug("read timeout (" << getTimeout() << "ms)");
            throw Timeout();
          }

          if (poll(POLLIN) & POLLHUP)
          {
            log_debug("eof in read");
            return 0;
          }

          do
          {
            log_debug("read");
            n = ::read(getFd(), buffer, bufsize);
            log_debug("read returns " << n);
          } while (n < 0 && errno == EINTR);

          if (n < 0)
            throw Exception("read");
        }
        else if (errno != 0 && errno != ECONNRESET)
          throw Exception("read");
      }

    }

    return n < 0 ? 0 : n;
  }
コード例 #25
0
ファイル: Service.cpp プロジェクト: kleopatra999/finx
void Service::checkServiceStart(void)
{
  int status = 0;
  int wpid;
  int options = WNOHANG | WUNTRACED;

  static int timeout;

  //
  // The child is the service launched by nxservice.
  // Each second we check for the child exit status.
  // If the child doesn't return, we use its logs to
  // retrieve the status.
  //

  #ifdef DEBUG
  logUser("Service::checkServiceStart: going to check the '%s' service status", getType());
  #endif

  for (;;)
  {
    #ifdef TEST
    logUser("Service::checkServiceStart: waiting for child pid %d.", getPid());
    #endif

    wpid = waitpid(getPid(), &status, options);

    if (wpid == -1)
    {
      #ifdef WARNING
      logUser("WARNING! Waitpid returns error: %d.", EGET());
      #endif

      //
      // "The process specified does not exist or is not
      // a child of the calling process."
      // We don't know why this happened, but we can try
      // to return a successful state.
      //

      exit(0);
    }
    else if (wpid == 0)
    {
      //
      // The child's state is not changed. Let's check
      // if there is a reason to believe it is running.
      //

      if (checkStart())
      {
        #ifdef DEBUG
        logUser("Service::checkServiceStart: '%s' successfully starts after waiting "
                    "for %d seconds.", getType(), timeout / 1000);
        #endif

        exit(0);
      }
    }
    else
    {
      //
      // The child's state changes, let's figure out why.
      //

      if (WIFSTOPPED(status))
      {
        #ifdef DEBUG
        logUser("Service::checkServiceStart: '%s' service has been stopped with signal %d "
                    "after waiting for %d seconds.", getType(), WSTOPSIG(status),
                        timeout / 1000);
        #endif

        exit(0);
      }
      else if (WIFEXITED(status))
      {
        #ifdef DEBUG
        logUser("Service::checkServiceStart: '%s' service exits with status %d after "
                    "waiting for %d seconds.", getType(), WEXITSTATUS(status),
                        timeout / 1000);
        #endif

        exit(WEXITSTATUS(status));
      }
      else if (WIFSIGNALED(status))
      {
        #ifdef DEBUG
        logUser("Service::checkServiceStart: '%s' service terminates with signal %d after "
                    "waiting for %d seconds.", getType(), WTERMSIG(status),
                        timeout / 1000);
        #endif

        //
        // FIXME: Do we need to better classify the signals?
        //

        switch (WTERMSIG(status))
        {
          case SIGABRT:
          case SIGSEGV:
          case SIGKILL:
            exit(1);
          default:
            exit(0);
        }
      }
      else
      {
        #ifdef WARNING
        logUser("Service::checkServiceStart: WARNING! Waitpid returns an unknown status: "
                    "%d.", status);
        #endif
      }
    }

    usleep(SERVICE_START_INTERVAL * 1000);

    timeout += SERVICE_START_INTERVAL;

    if (timeout / 1000 >= getTimeout())
    {
      #ifdef WARNING
      logUser("Service::checkServiceStart: WARNING! Assuming the '%s' starts after "
                  "waiting for %d seconds.", getType(), timeout / 1000);
      #endif

      exit(0);
    }
  }
}
コード例 #26
0
int main (int argc, char **argv)
{
	int c;
	int timeInSecs;
	int retval = 0;

	if (argc < 2) {
		showHelp(argv[0]);		// show help info and exit
		exit(-1);
	}

	while (1)
	{
		int option_index = 0;
		c = getopt_long(argc, argv, "ghqSt:v",
			       	long_options, &option_index);

		if (c == -1) // end of the options.
			break;

		switch (c)
		{
			case 0:
				break;

			case 'g':
				timeInSecs = getTimeout();
				if (!quiet_flag)
					printf(
					"Timeout is %d seconds\n",
					timeInSecs);
				retval = timeInSecs;
				break;

			case 'h':
				showHelp(argv[0]);  // show help info and exit
				break;

			case 's':
				shutdown();
				break;

			case 'S':
				retval = status();
				if (!quiet_flag) {
					printf("Status = %s (%d)\n",
						reasonToString(retval), retval);
				}
				break;

			case 't':
				timeInSecs = atoi(optarg);
				setTimeout(timeInSecs);
				timeInSecs = getTimeout();
				if (!quiet_flag)
					printf(
					"Timeout is %d Seconds\n",
					timeInSecs);
				break;

			default:
				showHelp(argv[0]);
				exit(-1);
		}
	}
	return(retval);
}
コード例 #27
0
void MachineItem::updateMachineItem()
{
    _name.setHtml("<font size=\"-2\" color=\"black\">name: <font size=\"-2\" color=\"blue\">"+getName());
    _address.setHtml("<font size=\"-2\" color=\"black\">address: <font size=\"-2\" color=\"blue\">"+getAddress());
    _default.setHtml("<font size=\"-2\" color=\"black\">default: <font size=\"-2\" color=\"green\">"+getDefault());
    _timeout.setHtml("<font size=\"-2\" color=\"black\">timeout: <font size=\"-2\" color=\"green\">"+getTimeout());
}
コード例 #28
0
void Mutex::lock( double secs )
{
  struct timespec timeout = getTimeout( secs );
  if ( pthread_mutex_timedlock( &mMutex, &timeout ) < 0 )
    throw ThreadException( stringtf( "Unable to timedlock pthread mutex: %s", strerror(errno) ) );
}
コード例 #29
0
ファイル: BasicModem.cpp プロジェクト: tausteen/dune
 std::string
 BasicModem::readLine(void)
 {
   Time::Counter<double> timer(getTimeout());
   return readLine(timer);
 }
コード例 #30
0
ファイル: scr_server.cpp プロジェクト: chagge/gym_torcs
/* Start a new race. */
static void
newrace(int index, tCarElt* car, tSituation *s)
{

    total_tics[index]=0;

    /***********************************************************************************
    ************************* UDP client identification ********************************
    ***********************************************************************************/

    bool identified=false;
    char line[UDP_MSGLEN];

    // Set timeout
    if (getTimeout()>0)
    	UDP_TIMEOUT = getTimeout();

    //Set sensor range
    if (strcmp(getVersion(),"2009")==0)
    {
    	__SENSORS_RANGE__ = 100;
    	printf("*****2009*****\n");
    }
    else if (strcmp(getVersion(),"2010")==0 || strcmp(getVersion(),"2011")==0)
        __SENSORS_RANGE__ = 200;
    else
    {
    	printf("%s is not a recognized version",getVersion());
    	exit(0);
    }

    listenSocket[index] = socket(AF_INET, SOCK_DGRAM, 0);
    if (listenSocket[index] < 0)
    {
        std::cerr << "Error: cannot create listenSocket!";
        exit(1);
    }

    srand(time(NULL));

    // Bind listen socket to listen port.
    serverAddress[index].sin_family = AF_INET;
    serverAddress[index].sin_addr.s_addr = htonl(INADDR_ANY);
    serverAddress[index].sin_port = htons(getUDPListenPort()+index);

    if (bind(listenSocket[index],
             (struct sockaddr *) &serverAddress[index],
             sizeof(serverAddress[index])) < 0)
    {
        std::cerr << "cannot bind socket";
        exit(1);
    }

    // Wait for connections from clients.
    listen(listenSocket[index], 5);

    std::cout << "Waiting for request on port " << getUDPListenPort()+index << "\n";

    // Loop until a client identifies correctly
    while (!identified)
    {

        clientAddressLength[index] = sizeof(clientAddress[index]);

        // Set line to all zeroes
        memset(line, 0x0, UDP_MSGLEN);
        if (recvfrom(listenSocket[index], line, UDP_MSGLEN, 0,
                     (struct sockaddr *) &clientAddress[index],
                     &clientAddressLength[index]) < 0)
        {
            std::cerr << "Error: problem in receiving from the listen socket";
            exit(1);
        }

#ifdef __UDP_SERVER_VERBOSE__
        // show the client's IP address
        std::cout << "  from " << inet_ntoa(clientAddress[index].sin_addr);

        // show the client's port number.
        std::cout << ":" << ntohs(clientAddress[index].sin_port) << "\n";

        // Show the line
        std::cout << "  Received: " << line << "\n";
#endif

        // compare received string with the ID
        if (strncmp(line,UDP_ID,3)==0)
        {
#ifdef __UDP_SERVER_VERBOSE__
            std::cout << "IDENTIFIED" << std::endl;
#endif
            std::string initStr(line);
            if (SimpleParser::parse(initStr,std::string("init"),trackSensAngle[index],19)==false)
            {
            	for (int i = 0; i < 19; ++i) {
            		trackSensAngle[index][i] =-90 + 10*i;
				}
            }
//            char line[UDP_MSGLEN];
            sprintf(line,"***identified***");
            // Sending the car state to the client
            if (sendto(listenSocket[index], line, strlen(line) + 1, 0,
                       (struct sockaddr *) &clientAddress[index],
                       sizeof(clientAddress[index])) < 0)
                std::cerr << "Error: cannot send identification message";
            identified=true;
        }
    }

	focusSens[index] = new Sensors(car, 5);//ML
	for (int i = 0; i < 5; ++i) {//ML
		focusSens[index]->setSensor(i,(car->_focusCmd)+i-2,200);//ML
	}//ML

    // Initialization of track sensors
    trackSens[index] = new Sensors(car, 19);
    for (int i = 0; i < 19; ++i) {
    	trackSens[index]->setSensor(i,trackSensAngle[index][i],__SENSORS_RANGE__);
#ifdef __UDP_SERVER_VERBOSE__
    	std::cout << "Set Track Sensors " << i+1 << " at angle " << trackSensAngle[index][i] << std::endl;
#endif
	}
    // Initialization of opponents sensors
    oppSens[index] = new ObstacleSensors(36, curTrack, car, s, __SENSORS_RANGE__);

    prevDist[index]=-1;
}