void CPage::LoadCache(ConnectionPtr connection) { Trace("LoadCache", "",0); ResultPtr result; ncc::safe_array<char> strQuery(10240); try { // load from the database snprintf(strQuery, strQuery.size(), SQL_WTT_LOAD_CACHE, m_runID); Trace("Query for LoadCache", strQuery, 0); result = connection->Query(strQuery); while(result->Next()) { RowPtr row = result->GetCurrentRow(); // add it std::string urlStr; urlStr = row->GetFieldString(1); { // scope for lock Mutex::Lock lock(sm_urlListLock); m_totalUrlList.push_back(urlStr); } } } catch (const std::exception& e) { LogError2("LoadCache() - Caught Exception", e.what(), 0, SC_ERR_GROUP_DB, SC_ERR_CODE_LOAD_CACHE); } }
/** * @brief 释放MySql连接 * @param connPtr 指定需释放的连接 */ void MySqlConnectionPool::releaseConnection(ConnectionPtr connPtr) { boost::mutex::scoped_lock lock(_mutex); if (connPtr.get()) { _connContainer.push_back(connPtr); } }
void CPage::loadContentError(ConnectionPtr connection) { Trace("loadContentError()", "", 0); std::string strQuery; try { Mutex::Lock lock(m_contentErrorListLock); // get all of the pages for this customer to test strQuery = Format(SQL_WTT_CONTENT_ERRORS); if (ResultPtr result = connection->Query(strQuery)) { while (result->Next()) { RowPtr row = result->GetCurrentRow(); StringIDList::value_type contentError(row->GetFieldString(1), row->GetFieldLong(2)); contentError.first = " " + contentError.first + " "; Trace("loadContentError() - loading string", contentError.first.c_str(), contentError.second); m_contentError.push_back(contentError); } } } catch (const std::exception& e) { LogError("Exception Caught:", e.what(), 0); } }
bool ServiceType::Register(const ConnectionPtr& connection, const Dob::Typesystem::HandlerId& handlerId, LamportClock& regClock, const bool overrideRegistration, const ConsumerId& consumer) { const ContextId context = connection->Id().m_contextId; if (m_typeIsContextShared && context != 0) { std::wostringstream ostr; ostr << "Service " << Typesystem::Operations::GetName(m_typeId) << ", which is ContextShared, can only be registered from context 0."; throw Safir::Dob::Typesystem::SoftwareViolationException(ostr.str(),__WFILE__,__LINE__); } ScopedTypeLock lck(m_typeLocks[context]); // Important to update the registration clock with the lock taken RegisterTime regTime = regClock.GetNewTimestamp(); return m_handlerRegistrations[context].Register(connection, handlerId, Dob::InstanceIdPolicy::RequestorDecidesInstanceId, // Dummy for services false, // false => no injection handler regTime, overrideRegistration, consumer); }
void OCommand::sendHeader( const uint64_t additionalSize ) { LBASSERT( !_impl->dispatcher ); LBASSERT( !_impl->isLocked ); LBASSERT( additionalSize > 0 ); const Connections& connections = getConnections(); for( ConnectionsCIter i = connections.begin(); i != connections.end(); ++i ) { ConnectionPtr connection = *i; connection->lockSend(); } _impl->isLocked = true; _impl->size = additionalSize; flush( true ); }
uint32_t LocalNode::removeListenerNB( ConnectionPtr connection ) { EQASSERT( isListening( )); EQASSERT( connection->isListening( )); connection->ref( CO_REFERENCED_PARAM ); NodeRemoveListenerPacket packet( connection, registerRequest( )); Nodes nodes; getNodes( nodes ); for( Nodes::iterator i = nodes.begin(); i != nodes.end(); ++i ) { (*i)->send( packet, connection->getDescription()->toString( )); } return packet.requestID; }
void LocalNode::_removeConnection( ConnectionPtr connection ) { EQASSERT( connection.isValid( )); _incoming.removeConnection( connection ); void* buffer( 0 ); uint64_t bytes( 0 ); connection->getRecvData( &buffer, &bytes ); EQASSERTINFO( !connection->isConnected() || buffer, *connection ); EQASSERT( !buffer || bytes == sizeof( uint64_t )); if( !connection->isClosed( )) connection->close(); // cancels pending IO's delete reinterpret_cast< uint64_t* >( buffer ); }
void CPage::loadPhraseCheck(ConnectionPtr connection) { Trace("loadPhraseCheck()", "", 0); std::string strQuery; try { Mutex::Lock lock(m_phraseListLock); strQuery = Format(SQL_WTT_PHRASE_WORDS, getPageID()); if (ResultPtr result = connection->Query(strQuery)) { Trace("RowPtr s:","",result->GetRowCount()); while (result->Next()) { RowPtr row = result->GetCurrentRow(); StringIDList::value_type phrase(row->GetFieldString(1), row->GetFieldLong(2)); Trace("loadPhraseCheck_LT(): pre", phrase.first.c_str(), phrase.second); std::transform(phrase.first.begin(), phrase.first.end(), phrase.first.begin(), tolower); Trace("loadPhraseCheck_LT(): post", phrase.first.c_str(), phrase.second); m_phrase.push_back(phrase); } } } catch (const std::exception& e) { LogError("Exception Caught:", e.what(), 0); } }
bool Connection::send( const Connections& connections, const Packet& packet, const bool isLocked ) { if( connections.empty( )) return true; bool success = true; for( Connections::const_iterator i= connections.begin(); i<connections.end(); ++i ) { ConnectionPtr connection = *i; if( !connection->send( &packet, packet.size, isLocked )) success = false; } return success; }
void ConnectionManager::stop(ConnectionPtr c) { #ifdef WT_THREADED std::unique_lock<std::mutex> lock{mutex_}; #endif // WT_THREADED std::set<ConnectionPtr>::iterator i = connections_.find(c); if(i != connections_.end()) { connections_.erase(i); } else { #ifndef WT_WIN32 /* * Error you may get when multiple transmitMore() were outstanding * during server push, and the last one indicated that the connection * needed to be closed: as a consequence they will all try to close * the connection. */ /* LOG_DEBUG("ConnectionManager::stop(): oops - stopping again?"); */ return; #endif // WIN32 } LOG_DEBUG("removed connection (#" << connections_.size() << ")"); #ifdef WT_THREADED lock.unlock(); #endif // WT_THREADED c->scheduleStop(); }
void ConnectionManager::addConnection(const ConnectionPtr& conn) { boost::mutex::scoped_lock lock(connections_mutex_); connections_.insert(conn); conn->addDropListener(boost::bind(&ConnectionManager::onConnectionDropped, this, _1)); }
void ServiceType::Unregister(const ConnectionPtr& connection, const Dob::Typesystem::HandlerId& handlerId) { const ContextId context = connection->Id().m_contextId; if (m_typeIsContextShared && context != 0) { std::wostringstream ostr; ostr << "Service " << Typesystem::Operations::GetName(m_typeId) << ", which is ContextShared, can only be unregistered from context 0."; throw Safir::Dob::Typesystem::SoftwareViolationException(ostr.str(),__WFILE__,__LINE__); } ScopedTypeLock lck(m_typeLocks[context]); if (handlerId == Dob::Typesystem::HandlerId::ALL_HANDLERS) { m_handlerRegistrations[context].UnregisterAll(connection, true); // true => explicit unregister } else { m_handlerRegistrations[context].Unregister(connection, handlerId); } }
void StartAccept() { NewConnection = boost::make_shared<Private::Connection, boost::asio::io_service &>(IoService); Acceptor.async_accept(NewConnection->GetSocket(), boost::bind(&EchoServer::HandleAccept, this, boost::asio::placeholders::error)); }
void HttpServer::destroy(ConnectionPtr connection, bool release) { connection->markToBeDeleted(); { std::lock_guard<std::mutex> lock(connections_mutex_); auto it = std::find_if(std::begin(connections_), std::end(connections_), [&](ConnectionPtr conn) { return connection == conn; }); if (it == std::end(connections_)) { return; } else { --connection_count_; connections_.erase(it); } } if (release) { HTTP::Connection::release(connection); } }
bool LocalNode::listen() { EQVERB << "Listener data: " << serialize() << std::endl; if( !isClosed() || !_connectSelf( )) return false; ConnectionDescriptions descriptions = getConnectionDescriptions(); for( ConnectionDescriptions::const_iterator i = descriptions.begin(); i != descriptions.end(); ++i ) { ConnectionDescriptionPtr description = *i; ConnectionPtr connection = Connection::create( description ); if( !connection ) continue; if( !connection->listen( )) { EQWARN << "Can't create listener connection: " << description << std::endl; return false; } _connectionNodes[ connection ] = this; _incoming.addConnection( connection ); if( description->type >= CONNECTIONTYPE_MULTICAST ) { MCData data; data.connection = connection; data.node = this; _multicasts.push_back( data ); } connection->acceptNB(); EQVERB << "Added node " << _id << " using " << connection << std::endl; } _state = STATE_LISTENING; EQVERB << base::className( this ) << " start command and receiver thread " << std::endl; _receiverThread->start(); EQINFO << *this << std::endl; return true; }
ConnectionPtr Connection::create( ConnectionDescriptionPtr description ) { ConnectionPtr connection; switch( description->type ) { case CONNECTIONTYPE_TCPIP: case CONNECTIONTYPE_SDP: connection = new SocketConnection( description->type ); break; case CONNECTIONTYPE_PIPE: connection = new PipeConnection; break; #ifdef _WIN32 case CONNECTIONTYPE_NAMEDPIPE: connection = new NamedPipeConnection; break; #endif case CONNECTIONTYPE_RSP: connection = new RSPConnection; break; #ifdef COLLAGE_USE_OFED case CONNECTIONTYPE_RDMA: connection = new RDMAConnection; break; #endif #ifdef COLLAGE_USE_UDT case CONNECTIONTYPE_UDT: connection = new UDTConnection; break; #endif default: LBWARN << "Connection type " << description->type << " not supported" << std::endl; return 0; } if( description->bandwidth == 0 ) description->bandwidth = connection->getDescription()->bandwidth; connection->_setDescription( description ); return connection; }
void ServiceType::UnregisterAll(const ConnectionPtr& connection, const bool explicitUnregister) { const ContextId context = connection->Id().m_contextId; ScopedTypeLock lck(m_typeLocks[context]); m_handlerRegistrations[context].UnregisterAll(connection, explicitUnregister); }
void Channel::join(ConnectionPtr con) { lastActivity = time(nullptr); ++participantCount; participants.insert(con); con->joinChannel(this); if (participantCount > topUsers) topUsers = participantCount; }
void my::GateServer::handle_connect(ConnectionPtr conn, boost::system::error_code err) { if (err) { LogW << "server name: " << conn->getNetId() << " connect error: " << err.message() << LogEnd; if (conn->getSocket().is_open()) { LogW << "Close Socket!!" << LogEnd; conn->getSocket().close(); } return; } else { //输出一下这个是成功连接了哪个服务器 LogD << "server name: " << conn->getNetId() << " connect success!" << LogEnd; try { static ip::tcp::no_delay option(true); conn->getSocket().set_option(option); //start conn->start(); }catch(std::exception& e) { LogE << "Connect to server EXCEPTION!!! server=" << conn->getNetId() << " reason=" << e.what() << LogEnd; } } }
void Instance::exit() { try { ConnectionPtr conn = getConnection("ua"); seq_t seq = conn->getNextSeq(); MsgBody body; user_access_server::client_methods::rpc::UnbindRequest unbind_req; body.addRequest(user_access_server::client_methods::rpc::CmdID_Unbind, seq, 0, unbind_req); conn->send(rpc::OP_REQUEST, body); } catch (...) { } closeAllConnections(); }
void Server::handleAccept(const boost::system::error_code & ec, const nexus::isocket & socket) { MLOG_MESSAGE(Info, "handleAccept(" << ec << ")"); if(!ec) { MLOG_MESSAGE(Debug, "accepted, local: " << (*socket)->local_endpoint() << ", remote: " << (*socket)->remote_endpoint()); (*socket)->set_option(boost::asio::ip::tcp::no_delay(true)); ConnectionPtr conn = new Connection(socket, handler_); conn->start(); startAccept(); } else { MLOG_MESSAGE(Warning, "Accept failed: " << ec << ", message: " << ec.message()); } }
bool Connection::send( const Connections& connections, Packet& packet, const void* data, const uint64_t dataSize, const bool isLocked ) { if( connections.empty( )) return true; if( dataSize <= 8 ) // fits in existing packet { if( dataSize != 0 ) memcpy( (char*)(&packet) + packet.size-8, data, dataSize ); return send( connections, packet, isLocked ); } const uint64_t headerSize = packet.size - 8; const uint64_t size = headerSize + dataSize; if( size > EQ_ASSEMBLE_THRESHOLD ) { // OPT: lock the connection and use two send() to avoid big memcpy packet.size = size; bool success = true; for( Connections::const_iterator i= connections.begin(); i<connections.end(); ++i ) { ConnectionPtr connection = *i; if( !isLocked ) connection->lockSend(); if( !connection->send( &packet, headerSize, true ) || !connection->send( data, dataSize, true )) { success = false; } if( !isLocked ) connection->unlockSend(); } return success; } char* buffer = (char*)alloca( size ); memcpy( buffer, &packet, packet.size-8 ); memcpy( buffer + packet.size-8, data, dataSize ); ((Packet*)buffer)->size = size; bool success = true; for( Connections::const_iterator i = connections.begin(); i < connections.end(); ++i ) { ConnectionPtr connection = *i; if( !connection->send( buffer, size, isLocked )) success = false; } return success; }
int CallInAuthenticateUser::authenticateUser() { UINT32 connectionId = APP_CONTEXT.getConnectionStore()->getConnectionIdForSessionId(mSessionId); ConnectionPtr currentConnection = APP_CONTEXT.getConnectionStore()->getConnection(connectionId); if (currentConnection == NULL) { WLog_Print(logger_CallInAuthenticateUser, WLOG_ERROR, "Cannot get Connection for sessionId %lu for resolved connectionId %lu", mSessionId, connectionId); mAuthStatus = -1; return -1; } WLog_Print(logger_CallInAuthenticateUser, WLOG_DEBUG, "authenticating user"); mAuthStatus = currentConnection->authenticateUser(mUserName, mDomainName, mPassword); WLog_Print(logger_CallInAuthenticateUser, WLOG_DEBUG, "authentication %s", mAuthStatus == 0 ? "succeeded" : "failed"); return mAuthStatus; }
/** * @brief 执行一条sql语句 * @param query 查询语句 * @return 返回是否执行成功 */ const bool MySqlConnectionPool::exec(const std::string& query) { ConnectionPtr connPtr = this->connection(); if (!connPtr.get()) { std::cout << "exec connPtr is null" << std::endl; return false; } if (::mysql_ping(&*connPtr)) { std::cout << "mysql ping is error" << std::endl; return false; } if (::mysql_real_query(&*connPtr, query.c_str(), (unsigned int)strlen(query.c_str()))) { std::cout << ::mysql_error(&*connPtr) << std::endl; this->releaseConnection(connPtr); return false; } this->releaseConnection(connPtr); return true; }
void ServiceServerLink::onConnectionDropped(const ConnectionPtr& conn) { ROS_ASSERT(conn == connection_); ROSCPP_LOG_DEBUG("Service client from [%s] for [%s] dropped", conn->getRemoteString().c_str(), service_name_.c_str()); dropped_ = true; clearCalls(); ServiceManager::instance()->removeServiceServerLink(shared_from_this()); }
void SmartSocket::handleReceive(const boost::system::error_code& error, size_t recvBytes) { try { if (error == error::message_size || (!error && recvBytes < sizeof(PacketHeader))) { notifyObservers(&ISocketStateObserver::onBadPacketSize, m_recvPeer, recvBytes); } else if (error) { auto conn = getExistingConnection(m_recvPeer); if (conn && !conn->isDead()) switch (error.value()) { case error::connection_aborted: case error::connection_refused: case error::connection_reset: notifyObservers(&ISocketStateObserver::onPeerDisconnect, conn); conn->markDead(true); break; default: notifyObservers(&ISocketStateObserver::onError, conn, error); break; } } else { ConnectionPtr conn = getOrCreateConnection(m_recvPeer); conn->handleReceive(std::make_shared<Packet>(m_recvBuf.data(), recvBytes)); conn->markDead(false); } } catch (const std::exception& ex) { LogError() << ex.what(); } catch (...) { LogFatal() << "unknown exception" << cSourceLocation; } startReceive(); }
void AsioServer::handleAccept(const boost::system::error_code& e){ LOG_DEBUG("AsioServer::handleAccept => accept a connection"); ConnectionPtr acceptConnection = newConnection_; newConnection_ = newConnection(); acceptor_.async_accept(newConnection_->getSocket(), boost::bind(&AsioServer::handleAccept, this, boost::asio::placeholders::error)); LOG_DEBUG("AsioServer::handleAccept => wait a new connection : cid = %d" , newConnection_->getId()); if(!e){ try{ acceptConnection->open(); LOG_DEBUG("AsioServer::handleAccept => new connection start : cid = %d" , acceptConnection->getId()); } catch (exception &e){ LOG_ERROR("AsioServer::handleAccept => new connection start error : what = %s" , e.what()); } } else { LOG_ERROR("AsioServer::handleAccept => error : " , e.message().c_str()); } }
void Tunnel::onHighWaterMarkWeak(const boost::weak_ptr<Tunnel>& wkTunnel, const ConnectionPtr& conn, size_t bytesToSent) { LOG_ERROR("onHighWaterMark " << conn->name() << " bytes " << bytesToSent); boost::shared_ptr<Tunnel> tunnel = wkTunnel.lock(); if (tunnel) { tunnel->onHighWaterMark(conn, bytesToSent); } }
void SendFrame::Process(ConnectionPtr conn) { if (!HeaderExists("destination")) { throw ConnectionException("destination header missing."); } std::string& destination = headers_["destination"]; if (!conn->IsAllowed(destination, write)) { throw ConnectionException("not allowed to send to destination: "+destination); } struct timeval t; gettimeofday(&t, NULL); boost::uuids::uuid uuid = boost::uuids::random_generator()(); headers_["message-id"] = boost::lexical_cast<std::string>(uuid); headers_["expires"] = "0"; headers_["priority"] = "4"; headers_["timestampmq"] = boost::lexical_cast<std::string>(t.tv_sec); conn->server().hub().Send(destination, shared_from_this()); }
AckChatMsg::AckChatMsg(InstancePtr instance, const UserID& target_uid, msg_id_t msg_id, AckChatMsg::CallbackPtr cb) { if (!msg_id) throw AppException("msg id is null"); instant_messaging_server::methods::rpc::AckChatMsgRequest ack_chat_req; ack_chat_req.mutable_sender_usr_id()->set_uid(target_uid.uid); if (!target_uid.domain.empty()) ack_chat_req.mutable_sender_usr_id()->set_domain(target_uid.domain); ack_chat_req.set_msg_id(msg_id); ConnectionPtr conn = instance->getConnection("ua"); seq_t seq = conn->getNextSeq(); MsgBody body; body.addTarget("im"); body.addRequest(instant_messaging_server::methods::rpc::CmdID_AckChatMsg, seq, 0, ack_chat_req); conn->send(rpc::OP_REQUEST, body); conn->addRequest(seq, cb); }