Commit 573defc9 authored by Pavel Vainerman's avatar Pavel Vainerman Committed by Pavel Vainerman

[conf]: supported external xml for configuration, supported create xml from text

parent 2455feab
...@@ -52,6 +52,9 @@ namespace uniset ...@@ -52,6 +52,9 @@ namespace uniset
/*! конфигурирование xml-файлом ( предпочтительный способ ) */ /*! конфигурирование xml-файлом ( предпочтительный способ ) */
Configuration( int argc, const char* const* argv, const std::string& xmlfile = "" ); Configuration( int argc, const char* const* argv, const std::string& xmlfile = "" );
/*! конфигурирование внешним xml */
Configuration( int argc, const char* const* argv, std::shared_ptr<UniXML> xml );
/*! конфигурирование xml-файлом */ /*! конфигурирование xml-файлом */
Configuration( int argc, const char* const* argv, std::shared_ptr<ObjectIndex> oind, const std::string& xmlfile = "" ); Configuration( int argc, const char* const* argv, std::shared_ptr<ObjectIndex> oind, const std::string& xmlfile = "" );
...@@ -251,6 +254,7 @@ namespace uniset ...@@ -251,6 +254,7 @@ namespace uniset
/*! инициализация "глобальной" конфигурации */ /*! инициализация "глобальной" конфигурации */
std::shared_ptr<Configuration> uniset_init( int argc, const char* const* argv, const std::string& xmlfile = "configure.xml" ); std::shared_ptr<Configuration> uniset_init( int argc, const char* const* argv, const std::string& xmlfile = "configure.xml" );
std::shared_ptr<Configuration> uniset_init( int argc, const char* const* argv, std::shared_ptr<UniXML> xml );
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
} // end of uniset namespace } // end of uniset namespace
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
......
...@@ -139,6 +139,9 @@ namespace uniset ...@@ -139,6 +139,9 @@ namespace uniset
std::string getFileName() const noexcept; std::string getFileName() const noexcept;
void createFromText( const std::string& text );
// Создать новый XML-документ // Создать новый XML-документ
void newDoc( const std::string& root_node, const std::string& xml_ver = "1.0"); void newDoc( const std::string& root_node, const std::string& xml_ver = "1.0");
......
...@@ -43,1437 +43,1466 @@ using namespace std; ...@@ -43,1437 +43,1466 @@ using namespace std;
static const string UniSetDefaultPort = "2809"; static const string UniSetDefaultPort = "2809";
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
static ostream& print_help( ostream& os, int width, const string& cmd, static ostream& print_help( ostream& os, int width, const string& cmd,
const string& help, const string& tab = "" ) const string& help, const string& tab = "" )
{ {
// чтобы не менять параметры основного потока // чтобы не менять параметры основного потока
// создаём свой stream... // создаём свой stream...
ostringstream info; ostringstream info;
info.setf(ios::left, ios::adjustfield); info.setf(ios::left, ios::adjustfield);
info << tab << setw(width) << cmd << " - " << help; info << tab << setw(width) << cmd << " - " << help;
return os << info.str(); return os << info.str();
} }
std::string uniset::Configuration::help() std::string uniset::Configuration::help()
{ {
ostringstream os; ostringstream os;
print_help(os, 25, "--confile", "Файл конфигурации. По умолчанию: configure.xml\n"); print_help(os, 25, "--confile", "Файл конфигурации. По умолчанию: configure.xml\n");
print_help(os, 25, "--uniset-port num", "использовать заданный порт (переопределяет 'port заданный в конф. файле в разделе <nodes><node.. port=''>)\n"); print_help(os, 25, "--uniset-port num", "использовать заданный порт (переопределяет 'port заданный в конф. файле в разделе <nodes><node.. port=''>)\n");
print_help(os, 25, "--localIOR {1,0}", "использовать локальные файлы для получения IOR (т.е. не использовать omniNames). Переопределяет параметр в конфигурационном файле.\n"); print_help(os, 25, "--localIOR {1,0}", "использовать локальные файлы для получения IOR (т.е. не использовать omniNames). Переопределяет параметр в конфигурационном файле.\n");
print_help(os, 25, "--transientIOR {1,0}", "использовать генерируемые IOR(не постоянные). Переопределяет параметр в конфигурационном файле. Default=0\n"); print_help(os, 25, "--transientIOR {1,0}", "использовать генерируемые IOR(не постоянные). Переопределяет параметр в конфигурационном файле. Default=0\n");
os << "\ndebug logs:\n"; os << "\ndebug logs:\n";
print_help(os, 25, "--ulog-add-levels", "добавить уровень вывода логов\n"); print_help(os, 25, "--ulog-add-levels", "добавить уровень вывода логов\n");
print_help(os, 25, "--ulog-del-levels", "удалить уровень вывода логов\n"); print_help(os, 25, "--ulog-del-levels", "удалить уровень вывода логов\n");
print_help(os, 25, "--ulog-show-microseconds", "Выводить время с микросекундами\n"); print_help(os, 25, "--ulog-show-microseconds", "Выводить время с микросекундами\n");
print_help(os, 25, "--ulog-show-milliseconds", "Выводить время с миллисекундами\n"); print_help(os, 25, "--ulog-show-milliseconds", "Выводить время с миллисекундами\n");
print_help(os, 25, "--ulog-no-debug", "отключение логов\n"); print_help(os, 25, "--ulog-no-debug", "отключение логов\n");
print_help(os, 25, "--ulog-logfile", "перенаправление лога в файл\n"); print_help(os, 25, "--ulog-logfile", "перенаправление лога в файл\n");
print_help(os, 25, "--ulog-levels N", "уровень 'говорливости' логов"); print_help(os, 25, "--ulog-levels N", "уровень 'говорливости' логов");
return os.str(); return os.str();
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
namespace uniset namespace uniset
{ {
static std::shared_ptr<Configuration> uconf; static std::shared_ptr<Configuration> uconf;
static std::shared_ptr<DebugStream> _ulog; static std::shared_ptr<DebugStream> _ulog;
std::shared_ptr<DebugStream> ulog() noexcept std::shared_ptr<DebugStream> ulog() noexcept
{ {
if( _ulog ) if( _ulog )
return _ulog; return _ulog;
_ulog = make_shared<DebugStream>(); _ulog = make_shared<DebugStream>();
_ulog->setLogName("ulog"); _ulog->setLogName("ulog");
return _ulog; return _ulog;
} }
std::shared_ptr<Configuration> uniset_conf() noexcept std::shared_ptr<Configuration> uniset_conf() noexcept
{ {
// Не делаем assert или exception // Не делаем assert или exception
// потому-что считаем, что может быть необходимость не вызывать uniset_init() // потому-что считаем, что может быть необходимость не вызывать uniset_init()
// Т.е. проверка if( uconf ) возлагается на пользователя. // Т.е. проверка if( uconf ) возлагается на пользователя.
// assert( uconf ); // assert( uconf );
// if( uconf == nullptr ) // if( uconf == nullptr )
// throw SystemError("Don`t init uniset configuration! First use uniset_init()."); // throw SystemError("Don`t init uniset configuration! First use uniset_init().");
return uconf; // см. uniset_init.. return uconf; // см. uniset_init..
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
Configuration::Configuration(): Configuration::Configuration():
oind(NULL), oind(NULL),
// _argc(0), unixml(nullptr),
// _argv(nullptr), // _argc(0),
NSName("NameService"), // _argv(nullptr),
repeatCount(2), repeatTimeout(100), NSName("NameService"),
localDBServer(uniset::DefaultObjectId), repeatCount(2), repeatTimeout(100),
localNode(uniset::DefaultObjectId), localDBServer(uniset::DefaultObjectId),
localNodeName(""), localNode(uniset::DefaultObjectId),
fileConfName(""), localNodeName(""),
heartbeat_msec(3000) fileConfName(""),
{ heartbeat_msec(3000)
// ulog.crit()<< " configuration FAILED!!!!!!!!!!!!!!!!!" << endl; {
// throw Exception(); // ulog.crit()<< " configuration FAILED!!!!!!!!!!!!!!!!!" << endl;
} // throw Exception();
}
Configuration::~Configuration()
{ Configuration::~Configuration()
if( oind ) {
oind.reset(); if( oind )
oind.reset();
if( unixml )
unixml.reset(); if( unixml )
unixml.reset();
for( int i = 0; i < _argc; i++ )
delete[] _argv[i]; for( int i = 0; i < _argc; i++ )
delete[] _argv[i];
delete[] _argv;
} delete[] _argv;
// --------------------------------------------------------------------------------- }
// ---------------------------------------------------------------------------------
Configuration::Configuration( int argc, const char* const* argv, const string& xmlfile ):
oind(nullptr), Configuration::Configuration( int argc, const char* const* argv, const string& xmlfile ):
unixml(nullptr), oind(nullptr),
// _argc(argc), unixml(nullptr),
// _argv(argv), // _argc(argc),
NSName("NameService"), // _argv(argv),
repeatCount(2), repeatTimeout(100), NSName("NameService"),
localDBServer(uniset::DefaultObjectId), repeatCount(2), repeatTimeout(100),
localNode(uniset::DefaultObjectId), localDBServer(uniset::DefaultObjectId),
localNodeName(""), localNode(uniset::DefaultObjectId),
fileConfName(xmlfile) localNodeName(""),
{ fileConfName(xmlfile)
initConfiguration(argc, argv); {
} initConfiguration(argc, argv);
// --------------------------------------------------------------------------------- }
Configuration::Configuration( int argc, const char* const* argv, shared_ptr<ObjectIndex> _oind, // ---------------------------------------------------------------------------------
const string& fileConf ): Configuration::Configuration( int argc, const char* const* argv, shared_ptr<ObjectIndex> _oind,
oind(nullptr), const string& fileConf ):
unixml(nullptr), oind(nullptr),
// _argc(argc), unixml(nullptr),
// _argv(argv), // _argc(argc),
NSName("NameService"), // _argv(argv),
repeatCount(2), repeatTimeout(100), NSName("NameService"),
localDBServer(uniset::DefaultObjectId), repeatCount(2), repeatTimeout(100),
localNode(uniset::DefaultObjectId), localDBServer(uniset::DefaultObjectId),
localNodeName(""), localNode(uniset::DefaultObjectId),
fileConfName(fileConf) localNodeName(""),
{ fileConfName(fileConf)
oind = _oind; {
initConfiguration(argc, argv); oind = _oind;
} initConfiguration(argc, argv);
// --------------------------------------------------------------------------------- }
Configuration::Configuration( int argc, const char* const* argv, const string& fileConf, // ---------------------------------------------------------------------------------
uniset::ObjectInfo* omap ): Configuration::Configuration( int argc, const char* const* argv, std::shared_ptr<UniXML> xml ):
oind(NULL), oind(nullptr),
// _argc(argc), unixml(xml),
// _argv(argv), NSName("NameService"),
NSName("NameService"), repeatCount(2), repeatTimeout(100),
repeatCount(2), repeatTimeout(100), localDBServer(uniset::DefaultObjectId),
localDBServer(uniset::DefaultObjectId), localNode(uniset::DefaultObjectId),
localNode(uniset::DefaultObjectId), localNodeName(""),
localNodeName(""), fileConfName(xml->getFileName())
fileConfName(fileConf) {
{ initConfiguration(argc, argv);
shared_ptr<ObjectIndex_Array> _oi = make_shared<ObjectIndex_Array>(omap); }
oind = static_pointer_cast<ObjectIndex>(_oi); // ---------------------------------------------------------------------------------
Configuration::Configuration( int argc, const char* const* argv, const string& fileConf,
initConfiguration(argc, argv); uniset::ObjectInfo* omap ):
} oind(NULL),
// --------------------------------------------------------------------------------- // _argc(argc),
void Configuration::initConfiguration( int argc, const char* const* argv ) // _argv(argv),
{ NSName("NameService"),
// т.к. мы не знаем откуда эти argc и argv и может они будут удалены сразу после завершения функции repeatCount(2), repeatTimeout(100),
// то надёжнее скопировать себе всё.. localDBServer(uniset::DefaultObjectId),
_argc = argc; localNode(uniset::DefaultObjectId),
_argv = new const char* [argc]; localNodeName(""),
fileConfName(fileConf)
for( int i = 0; i < argc; i++ ) {
_argv[i] = uniset::uni_strdup(argv[i]); shared_ptr<ObjectIndex_Array> _oi = make_shared<ObjectIndex_Array>(omap);
oind = static_pointer_cast<ObjectIndex>(_oi);
// инициализировать надо после argc,argv
if( fileConfName.empty() ) initConfiguration(argc, argv);
setConfFileName(); }
// ---------------------------------------------------------------------------------
// PassiveTimer pt(UniSetTimer::WaitUpTime); void Configuration::initConfiguration( int argc, const char* const* argv )
ulogsys << "*** configure from file: " << fileConfName << endl; {
// т.к. мы не знаем откуда эти argc и argv и может они будут удалены сразу после завершения функции
// ------------------------------------------------------------------------- // то надёжнее скопировать себе всё..
xmlSensorsSec = 0; _argc = argc;
xmlObjectsSec = 0; _argv = new const char* [argc];
xmlControllersSec = 0;
xmlServicesSec = 0; for( int i = 0; i < argc; i++ )
xmlNodesSec = 0; _argv[i] = uniset::uni_strdup(argv[i]);
// -------------------------------------------------------------------------
char curdir[FILENAME_MAX]; // инициализировать надо после argc,argv
if( fileConfName.empty() )
if( getcwd(curdir, FILENAME_MAX) == NULL ) setConfFileName();
rootDir = "";
else // PassiveTimer pt(UniSetTimer::WaitUpTime);
rootDir = string(curdir) + "/"; ulogsys << "*** configure from file: " << fileConfName << endl;
{ // -------------------------------------------------------------------------
ostringstream s; xmlSensorsSec = 0;
s << this << "NameService"; xmlObjectsSec = 0;
NSName = s.str(); xmlControllersSec = 0;
} xmlServicesSec = 0;
xmlNodesSec = 0;
try // -------------------------------------------------------------------------
{ char curdir[FILENAME_MAX];
try if( getcwd(curdir, FILENAME_MAX) == NULL )
{ rootDir = "";
if( !unixml ) else
unixml = make_shared<UniXML>(); rootDir = string(curdir) + "/";
if( !unixml->isOpen() ) {
{ ostringstream s;
uinfo << "(Configuration): open from file " << fileConfName << endl; s << this << "NameService";
unixml->open(fileConfName); NSName = s.str();
} }
}
catch(...) try
{ {
ostringstream err;
err << "(Configuration): FAILED open configuration from " << fileConfName; try
ulogany << err.str() << endl; {
throw uniset::SystemError(err.str()); if( !unixml )
} unixml = make_shared<UniXML>();
if( !unixml->isOpen() )
// cerr << "*************** initConfiguration: xmlOpen: " << pt.getCurrent() << " msec " << endl; {
// pt.reset(); uinfo << "(Configuration): open from file " << fileConfName << endl;
unixml->open(fileConfName);
// Init ObjectIndex interface }
{ }
if( oind == nullptr ) catch(...)
{ {
UniXML::iterator it = unixml->findNode(unixml->getFirstNode(), "ObjectsMap"); ostringstream err;
err << "(Configuration): FAILED open configuration from " << fileConfName;
if( !it ) ulogany << err.str() << endl;
{ throw uniset::SystemError(err.str());
ucrit << "(Configuration:init): not found <ObjectsMap> node in " << fileConfName << endl; }
throw uniset::SystemError("(Configuration:init): not found <ObjectsMap> node in " + fileConfName );
}
// cerr << "*************** initConfiguration: xmlOpen: " << pt.getCurrent() << " msec " << endl;
try // pt.reset();
{
if( it.getIntProp("idfromfile") == 0 ) // Init ObjectIndex interface
{ {
shared_ptr<ObjectIndex_XML> oi = make_shared<ObjectIndex_XML>(unixml); //(fileConfName); if( oind == nullptr )
oind = static_pointer_cast<ObjectIndex>(oi); {
} UniXML::iterator it = unixml->findNode(unixml->getFirstNode(), "ObjectsMap");
else
{ if( !it )
shared_ptr<ObjectIndex_idXML> oi = make_shared<ObjectIndex_idXML>(unixml); //(fileConfName); {
oind = static_pointer_cast<ObjectIndex>(oi); ucrit << "(Configuration:init): not found <ObjectsMap> node in " << fileConfName << endl;
} throw uniset::SystemError("(Configuration:init): not found <ObjectsMap> node in " + fileConfName );
} }
catch( const uniset::Exception& ex )
{ try
ucrit << ex << endl; {
throw; if( it.getIntProp("idfromfile") == 0 )
} {
} shared_ptr<ObjectIndex_XML> oi = make_shared<ObjectIndex_XML>(unixml); //(fileConfName);
} oind = static_pointer_cast<ObjectIndex>(oi);
}
// Настраиваем отладочные логи else
initLogStream(ulog(), "ulog"); {
shared_ptr<ObjectIndex_idXML> oi = make_shared<ObjectIndex_idXML>(unixml); //(fileConfName);
// default init... oind = static_pointer_cast<ObjectIndex>(oi);
transientIOR = false; }
localIOR = false; }
catch( const uniset::Exception& ex )
string lnode( getArgParam("--localNode") ); {
ucrit << ex << endl;
if( !lnode.empty() ) throw;
setLocalNode(lnode); }
}
initParameters(); }
initRepSections();
// Настраиваем отладочные логи
iorfile = make_shared<IORFile>(getLockDir()); initLogStream(ulog(), "ulog");
// localIOR // default init...
int lior = getArgInt("--localIOR"); transientIOR = false;
localIOR = false;
if( lior )
localIOR = lior; string lnode( getArgParam("--localNode") );
// transientIOR if( !lnode.empty() )
int tior = getArgInt("--transientIOR"); setLocalNode(lnode);
if( tior ) initParameters();
transientIOR = tior; initRepSections();
if( imagesDir[0] != '/' && imagesDir[0] != '.' ) iorfile = make_shared<IORFile>(getLockDir());
imagesDir = dataDir + imagesDir + "/";
// localIOR
// считываем список узлов int lior = getArgInt("--localIOR");
createNodesList();
if( lior )
std::list< std::pair<string, string> > omniParams; localIOR = lior;
// ---------------------------------------------------------------------------------
UniXML::iterator omniIt(unixml->findNode(unixml->getFirstNode(), "omniORB") ); // transientIOR
int tior = getArgInt("--transientIOR");
if( omniIt && omniIt.goChildren() )
{ if( tior )
for(; omniIt.getCurrent(); omniIt++ ) transientIOR = tior;
{
std::string p(omniIt.getProp("name")); if( imagesDir[0] != '/' && imagesDir[0] != '.' )
imagesDir = dataDir + imagesDir + "/";
if( p.empty() )
{ // считываем список узлов
uwarn << "(Configuration::init): unknown omniORB param...name=''" << endl; createNodesList();
}
else std::list< std::pair<string, string> > omniParams;
{ // ---------------------------------------------------------------------------------
// для endPoint надо отдельно проверить доступность адреса UniXML::iterator omniIt(unixml->findNode(unixml->getFirstNode(), "omniORB") );
// иначе инициализация omni не произойдёт, а нужно чтобы
// всё запускалось даже если сеть не вся "поднялась" if( omniIt && omniIt.goChildren() )
if( p == "endPoint" ) {
{ for(; omniIt.getCurrent(); omniIt++ )
const string param(omniIt.getProp("arg")); {
bool endPointIsAvailable = omniIt.getProp("ignore_checking").empty() ? checkOmniORBendPoint(param) : true; std::string p(omniIt.getProp("name"));
// по умолчанию "недоступность" игнорируется if( p.empty() )
// но если указан параметр 'error_if_not_available' {
// то кидаем исключение при недоступности uwarn << "(Configuration::init): unknown omniORB param...name=''" << endl;
if( !endPointIsAvailable && !omniIt.getProp("error_if_not_available").empty() ) }
{ else
ostringstream err; {
err << "Configuration: ERROR: endpoint '" // для endPoint надо отдельно проверить доступность адреса
<< param // иначе инициализация omni не произойдёт, а нужно чтобы
<< "' not available!"; // всё запускалось даже если сеть не вся "поднялась"
if( p == "endPoint" )
ucrit << err.str() << endl; {
throw Exception(err.str()); const string param(omniIt.getProp("arg"));
} bool endPointIsAvailable = omniIt.getProp("ignore_checking").empty() ? checkOmniORBendPoint(param) : true;
if( endPointIsAvailable ) // по умолчанию "недоступность" игнорируется
{ // но если указан параметр 'error_if_not_available'
uinfo << "(Configuration): add omniORB option '" << p << "' " << param << endl; // то кидаем исключение при недоступности
omniParams.emplace_back( std::make_pair(p, param) ); if( !endPointIsAvailable && !omniIt.getProp("error_if_not_available").empty() )
} {
} ostringstream err;
else err << "Configuration: ERROR: endpoint '"
{ << param
const string a(omniIt.getProp("arg")); << "' not available!";
uinfo << "(Configuration): add omniORB option '" << p << "' " << a << endl;
omniParams.emplace_back( std::make_pair(p, a) ); ucrit << err.str() << endl;
} throw Exception(err.str());
} }
}
} if( endPointIsAvailable )
{
uinfo << "(Configuration): add omniORB option '" << p << "' " << param << endl;
xmlNode* nsnode = getNode("NameService"); omniParams.emplace_back( std::make_pair(p, param) );
}
// --------------------------------------------------------------------------------- }
// формируем options для ORB_init() else
// Прототип из документации на omniORB4: const char* options[][2] = { { "traceLevel", "1" }, { 0, 0 } }; {
// -------------------------------------------------- const string a(omniIt.getProp("arg"));
// + спискок узлов (сформированный из configure.xml) uinfo << "(Configuration): add omniORB option '" << p << "' " << a << endl;
// + список параметров omniORB из секции <omniORB> omniParams.emplace_back( std::make_pair(p, a) );
// +1 для завершающего {0,0} }
int onum = lnodes.size() + omniParams.size() + 1; }
}
if( nsnode ) }
onum += 1; // +1 --> IniRef NameService=
const char* (*omni_options)[2] = new const char* [onum][2]; xmlNode* nsnode = getNode("NameService");
int i = 0; // ---------------------------------------------------------------------------------
// формируем options для ORB_init()
// формируем новые, используя i в качестве индекса // Прототип из документации на omniORB4: const char* options[][2] = { { "traceLevel", "1" }, { 0, 0 } };
for( const auto& it : lnodes ) // --------------------------------------------------
{ // + спискок узлов (сформированный из configure.xml)
// делаем uni_strdup чтобы потом не думая // + список параметров omniORB из секции <omniORB>
// "где мы выделяли, а где не мы" // +1 для завершающего {0,0}
// делать delete[] int onum = lnodes.size() + omniParams.size() + 1;
omni_options[i][0] = uni_strdup("InitRef");
if( nsnode )
string name(oind->getNodeName(it.id)); onum += 1; // +1 --> IniRef NameService=
ostringstream o;
o << this << name; const char* (*omni_options)[2] = new const char* [onum][2];
name = o.str();
o << "=corbaname::" << it.host << ":" << it.port; int i = 0;
omni_options[i][1] = uni_strdup(o.str());
// формируем новые, используя i в качестве индекса
uinfo << "(Configuration): add omniORB option 'InitRef' (nodes) " << o.str() << endl; for( const auto& it : lnodes )
i++; {
// делаем uni_strdup чтобы потом не думая
ostringstream uri; // "где мы выделяли, а где не мы"
uri << "corbaname::" << it.host << ":" << it.port; // делать delete[]
omni_options[i][0] = uni_strdup("InitRef");
if( !omni::omniInitialReferences::setFromArgs(name.c_str(), uri.str().c_str()) )
ucrit << "(Configuration): init omniInitialReferences: FAILED ADD name=" << name << " uri=" << uri.str() << endl; string name(oind->getNodeName(it.id));
ostringstream o;
assert( i < onum ); o << this << name;
} name = o.str();
o << "=corbaname::" << it.host << ":" << it.port;
for( const auto& p : omniParams ) omni_options[i][1] = uni_strdup(o.str());
{
// делаем uni_strdup чтобы потом не думая uinfo << "(Configuration): add omniORB option 'InitRef' (nodes) " << o.str() << endl;
// "где мы выделяли, а где не мы" i++;
// делать delete[]
omni_options[i][0] = uni_strdup(p.first); ostringstream uri;
omni_options[i][1] = uni_strdup(p.second); uri << "corbaname::" << it.host << ":" << it.port;
i++;
assert( i < onum ); if( !omni::omniInitialReferences::setFromArgs(name.c_str(), uri.str().c_str()) )
} ucrit << "(Configuration): init omniInitialReferences: FAILED ADD name=" << name << " uri=" << uri.str() << endl;
// initRef for NameService assert( i < onum );
if( nsnode ) }
{
// делаем uni_strdup чтобы потом не думая for( const auto& p : omniParams )
// "где мы выделяли, а где не мы" {
// делать delete[] // делаем uni_strdup чтобы потом не думая
omni_options[i][0] = uni_strdup("InitRef"); // "где мы выделяли, а где не мы"
string defPort( getPort( getProp(nsnode, "port") ) ); // делать delete[]
omni_options[i][0] = uni_strdup(p.first);
ostringstream param; omni_options[i][1] = uni_strdup(p.second);
param << this << "NameService=corbaname::" << getProp(nsnode, "host") << ":" << defPort; i++;
omni_options[i][1] = uni_strdup(param.str()); assert( i < onum );
uinfo << "(Configuration): add omniORB option 'InitRef' " << param.str() << endl; }
{ // initRef for NameService
ostringstream ns_name; if( nsnode )
ns_name << this << "NameService"; {
ostringstream uri; // делаем uni_strdup чтобы потом не думая
uri << "corbaname::" << getProp(nsnode, "host") << ":" << defPort; // "где мы выделяли, а где не мы"
// делать delete[]
if( !omni::omniInitialReferences::setFromArgs(ns_name.str().c_str(), uri.str().c_str()) ) omni_options[i][0] = uni_strdup("InitRef");
cerr << "**********************!!!! FAILED ADD name=" << ns_name.str() << " uri=" << uri.str() << endl; string defPort( getPort( getProp(nsnode, "port") ) );
}
ostringstream param;
i++; param << this << "NameService=corbaname::" << getProp(nsnode, "host") << ":" << defPort;
} omni_options[i][1] = uni_strdup(param.str());
else uinfo << "(Configuration): add omniORB option 'InitRef' " << param.str() << endl;
uwarn << "(Configuration): не нашли раздела 'NameService' \n";
{
omni_options[i][0] = 0; ostringstream ns_name;
omni_options[i][1] = 0; ns_name << this << "NameService";
// ------------- CORBA INIT ------------- ostringstream uri;
// orb init uri << "corbaname::" << getProp(nsnode, "host") << ":" << defPort;
orb = CORBA::ORB_init(_argc, (char**)_argv, "omniORB4", omni_options);
if( !omni::omniInitialReferences::setFromArgs(ns_name.str().c_str(), uri.str().c_str()) )
// освобождаем память.. cerr << "**********************!!!! FAILED ADD name=" << ns_name.str() << " uri=" << uri.str() << endl;
for( int k = 0; k < onum; k++ ) }
{
// на самом деле последний элемент = {0,0} i++;
// но delete от 0 разрешён и не приводит "к краху" }
// так что отдельно не обрабатываем этот случай. else
uwarn << "(Configuration): не нашли раздела 'NameService' \n";
delete[] omni_options[k][0]; // см. uni_strdup()
delete[] omni_options[k][1]; // см. uni_strdup() omni_options[i][0] = 0;
} omni_options[i][1] = 0;
// ------------- CORBA INIT -------------
delete[] omni_options; // orb init
orb = CORBA::ORB_init(_argc, (char**)_argv, "omniORB4", omni_options);
// create policy
CORBA::Object_var obj = orb->resolve_initial_references("RootPOA"); // освобождаем память..
PortableServer::POA_var root_poa = PortableServer::POA::_narrow(obj); for( int k = 0; k < onum; k++ )
{
if( transientIOR == false ) // на самом деле последний элемент = {0,0}
{ // но delete от 0 разрешён и не приводит "к краху"
policyList.length(3); // так что отдельно не обрабатываем этот случай.
policyList[0] = root_poa->create_lifespan_policy(PortableServer::PERSISTENT);
policyList[1] = root_poa->create_id_assignment_policy(PortableServer::USER_ID); delete[] omni_options[k][0]; // см. uni_strdup()
policyList[2] = root_poa->create_request_processing_policy(PortableServer::USE_ACTIVE_OBJECT_MAP_ONLY); delete[] omni_options[k][1]; // см. uni_strdup()
// policyList[3] = root_poa->create_thread_policy(PortableServer::SINGLE_THREAD_MODEL); }
}
else delete[] omni_options;
{
policyList.length(3); // create policy
policyList[0] = root_poa->create_lifespan_policy(PortableServer::TRANSIENT); CORBA::Object_var obj = orb->resolve_initial_references("RootPOA");
policyList[1] = root_poa->create_servant_retention_policy(PortableServer::RETAIN); PortableServer::POA_var root_poa = PortableServer::POA::_narrow(obj);
policyList[2] = root_poa->create_request_processing_policy(PortableServer::USE_ACTIVE_OBJECT_MAP_ONLY);
// policyList[3] = root_poa->create_thread_policy(PortableServer::SINGLE_THREAD_MODEL); if( transientIOR == false )
} {
policyList.length(3);
// --------------------------------------- policyList[0] = root_poa->create_lifespan_policy(PortableServer::PERSISTENT);
policyList[1] = root_poa->create_id_assignment_policy(PortableServer::USER_ID);
} policyList[2] = root_poa->create_request_processing_policy(PortableServer::USE_ACTIVE_OBJECT_MAP_ONLY);
catch( const uniset::Exception& ex ) // policyList[3] = root_poa->create_thread_policy(PortableServer::SINGLE_THREAD_MODEL);
{ }
ucrit << "Configuration:" << ex << endl; else
throw; {
} policyList.length(3);
catch(...) policyList[0] = root_poa->create_lifespan_policy(PortableServer::TRANSIENT);
{ policyList[1] = root_poa->create_servant_retention_policy(PortableServer::RETAIN);
ucrit << "Configuration: INIT FAILED!!!!" << endl; policyList[2] = root_poa->create_request_processing_policy(PortableServer::USE_ACTIVE_OBJECT_MAP_ONLY);
throw Exception("Configuration: INIT FAILED!!!!"); // policyList[3] = root_poa->create_thread_policy(PortableServer::SINGLE_THREAD_MODEL);
} }
// cerr << "*************** initConfiguration: " << pt.getCurrent() << " msec " << endl; // ---------------------------------------
}
}
// ------------------------------------------------------------------------- catch( const uniset::Exception& ex )
std::string Configuration::getArg2Param( const std::string& name, const std::string& defval, const std::string& defval2 ) const noexcept {
{ ucrit << "Configuration:" << ex << endl;
return uniset::getArg2Param(name, _argc, _argv, defval, defval2); throw;
} }
catch(...)
string Configuration::getArgParam( const string& name, const string& defval ) const noexcept {
{ ucrit << "Configuration: INIT FAILED!!!!" << endl;
return uniset::getArgParam(name, _argc, _argv, defval); throw Exception("Configuration: INIT FAILED!!!!");
} }
int Configuration::getArgInt( const string& name, const string& defval ) const noexcept // cerr << "*************** initConfiguration: " << pt.getCurrent() << " msec " << endl;
{ }
return uniset::uni_atoi(getArgParam( name, defval ));
} // -------------------------------------------------------------------------
std::string Configuration::getArg2Param( const std::string& name, const std::string& defval, const std::string& defval2 ) const noexcept
int Configuration::getArgPInt( const string& name, int defval ) const noexcept {
{ return uniset::getArg2Param(name, _argc, _argv, defval, defval2);
return uniset::getArgPInt(name, _argc, _argv, "", defval); }
}
string Configuration::getArgParam( const string& name, const string& defval ) const noexcept
int Configuration::getArgPInt( const string& name, const string& strdefval, int defval ) const noexcept {
{ return uniset::getArgParam(name, _argc, _argv, defval);
return uniset::getArgPInt(name, _argc, _argv, strdefval, defval); }
}
int Configuration::getArgInt( const string& name, const string& defval ) const noexcept
// ------------------------------------------------------------------------- {
void Configuration::initParameters() return uniset::uni_atoi(getArgParam( name, defval ));
{ }
xmlNode* root = unixml->findNode( unixml->getFirstNode(), "UniSet" );
int Configuration::getArgPInt( const string& name, int defval ) const noexcept
if( !root ) {
{ return uniset::getArgPInt(name, _argc, _argv, "", defval);
ucrit << "Configuration: INIT PARAM`s FAILED! <UniSet>...</UniSet> not found" << endl; }
throw uniset::SystemError("Configuration: INIT PARAM`s FAILED! <UniSet>...</UniSet> not found!");
} int Configuration::getArgPInt( const string& name, const string& strdefval, int defval ) const noexcept
{
UniXML::iterator it(root); return uniset::getArgPInt(name, _argc, _argv, strdefval, defval);
}
if( !it.goChildren() )
{ // -------------------------------------------------------------------------
ucrit << "Configuration: INIT PARAM`s FAILED!!!!" << endl; void Configuration::initParameters()
throw uniset::SystemError("Configuration: INIT PARAM`s FAILED!!!!"); {
} xmlNode* root = unixml->findNode( unixml->getFirstNode(), "UniSet" );
httpResolverPort = 8008; if( !root )
{
for( ; it.getCurrent(); it.goNext() ) ucrit << "Configuration: INIT PARAM`s FAILED! <UniSet>...</UniSet> not found" << endl;
{ throw uniset::SystemError("Configuration: INIT PARAM`s FAILED! <UniSet>...</UniSet> not found!");
string name( it.getName() ); }
if( name == "LocalNode" ) UniXML::iterator it(root);
{
if( localNode == uniset::DefaultObjectId ) if( !it.goChildren() )
{ {
string nodename( it.getProp("name") ); ucrit << "Configuration: INIT PARAM`s FAILED!!!!" << endl;
setLocalNode(nodename); throw uniset::SystemError("Configuration: INIT PARAM`s FAILED!!!!");
} }
}
else if( name == "LocalDBServer" ) httpResolverPort = 8008;
{
name = it.getProp("name"); for( ; it.getCurrent(); it.goNext() )
//DBServer {
string secDB( getServicesSection() + "/" + name); string name( it.getName() );
localDBServer = oind->getIdByName(secDB);
if( name == "LocalNode" )
if( localDBServer == DefaultObjectId ) {
{ if( localNode == uniset::DefaultObjectId )
ostringstream msg; {
msg << "Configuration: DBServer '" << secDB << "' not found ServiceID in <services>!"; string nodename( it.getProp("name") );
ucrit << msg.str() << endl; setLocalNode(nodename);
throw uniset::SystemError(msg.str()); }
} }
} else if( name == "LocalDBServer" )
else if( name == "CountOfNet" ) {
{ name = it.getProp("name");
countOfNet = it.getIntProp("name"); //DBServer
} string secDB( getServicesSection() + "/" + name);
else if( name == "RepeatTimeoutMS" ) localDBServer = oind->getIdByName(secDB);
{
repeatTimeout = it.getPIntProp("name", 50); if( localDBServer == DefaultObjectId )
} {
else if( name == "RepeatCount" ) ostringstream msg;
{ msg << "Configuration: DBServer '" << secDB << "' not found ServiceID in <services>!";
repeatCount = it.getPIntProp("name", 1); ucrit << msg.str() << endl;
} throw uniset::SystemError(msg.str());
else if( name == "ImagesPath" ) }
{ }
imagesDir = dataDir + it.getProp("name") + "/"; // ???????? else if( name == "CountOfNet" )
} {
else if( name == "HttpResolver" ) countOfNet = it.getIntProp("name");
{ }
httpResolverPort = it.getPIntProp("port", httpResolverPort); else if( name == "RepeatTimeoutMS" )
} {
else if( name == "LocalIOR" ) repeatTimeout = it.getPIntProp("name", 50);
{ }
localIOR = it.getIntProp("name"); else if( name == "RepeatCount" )
} {
else if( name == "TransientIOR" ) repeatCount = it.getPIntProp("name", 1);
{ }
transientIOR = it.getIntProp("name"); else if( name == "ImagesPath" )
} {
else if( name == "DataDir" ) imagesDir = dataDir + it.getProp("name") + "/"; // ????????
{ }
dataDir = it.getProp("name"); else if( name == "HttpResolver" )
{
if( dataDir.empty() ) httpResolverPort = it.getPIntProp("port", httpResolverPort);
dataDir = getRootDir(); }
} else if( name == "LocalIOR" )
else if( name == "BinDir" ) {
{ localIOR = it.getIntProp("name");
binDir = it.getProp("name"); }
else if( name == "TransientIOR" )
if( binDir.empty() ) {
binDir = getRootDir(); transientIOR = it.getIntProp("name");
} }
else if( name == "LogDir" ) else if( name == "DataDir" )
{ {
logDir = it.getProp("name"); dataDir = it.getProp("name");
if( logDir.empty() ) if( dataDir.empty() )
logDir = getRootDir(); dataDir = getRootDir();
} }
else if( name == "LockDir" ) else if( name == "BinDir" )
{ {
lockDir = it.getProp("name"); binDir = it.getProp("name");
if( lockDir.empty() ) if( binDir.empty() )
lockDir = getRootDir(); binDir = getRootDir();
} }
else if( name == "ConfDir" ) else if( name == "LogDir" )
{ {
confDir = it.getProp("name"); logDir = it.getProp("name");
if( confDir.empty() ) if( logDir.empty() )
confDir = getRootDir(); logDir = getRootDir();
} }
} else if( name == "LockDir" )
{
// Heartbeat init... lockDir = it.getProp("name");
xmlNode* cnode = getNode("HeartBeatTime");
if( lockDir.empty() )
if( cnode ) lockDir = getRootDir();
{ }
UniXML::iterator hit(cnode); else if( name == "ConfDir" )
heartbeat_msec = hit.getIntProp("msec"); {
confDir = it.getProp("name");
if( heartbeat_msec <= 0 )
heartbeat_msec = 3000; if( confDir.empty() )
} confDir = getRootDir();
}
// NC ready timeout init... }
cnode = getNode("NCReadyTimeout");
// Heartbeat init...
if( cnode ) xmlNode* cnode = getNode("HeartBeatTime");
{
UniXML::iterator hit(cnode); if( cnode )
ncreadytimeout_msec = hit.getIntProp("msec"); {
UniXML::iterator hit(cnode);
if( ncreadytimeout_msec < 0 ) heartbeat_msec = hit.getIntProp("msec");
ncreadytimeout_msec = UniSetTimer::WaitUpTime;
else if( ncreadytimeout_msec == 0 ) if( heartbeat_msec <= 0 )
ncreadytimeout_msec = 180000; heartbeat_msec = 3000;
} }
// startup ingore timeout init... // NC ready timeout init...
cnode = getNode("StartUpIgnoreTimeout"); cnode = getNode("NCReadyTimeout");
if( cnode ) if( cnode )
{ {
UniXML::iterator hit(cnode); UniXML::iterator hit(cnode);
startupIgnoretimeout_msec = hit.getIntProp("msec"); ncreadytimeout_msec = hit.getIntProp("msec");
if( startupIgnoretimeout_msec < 0 ) if( ncreadytimeout_msec < 0 )
startupIgnoretimeout_msec = UniSetTimer::WaitUpTime; ncreadytimeout_msec = UniSetTimer::WaitUpTime;
else if( startupIgnoretimeout_msec == 0 ) else if( ncreadytimeout_msec == 0 )
startupIgnoretimeout_msec = 5000; ncreadytimeout_msec = 180000;
} }
}
// ------------------------------------------------------------------------- // startup ingore timeout init...
void Configuration::setLocalNode( const string& nodename ) cnode = getNode("StartUpIgnoreTimeout");
{
localNode = oind->getIdByName(nodename); if( cnode )
{
if( localNode == DefaultObjectId ) UniXML::iterator hit(cnode);
{ startupIgnoretimeout_msec = hit.getIntProp("msec");
stringstream err;
err << "(Configuration::setLocalNode): Not found node '" << nodename << "'"; if( startupIgnoretimeout_msec < 0 )
ucrit << err.str() << endl; startupIgnoretimeout_msec = UniSetTimer::WaitUpTime;
throw uniset::SystemError(err.str()); else if( startupIgnoretimeout_msec == 0 )
} startupIgnoretimeout_msec = 5000;
}
localNodeName = nodename; }
oind->initLocalNode(localNode); // -------------------------------------------------------------------------
} void Configuration::setLocalNode( const string& nodename )
// ------------------------------------------------------------------------- {
bool Configuration::checkOmniORBendPoint( const std::string& endPoint ) localNode = oind->getIdByName(nodename);
{
// проверяем доступность endPoint попыткой создать соединение if( localNode == DefaultObjectId )
auto ep = omni::giopEndpoint::str2Endpoint( endPoint.c_str() ); {
stringstream err;
if( !ep ) err << "(Configuration::setLocalNode): Not found node '" << nodename << "'";
return false; ucrit << err.str() << endl;
throw uniset::SystemError(err.str());
bool ret = false; }
try localNodeName = nodename;
{ oind->initLocalNode(localNode);
ret = ep->Bind(); }
// -------------------------------------------------------------------------
if( ret ) bool Configuration::checkOmniORBendPoint( const std::string& endPoint )
ep->Shutdown(); {
} // проверяем доступность endPoint попыткой создать соединение
catch( std::exception& ex ) auto ep = omni::giopEndpoint::str2Endpoint( endPoint.c_str() );
{
uwarn << "(Configuration::checkOmniORBendPoint): " << ex.what() << endl; if( !ep )
ret = false; return false;
}
bool ret = false;
ulogsys << "(Configuration::checkOmniORBendPoint): check " << endPoint << " "
<< ( ret ? "OK" : "FAILED" ) try
<< endl; {
ret = ep->Bind();
return ret;
} if( ret )
// ------------------------------------------------------------------------- ep->Shutdown();
xmlNode* Configuration::getNode(const string& path) const noexcept }
{ catch( std::exception& ex )
return unixml->findNode(unixml->getFirstNode(), path); {
} uwarn << "(Configuration::checkOmniORBendPoint): " << ex.what() << endl;
// ------------------------------------------------------------------------- ret = false;
string Configuration::getProp(xmlNode* node, const string& name) const noexcept }
{
return UniXML::getProp(node, name); ulogsys << "(Configuration::checkOmniORBendPoint): check " << endPoint << " "
} << ( ret ? "OK" : "FAILED" )
int Configuration::getIntProp(xmlNode* node, const string& name) const noexcept << endl;
{
return UniXML::getIntProp(node, name); return ret;
} }
int Configuration::getPIntProp(xmlNode* node, const string& name, int def) const noexcept // -------------------------------------------------------------------------
{ xmlNode* Configuration::getNode(const string& path) const noexcept
return UniXML::getPIntProp(node, name, def); {
} return unixml->findNode(unixml->getFirstNode(), path);
}
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
string Configuration::getField(const string& path) const noexcept string Configuration::getProp(xmlNode* node, const string& name) const noexcept
{ {
return getProp(getNode(path), "name"); return UniXML::getProp(node, name);
} }
int Configuration::getIntProp(xmlNode* node, const string& name) const noexcept
// ------------------------------------------------------------------------- {
int Configuration::getIntField(const std::string& path) const noexcept return UniXML::getIntProp(node, name);
{ }
return unixml->getIntProp(getNode(path), "name"); int Configuration::getPIntProp(xmlNode* node, const string& name, int def) const noexcept
} {
return UniXML::getPIntProp(node, name, def);
// ------------------------------------------------------------------------- }
int Configuration::getPIntField(const std::string& path, int def) const noexcept
{ // -------------------------------------------------------------------------
int i = getIntField(path);; string Configuration::getField(const string& path) const noexcept
{
if (i <= 0) return getProp(getNode(path), "name");
return def; }
return i; // -------------------------------------------------------------------------
} int Configuration::getIntField(const std::string& path) const noexcept
{
// ------------------------------------------------------------------------- return unixml->getIntProp(getNode(path), "name");
xmlNode* Configuration::findNode(xmlNode* node, const std::string& snode, const std::string& sname) const noexcept }
{
if( !unixml->isOpen() ) // -------------------------------------------------------------------------
return 0; int Configuration::getPIntField(const std::string& path, int def) const noexcept
{
return unixml->findNode(node, snode, sname); int i = getIntField(path);;
}
// ------------------------------------------------------------------------- if (i <= 0)
string Configuration::getRootDir() const noexcept return def;
{
return rootDir; return i;
} }
// -------------------------------------------------------------------------
int Configuration::getArgc() const noexcept // -------------------------------------------------------------------------
{ xmlNode* Configuration::findNode(xmlNode* node, const std::string& snode, const std::string& sname) const noexcept
return _argc; {
} if( !unixml->isOpen() )
// ------------------------------------------------------------------------- return 0;
const char* const* Configuration::getArgv() const noexcept
{ return unixml->findNode(node, snode, sname);
return _argv; }
} // -------------------------------------------------------------------------
// ------------------------------------------------------------------------- string Configuration::getRootDir() const noexcept
ObjectId Configuration::getDBServer() const noexcept {
{ return rootDir;
return localDBServer; /*!< получение идентификатора DBServer-а */ }
} // -------------------------------------------------------------------------
// ------------------------------------------------------------------------- int Configuration::getArgc() const noexcept
ObjectId Configuration::getLocalNode() const noexcept {
{ return _argc;
return localNode; /*!< получение идентификатора локального узла */ }
} // -------------------------------------------------------------------------
// ------------------------------------------------------------------------- const char* const* Configuration::getArgv() const noexcept
string Configuration::getLocalNodeName() const noexcept {
{ return _argv;
return localNodeName; /*!< получение название локального узла */ }
} // -------------------------------------------------------------------------
// ------------------------------------------------------------------------- ObjectId Configuration::getDBServer() const noexcept
const string Configuration::getNSName() const noexcept {
{ return localDBServer; /*!< получение идентификатора DBServer-а */
return NSName; }
} // -------------------------------------------------------------------------
// ------------------------------------------------------------------------- ObjectId Configuration::getLocalNode() const noexcept
string Configuration::getRootSection() const noexcept {
{ return localNode; /*!< получение идентификатора локального узла */
return secRoot; }
} // -------------------------------------------------------------------------
// ------------------------------------------------------------------------- string Configuration::getLocalNodeName() const noexcept
string Configuration::getSensorsSection() const noexcept {
{ return localNodeName; /*!< получение название локального узла */
return secSensors; }
} // -------------------------------------------------------------------------
// ------------------------------------------------------------------------- const string Configuration::getNSName() const noexcept
string Configuration::getObjectsSection() const noexcept {
{ return NSName;
return secObjects; }
} // -------------------------------------------------------------------------
// ------------------------------------------------------------------------- string Configuration::getRootSection() const noexcept
string Configuration::getControllersSection() const noexcept {
{ return secRoot;
return secControlles; }
} // -------------------------------------------------------------------------
// ------------------------------------------------------------------------- string Configuration::getSensorsSection() const noexcept
string Configuration::getServicesSection() const noexcept {
{ return secSensors;
return secServices; }
} // -------------------------------------------------------------------------
string Configuration::getObjectsSection() const noexcept
// ------------------------------------------------------------------------- {
void Configuration::createNodesList() return secObjects;
{ }
xmlNode* omapnode = unixml->findNode(unixml->getFirstNode(), "ObjectsMap"); // -------------------------------------------------------------------------
string Configuration::getControllersSection() const noexcept
if( !omapnode ) {
{ return secControlles;
ucrit << "(Configuration): <ObjectsMap> not found!!!" << endl; }
throw uniset::SystemError("(Configuration): <ObjectsMap> not found!"); // -------------------------------------------------------------------------
} string Configuration::getServicesSection() const noexcept
{
return secServices;
xmlNode* node = unixml->findNode(omapnode, "nodes"); }
if(!node) // -------------------------------------------------------------------------
{ void Configuration::createNodesList()
ucrit << "(Configuration): <nodes> section not found!" << endl; {
throw uniset::SystemError("(Configiuration): <nodes> section not found"); xmlNode* omapnode = unixml->findNode(unixml->getFirstNode(), "ObjectsMap");
}
if( !omapnode )
UniXML::iterator it(node); {
(void)it.goChildren(); ucrit << "(Configuration): <ObjectsMap> not found!!!" << endl;
throw uniset::SystemError("(Configuration): <ObjectsMap> not found!");
// определяем порт }
string defPort(getPort(unixml->getProp(node, "port")));
lnodes.clear(); xmlNode* node = unixml->findNode(omapnode, "nodes");
for( ; it; it.goNext() ) if(!node)
{ {
string sname(getProp(it, "name")); ucrit << "(Configuration): <nodes> section not found!" << endl;
throw uniset::SystemError("(Configiuration): <nodes> section not found");
if(sname.empty()) }
{
ucrit << "Configuration(createNodesList): unknown name='' in <nodes> " << endl; UniXML::iterator it(node);
throw uniset::SystemError("Configuration(createNodesList: unknown name='' in <nodes>"); (void)it.goChildren();
}
// определяем порт
string nodename(sname); string defPort(getPort(unixml->getProp(node, "port")));
// string virtnode = oind->getVirtualNodeName(nodename);
// if( virtnode.empty() ) lnodes.clear();
// nodename = oind->mkFullNodeName(nodename,nodename);
for( ; it; it.goNext() )
NodeInfo ninf; {
ninf.id = oind->getIdByName(nodename); string sname(getProp(it, "name"));
if( ninf.id == DefaultObjectId ) if(sname.empty())
{ {
ucrit << "Configuration(createNodesList): Not found ID for node '" << nodename << "'" << endl; ucrit << "Configuration(createNodesList): unknown name='' in <nodes> " << endl;
throw uniset::SystemError("Configuration(createNodesList): Not found ID for node '" + nodename + "'"); throw uniset::SystemError("Configuration(createNodesList: unknown name='' in <nodes>");
} }
ninf.host = getProp(it, "ip").c_str(); string nodename(sname);
string tp(getProp(it, "port")); // string virtnode = oind->getVirtualNodeName(nodename);
// if( virtnode.empty() )
if( tp.empty() ) // nodename = oind->mkFullNodeName(nodename,nodename);
ninf.port = defPort.c_str();
else NodeInfo ninf;
ninf.port = tp.c_str(); ninf.id = oind->getIdByName(nodename);
string tmp(it.getProp("dbserver")); if( ninf.id == DefaultObjectId )
{
if( tmp.empty() ) ucrit << "Configuration(createNodesList): Not found ID for node '" << nodename << "'" << endl;
ninf.dbserver = uniset::DefaultObjectId; throw uniset::SystemError("Configuration(createNodesList): Not found ID for node '" + nodename + "'");
else }
{
string dname(getServicesSection() + "/" + tmp); ninf.host = getProp(it, "ip").c_str();
ninf.dbserver = oind->getIdByName(dname); string tp(getProp(it, "port"));
if( ninf.dbserver == DefaultObjectId ) if( tp.empty() )
{ ninf.port = defPort.c_str();
ucrit << "Configuration(createNodesList): Not found ID for DBServer name='" << dname << "'" << endl; else
throw uniset::SystemError("Configuration(createNodesList: Not found ID for DBServer name='" + dname + "'"); ninf.port = tp.c_str();
}
} string tmp(it.getProp("dbserver"));
if( ninf.id == getLocalNode() ) if( tmp.empty() )
localDBServer = ninf.dbserver; ninf.dbserver = uniset::DefaultObjectId;
else
ninf.connected = false; {
string dname(getServicesSection() + "/" + tmp);
initNode(ninf, it); ninf.dbserver = oind->getIdByName(dname);
uinfo << "Configuration(createNodesList): add to list of nodes: node=" << nodename << " id=" << ninf.id << endl;
lnodes.emplace_back( std::move(ninf) ); if( ninf.dbserver == DefaultObjectId )
} {
ucrit << "Configuration(createNodesList): Not found ID for DBServer name='" << dname << "'" << endl;
uinfo << "Configuration(createNodesList): size of node list " << lnodes.size() << endl; throw uniset::SystemError("Configuration(createNodesList: Not found ID for DBServer name='" + dname + "'");
} }
// ------------------------------------------------------------------------- }
void Configuration::initNode( uniset::NodeInfo& ninfo, UniXML::iterator& it ) noexcept
{ if( ninf.id == getLocalNode() )
if( ninfo.id == getLocalNode() ) localDBServer = ninf.dbserver;
ninfo.connected = true;
else ninf.connected = false;
ninfo.connected = false;
} initNode(ninf, it);
// ------------------------------------------------------------------------- uinfo << "Configuration(createNodesList): add to list of nodes: node=" << nodename << " id=" << ninf.id << endl;
string Configuration::getPropByNodeName(const string& nodename, const string& prop) const noexcept lnodes.emplace_back( std::move(ninf) );
{ }
xmlNode* node = getNode(nodename);
uinfo << "Configuration(createNodesList): size of node list " << lnodes.size() << endl;
if(node == NULL) }
return ""; // -------------------------------------------------------------------------
void Configuration::initNode( uniset::NodeInfo& ninfo, UniXML::iterator& it ) noexcept
return getProp(node, prop); {
} if( ninfo.id == getLocalNode() )
// ------------------------------------------------------------------------- ninfo.connected = true;
xmlNode* Configuration::initLogStream( std::shared_ptr<DebugStream> deb, const string& _debname ) noexcept else
{ ninfo.connected = false;
if( !deb ) }
return NULL; // -------------------------------------------------------------------------
string Configuration::getPropByNodeName(const string& nodename, const string& prop) const noexcept
return initLogStream( deb.get(), _debname ); {
} xmlNode* node = getNode(nodename);
// -------------------------------------------------------------------------
xmlNode* Configuration::initLogStream( DebugStream& deb, const string& _debname ) noexcept if(node == NULL)
{ return "";
return initLogStream(&deb, _debname);
} return getProp(node, prop);
// ------------------------------------------------------------------------- }
xmlNode* Configuration::initLogStream( DebugStream* deb, const string& _debname ) noexcept // -------------------------------------------------------------------------
{ xmlNode* Configuration::initLogStream( std::shared_ptr<DebugStream> deb, const string& _debname ) noexcept
if( !deb ) {
return nullptr; if( !deb )
return NULL;
if( _debname.empty() )
{ return initLogStream( deb.get(), _debname );
deb->any() << "(Configuration)(initLogStream): INIT DEBUG FAILED!!!" << endl; }
return nullptr; // -------------------------------------------------------------------------
} xmlNode* Configuration::initLogStream( DebugStream& deb, const string& _debname ) noexcept
{
return initLogStream(&deb, _debname);
string debname(_debname); }
// -------------------------------------------------------------------------
xmlNode* dnode = getNode(_debname); xmlNode* Configuration::initLogStream( DebugStream* deb, const string& _debname ) noexcept
{
if( dnode == NULL ) if( !deb )
deb->any() << "(Configuration)(initLogStream): WARNING! Not found conf. section for log '" << _debname << "'" << endl; return nullptr;
else if( deb->getLogName().empty() )
{ if( _debname.empty() )
if( !getProp(dnode, "name").empty() ) {
{ deb->any() << "(Configuration)(initLogStream): INIT DEBUG FAILED!!!" << endl;
debname = getProp(dnode, "name"); return nullptr;
deb->setLogName(debname); }
}
}
string debname(_debname);
string no_deb("--" + debname + "-no-debug");
xmlNode* dnode = getNode(_debname);
for (int i = 1; i < _argc; i++)
{ if( dnode == NULL )
if( no_deb == _argv[i] ) deb->any() << "(Configuration)(initLogStream): WARNING! Not found conf. section for log '" << _debname << "'" << endl;
{ else if( deb->getLogName().empty() )
deb->addLevel(Debug::NONE); {
return dnode; if( !getProp(dnode, "name").empty() )
} {
} debname = getProp(dnode, "name");
deb->setLogName(debname);
string debug_file(""); }
}
// смотрим настройки файла
if( dnode ) string no_deb("--" + debname + "-no-debug");
{
string conf_debug_levels(getProp(dnode, "levels")); for (int i = 1; i < _argc; i++)
{
if( !conf_debug_levels.empty() ) if( no_deb == _argv[i] )
deb->addLevel( Debug::value(conf_debug_levels) ); {
else deb->addLevel(Debug::NONE);
deb->addLevel(Debug::NONE); return dnode;
}
debug_file = getProp(dnode, "file"); }
}
string debug_file("");
// теперь смотрим командную строку
string logfile("--" + debname + "-logfile"); // смотрим настройки файла
string add_level("--" + debname + "-add-levels"); if( dnode )
string del_level("--" + debname + "-del-levels"); {
string show_msec("--" + debname + "-show-milliseconds"); string conf_debug_levels(getProp(dnode, "levels"));
string show_usec("--" + debname + "-show-microseconds");
string verb_level("--" + debname + "-verbosity"); if( !conf_debug_levels.empty() )
deb->addLevel( Debug::value(conf_debug_levels) );
// смотрим командную строку else
for (int i = 1; i < (_argc - 1); i++) deb->addLevel(Debug::NONE);
{
if( logfile == _argv[i] ) // "--debug-logfile" debug_file = getProp(dnode, "file");
{ }
debug_file = string(_argv[i + 1]);
} // теперь смотрим командную строку
else if( add_level == _argv[i] ) // "--debug-add-levels" string logfile("--" + debname + "-logfile");
{ string add_level("--" + debname + "-add-levels");
deb->addLevel(Debug::value(_argv[i + 1])); string del_level("--" + debname + "-del-levels");
} string show_msec("--" + debname + "-show-milliseconds");
else if( del_level == _argv[i] ) // "--debug-del-levels" string show_usec("--" + debname + "-show-microseconds");
{ string verb_level("--" + debname + "-verbosity");
deb->delLevel(Debug::value(_argv[i + 1]));
} // смотрим командную строку
else if( show_usec == _argv[i] ) for (int i = 1; i < (_argc - 1); i++)
{ {
deb->showMicroseconds(true); if( logfile == _argv[i] ) // "--debug-logfile"
} {
else if( show_msec == _argv[i] ) debug_file = string(_argv[i + 1]);
{ }
deb->showMilliseconds(true); else if( add_level == _argv[i] ) // "--debug-add-levels"
} {
else if( verb_level == _argv[i] ) deb->addLevel(Debug::value(_argv[i + 1]));
{ }
deb->verbose(uniset::uni_atoi(_argv[i+1])); else if( del_level == _argv[i] ) // "--debug-del-levels"
} {
} deb->delLevel(Debug::value(_argv[i + 1]));
}
if( !debug_file.empty() ) else if( show_usec == _argv[i] )
deb->logFile(debug_file); {
deb->showMicroseconds(true);
return dnode; }
} else if( show_msec == _argv[i] )
// ------------------------------------------------------------------------- {
uniset::ListOfNode::const_iterator Configuration::listNodesBegin() const noexcept deb->showMilliseconds(true);
{ }
return lnodes.begin(); else if( verb_level == _argv[i] )
} {
// ------------------------------------------------------------------------- deb->verbose(uniset::uni_atoi(_argv[i + 1]));
uniset::ListOfNode::const_iterator Configuration::listNodesEnd() const noexcept }
{ }
return lnodes.end();
} if( !debug_file.empty() )
// ------------------------------------------------------------------------- deb->logFile(debug_file);
const std::shared_ptr<UniXML> Configuration::getConfXML() const noexcept
{ return dnode;
return unixml; }
} // -------------------------------------------------------------------------
// ------------------------------------------------------------------------- uniset::ListOfNode::const_iterator Configuration::listNodesBegin() const noexcept
CORBA::ORB_ptr Configuration::getORB() const {
{ return lnodes.begin();
return CORBA::ORB::_duplicate(orb); }
} // -------------------------------------------------------------------------
// ------------------------------------------------------------------------- uniset::ListOfNode::const_iterator Configuration::listNodesEnd() const noexcept
const CORBA::PolicyList Configuration::getPolicy() const noexcept {
{ return lnodes.end();
return policyList; }
} // -------------------------------------------------------------------------
// ------------------------------------------------------------------------- const std::shared_ptr<UniXML> Configuration::getConfXML() const noexcept
static std::string makeSecName( const std::string& sec, const std::string& name ) noexcept {
{ return unixml;
ostringstream n; }
n << sec << "/" << name; // -------------------------------------------------------------------------
return n.str(); CORBA::ORB_ptr Configuration::getORB() const
} {
// ------------------------------------------------------------------------- return CORBA::ORB::_duplicate(orb);
void Configuration::initRepSections() }
{ // -------------------------------------------------------------------------
// Реализация под жёсткую структуру репозитория const CORBA::PolicyList Configuration::getPolicy() const noexcept
xmlNode* node( unixml->findNode(unixml->getFirstNode(), "RootSection") ); {
return policyList;
if( node == NULL ) }
{ // -------------------------------------------------------------------------
ostringstream msg; static std::string makeSecName( const std::string& sec, const std::string& name ) noexcept
msg << "Configuration(initRepSections): Not found section <RootSection> in " << fileConfName; {
ucrit << msg.str() << endl; ostringstream n;
throw uniset::SystemError(msg.str()); n << sec << "/" << name;
} return n.str();
}
secRoot = unixml->getProp(node, "name"); // -------------------------------------------------------------------------
void Configuration::initRepSections()
std::tie(secSensors, xmlSensorsSec) = getRepSectionName("sensors"); {
secSensors = makeSecName(secRoot, secSensors); // Реализация под жёсткую структуру репозитория
xmlNode* node( unixml->findNode(unixml->getFirstNode(), "RootSection") );
std::tie(secObjects, xmlObjectsSec) = getRepSectionName("objects");
secObjects = makeSecName(secRoot, secObjects); if( node == NULL )
{
std::tie(secControlles, xmlControllersSec) = getRepSectionName("controllers"); ostringstream msg;
secControlles = makeSecName(secRoot, secControlles); msg << "Configuration(initRepSections): Not found section <RootSection> in " << fileConfName;
ucrit << msg.str() << endl;
std::tie(secServices, xmlServicesSec) = getRepSectionName("services"); throw uniset::SystemError(msg.str());
secServices = makeSecName(secRoot, secServices); }
}
// ------------------------------------------------------------------------- secRoot = unixml->getProp(node, "name");
std::pair<string, xmlNode*> Configuration::getRepSectionName( const string& sec ) std::tie(secSensors, xmlSensorsSec) = getRepSectionName("sensors");
{ secSensors = makeSecName(secRoot, secSensors);
xmlNode* secnode = unixml->findNode(unixml->getFirstNode(), sec);
std::tie(secObjects, xmlObjectsSec) = getRepSectionName("objects");
if( secnode == NULL ) secObjects = makeSecName(secRoot, secObjects);
{
ostringstream msg; std::tie(secControlles, xmlControllersSec) = getRepSectionName("controllers");
msg << "Configuration(initRepSections): Not found section '" << sec << "' in " << fileConfName; secControlles = makeSecName(secRoot, secControlles);
ucrit << msg.str() << endl;
throw uniset::SystemError(msg.str()); std::tie(secServices, xmlServicesSec) = getRepSectionName("services");
} secServices = makeSecName(secRoot, secServices);
}
string ret(unixml->getProp(secnode, "section")); // -------------------------------------------------------------------------
if( ret.empty() ) std::pair<string, xmlNode*> Configuration::getRepSectionName( const string& sec )
ret = unixml->getProp(secnode, "name"); {
xmlNode* secnode = unixml->findNode(unixml->getFirstNode(), sec);
return std::make_pair(ret, secnode);
} if( secnode == NULL )
// ------------------------------------------------------------------------- {
void Configuration::setConfFileName( const string& fn ) ostringstream msg;
{ msg << "Configuration(initRepSections): Not found section '" << sec << "' in " << fileConfName;
if( !fn.empty() ) ucrit << msg.str() << endl;
{ throw uniset::SystemError(msg.str());
fileConfName = fn; }
return;
} string ret(unixml->getProp(secnode, "section"));
// Определение конфигурационного файла if( ret.empty() )
// в порядке убывания приоритета ret = unixml->getProp(secnode, "name");
string tmp( getArgParam("--confile") ); return std::make_pair(ret, secnode);
}
if( !tmp.empty() ) // -------------------------------------------------------------------------
{ void Configuration::setConfFileName( const string& fn )
fileConfName = tmp; {
} if( !fn.empty() )
else if( getenv("UNISET_CONFILE") != NULL ) {
{ fileConfName = fn;
fileConfName = getenv("UNISET_CONFILE"); return;
} }
if( fileConfName.empty() ) // Определение конфигурационного файла
{ // в порядке убывания приоритета
ostringstream msg;
msg << "\n\n***** CRIT: Unknown configure file." << endl string tmp( getArgParam("--confile") );
<< " Use --confile filename " << endl
<< " OR define enviropment variable UNISET_CONFILE" << endl; if( !tmp.empty() )
ucrit << msg.str(); {
throw uniset::SystemError(msg.str()); fileConfName = tmp;
} }
} else if( getenv("UNISET_CONFILE") != NULL )
// ------------------------------------------------------------------------- {
string Configuration::getPort( const string& port ) const noexcept fileConfName = getenv("UNISET_CONFILE");
{ }
// Порт задан в параметрах программы
string defport(getArgParam("--uniset-port")); if( fileConfName.empty() )
{
if( !defport.empty() ) ostringstream msg;
return defport; msg << "\n\n***** CRIT: Unknown configure file." << endl
<< " Use --confile filename " << endl
// Порт задан в переменной окружения << " OR define enviropment variable UNISET_CONFILE" << endl;
if( getenv("UNISET_PORT") != NULL ) ucrit << msg.str();
{ throw uniset::SystemError(msg.str());
defport = getenv("UNISET_PORT"); }
return defport; }
} // -------------------------------------------------------------------------
string Configuration::getPort( const string& port ) const noexcept
// Порт задан в параметрах {
if( !port.empty() ) // Порт задан в параметрах программы
return port; string defport(getArgParam("--uniset-port"));
// Порт по умолчанию if( !defport.empty() )
return UniSetDefaultPort; return defport;
}
// ------------------------------------------------------------------------- // Порт задан в переменной окружения
ObjectId Configuration::getSensorID( const std::string& name ) const noexcept if( getenv("UNISET_PORT") != NULL )
{ {
if( name.empty() ) defport = getenv("UNISET_PORT");
return DefaultObjectId; return defport;
}
return oind->getIdByName(getSensorsSection() + "/" + name);
} // Порт задан в параметрах
// ------------------------------------------------------------------------- if( !port.empty() )
ObjectId Configuration::getControllerID( const std::string& name ) const noexcept return port;
{
if( name.empty() ) // Порт по умолчанию
return DefaultObjectId; return UniSetDefaultPort;
}
return oind->getIdByName(getControllersSection() + "/" + name); // -------------------------------------------------------------------------
} ObjectId Configuration::getSensorID( const std::string& name ) const noexcept
// ------------------------------------------------------------------------- {
ObjectId Configuration::getObjectID( const std::string& name ) const noexcept if( name.empty() )
{ return DefaultObjectId;
if( name.empty() )
return DefaultObjectId; return oind->getIdByName(getSensorsSection() + "/" + name);
}
return oind->getIdByName(getObjectsSection() + "/" + name); // -------------------------------------------------------------------------
} ObjectId Configuration::getControllerID( const std::string& name ) const noexcept
// ------------------------------------------------------------------------- {
ObjectId Configuration::getServiceID( const std::string& name ) const noexcept if( name.empty() )
{ return DefaultObjectId;
if( name.empty() )
return DefaultObjectId; return oind->getIdByName(getControllersSection() + "/" + name);
}
return oind->getIdByName(getServicesSection() + "/" + name); // -------------------------------------------------------------------------
} ObjectId Configuration::getObjectID( const std::string& name ) const noexcept
// ------------------------------------------------------------------------- {
uniset::ObjectId Configuration::getNodeID( const std::string& name ) const noexcept if( name.empty() )
{ return DefaultObjectId;
if( name.empty() )
return DefaultObjectId; return oind->getIdByName(getObjectsSection() + "/" + name);
}
return oind->getNodeId( name ); // -------------------------------------------------------------------------
} ObjectId Configuration::getServiceID( const std::string& name ) const noexcept
// ------------------------------------------------------------------------- {
ObjectId Configuration::getAnyID( const string& name ) const noexcept if( name.empty() )
{ return DefaultObjectId;
ObjectId id = DefaultObjectId;
return oind->getIdByName(getServicesSection() + "/" + name);
if( uniset::is_digit(name) ) }
return uni_atoi(name); // -------------------------------------------------------------------------
uniset::ObjectId Configuration::getNodeID( const std::string& name ) const noexcept
// ищем в <sensors> {
id = getSensorID(name); if( name.empty() )
return DefaultObjectId;
// ищем в <objects>
if( id == DefaultObjectId ) return oind->getNodeId( name );
id = getObjectID(name); }
// -------------------------------------------------------------------------
// ищем в <controllers> ObjectId Configuration::getAnyID( const string& name ) const noexcept
if( id == DefaultObjectId ) {
id = getObjectID(name); ObjectId id = DefaultObjectId;
// ищем в <nodes> if( uniset::is_digit(name) )
if( id == DefaultObjectId ) return uni_atoi(name);
id = getNodeID(name);
// ищем в <sensors>
// ищем в <services> id = getSensorID(name);
if( id == DefaultObjectId )
id = getServiceID(name); // ищем в <objects>
if( id == DefaultObjectId )
return id; id = getObjectID(name);
}
// ------------------------------------------------------------------------- // ищем в <controllers>
const string Configuration::getConfFileName() const noexcept if( id == DefaultObjectId )
{ id = getObjectID(name);
return fileConfName;
} // ищем в <nodes>
// ------------------------------------------------------------------------- if( id == DefaultObjectId )
string Configuration::getImagesDir() const noexcept id = getNodeID(name);
{
return imagesDir; // временно // ищем в <services>
} if( id == DefaultObjectId )
// ------------------------------------------------------------------------- id = getServiceID(name);
timeout_t Configuration::getHeartBeatTime() const noexcept
{ return id;
return heartbeat_msec; }
} // -------------------------------------------------------------------------
const string Configuration::getConfFileName() const noexcept
timeout_t Configuration::getNCReadyTimeout() const noexcept {
{ return fileConfName;
return ncreadytimeout_msec; }
} // -------------------------------------------------------------------------
string Configuration::getImagesDir() const noexcept
timeout_t Configuration::getStartupIgnoreTimeout() const noexcept {
{ return imagesDir; // временно
return startupIgnoretimeout_msec; }
} // -------------------------------------------------------------------------
// ------------------------------------------------------------------------- timeout_t Configuration::getHeartBeatTime() const noexcept
const string Configuration::getConfDir() const noexcept {
{ return heartbeat_msec;
return confDir; }
}
timeout_t Configuration::getNCReadyTimeout() const noexcept
const string Configuration::getDataDir() const noexcept {
{ return ncreadytimeout_msec;
return dataDir; }
}
timeout_t Configuration::getStartupIgnoreTimeout() const noexcept
const string Configuration::getBinDir() const noexcept {
{ return startupIgnoretimeout_msec;
return binDir; }
} // -------------------------------------------------------------------------
const string Configuration::getConfDir() const noexcept
const string Configuration::getLogDir() const noexcept {
{ return confDir;
return logDir; }
}
const string Configuration::getDataDir() const noexcept
const string Configuration::getLockDir() const noexcept {
{ return dataDir;
return lockDir; }
}
const string Configuration::getBinDir() const noexcept
const string Configuration::getDocDir() const noexcept {
{ return binDir;
return docDir; }
}
const string Configuration::getLogDir() const noexcept
bool Configuration::isLocalIOR() const noexcept {
{ return logDir;
return localIOR; }
}
const string Configuration::getLockDir() const noexcept
bool Configuration::isTransientIOR() const noexcept {
{ return lockDir;
return transientIOR; }
}
const string Configuration::getDocDir() const noexcept
size_t Configuration::getHttpResovlerPort() const noexcept {
{ return docDir;
return httpResolverPort; }
}
bool Configuration::isLocalIOR() const noexcept
std::string Configuration::getNodeIp( uniset::ObjectId node ) {
{ return localIOR;
UniXML::iterator nIt = getXMLObjectNode(node); }
if( !nIt ) bool Configuration::isTransientIOR() const noexcept
return ""; {
return transientIOR;
return nIt.getProp("ip"); }
}
// ------------------------------------------------------------------------- size_t Configuration::getHttpResovlerPort() const noexcept
xmlNode* Configuration::getXMLSensorsSection() noexcept {
{ return httpResolverPort;
if( xmlSensorsSec ) }
return xmlSensorsSec;
std::string Configuration::getNodeIp( uniset::ObjectId node )
xmlSensorsSec = unixml->findNode(unixml->getFirstNode(), "sensors"); {
return xmlSensorsSec; UniXML::iterator nIt = getXMLObjectNode(node);
}
// ------------------------------------------------------------------------- if( !nIt )
xmlNode* Configuration::getXMLObjectsSection() noexcept return "";
{
if( xmlObjectsSec ) return nIt.getProp("ip");
return xmlObjectsSec; }
// -------------------------------------------------------------------------
xmlObjectsSec = unixml->findNode(unixml->getFirstNode(), "objects"); xmlNode* Configuration::getXMLSensorsSection() noexcept
return xmlObjectsSec; {
} if( xmlSensorsSec )
// ------------------------------------------------------------------------- return xmlSensorsSec;
xmlNode* Configuration::getXMLControllersSection() noexcept
{ xmlSensorsSec = unixml->findNode(unixml->getFirstNode(), "sensors");
if( xmlControllersSec ) return xmlSensorsSec;
return xmlControllersSec; }
// -------------------------------------------------------------------------
xmlControllersSec = unixml->findNode(unixml->getFirstNode(), "controllers"); xmlNode* Configuration::getXMLObjectsSection() noexcept
return xmlControllersSec; {
if( xmlObjectsSec )
} return xmlObjectsSec;
// -------------------------------------------------------------------------
xmlNode* Configuration::getXMLServicesSection() noexcept xmlObjectsSec = unixml->findNode(unixml->getFirstNode(), "objects");
{ return xmlObjectsSec;
if( xmlServicesSec ) }
return xmlServicesSec; // -------------------------------------------------------------------------
xmlNode* Configuration::getXMLControllersSection() noexcept
xmlServicesSec = unixml->findNode(unixml->getFirstNode(), "services"); {
return xmlServicesSec; if( xmlControllersSec )
} return xmlControllersSec;
// -------------------------------------------------------------------------
xmlNode* Configuration::getXMLNodesSection() noexcept xmlControllersSec = unixml->findNode(unixml->getFirstNode(), "controllers");
{ return xmlControllersSec;
if( xmlNodesSec )
return xmlNodesSec; }
// -------------------------------------------------------------------------
xmlNodesSec = unixml->findNode(unixml->getFirstNode(), "nodes"); xmlNode* Configuration::getXMLServicesSection() noexcept
return xmlNodesSec; {
} if( xmlServicesSec )
// ------------------------------------------------------------------------- return xmlServicesSec;
xmlNode* Configuration::getXMLObjectNode( uniset::ObjectId id ) const noexcept
{ xmlServicesSec = unixml->findNode(unixml->getFirstNode(), "services");
const ObjectInfo* i = oind->getObjectInfo(id); return xmlServicesSec;
}
if( i ) // -------------------------------------------------------------------------
return i->xmlnode; xmlNode* Configuration::getXMLNodesSection() noexcept
{
return 0; if( xmlNodesSec )
} return xmlNodesSec;
// -------------------------------------------------------------------------
UniversalIO::IOType Configuration::getIOType( uniset::ObjectId id ) const noexcept xmlNodesSec = unixml->findNode(unixml->getFirstNode(), "nodes");
{ return xmlNodesSec;
const ObjectInfo* i = oind->getObjectInfo(id); }
// -------------------------------------------------------------------------
if( i && i->xmlnode ) xmlNode* Configuration::getXMLObjectNode( uniset::ObjectId id ) const noexcept
{ {
UniXML::iterator it(i->xmlnode); const ObjectInfo* i = oind->getObjectInfo(id);
return uniset::getIOType( it.getProp("iotype") );
} if( i )
return i->xmlnode;
return UniversalIO::UnknownIOType;
} return 0;
// ------------------------------------------------------------------------- }
UniversalIO::IOType Configuration::getIOType( const std::string& name ) const noexcept // -------------------------------------------------------------------------
{ UniversalIO::IOType Configuration::getIOType( uniset::ObjectId id ) const noexcept
// Если указано "короткое" имя {
// то просто сперва ищём ID, а потом по нему const ObjectInfo* i = oind->getObjectInfo(id);
// iotype
ObjectId id = getSensorID(name); if( i && i->xmlnode )
{
if( id != DefaultObjectId ) UniXML::iterator it(i->xmlnode);
return getIOType(id); return uniset::getIOType( it.getProp("iotype") );
}
// Пробуем искать, считая, что задано mapname
// ("RootSection/Sensors/name") return UniversalIO::UnknownIOType;
const ObjectInfo* i = oind->getObjectInfo(name); }
// -------------------------------------------------------------------------
if( i && i->xmlnode ) UniversalIO::IOType Configuration::getIOType( const std::string& name ) const noexcept
{ {
UniXML::iterator it(i->xmlnode); // Если указано "короткое" имя
return uniset::getIOType( it.getProp("iotype") ); // то просто сперва ищём ID, а потом по нему
} // iotype
ObjectId id = getSensorID(name);
return UniversalIO::UnknownIOType;
} if( id != DefaultObjectId )
// ------------------------------------------------------------------------- return getIOType(id);
size_t Configuration::getCountOfNet() const noexcept
{ // Пробуем искать, считая, что задано mapname
return countOfNet; // ("RootSection/Sensors/name")
} const ObjectInfo* i = oind->getObjectInfo(name);
// -------------------------------------------------------------------------
timeout_t Configuration::getRepeatTimeout() const noexcept if( i && i->xmlnode )
{ {
return repeatTimeout; UniXML::iterator it(i->xmlnode);
} return uniset::getIOType( it.getProp("iotype") );
// ------------------------------------------------------------------------- }
size_t Configuration::getRepeatCount() const noexcept
{ return UniversalIO::UnknownIOType;
return repeatCount; }
} // -------------------------------------------------------------------------
// ------------------------------------------------------------------------- size_t Configuration::getCountOfNet() const noexcept
std::shared_ptr<Configuration> uniset_init( int argc, const char* const* argv, const std::string& xmlfile ) {
{ return countOfNet;
if( uniset::uconf ) }
{ // -------------------------------------------------------------------------
cerr << "Reusable call uniset_init... ignore.." << endl; timeout_t Configuration::getRepeatTimeout() const noexcept
return uniset::uconf; {
} return repeatTimeout;
}
// atexit( UniSetActivator::normalexit ); // -------------------------------------------------------------------------
// set_terminate( UniSetActivator::normalterminate ); // ловушка для неизвестных исключений size_t Configuration::getRepeatCount() const noexcept
{
string confile = uniset::getArgParam( "--confile", argc, argv, xmlfile ); return repeatCount;
uniset::uconf = make_shared<Configuration>(argc, argv, confile); }
// -------------------------------------------------------------------------
return uniset::uconf; std::shared_ptr<Configuration> uniset_init( int argc, const char* const* argv, const std::string& xmlfile )
} {
if( uniset::uconf )
// ------------------------------------------------------------------------- {
cerr << "Reusable call uniset_init... ignore.." << endl;
// ------------------------------------------------------------------------- return uniset::uconf;
}
// atexit( UniSetActivator::normalexit );
// set_terminate( UniSetActivator::normalterminate ); // ловушка для неизвестных исключений
string confile = uniset::getArgParam( "--confile", argc, argv, xmlfile );
uniset::uconf = make_shared<Configuration>(argc, argv, confile);
return uniset::uconf;
}
// -------------------------------------------------------------------------
std::shared_ptr<Configuration> uniset_init( int argc, const char* const* argv, std::shared_ptr<UniXML> xml )
{
if( uniset::uconf )
{
cerr << "Reusable call uniset_init... ignore.." << endl;
return uniset::uconf;
}
// atexit( UniSetActivator::normalexit );
// set_terminate( UniSetActivator::normalterminate ); // ловушка для неизвестных исключений
uniset::uconf = make_shared<Configuration>(argc, argv, xml);
return uniset::uconf;
}
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
} // end of UniSetTypes namespace } // end of UniSetTypes namespace
...@@ -49,7 +49,7 @@ UniXML::UniXML(const string& fname): ...@@ -49,7 +49,7 @@ UniXML::UniXML(const string& fname):
{ {
open(filename); open(filename);
} }
// -----------------------------------------------------------------------------
UniXML::UniXML() UniXML::UniXML()
{ {
} }
...@@ -64,7 +64,7 @@ string UniXML::getFileName() const noexcept ...@@ -64,7 +64,7 @@ string UniXML::getFileName() const noexcept
return filename; return filename;
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
void UniXML::newDoc(const string& root_node, const string& xml_ver) void UniXML::newDoc( const string& root_node, const string& xml_ver )
{ {
assert(doc == nullptr); // предыдущий doc не удален из памяти assert(doc == nullptr); // предыдущий doc не удален из памяти
...@@ -107,6 +107,33 @@ UniXML::iterator UniXML::end() noexcept ...@@ -107,6 +107,33 @@ UniXML::iterator UniXML::end() noexcept
return iterator(NULL); return iterator(NULL);
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
static void suppress(void *ctx, const char *msg, ...)
{
}
// -----------------------------------------------------------------------------
void UniXML::createFromText( const std::string& text )
{
assert(doc == nullptr); // предыдущий doc не удален из памяти
// hide console errors
// xmlSetGenericErrorFunc(NULL,suppress);
xmlKeepBlanksDefault(0);
// Can read files in any encoding, recode to UTF-8 internally
xmlDoc* d = xmlParseDoc((const xmlChar*)text.c_str());
if( d == NULL )
throw SystemError("UniXML(createFromText): parse error");
doc = std::unique_ptr<xmlDoc, UniXMLDocDeleter>(d);
// Support for XInclude (see eterbug #6304)
// main tag must to have follow property: xmlns:xi="http://www.w3.org/2001/XInclude"
//For include: <xi:include href="test2.xml"/>
xmlXIncludeProcess(doc.get());
}
// -----------------------------------------------------------------------------
void UniXML::open( const string& _filename ) void UniXML::open( const string& _filename )
{ {
assert( doc == nullptr ); // предыдущий doc не удален из памяти assert( doc == nullptr ); // предыдущий doc не удален из памяти
......
...@@ -210,3 +210,30 @@ TEST_CASE("UniXML::iterator::getPropList", "[unixml][iterator-proplist][basic]" ...@@ -210,3 +210,30 @@ TEST_CASE("UniXML::iterator::getPropList", "[unixml][iterator-proplist][basic]"
} }
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
TEST_CASE("UniXML createFromText", "[unixml][createFromText]" )
{
UniXML uxml;
CHECK_FALSE( uxml.isOpen() );
const string text = \
"<?xml version=\"1.0\" encoding=\"utf-8\"?> \
<TestConf xmlns:xi=\"http://www.w3.org/2001/XInclude\"> \
<UserData/> \
<UniSet> \
</UniSet> \
</TestConf>";
REQUIRE_NOTHROW(uxml.createFromText(text));
CHECK( uxml.isOpen() );
xmlNode* cnode = uxml.findNode(uxml.getFirstNode(), "UniSet");
CHECK( cnode != NULL );
uxml.close();
CHECK_FALSE( uxml.isOpen() );
const string badtext = "<?xml version=";
REQUIRE_THROWS_AS(uxml.createFromText(badtext), uniset::SystemError& );
}
// -----------------------------------------------------------------------------
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