Commit 69a42967 authored by Pavel Vainerman's avatar Pavel Vainerman

[http-resolver]: added to UInterface

parent 3d2b8079
......@@ -27,6 +27,7 @@
<DocDir name="./"/>
<LockDir name="/tmp/"/>
<HttpResolver name="HttpResolver"/>
<LocalIOR name="1"/>
<Services>
<LocalTimeService AskLifeTimeSEC="10" MaxCountTimers="100" name="TimeService"/>
<LocalInfoServer dbrepeat="1" name="InfoServer">
......
......@@ -32,74 +32,74 @@ const std::string HTTP_RESOLVER_API_VERSION = "v01";
// -------------------------------------------------------------------------
namespace uniset
{
//------------------------------------------------------------------------------------------
/*!
\page page_HttpResolver Http-cервис для получения CORBA-ссылок на объекты (HttpResolver)
//------------------------------------------------------------------------------------------
/*!
\page page_HttpResolver Http-cервис для получения CORBA-ссылок на объекты (HttpResolver)
- \ref sec_HttpResolver_Comm
- \ref sec_HttpResolver_Comm
\section sec_HttpResolver_Comm Общее описание работы HttpResolver
HttpResolver это сервис, который отдаёт CORBA-ссылки (в виде строки)
на объекты запущенные на данном узле в режиме LocalIOR. Т.е. когда ссылки
публикуются в файлах.
*/
class HttpResolver:
public Poco::Net::HTTPRequestHandler
{
public:
HttpResolver( const std::string& name, int argc, const char* const* argv, const std::string& prefix );
virtual ~HttpResolver();
\section sec_HttpResolver_Comm Общее описание работы HttpResolver
HttpResolver это сервис, который отдаёт CORBA-ссылки (в виде строки)
на объекты запущенные на данном узле в режиме LocalIOR. Т.е. когда ссылки
публикуются в файлах.
*/
class HttpResolver:
public Poco::Net::HTTPRequestHandler
{
public:
HttpResolver( const std::string& name, int argc, const char* const* argv, const std::string& prefix );
virtual ~HttpResolver();
/*! глобальная функция для инициализации объекта */
static std::shared_ptr<HttpResolver> init_resolver( int argc, const char* const* argv, const std::string& prefix = "httpresolver-" );
/*! глобальная функция для инициализации объекта */
static std::shared_ptr<HttpResolver> init_resolver( int argc, const char* const* argv, const std::string& prefix = "httpresolver-" );
/*! глобальная функция для вывода help-а */
static void help_print();
/*! глобальная функция для вывода help-а */
static void help_print();
inline std::shared_ptr<DebugStream> log()
{
return rlog;
}
inline std::shared_ptr<DebugStream> log()
{
return rlog;
}
virtual void handleRequest( Poco::Net::HTTPServerRequest& req, Poco::Net::HTTPServerResponse& resp ) override;
virtual void handleRequest( Poco::Net::HTTPServerRequest& req, Poco::Net::HTTPServerResponse& resp ) override;
void run();
void run();
protected:
protected:
Poco::JSON::Object::Ptr respError( Poco::Net::HTTPServerResponse& resp, Poco::Net::HTTPResponse::HTTPStatus s, const std::string& message );
Poco::JSON::Object::Ptr httpGetRequest( const std::string& cmd, const Poco::URI::QueryParameters& p );
Poco::JSON::Object::Ptr httpJsonResolve( const std::string& query, const Poco::URI::QueryParameters& p );
std::string httpTextResolve( const std::string& query, const Poco::URI::QueryParameters& p );
Poco::JSON::Object::Ptr respError( Poco::Net::HTTPServerResponse& resp, Poco::Net::HTTPResponse::HTTPStatus s, const std::string& message );
Poco::JSON::Object::Ptr httpGetRequest( const std::string& cmd, const Poco::URI::QueryParameters& p );
Poco::JSON::Object::Ptr httpJsonResolve( const std::string& query, const Poco::URI::QueryParameters& p );
std::string httpTextResolve( const std::string& query, const Poco::URI::QueryParameters& p );
std::shared_ptr<Poco::Net::HTTPServer> httpserv;
std::string httpHost = { "" };
int httpPort = { 0 };
std::string httpCORS_allow = { "*" };
std::string httpReplyAddr = { "" };
std::shared_ptr<Poco::Net::HTTPServer> httpserv;
std::string httpHost = { "" };
int httpPort = { 0 };
std::string httpCORS_allow = { "*" };
std::string httpReplyAddr = { "" };
std::shared_ptr<DebugStream> rlog;
std::string myname;
std::shared_ptr<DebugStream> rlog;
std::string myname;
std::shared_ptr<IORFile> iorfile;
std::shared_ptr<IORFile> iorfile;
class HttpResolverRequestHandlerFactory:
public Poco::Net::HTTPRequestHandlerFactory
{
public:
HttpResolverRequestHandlerFactory( HttpResolver* r ): resolver(r) {}
virtual ~HttpResolverRequestHandlerFactory() {}
class HttpResolverRequestHandlerFactory:
public Poco::Net::HTTPRequestHandlerFactory
{
public:
HttpResolverRequestHandlerFactory( HttpResolver* r ): resolver(r) {}
virtual ~HttpResolverRequestHandlerFactory() {}
virtual Poco::Net::HTTPRequestHandler* createRequestHandler( const Poco::Net::HTTPServerRequest& req ) override;
virtual Poco::Net::HTTPRequestHandler* createRequestHandler( const Poco::Net::HTTPServerRequest& req ) override;
private:
HttpResolver* resolver;
};
private:
HttpResolver* resolver;
};
private:
};
// ----------------------------------------------------------------------------------
private:
};
// ----------------------------------------------------------------------------------
} // end of namespace uniset
//------------------------------------------------------------------------------------------
#endif
......@@ -6,33 +6,33 @@ using namespace std;
// --------------------------------------------------------------------------
int main(int argc, char** argv)
{
// std::ios::sync_with_stdio(false);
// std::ios::sync_with_stdio(false);
try
{
if( argc > 1 && (!strcmp(argv[1], "--help") || !strcmp(argv[1], "-h")) )
{
cout << "--confile filename - configuration file. Default: configure.xml" << endl;
HttpResolver::help_print();
return 0;
}
try
{
if( argc > 1 && (!strcmp(argv[1], "--help") || !strcmp(argv[1], "-h")) )
{
cout << "--confile filename - configuration file. Default: configure.xml" << endl;
HttpResolver::help_print();
return 0;
}
auto resolver = HttpResolver::init_resolver(argc, argv);
auto resolver = HttpResolver::init_resolver(argc, argv);
if( !resolver )
return 1;
if( !resolver )
return 1;
resolver->run();
return 0;
}
catch( const std::exception& ex )
{
cerr << "(HttpResolver::main): " << ex.what() << endl;
}
catch(...)
{
cerr << "(HttpResolver::main): catch ..." << endl;
}
resolver->run();
return 0;
}
catch( const std::exception& ex )
{
cerr << "(HttpResolver::main): " << ex.what() << endl;
}
catch(...)
{
cerr << "(HttpResolver::main): catch ..." << endl;
}
return 1;
return 1;
}
......@@ -121,6 +121,7 @@ namespace uniset
const std::string getConfFileName() const noexcept;
std::string getImagesDir() const noexcept;
std::string getNodeIp( uniset::ObjectId node );
timeout_t getHeartBeatTime() const noexcept;
timeout_t getNCReadyTimeout() const noexcept;
......@@ -136,6 +137,7 @@ namespace uniset
bool isLocalIOR() const noexcept;
bool isTransientIOR() const noexcept;
size_t getHttpResovlerPort() const noexcept;
/*! получить значение указанного параметра, или значение по умолчанию */
std::string getArgParam(const std::string& name, const std::string& defval = "") const noexcept;
......@@ -202,6 +204,8 @@ namespace uniset
timeout_t repeatTimeout = { 50 }; /*!< пауза между попытками [мс] */
size_t httpResolverPort = { 8008 };
uniset::ListOfNode lnodes;
// repository
......
......@@ -33,19 +33,19 @@ namespace uniset
{
public:
IORFile( const std::string& iordir );
~IORFile();
IORFile( const std::string& iordir );
~IORFile();
std::string getIOR( const ObjectId id );
void setIOR( const ObjectId id, const std::string& sior );
void unlinkIOR( const ObjectId id );
std::string getIOR( const ObjectId id );
void setIOR( const ObjectId id, const std::string& sior );
void unlinkIOR( const ObjectId id );
std::string getFileName( const ObjectId id );
std::string getFileName( const ObjectId id );
private:
std::string iordir;
};
// -----------------------------------------------------------------------------------------
private:
std::string iordir;
};
// -----------------------------------------------------------------------------------------
} // end of namespace
// -----------------------------------------------------------------------------------------
#endif
#ifndef DISABLE_REST_API
/*
* Copyright (c) 2020 Pavel Vainerman.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, version 2.1.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Lesser Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
// -------------------------------------------------------------------------
#ifndef UHttpClient_H_
#define UHttpClient_H_
// -------------------------------------------------------------------------
#include <string>
#include <Poco/Net/HTTPClientSession.h>
#include "DebugStream.h"
// -------------------------------------------------------------------------
namespace uniset
{
namespace UHttp
{
class UHttpClient
{
public:
UHttpClient();
virtual ~UHttpClient();
// http://site.com/query?params
// \return ""
std::string get( const std::string& host, int port, const std::string& request );
protected:
Poco::Net::HTTPClientSession session;
private:
};
}
}
// -------------------------------------------------------------------------
#endif // UHttpClient_H_
// -------------------------------------------------------------------------
#endif
......@@ -36,6 +36,9 @@
#include "IOController_i.hh"
#include "MessageType.h"
#include "Configuration.h"
#ifndef DISABLE_REST_API
#include "UHttpClient.h"
#endif
// -----------------------------------------------------------------------------------------
namespace uniset
{
......@@ -301,6 +304,7 @@ namespace uniset
protected:
std::string set_err(const std::string& pre, const uniset::ObjectId id, const uniset::ObjectId node) const;
std::string httpResolve( const uniset::ObjectId id, const uniset::ObjectId node ) const;
private:
void init();
......
......@@ -2,7 +2,7 @@
# This file is part of the UniSet library #
############################################################################
noinst_LTLIBRARIES = libHttp.la
libHttp_la_SOURCES = UHttpRequestHandler.cc UHttpServer.cc
libHttp_la_SOURCES = UHttpRequestHandler.cc UHttpServer.cc UHttpClient.cc
libHttp_la_CXXFLAGS = $(POCO_CFLAGS)
libHttp_la_LIBADD = $(POCO_LIBS)
......
#ifndef DISABLE_REST_API
/*
* Copyright (c) 2020 Pavel Vainerman.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, version 2.1.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Lesser Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
// -------------------------------------------------------------------------
#include <sstream>
#include <Poco/Net/HTTPRequest.h>
#include <Poco/Net/HTTPClientSession.h>
#include <Poco/Net/HTTPResponse.h>
#include <Poco/StreamCopier.h>
#include "UHttpClient.h"
#include "Exceptions.h"
// -------------------------------------------------------------------------
using namespace Poco::Net;
// -------------------------------------------------------------------------
namespace uniset
{
using namespace UHttp;
// -------------------------------------------------------------------------
UHttpClient::UHttpClient()
{
}
// -------------------------------------------------------------------------
UHttpClient::~UHttpClient()
{
}
// -------------------------------------------------------------------------
std::string UHttpClient::get( const std::string& host, int port, const std::string& query )
{
session.setHost(host);
session.setPort(port);
HTTPRequest request(HTTPRequest::HTTP_GET, query, HTTPMessage::HTTP_1_1);
session.sendRequest(request);
HTTPResponse response;
std::istream& rs = session.receiveResponse(response);
if( response.getStatus() != Poco::Net::HTTPResponse::HTTP_OK )
return "";
std::stringstream ret;
Poco::StreamCopier::copyStream(rs, ret);
return ret.str();
}
// -------------------------------------------------------------------------
} // end of namespace uniset
// -------------------------------------------------------------------------
#endif // #ifndef DISABLE_REST_API
......@@ -305,6 +305,7 @@ namespace uniset
// transientIOR
int tior = getArgInt("--transientIOR");
if( tior )
transientIOR = tior;
......@@ -602,6 +603,10 @@ namespace uniset
else if( name == "LocalIOR" )
{
localIOR = it.getIntProp("name");
httpResolverPort = it.getIntProp("httpResolverPort");
if( httpResolverPort <= 0 )
httpResolverPort = 8008;
}
else if( name == "TransientIOR" )
{
......@@ -1113,7 +1118,7 @@ namespace uniset
}
// -------------------------------------------------------------------------
std::pair<string,xmlNode*> Configuration::getRepSectionName( const string& sec )
std::pair<string, xmlNode*> Configuration::getRepSectionName( const string& sec )
{
xmlNode* secnode = unixml->findNode(unixml->getFirstNode(), sec);
......@@ -1323,6 +1328,20 @@ namespace uniset
return transientIOR;
}
size_t Configuration::getHttpResovlerPort() const noexcept
{
return httpResolverPort;
}
std::string Configuration::getNodeIp( uniset::ObjectId node )
{
UniXML::iterator nIt = getXMLObjectNode(node);
if( !nIt )
return "";
return nIt.getProp("ip");
}
// -------------------------------------------------------------------------
xmlNode* Configuration::getXMLSensorsSection() noexcept
{
......
......@@ -874,9 +874,9 @@ namespace uniset
}
// ------------------------------------------------------------------------------------------------------------
uniset::ObjectPtr UInterface::resolve( const uniset::ObjectId rid , const uniset::ObjectId node ) const
uniset::ObjectPtr UInterface::resolve( const uniset::ObjectId rid, const uniset::ObjectId node ) const
{
if ( rid == uniset::DefaultObjectId )
if( rid == uniset::DefaultObjectId )
throw uniset::ResolveNameError("UI(resolve): ID=uniset::DefaultObjectId");
if( node == uniset::DefaultObjectId )
......@@ -896,7 +896,12 @@ namespace uniset
if( CORBA::is_nil(orb) )
orb = uconf->getORB();
string sior(uconf->iorfile->getIOR(rid));
string sior;
if( node == uconf->getLocalNode() )
sior = uconf->iorfile->getIOR(rid);
else
sior = httpResolve(rid, node);
if( !sior.empty() )
{
......@@ -904,13 +909,11 @@ namespace uniset
rcache.cache(rid, node, nso); // заносим в кэш
return nso._retn();
}
else
{
// если NameService недоступен то,
// сразу выдаём ошибку
uwarn << "not found IOR-file for " << uconf->oind->getNameById(rid) << endl;
throw uniset::ResolveNameError();
}
uwarn << "not found IOR-file for " << uconf->oind->getNameById(rid)
<< " node=" << uconf->oind->getNameById(node)
<< endl;
throw uniset::ResolveNameError();
}
if( node != uconf->getLocalNode() )
......@@ -1019,6 +1022,36 @@ namespace uniset
}
// -------------------------------------------------------------------------------------------
std::string UInterface::httpResolve( const uniset::ObjectId id, const uniset::ObjectId node ) const
{
#ifndef DISABLE_REST_API
size_t port = uconf->getHttpResovlerPort();
if( port == 0 )
return "";
const std::string host = uconf->getNodeIp(node);
if( host.empty() )
return "";
string ret;
const string query = "api/v01/resolve/text?" + std::to_string(id);
for( size_t i = 0; i < uconf->getRepeatCount(); i++ )
{
ret = resolver.get(host, port, query);
if( !ret.empty() )
return ret;
msleep(uconf->getRepeatTimeout());
}
#endif
return "";
}
// -------------------------------------------------------------------------------------------
void UInterface::send( const uniset::ObjectId name, const uniset::TransportMessage& msg, const uniset::ObjectId node )
{
if ( name == uniset::DefaultObjectId )
......
......@@ -11,11 +11,11 @@ TEST_CASE("IORFile", "[iorfile][basic]" )
{
CHECK( uniset_conf() != nullptr );
ObjectId testID = 1;
const std::string iorstr("testIORstring");
IORFile ior(uniset_conf()->getLockDir());
ior.setIOR(testID, iorstr);
REQUIRE( ior.getIOR(testID) == iorstr );
ObjectId testID = 1;
const std::string iorstr("testIORstring");
IORFile ior(uniset_conf()->getLockDir());
ior.setIOR(testID, iorstr);
REQUIRE( ior.getIOR(testID) == iorstr );
CHECK( file_exist(ior.getFileName(testID)) );
ior.unlinkIOR(testID);
......
......@@ -24,6 +24,11 @@
./extensions/DBServer-SQLite/SQLiteInterface.cc
./extensions/DBServer-SQLite/SQLiteInterface.h
./extensions/DBServer-SQLite/test.cc
./extensions/HttpResolver/HttpResolver.cc
./extensions/HttpResolver/HttpResolver.h
./extensions/HttpResolver/HttpResolverSugar.h
./extensions/HttpResolver/main.cc
./extensions/HttpResolver/Makefile.am
./extensions/include/Calibration.h
./extensions/include/ComediInterface.h
./extensions/include/DigitalFilter.h
......@@ -185,43 +190,6 @@
./extensions/SMViewer/Makefile.am
./extensions/SMViewer/SMViewer.cc
./extensions/SMViewer/SMViewer.h
./extensions/tests1/Makefile.am
./extensions/tests1/MBSlaveTest/Makefile.am
./extensions/tests1/MBSlaveTest/mbslave-test.cc
./extensions/tests1/MBSlaveTest/TestProc.cc
./extensions/tests1/MBSlaveTest/TestProc.h
./extensions/tests1/MBSlaveTest/testproc.src.xml
./extensions/tests1/MQPerfTest/Makefile.am
./extensions/tests1/MQPerfTest/mq-test.cc
./extensions/tests1/MQPerfTest/TestProc.cc
./extensions/tests1/MQPerfTest/TestProc.h
./extensions/tests1/MQPerfTest/testproc.src.xml
./extensions/tests1/r/t.cc
./extensions/tests1/SMemoryTest/LostPassiveTestProc.cc
./extensions/tests1/SMemoryTest/LostPassiveTestProc.h
./extensions/tests1/SMemoryTest/LostTestProc.cc
./extensions/tests1/SMemoryTest/LostTestProc.h
./extensions/tests1/SMemoryTest/losttestproc.src.xml
./extensions/tests1/SMemoryTest/Makefile.am
./extensions/tests1/SMemoryTest/smemory-test.cc
./extensions/tests1/SMemoryTest/sm-lostmessage-test.cc
./extensions/tests1/SMemoryTest/TestProc.cc
./extensions/tests1/SMemoryTest/TestProc.h
./extensions/tests1/SMemoryTest/testproc.src.xml
./extensions/tests1/sm_perf_test2.cc
./extensions/tests1/sm_perf_test.cc
./extensions/tests1/sz.cc
./extensions/tests1/test_calibration.cc
./extensions/tests1/test_digitalfilter.cc
./extensions/tests1/test_iobase.cc
./extensions/tests1/test_iobase_with_sm.cc
./extensions/tests1/test_restapi_uniset.cc
./extensions/tests1/tests.cc
./extensions/tests1/tests_with_conf.cc
./extensions/tests1/tests_with_sm.cc
./extensions/tests1/tests_with_sm.h
./extensions/tests1/test_ui.cc
./extensions/tests1/test_vtypes.cc
./extensions/tests/Makefile.am
./extensions/tests/MBSlaveTest/Makefile.am
./extensions/tests/MBSlaveTest/mbslave-test.cc
......@@ -264,7 +232,6 @@
./extensions/UNetUDP/tests/Makefile.am
./extensions/UNetUDP/tests/tests_individual_process.cc
./extensions/UNetUDP/tests/tests_with_sm.cc
./extensions/UNetUDP/tests/test_unetudp1.cc
./extensions/UNetUDP/tests/test_unetudp.cc
./extensions/UNetUDP/tests/u.cc
./extensions/UNetUDP/tests/urecv_perf_test.cc
......@@ -358,6 +325,7 @@
./include/UA.h
./include/UDPCore.h
./include/UHelpers.h
./include/UHttpClient.h
./include/UHttpRequestHandler.h
./include/UHttpServer.h
./include/UInterface.h
......@@ -368,6 +336,7 @@
./include/unisetstd.h
./include/UniSetTypes.h
./include/UniXML.h
./include/UResolver.h
./include/USocket.h
./include/UTCPCore.h
./include/UTCPSocket.h
......@@ -380,6 +349,7 @@
./src/Communications/ComPort485F.cc
./src/Communications/ComPort.cc
./src/Communications/Http/Makefile.am
./src/Communications/Http/UHttpClient.cc
./src/Communications/Http/UHttpRequestHandler.cc
./src/Communications/Http/UHttpServer.cc
./src/Communications/Makefile.am
......@@ -416,6 +386,8 @@
./src/Core/UniSetObject_iSK.cc
./src/Core/UniSetTypes.cc
./src/Core/UniSetTypes_iSK.cc
./src/Core/UResolver.cc
./src/Core/UResolver_iSK.cc
./src/Log/Debug.cc
./src/Log/DebugExtBuf.h
./src/Log/DebugStream.cc
......
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