Commit dbc31878 authored by Pavel Vainerman's avatar Pavel Vainerman

(UHttp): предварительная реализация http-сервера в UniSetActivator

и получение информации по объекту. Включил json.hpp прямо в проект (в git проекта).
parent ef9bd60a
...@@ -88,8 +88,7 @@ DB: Сделать регулируемый буфер на INSERT-ы БД, чт ...@@ -88,8 +88,7 @@ DB: Сделать регулируемый буфер на INSERT-ы БД, чт
ИДЕИ ИДЕИ
----- -----
1) HTTPServer в каждом объекте отдающий JSON с внутренними параметрами. 1) HTTPServer в UniSetActivator, для обращения к объектам
================== ==================
......
...@@ -2,7 +2,7 @@ ...@@ -2,7 +2,7 @@
ulimit -Sc 1000000 ulimit -Sc 1000000
./uniset2-start.sh -f ./uniset2-nullController --name SharedMemory1 --confile test.xml --ulog-add-levels any $* ./uniset2-start.sh -f ./uniset2-nullController --name SharedMemory1 --confile test.xml --ulog-add-levels level1,warn,crit $*
#info,warn,crit,system,level9 > 1.log #info,warn,crit,system,level9 > 1.log
#--c-filter-field cfilter --c-filter-value test1 --s-filter-field io --s-filter-value 1 #--c-filter-field cfilter --c-filter-value test1 --s-filter-field io --s-filter-value 1
...@@ -69,12 +69,12 @@ if test -n "$poco_old"; then ...@@ -69,12 +69,12 @@ if test -n "$poco_old"; then
POCO_CFLAGS="${POCO_CFLAGS} -DPOCO_OLD_VERSION" POCO_CFLAGS="${POCO_CFLAGS} -DPOCO_OLD_VERSION"
fi fi
AC_MSG_CHECKING([check json]) #AC_MSG_CHECKING([check json])
if test -a "/usr/include/json.hpp"; then #if test -a "/usr/include/json.hpp"; then
AC_MSG_RESULT([ok]) # AC_MSG_RESULT([ok])
else #else
AC_MSG_ERROR([json.hpp not found]) # AC_MSG_ERROR([json.hpp not found])
fi #fi
#check sqlite support #check sqlite support
AC_MSG_CHECKING([sqlite support]) AC_MSG_CHECKING([sqlite support])
......
...@@ -29,6 +29,8 @@ ...@@ -29,6 +29,8 @@
#include "UniSetObject.h" #include "UniSetObject.h"
#include "UniSetManager.h" #include "UniSetManager.h"
#include "OmniThreadCreator.h" #include "OmniThreadCreator.h"
#include "UHttpRequestHandler.h"
#include "UHttpServer.h"
//---------------------------------------------------------------------------------------- //----------------------------------------------------------------------------------------
class UniSetActivator; class UniSetActivator;
typedef std::shared_ptr<UniSetActivator> UniSetActivatorPtr; typedef std::shared_ptr<UniSetActivator> UniSetActivatorPtr;
...@@ -49,7 +51,8 @@ typedef std::shared_ptr<UniSetActivator> UniSetActivatorPtr; ...@@ -49,7 +51,8 @@ typedef std::shared_ptr<UniSetActivator> UniSetActivatorPtr;
* --uniset-abort-script - скрипт запускаемый при вылете, в качестве аргумента передаётся имя программы и pid * --uniset-abort-script - скрипт запускаемый при вылете, в качестве аргумента передаётся имя программы и pid
*/ */
class UniSetActivator: class UniSetActivator:
public UniSetManager public UniSetManager,
public UniSetTypes::UHttp::IHttpRequestRegistry
{ {
public: public:
...@@ -82,6 +85,8 @@ class UniSetActivator: ...@@ -82,6 +85,8 @@ class UniSetActivator:
return abortScript; return abortScript;
} }
virtual nlohmann::json getDataByName( const std::string& name ) override;
protected: protected:
virtual void work(); virtual void work();
...@@ -118,6 +123,10 @@ class UniSetActivator: ...@@ -118,6 +123,10 @@ class UniSetActivator:
bool _noUseGdbForStackTrace = { false }; bool _noUseGdbForStackTrace = { false };
std::string abortScript = { "" }; // скрипт вызываемый при прерывании программы (SIGSEGV,SIGABRT) std::string abortScript = { "" }; // скрипт вызываемый при прерывании программы (SIGSEGV,SIGABRT)
std::shared_ptr<UniSetTypes::UHttp::UHttpServer> httpserv;
std::string httpHost = { "" };
int httpPort = { 0 };
}; };
//---------------------------------------------------------------------------------------- //----------------------------------------------------------------------------------------
#endif #endif
......
...@@ -124,6 +124,9 @@ class UniSetManager: ...@@ -124,6 +124,9 @@ class UniSetManager:
//! \note Переопределяя не забывайте вызвать базовую //! \note Переопределяя не забывайте вызвать базовую
virtual bool deactivateObject() override; virtual bool deactivateObject() override;
const std::shared_ptr<UniSetObject> findObject( const std::string& name );
const std::shared_ptr<UniSetManager> findManager( const std::string& name );
typedef UniSetManagerList::iterator MListIterator; typedef UniSetManagerList::iterator MListIterator;
int getObjectsInfo(const std::shared_ptr<UniSetManager>& mngr, UniSetTypes::SimpleInfoSeq* seq, int getObjectsInfo(const std::shared_ptr<UniSetManager>& mngr, UniSetTypes::SimpleInfoSeq* seq,
......
...@@ -41,6 +41,7 @@ ...@@ -41,6 +41,7 @@
#include "ThreadCreator.h" #include "ThreadCreator.h"
#include "LT_Object.h" #include "LT_Object.h"
#include "MQMutex.h" #include "MQMutex.h"
#include "UHttpRequestHandler.h"
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
//#include <omnithread.h> //#include <omnithread.h>
...@@ -71,7 +72,8 @@ typedef std::list< std::shared_ptr<UniSetObject> > ObjectsList; /*!< Спи ...@@ -71,7 +72,8 @@ typedef std::list< std::shared_ptr<UniSetObject> > ObjectsList; /*!< Спи
class UniSetObject: class UniSetObject:
public std::enable_shared_from_this<UniSetObject>, public std::enable_shared_from_this<UniSetObject>,
public POA_UniSetObject_i, public POA_UniSetObject_i,
public LT_Object public LT_Object,
public UniSetTypes::UHttp::IHttpRequest
{ {
public: public:
UniSetObject( const std::string& name, const std::string& section ); UniSetObject( const std::string& name, const std::string& section );
...@@ -99,6 +101,8 @@ class UniSetObject: ...@@ -99,6 +101,8 @@ class UniSetObject:
//! поместить сообщение в очередь //! поместить сообщение в очередь
virtual void push( const UniSetTypes::TransportMessage& msg ) override; virtual void push( const UniSetTypes::TransportMessage& msg ) override;
virtual nlohmann::json getData() override;
// -------------- вспомогательные -------------- // -------------- вспомогательные --------------
/*! получить ссылку (на себя) */ /*! получить ссылку (на себя) */
UniSetTypes::ObjectPtr getRef() const; UniSetTypes::ObjectPtr getRef() const;
......
This source diff could not be displayed because it is too large. You can view the blob instead.
...@@ -26,7 +26,7 @@ using namespace UHttp; ...@@ -26,7 +26,7 @@ using namespace UHttp;
UHttpRequestHandler::UHttpRequestHandler(std::shared_ptr<IHttpRequestRegistry> _registry ): UHttpRequestHandler::UHttpRequestHandler(std::shared_ptr<IHttpRequestRegistry> _registry ):
registry(_registry) registry(_registry)
{ {
log = make_shared<DebugStream>();
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
void UHttpRequestHandler::handleRequest( Poco::Net::HTTPServerRequest& req, Poco::Net::HTTPServerResponse& resp ) void UHttpRequestHandler::handleRequest( Poco::Net::HTTPServerRequest& req, Poco::Net::HTTPServerResponse& resp )
...@@ -72,7 +72,7 @@ void UHttpRequestHandler::handleRequest( Poco::Net::HTTPServerRequest& req, Poco ...@@ -72,7 +72,7 @@ void UHttpRequestHandler::handleRequest( Poco::Net::HTTPServerRequest& req, Poco
resp.setContentType("text/json"); resp.setContentType("text/json");
std::ostream& out = resp.send(); std::ostream& out = resp.send();
auto json = registry->getData(objectName); auto json = registry->getDataByName(objectName);
out << json.dump(); out << json.dump();
out.flush(); out.flush();
} }
......
...@@ -14,8 +14,10 @@ ...@@ -14,8 +14,10 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
#include <sstream>
#include <Poco/URI.h> #include <Poco/URI.h>
#include "UHttpServer.h" #include "UHttpServer.h"
#include "Exceptions.h"
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
using namespace Poco::Net; using namespace Poco::Net;
using namespace UniSetTypes; using namespace UniSetTypes;
...@@ -25,48 +27,51 @@ using namespace UHttp; ...@@ -25,48 +27,51 @@ using namespace UHttp;
UHttpServer::UHttpServer(std::shared_ptr<IHttpRequestRegistry>& supplier, const std::string& _host, int _port ): UHttpServer::UHttpServer(std::shared_ptr<IHttpRequestRegistry>& supplier, const std::string& _host, int _port ):
sa(_host,_port) sa(_host,_port)
{ {
/*! \FIXME: доделать конфигурирование параметров */ try
HTTPServerParams* httpParams = new HTTPServerParams; {
httpParams->setMaxQueued(100); mylog = std::make_shared<DebugStream>();
httpParams->setMaxThreads(1);
/*! \FIXME: доделать конфигурирование параметров */
HTTPServerParams* httpParams = new HTTPServerParams;
httpParams->setMaxQueued(100);
httpParams->setMaxThreads(1);
reqFactory = std::make_shared<UHttpRequestHandlerFactory>(supplier);
reqFactory = std::make_shared<UHttpRequestHandlerFactory>(supplier); http = std::make_shared<Poco::Net::HTTPServer>(reqFactory.get(), ServerSocket(sa), httpParams );
}
catch( std::exception& ex )
{
std::stringstream err;
err << "(UHttpServer::init): " << _host << ":" << _port << " ERROR: " << ex.what();
throw UniSetTypes::SystemError(err.str());
}
http = std::make_shared<Poco::Net::HTTPServer>(reqFactory.get(), ServerSocket(sa), httpParams ); mylog->info() << "(UHttpServer::init): init " << _host << ":" << _port << std::endl;
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
UHttpServer::~UHttpServer() UHttpServer::~UHttpServer()
{ {
if( http )
http->stop();
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
UHttpServer::UHttpServer() void UHttpServer::start()
{ {
http->start();
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
std::shared_ptr<DebugStream> UHttpServer::log() void UHttpServer::stop()
{ {
return mylog; http->stop();
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
void UHttpServer::run( bool thread ) UHttpServer::UHttpServer()
{ {
if( !thread ) }
{ // -------------------------------------------------------------------------
try std::shared_ptr<DebugStream> UHttpServer::log()
{ {
http->start(); return mylog;
pause();
http->stop();
}
catch( std::exception& ex )
{
mylog->crit() << "(UHttpServer): " << ex.what() << std::endl;
throw ex;
}
return;
}
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
...@@ -525,6 +525,15 @@ void UniSetActivator::init() ...@@ -525,6 +525,15 @@ void UniSetActivator::init()
abortScript = conf->getArgParam("--uniset-abort-script", ""); abortScript = conf->getArgParam("--uniset-abort-script", "");
if( findArgParam("--activator-run-httpserver", conf->getArgc(), conf->getArgv()) != -1 )
{
httpHost = conf->getArgParam("--activator-httpserver-host", "localhost");
ostringstream s;
s << (getId()==DefaultObjectId ? 8080 : getId() );
httpPort = conf->getArgInt("--activator-httpserver-port", s.str());
ulog1 << myname << "(init): http server parameters " << httpHost << ":" << httpPort << endl;
}
orb = conf->getORB(); orb = conf->getORB();
CORBA::Object_var obj = orb->resolve_initial_references("RootPOA"); CORBA::Object_var obj = orb->resolve_initial_references("RootPOA");
PortableServer::POA_var root_poa = PortableServer::POA::_narrow(obj); PortableServer::POA_var root_poa = PortableServer::POA::_narrow(obj);
...@@ -653,6 +662,21 @@ void UniSetActivator::run( bool thread ) ...@@ -653,6 +662,21 @@ void UniSetActivator::run( bool thread )
set_signals(true); set_signals(true);
if( !httpHost.empty() )
{
try
{
auto reg = dynamic_pointer_cast<UHttp::IHttpRequestRegistry>(shared_from_this());
httpserv = make_shared<UHttp::UHttpServer>(reg,httpHost,httpPort);
httpserv->start();
}
catch( std::exception& ex )
{
uwarn << myname << "(run): init http server error: " << ex.what() << endl;
}
}
if( thread ) if( thread )
{ {
uinfo << myname << "(run): запускаемся с созданием отдельного потока... " << endl; uinfo << myname << "(run): запускаемся с созданием отдельного потока... " << endl;
...@@ -687,6 +711,9 @@ void UniSetActivator::stop() ...@@ -687,6 +711,9 @@ void UniSetActivator::stop()
pman->discard_requests(true); pman->discard_requests(true);
ulogsys << myname << "(stop): discard request ok." << endl; ulogsys << myname << "(stop): discard request ok." << endl;
if( httpserv )
httpserv->stop();
} }
// ------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------
...@@ -721,6 +748,10 @@ void UniSetActivator::work() ...@@ -721,6 +748,10 @@ void UniSetActivator::work()
ucrit << myname << "(work): line: " << fe.line() << endl; ucrit << myname << "(work): line: " << fe.line() << endl;
ucrit << myname << "(work): mesg: " << fe.errmsg() << endl; ucrit << myname << "(work): mesg: " << fe.errmsg() << endl;
} }
catch( std::exception& ex )
{
ucrit << myname << "(work): catch: " << ex.what() << endl;
}
ulogsys << myname << "(work): orb thread stopped!" << endl << flush; ulogsys << myname << "(work): orb thread stopped!" << endl << flush;
...@@ -830,6 +861,21 @@ UniSetActivator::TerminateEvent_Signal UniSetActivator::signal_terminate_event() ...@@ -830,6 +861,21 @@ UniSetActivator::TerminateEvent_Signal UniSetActivator::signal_terminate_event()
return s_term; return s_term;
} }
// ------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------
nlohmann::json UniSetActivator::getDataByName( const string& name )
{
auto obj = findObject(name);
if( obj )
return obj->getData();
auto man = findManager(name);
if( man )
return man->getData();
//! \todo Продумать что возвращать если объект не найден
nlohmann::json j = "";
return j; // return empty json
}
// ------------------------------------------------------------------------------------------
void UniSetActivator::terminated( int signo ) void UniSetActivator::terminated( int signo )
{ {
if( !g_act ) if( !g_act )
......
...@@ -409,6 +409,30 @@ bool UniSetManager::deactivateObject() ...@@ -409,6 +409,30 @@ bool UniSetManager::deactivateObject()
return true; return true;
} }
// ------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------
const std::shared_ptr<UniSetObject> UniSetManager::findObject( const string& name )
{
uniset_rwmutex_rlock lock(olistMutex);
for( auto&& o: olist )
{
if( o->getName() == name )
return o;
}
return nullptr;
}
// ------------------------------------------------------------------------------------------
const std::shared_ptr<UniSetManager> UniSetManager::findManager( const string& name )
{
uniset_rwmutex_rlock lock(mlistMutex);
for( auto&& m: mlist )
{
if( m->getName() == name )
return m;
}
return nullptr;
}
// ------------------------------------------------------------------------------------------
void UniSetManager::sigterm( int signo ) void UniSetManager::sigterm( int signo )
{ {
sig = signo; sig = signo;
......
...@@ -379,6 +379,20 @@ void UniSetObject::push( const TransportMessage& tm ) ...@@ -379,6 +379,20 @@ void UniSetObject::push( const TransportMessage& tm )
termWaiting(); termWaiting();
} }
// ------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------
nlohmann::json UniSetObject::getData()
{
nlohmann::json jdata;
jdata["name"] = myname;
jdata["id"] = getId();
jdata["msgCount"] = countMessages();
jdata["lostMessages"] = getCountOfLostMessages();
jdata["maxSizeOfMessageQueue"] = getMaxSizeOfMessageQueue();
jdata["isActive"] = isActive();
jdata["objectType"] = getType();
return jdata;
}
// ------------------------------------------------------------------------------------------
ObjectPtr UniSetObject::getRef() const ObjectPtr UniSetObject::getRef() const
{ {
UniSetTypes::uniset_rwmutex_rlock lock(refmutex); UniSetTypes::uniset_rwmutex_rlock lock(refmutex);
......
...@@ -16,11 +16,11 @@ class UTestSupplier: ...@@ -16,11 +16,11 @@ class UTestSupplier:
{ {
nlohmann::json j; nlohmann::json j;
j["test"] = 23; j["test"] = 42;
return j; return j;
} }
}; };
// --------------------------------------------------------------------------
class UTestRequestRegistry: class UTestRequestRegistry:
public UHttp::IHttpRequestRegistry public UHttp::IHttpRequestRegistry
{ {
...@@ -29,9 +29,11 @@ class UTestRequestRegistry: ...@@ -29,9 +29,11 @@ class UTestRequestRegistry:
virtual ~UTestRequestRegistry(){} virtual ~UTestRequestRegistry(){}
virtual nlohmann::json getData( const std::string& name ) override virtual nlohmann::json getDataByName( const std::string& name ) override
{ {
return sup.getData(); nlohmann::json j = sup.getData();
j["name"] = name;
return j;
} }
private: private:
...@@ -47,7 +49,11 @@ int main(int argc, const char** argv) ...@@ -47,7 +49,11 @@ int main(int argc, const char** argv)
auto ireg = dynamic_pointer_cast<UHttp::IHttpRequestRegistry>(reg); auto ireg = dynamic_pointer_cast<UHttp::IHttpRequestRegistry>(reg);
auto http = make_shared<UHttp::UHttpServer>(ireg,"localhost", 5555); auto http = make_shared<UHttp::UHttpServer>(ireg,"localhost", 5555);
http->run(false); http->log()->level(Debug::ANY);
http->start();
pause();
http->stop();
return 0; return 0;
} }
catch( const std::exception& e ) catch( const std::exception& e )
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment