Commit 6e177d62 authored by Pavel Vainerman's avatar Pavel Vainerman

(DB): глобальный рефакторинг: встроил в DBServer-а поддержку LogServer.

parent ea2e7544
...@@ -32,15 +32,13 @@ ...@@ -32,15 +32,13 @@
#include "Configuration.h" #include "Configuration.h"
#include "Debug.h" #include "Debug.h"
#include "UniXML.h" #include "UniXML.h"
#include "DBLogSugar.h"
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
using namespace UniSetTypes; using namespace UniSetTypes;
using namespace std; using namespace std;
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
#define dblog if( ulog()->debugging(DBLogInfoLevel) ) ulog()->debug(DBLogInfoLevel) DBServer_MySQL::DBServer_MySQL(ObjectId id, const std::string& prefix ):
// -------------------------------------------------------------------------- DBServer(id,prefix),
DBServer_MySQL::DBServer_MySQL(ObjectId id):
DBServer(id),
db(new MySQLInterface()),
PingTime(300000), PingTime(300000),
ReconnectTime(180000), ReconnectTime(180000),
connect_ok(false), connect_ok(false),
...@@ -55,41 +53,26 @@ DBServer_MySQL::DBServer_MySQL(ObjectId id): ...@@ -55,41 +53,26 @@ DBServer_MySQL::DBServer_MySQL(ObjectId id):
throw Exception(msg.str()); throw Exception(msg.str());
} }
db = make_shared<MySQLInterface>();
mqbuf.setName(myname + "_qbufMutex"); mqbuf.setName(myname + "_qbufMutex");
} }
DBServer_MySQL::DBServer_MySQL(): DBServer_MySQL::DBServer_MySQL( const std::string& prefix ):
DBServer(uniset_conf()->getDBServer()), DBServer_MySQL(uniset_conf()->getDBServer(),prefix)
db(new MySQLInterface()),
PingTime(300000),
ReconnectTime(180000),
connect_ok(false),
activate(true),
qbufSize(200),
lastRemove(false)
{ {
// init();
if( getId() == DefaultObjectId )
{
ostringstream msg;
msg << "(DBServer_MySQL): init failed! Unknown ID!" << endl;
throw Exception(msg.str());
}
mqbuf.setName(myname + "_qbufMutex");
} }
//-------------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------------
DBServer_MySQL::~DBServer_MySQL() DBServer_MySQL::~DBServer_MySQL()
{ {
if( db != NULL ) if( db )
{
db->close(); db->close();
delete db;
}
} }
//-------------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------------
void DBServer_MySQL::sysCommand( const UniSetTypes::SystemMessage* sm ) void DBServer_MySQL::sysCommand( const UniSetTypes::SystemMessage* sm )
{ {
DBServer::sysCommand(sm);
switch( sm->command ) switch( sm->command )
{ {
case SystemMessage::StartUp: case SystemMessage::StartUp:
...@@ -128,26 +111,26 @@ void DBServer_MySQL::confirmInfo( const UniSetTypes::ConfirmMessage* cem ) ...@@ -128,26 +111,26 @@ void DBServer_MySQL::confirmInfo( const UniSetTypes::ConfirmMessage* cem )
<< " AND time='" << timeToString(cem->time, ":") << " '" << " AND time='" << timeToString(cem->time, ":") << " '"
<< " AND time_usec='" << cem->time_usec << " '"; << " AND time_usec='" << cem->time_usec << " '";
dblog << myname << "(update_confirm): " << data.str() << endl; dbinfo << myname << "(update_confirm): " << data.str() << endl;
if( !writeToBase(data.str()) ) if( !writeToBase(data.str()) )
{ {
ucrit << myname << "(update_confirm): db error: " << db->error() << endl; dbcrit << myname << "(update_confirm): db error: " << db->error() << endl;
} }
} }
catch( const Exception& ex ) catch( const Exception& ex )
{ {
ucrit << myname << "(update_confirm): " << ex << endl; dbcrit << myname << "(update_confirm): " << ex << endl;
} }
catch( const std::exception& ex ) catch( const std::exception& ex )
{ {
ucrit << myname << "(update_confirm): exception: " << ex.what() << endl; dbcrit << myname << "(update_confirm): exception: " << ex.what() << endl;
} }
} }
//-------------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------------
bool DBServer_MySQL::writeToBase( const string& query ) bool DBServer_MySQL::writeToBase( const string& query )
{ {
dblog << myname << "(writeToBase): " << query << endl; dbinfo << myname << "(writeToBase): " << query << endl;
// cout << "DBServer_MySQL: " << query << endl; // cout << "DBServer_MySQL: " << query << endl;
if( !db || !connect_ok ) if( !db || !connect_ok )
...@@ -166,7 +149,7 @@ bool DBServer_MySQL::writeToBase( const string& query ) ...@@ -166,7 +149,7 @@ bool DBServer_MySQL::writeToBase( const string& query )
qbuf.pop(); qbuf.pop();
ucrit << myname << "(writeToBase): DB not connected! buffer(" << qbufSize dbcrit << myname << "(writeToBase): DB not connected! buffer(" << qbufSize
<< ") overflow! lost query: " << qlost << endl; << ") overflow! lost query: " << qlost << endl;
} }
...@@ -207,7 +190,7 @@ void DBServer_MySQL::flushBuffer() ...@@ -207,7 +190,7 @@ void DBServer_MySQL::flushBuffer()
string err(db->error()); string err(db->error());
if( !err.empty() ) if( !err.empty() )
ucrit << myname << "(writeToBase): error: " << err << dbcrit << myname << "(writeToBase): error: " << err <<
" lost query: " << qbuf.front() << endl; " lost query: " << qbuf.front() << endl;
qbuf.pop(); qbuf.pop();
...@@ -239,27 +222,27 @@ void DBServer_MySQL::sensorInfo( const UniSetTypes::SensorMessage* si ) ...@@ -239,27 +222,27 @@ void DBServer_MySQL::sensorInfo( const UniSetTypes::SensorMessage* si )
<< val << "','" // value << val << "','" // value
<< si->node << "')"; // node << si->node << "')"; // node
dblog << myname << "(insert_main_history): " << data.str() << endl; dbinfo << myname << "(insert_main_history): " << data.str() << endl;
if( !writeToBase(data.str()) ) if( !writeToBase(data.str()) )
{ {
ucrit << myname << "(insert) sensor msg error: " << db->error() << endl; dbcrit << myname << "(insert) sensor msg error: " << db->error() << endl;
} }
} }
catch( const Exception& ex ) catch( const Exception& ex )
{ {
ucrit << myname << "(insert_main_history): " << ex << endl; dbcrit << myname << "(insert_main_history): " << ex << endl;
} }
catch( const std::exception& ex ) catch( const std::exception& ex )
{ {
ucrit << myname << "(insert_main_history): catch: " << ex.what() << endl; dbcrit << myname << "(insert_main_history): catch: " << ex.what() << endl;
} }
} }
//-------------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------------
void DBServer_MySQL::init_dbserver() void DBServer_MySQL::initDBServer()
{ {
DBServer::init_dbserver(); DBServer::initDBServer();
dblog << myname << "(init): ..." << endl; dbinfo << myname << "(init): ..." << endl;
if( connect_ok ) if( connect_ok )
{ {
...@@ -286,7 +269,7 @@ void DBServer_MySQL::init_dbserver() ...@@ -286,7 +269,7 @@ void DBServer_MySQL::init_dbserver()
UniXML::iterator it(node); UniXML::iterator it(node);
dblog << myname << "(init): init connection.." << endl; dbinfo << myname << "(init): init connection.." << endl;
string dbname(conf->getProp(node, "dbname")); string dbname(conf->getProp(node, "dbname"));
string dbnode(conf->getProp(node, "dbnode")); string dbnode(conf->getProp(node, "dbnode"));
string user(conf->getProp(node, "dbuser")); string user(conf->getProp(node, "dbuser"));
...@@ -309,7 +292,7 @@ void DBServer_MySQL::init_dbserver() ...@@ -309,7 +292,7 @@ void DBServer_MySQL::init_dbserver()
if( dbnode.empty() ) if( dbnode.empty() )
dbnode = "localhost"; dbnode = "localhost";
dblog << myname << "(init): connect dbnode=" << dbnode dbinfo << myname << "(init): connect dbnode=" << dbnode
<< "\tdbname=" << dbname << "\tdbname=" << dbname
<< " pingTime=" << PingTime << " pingTime=" << PingTime
<< " ReconnectTime=" << ReconnectTime << endl; << " ReconnectTime=" << ReconnectTime << endl;
...@@ -317,7 +300,7 @@ void DBServer_MySQL::init_dbserver() ...@@ -317,7 +300,7 @@ void DBServer_MySQL::init_dbserver()
if( !db->connect(dbnode, user, password, dbname) ) if( !db->connect(dbnode, user, password, dbname) )
{ {
// ostringstream err; // ostringstream err;
ucrit << myname dbcrit << myname
<< "(init): DB connection error: " << "(init): DB connection error: "
<< db->error() << endl; << db->error() << endl;
// throw Exception( string(myname+"(init): не смогли создать соединение с БД "+db->error()) ); // throw Exception( string(myname+"(init): не смогли создать соединение с БД "+db->error()) );
...@@ -325,7 +308,7 @@ void DBServer_MySQL::init_dbserver() ...@@ -325,7 +308,7 @@ void DBServer_MySQL::init_dbserver()
} }
else else
{ {
dblog << myname << "(init): connect [OK]" << endl; dbinfo << myname << "(init): connect [OK]" << endl;
connect_ok = true; connect_ok = true;
askTimer(DBServer_MySQL::ReconnectTimer, 0); askTimer(DBServer_MySQL::ReconnectTimer, 0);
askTimer(DBServer_MySQL::PingTimer, PingTime); askTimer(DBServer_MySQL::PingTimer, PingTime);
...@@ -344,7 +327,7 @@ void DBServer_MySQL::createTables( MySQLInterface* db ) ...@@ -344,7 +327,7 @@ void DBServer_MySQL::createTables( MySQLInterface* db )
if(!it) if(!it)
{ {
ucrit << myname << ": section <Tables> not found.." << endl; dbcrit << myname << ": section <Tables> not found.." << endl;
throw Exception(); throw Exception();
} }
...@@ -352,25 +335,27 @@ void DBServer_MySQL::createTables( MySQLInterface* db ) ...@@ -352,25 +335,27 @@ void DBServer_MySQL::createTables( MySQLInterface* db )
{ {
if( it.getName() != "comment" ) if( it.getName() != "comment" )
{ {
dblog << myname << "(createTables): create " << it.getName() << endl; dbinfo << myname << "(createTables): create " << it.getName() << endl;
ostringstream query; ostringstream query;
query << "CREATE TABLE " << conf->getProp(it, "name") << "(" << conf->getProp(it, "create") << ")"; query << "CREATE TABLE " << conf->getProp(it, "name") << "(" << conf->getProp(it, "create") << ")";
if( !db->query(query.str()) ) if( !db->query(query.str()) )
ucrit << myname << "(createTables): error: \t\t" << db->error() << endl; dbcrit << myname << "(createTables): error: \t\t" << db->error() << endl;
} }
} }
} }
//-------------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------------
void DBServer_MySQL::timerInfo( const UniSetTypes::TimerMessage* tm ) void DBServer_MySQL::timerInfo( const UniSetTypes::TimerMessage* tm )
{ {
DBServer::timerInfo(tm);
switch( tm->id ) switch( tm->id )
{ {
case DBServer_MySQL::PingTimer: case DBServer_MySQL::PingTimer:
{ {
if( !db->ping() ) if( !db->ping() )
{ {
uwarn << myname << "(timerInfo): DB lost connection.." << endl; dbwarn << myname << "(timerInfo): DB lost connection.." << endl;
connect_ok = false; connect_ok = false;
askTimer(DBServer_MySQL::PingTimer, 0); askTimer(DBServer_MySQL::PingTimer, 0);
askTimer(DBServer_MySQL::ReconnectTimer, ReconnectTime); askTimer(DBServer_MySQL::ReconnectTimer, ReconnectTime);
...@@ -378,14 +363,14 @@ void DBServer_MySQL::timerInfo( const UniSetTypes::TimerMessage* tm ) ...@@ -378,14 +363,14 @@ void DBServer_MySQL::timerInfo( const UniSetTypes::TimerMessage* tm )
else else
{ {
connect_ok = true; connect_ok = true;
dblog << myname << "(timerInfo): DB ping ok" << endl; dbinfo << myname << "(timerInfo): DB ping ok" << endl;
} }
} }
break; break;
case DBServer_MySQL::ReconnectTimer: case DBServer_MySQL::ReconnectTimer:
{ {
dblog << myname << "(timerInfo): reconnect timer" << endl; dbinfo << myname << "(timerInfo): reconnect timer" << endl;
if( db->isConnection() ) if( db->isConnection() )
{ {
...@@ -397,16 +382,46 @@ void DBServer_MySQL::timerInfo( const UniSetTypes::TimerMessage* tm ) ...@@ -397,16 +382,46 @@ void DBServer_MySQL::timerInfo( const UniSetTypes::TimerMessage* tm )
} }
connect_ok = false; connect_ok = false;
uwarn << myname << "(timerInfo): DB no connection.." << endl; dbwarn << myname << "(timerInfo): DB no connection.." << endl;
} }
else else
init_dbserver(); initDBServer();
} }
break; break;
default: default:
uwarn << myname << "(timerInfo): Unknown TimerID=" << tm->id << endl; dbwarn << myname << "(timerInfo): Unknown TimerID=" << tm->id << endl;
break; break;
} }
} }
//-------------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------------
std::shared_ptr<DBServer_MySQL> DBServer_MySQL::init_dbserver( int argc, const char* const* argv, const std::string& prefix )
{
auto conf = uniset_conf();
ObjectId ID = conf->getDBServer();
string name = conf->getArgParam("--" + prefix + "-name", "");
if( !name.empty() )
{
ObjectId ID = conf->getObjectID(name);
if( ID == UniSetTypes::DefaultObjectId )
{
cerr << "(DBServer_MySQL): Unknown ObjectID for '" << name << endl;
return 0;
}
}
uinfo << "(DBServer_MySQL): name = " << name << "(" << ID << ")" << endl;
return make_shared<DBServer_MySQL>(ID, prefix);
}
// -----------------------------------------------------------------------------
void DBServer_MySQL::help_print( int argc, const char* const* argv )
{
cout << "Default: prefix='mysql'" << endl;
cout << "--prefix-name objectID - ObjectID. Default: 'conf->getDBServer()'" << endl;
cout << DBServer::help_print() << endl;
}
// -----------------------------------------------------------------------------
...@@ -135,16 +135,21 @@ class DBServer_MySQL: ...@@ -135,16 +135,21 @@ class DBServer_MySQL:
public DBServer public DBServer
{ {
public: public:
DBServer_MySQL( UniSetTypes::ObjectId id ); DBServer_MySQL( UniSetTypes::ObjectId id, const std::string& prefix );
DBServer_MySQL(); DBServer_MySQL( const std::string& prefix );
~DBServer_MySQL(); virtual ~DBServer_MySQL();
static const Debug::type DBLogInfoLevel = Debug::LEVEL9; /*! глобальная функция для инициализации объекта */
static std::shared_ptr<DBServer_MySQL> init_dbserver( int argc, const char* const* argv, const std::string& prefix = "mysql" );
/*! глобальная функция для вывода help-а */
static void help_print( int argc, const char* const* argv );
protected: protected:
typedef std::map<int, std::string> DBTableMap; typedef std::map<int, std::string> DBTableMap;
virtual void initDB(MySQLInterface* db) {}; virtual void initDBServer() override;
virtual void initDB( std::shared_ptr<MySQLInterface>& db ) {};
virtual void initDBTableMap(DBTableMap& tblMap) {}; virtual void initDBTableMap(DBTableMap& tblMap) {};
virtual void timerInfo( const UniSetTypes::TimerMessage* tm ) override; virtual void timerInfo( const UniSetTypes::TimerMessage* tm ) override;
...@@ -153,7 +158,6 @@ class DBServer_MySQL: ...@@ -153,7 +158,6 @@ class DBServer_MySQL:
virtual void confirmInfo( const UniSetTypes::ConfirmMessage* cmsg ) override; virtual void confirmInfo( const UniSetTypes::ConfirmMessage* cmsg ) override;
bool writeToBase( const string& query ); bool writeToBase( const string& query );
virtual void init_dbserver();
void createTables( MySQLInterface* db ); void createTables( MySQLInterface* db );
inline const char* tblName(int key) inline const char* tblName(int key)
...@@ -169,7 +173,7 @@ class DBServer_MySQL: ...@@ -169,7 +173,7 @@ class DBServer_MySQL:
}; };
MySQLInterface* db; std::shared_ptr<MySQLInterface> db;
int PingTime; int PingTime;
int ReconnectTime; int ReconnectTime;
bool connect_ok; /*! признак наличия соеднинения с сервером БД */ bool connect_ok; /*! признак наличия соеднинения с сервером БД */
......
...@@ -6,58 +6,25 @@ ...@@ -6,58 +6,25 @@
using namespace UniSetTypes; using namespace UniSetTypes;
using namespace std; using namespace std;
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
static void short_usage()
{
cout << "Usage: uniset-mysql-dbserver [--name ObjectId] [--confile configure.xml]\n";
}
// --------------------------------------------------------------------------
int main(int argc, char** argv) int main(int argc, char** argv)
{ {
std::ios::sync_with_stdio(false); std::ios::sync_with_stdio(false);
try try
{ {
if( argc > 1 && !strcmp(argv[1], "--help") ) if( argc > 1 && (!strcmp(argv[1], "--help") || !strcmp(argv[1], "-h")) )
{ {
short_usage(); cout << "--confile filename - configuration file. Default: configure.xml" << endl;
DBServer_MySQL::help_print(argc,argv);
return 0; return 0;
} }
auto conf = uniset_init(argc, argv, "configure.xml"); auto conf = uniset_init(argc, argv, "configure.xml");
ObjectId ID = conf->getDBServer(); auto db = DBServer_MySQL::init_dbserver(argc,argv);
// определяем ID объекта
string name = conf->getArgParam("--name");
if( !name.empty())
{
if( ID != UniSetTypes::DefaultObjectId )
{
uwarn << "(DBServer::main): переопределяем ID заданный в "
<< conf->getConfFileName() << endl;
}
ID = conf->oind->getIdByName(conf->getServicesSection() + "/" + name);
if( ID == UniSetTypes::DefaultObjectId )
{
cerr << "(DBServer::main): идентификатор '" << name
<< "' не найден в конф. файле!"
<< " в секции " << conf->getServicesSection() << endl;
return 1;
}
}
else if( ID == UniSetTypes::DefaultObjectId )
{
cerr << "(DBServer::main): Не удалось определить ИДЕНТИФИКАТОР сервера" << endl;
short_usage();
return 1;
}
DBServer_MySQL dbs(ID);
auto act = UniSetActivator::Instance(); auto act = UniSetActivator::Instance();
act->add(dbs.get_ptr()); act->add(db);
act->run(false); act->run(false);
} }
catch( const std::exception& ex ) catch( const std::exception& ex )
......
...@@ -8,14 +8,13 @@ ...@@ -8,14 +8,13 @@
#include "Configuration.h" #include "Configuration.h"
#include "Debug.h" #include "Debug.h"
#include "UniXML.h" #include "UniXML.h"
#include "DBLogSugar.h"
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
using namespace UniSetTypes; using namespace UniSetTypes;
using namespace std; using namespace std;
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
#define dblog if( ulog()->debugging(DBLogInfoLevel) ) ulog()->debug(DBLogInfoLevel)
// --------------------------------------------------------------------------
DBServer_PostgreSQL::DBServer_PostgreSQL(ObjectId id, const std::string& prefix ): DBServer_PostgreSQL::DBServer_PostgreSQL(ObjectId id, const std::string& prefix ):
DBServer(id), DBServer(id,prefix),
PingTime(300000), PingTime(300000),
ReconnectTime(180000), ReconnectTime(180000),
connect_ok(false), connect_ok(false),
...@@ -61,6 +60,8 @@ DBServer_PostgreSQL::~DBServer_PostgreSQL() ...@@ -61,6 +60,8 @@ DBServer_PostgreSQL::~DBServer_PostgreSQL()
//-------------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------------
void DBServer_PostgreSQL::sysCommand( const UniSetTypes::SystemMessage* sm ) void DBServer_PostgreSQL::sysCommand( const UniSetTypes::SystemMessage* sm )
{ {
DBServer::sysCommand(sm);
switch( sm->command ) switch( sm->command )
{ {
case SystemMessage::StartUp: case SystemMessage::StartUp:
...@@ -88,6 +89,7 @@ void DBServer_PostgreSQL::sysCommand( const UniSetTypes::SystemMessage* sm ) ...@@ -88,6 +89,7 @@ void DBServer_PostgreSQL::sysCommand( const UniSetTypes::SystemMessage* sm )
//-------------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------------
void DBServer_PostgreSQL::confirmInfo( const UniSetTypes::ConfirmMessage* cem ) void DBServer_PostgreSQL::confirmInfo( const UniSetTypes::ConfirmMessage* cem )
{ {
DBServer::confirmInfo(cem);
try try
{ {
ostringstream data; ostringstream data;
...@@ -99,26 +101,26 @@ void DBServer_PostgreSQL::confirmInfo( const UniSetTypes::ConfirmMessage* cem ) ...@@ -99,26 +101,26 @@ void DBServer_PostgreSQL::confirmInfo( const UniSetTypes::ConfirmMessage* cem )
<< " AND time='" << timeToString(cem->time, ":") << " '" << " AND time='" << timeToString(cem->time, ":") << " '"
<< " AND time_usec='" << cem->time_usec << " '"; << " AND time_usec='" << cem->time_usec << " '";
dblog << myname << "(update_confirm): " << data.str() << endl; dbinfo << myname << "(update_confirm): " << data.str() << endl;
if( !writeToBase(data.str()) ) if( !writeToBase(data.str()) )
{ {
ucrit << myname << "(update_confirm): db error: " << db->error() << endl; dbcrit << myname << "(update_confirm): db error: " << db->error() << endl;
} }
} }
catch( const Exception& ex ) catch( const Exception& ex )
{ {
ucrit << myname << "(update_confirm): " << ex << endl; dbcrit << myname << "(update_confirm): " << ex << endl;
} }
catch( ... ) catch( ... )
{ {
ucrit << myname << "(update_confirm): catch..." << endl; dbcrit << myname << "(update_confirm): catch..." << endl;
} }
} }
//-------------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------------
bool DBServer_PostgreSQL::writeToBase( const string& query ) bool DBServer_PostgreSQL::writeToBase( const string& query )
{ {
dblog << myname << "(writeToBase): " << query << endl; dbinfo << myname << "(writeToBase): " << query << endl;
if( !db || !connect_ok ) if( !db || !connect_ok )
{ {
...@@ -135,7 +137,7 @@ bool DBServer_PostgreSQL::writeToBase( const string& query ) ...@@ -135,7 +137,7 @@ bool DBServer_PostgreSQL::writeToBase( const string& query )
qlost = qbuf.front(); qlost = qbuf.front();
qbuf.pop(); qbuf.pop();
ucrit << myname << "(writeToBase): DB not connected! buffer(" << qbufSize dbcrit << myname << "(writeToBase): DB not connected! buffer(" << qbufSize
<< ") overflow! lost query: " << qlost << endl; << ") overflow! lost query: " << qlost << endl;
} }
...@@ -161,7 +163,7 @@ void DBServer_PostgreSQL::flushBuffer() ...@@ -161,7 +163,7 @@ void DBServer_PostgreSQL::flushBuffer()
{ {
if(!db->insertAndSaveRowid( qbuf.front() )) if(!db->insertAndSaveRowid( qbuf.front() ))
{ {
ucrit << myname << "(writeToBase): error: " << db->error() << " lost query: " << qbuf.front() << endl; dbcrit << myname << "(writeToBase): error: " << db->error() << " lost query: " << qbuf.front() << endl;
} }
qbuf.pop(); qbuf.pop();
...@@ -195,27 +197,27 @@ void DBServer_PostgreSQL::sensorInfo( const UniSetTypes::SensorMessage* si ) ...@@ -195,27 +197,27 @@ void DBServer_PostgreSQL::sensorInfo( const UniSetTypes::SensorMessage* si )
<< si->value << "," // value << si->value << "," // value
<< si->node << ")"; // node << si->node << ")"; // node
dblog << myname << "(insert_main_history): " << data.str() << endl; dbinfo << myname << "(insert_main_history): " << data.str() << endl;
if( !writeToBase(data.str()) ) if( !writeToBase(data.str()) )
{ {
ucrit << myname << "(insert) sensor msg error: " << db->error() << endl; dbcrit << myname << "(insert) sensor msg error: " << db->error() << endl;
} }
} }
catch( const Exception& ex ) catch( const Exception& ex )
{ {
ucrit << myname << "(insert_main_history): " << ex << endl; dbcrit << myname << "(insert_main_history): " << ex << endl;
} }
catch( ... ) catch( ... )
{ {
ucrit << myname << "(insert_main_history): catch ..." << endl; dbcrit << myname << "(insert_main_history): catch ..." << endl;
} }
} }
//-------------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------------
void DBServer_PostgreSQL::init_dbserver() void DBServer_PostgreSQL::initDBServer()
{ {
DBServer::init_dbserver(); DBServer::initDBServer();
dblog << myname << "(init): ..." << endl; dbinfo << myname << "(init): ..." << endl;
if( connect_ok ) if( connect_ok )
{ {
...@@ -242,7 +244,7 @@ void DBServer_PostgreSQL::init_dbserver() ...@@ -242,7 +244,7 @@ void DBServer_PostgreSQL::init_dbserver()
UniXML::iterator it(node); UniXML::iterator it(node);
dblog << myname << "(init): init connection.." << endl; dbinfo << myname << "(init): init connection.." << endl;
string dbname(conf->getProp(node, "dbname")); string dbname(conf->getProp(node, "dbname"));
string dbnode(conf->getProp(node, "dbnode")); string dbnode(conf->getProp(node, "dbnode"));
string user(conf->getProp(node, "dbuser")); string user(conf->getProp(node, "dbuser"));
...@@ -265,19 +267,19 @@ void DBServer_PostgreSQL::init_dbserver() ...@@ -265,19 +267,19 @@ void DBServer_PostgreSQL::init_dbserver()
if( dbnode.empty() ) if( dbnode.empty() )
dbnode = "localhost"; dbnode = "localhost";
dblog << myname << "(init): connect dbnode=" << dbnode dbinfo << myname << "(init): connect dbnode=" << dbnode
<< "\tdbname=" << dbname << "\tdbname=" << dbname
<< " pingTime=" << PingTime << " pingTime=" << PingTime
<< " ReconnectTime=" << ReconnectTime << endl; << " ReconnectTime=" << ReconnectTime << endl;
if( !db->connect(dbnode, user, password, dbname) ) if( !db->connect(dbnode, user, password, dbname) )
{ {
uwarn << myname << "(init): DB connection error: " << db->error() << endl; dbwarn << myname << "(init): DB connection error: " << db->error() << endl;
askTimer(DBServer_PostgreSQL::ReconnectTimer, ReconnectTime); askTimer(DBServer_PostgreSQL::ReconnectTimer, ReconnectTime);
} }
else else
{ {
dblog << myname << "(init): connect [OK]" << endl; dbinfo << myname << "(init): connect [OK]" << endl;
connect_ok = true; connect_ok = true;
askTimer(DBServer_PostgreSQL::ReconnectTimer, 0); askTimer(DBServer_PostgreSQL::ReconnectTimer, 0);
askTimer(DBServer_PostgreSQL::PingTimer, PingTime); askTimer(DBServer_PostgreSQL::PingTimer, PingTime);
...@@ -296,7 +298,7 @@ void DBServer_PostgreSQL::createTables( std::shared_ptr<PostgreSQLInterface>& db ...@@ -296,7 +298,7 @@ void DBServer_PostgreSQL::createTables( std::shared_ptr<PostgreSQLInterface>& db
if(!it) if(!it)
{ {
ucrit << myname << ": section <Tables> not found.." << endl; dbcrit << myname << ": section <Tables> not found.." << endl;
throw Exception(); throw Exception();
} }
...@@ -304,13 +306,13 @@ void DBServer_PostgreSQL::createTables( std::shared_ptr<PostgreSQLInterface>& db ...@@ -304,13 +306,13 @@ void DBServer_PostgreSQL::createTables( std::shared_ptr<PostgreSQLInterface>& db
{ {
if( it.getName() != "comment" ) if( it.getName() != "comment" )
{ {
ucrit << myname << "(createTables): create " << it.getName() << endl; dbcrit << myname << "(createTables): create " << it.getName() << endl;
ostringstream query; ostringstream query;
query << "CREATE TABLE " << conf->getProp(it, "name") << "(" << conf->getProp(it, "create") << ")"; query << "CREATE TABLE " << conf->getProp(it, "name") << "(" << conf->getProp(it, "create") << ")";
if( !db->query(query.str()) ) if( !db->query(query.str()) )
{ {
ucrit << myname << "(createTables): error: \t\t" << db->error() << endl; dbcrit << myname << "(createTables): error: \t\t" << db->error() << endl;
} }
} }
} }
...@@ -318,13 +320,15 @@ void DBServer_PostgreSQL::createTables( std::shared_ptr<PostgreSQLInterface>& db ...@@ -318,13 +320,15 @@ void DBServer_PostgreSQL::createTables( std::shared_ptr<PostgreSQLInterface>& db
//-------------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------------
void DBServer_PostgreSQL::timerInfo( const UniSetTypes::TimerMessage* tm ) void DBServer_PostgreSQL::timerInfo( const UniSetTypes::TimerMessage* tm )
{ {
DBServer::timerInfo(tm);
switch( tm->id ) switch( tm->id )
{ {
case DBServer_PostgreSQL::PingTimer: case DBServer_PostgreSQL::PingTimer:
{ {
if( !db->ping() ) if( !db->ping() )
{ {
uwarn << myname << "(timerInfo): DB lost connection.." << endl; dbwarn << myname << "(timerInfo): DB lost connection.." << endl;
connect_ok = false; connect_ok = false;
askTimer(DBServer_PostgreSQL::PingTimer, 0); askTimer(DBServer_PostgreSQL::PingTimer, 0);
askTimer(DBServer_PostgreSQL::ReconnectTimer, ReconnectTime); askTimer(DBServer_PostgreSQL::ReconnectTimer, ReconnectTime);
...@@ -332,14 +336,14 @@ void DBServer_PostgreSQL::timerInfo( const UniSetTypes::TimerMessage* tm ) ...@@ -332,14 +336,14 @@ void DBServer_PostgreSQL::timerInfo( const UniSetTypes::TimerMessage* tm )
else else
{ {
connect_ok = true; connect_ok = true;
dblog << myname << "(timerInfo): DB ping ok" << endl; dbinfo << myname << "(timerInfo): DB ping ok" << endl;
} }
} }
break; break;
case DBServer_PostgreSQL::ReconnectTimer: case DBServer_PostgreSQL::ReconnectTimer:
{ {
dblog << myname << "(timerInfo): reconnect timer" << endl; dbinfo << myname << "(timerInfo): reconnect timer" << endl;
if( db->isConnection() ) if( db->isConnection() )
{ {
...@@ -351,15 +355,15 @@ void DBServer_PostgreSQL::timerInfo( const UniSetTypes::TimerMessage* tm ) ...@@ -351,15 +355,15 @@ void DBServer_PostgreSQL::timerInfo( const UniSetTypes::TimerMessage* tm )
} }
connect_ok = false; connect_ok = false;
uwarn << myname << "(timerInfo): DB no connection.." << endl; dbwarn << myname << "(timerInfo): DB no connection.." << endl;
} }
else else
init_dbserver(); initDBServer();
} }
break; break;
default: default:
uwarn << myname << "(timerInfo): Unknown TimerID=" << tm->id << endl; dbwarn << myname << "(timerInfo): Unknown TimerID=" << tm->id << endl;
break; break;
} }
} }
...@@ -393,7 +397,7 @@ std::shared_ptr<DBServer_PostgreSQL> DBServer_PostgreSQL::init_dbserver( int arg ...@@ -393,7 +397,7 @@ std::shared_ptr<DBServer_PostgreSQL> DBServer_PostgreSQL::init_dbserver( int arg
if( ID == UniSetTypes::DefaultObjectId ) if( ID == UniSetTypes::DefaultObjectId )
{ {
ucrit << "(DBServer_PostgreSQL): Unknown ObjectID for '" << name << endl; cerr << "(DBServer_PostgreSQL): Unknown ObjectID for '" << name << endl;
return 0; return 0;
} }
} }
...@@ -404,9 +408,8 @@ std::shared_ptr<DBServer_PostgreSQL> DBServer_PostgreSQL::init_dbserver( int arg ...@@ -404,9 +408,8 @@ std::shared_ptr<DBServer_PostgreSQL> DBServer_PostgreSQL::init_dbserver( int arg
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
void DBServer_PostgreSQL::help_print( int argc, const char* const* argv ) void DBServer_PostgreSQL::help_print( int argc, const char* const* argv )
{ {
auto conf = uniset_conf();
cout << "Default: prefix='pgsql'" << endl; cout << "Default: prefix='pgsql'" << endl;
cout << "--prefix-name objectID - ObjectID. Default: 'conf->getDBServer()'" << endl; cout << "--prefix-name objectID - ObjectID. Default: 'conf->getDBServer()'" << endl;
cout << DBServer::help_print() << endl;
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
...@@ -15,8 +15,6 @@ class DBServer_PostgreSQL: ...@@ -15,8 +15,6 @@ class DBServer_PostgreSQL:
DBServer_PostgreSQL(); DBServer_PostgreSQL();
virtual ~DBServer_PostgreSQL(); virtual ~DBServer_PostgreSQL();
static const Debug::type DBLogInfoLevel = Debug::LEVEL9;
/*! глобальная функция для инициализации объекта */ /*! глобальная функция для инициализации объекта */
static std::shared_ptr<DBServer_PostgreSQL> init_dbserver( int argc, const char* const* argv, const std::string& prefix = "pgsql" ); static std::shared_ptr<DBServer_PostgreSQL> init_dbserver( int argc, const char* const* argv, const std::string& prefix = "pgsql" );
...@@ -26,6 +24,7 @@ class DBServer_PostgreSQL: ...@@ -26,6 +24,7 @@ class DBServer_PostgreSQL:
protected: protected:
typedef std::map<int, std::string> DBTableMap; typedef std::map<int, std::string> DBTableMap;
virtual void initDBServer() override;
virtual void initDB( std::shared_ptr<PostgreSQLInterface>& db ) {}; virtual void initDB( std::shared_ptr<PostgreSQLInterface>& db ) {};
virtual void initDBTableMap(DBTableMap& tblMap) {}; virtual void initDBTableMap(DBTableMap& tblMap) {};
...@@ -36,7 +35,6 @@ class DBServer_PostgreSQL: ...@@ -36,7 +35,6 @@ class DBServer_PostgreSQL:
virtual void sigterm( int signo ) override; virtual void sigterm( int signo ) override;
bool writeToBase( const string& query ); bool writeToBase( const string& query );
virtual void init_dbserver();
void createTables( std::shared_ptr<PostgreSQLInterface>& db ); void createTables( std::shared_ptr<PostgreSQLInterface>& db );
inline const char* tblName(int key) inline const char* tblName(int key)
......
...@@ -8,15 +8,17 @@ using namespace std; ...@@ -8,15 +8,17 @@ using namespace std;
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
int main(int argc, char** argv) int main(int argc, char** argv)
{ {
std::ios::sync_with_stdio(false);
try try
{ {
if( argc > 1 && !strcmp(argv[1], "--help") ) if( argc > 1 && (!strcmp(argv[1], "--help") || !strcmp(argv[1], "-h")) )
{ {
cout << "--confile filename - configuration file. Default: configure.xml" << endl;
DBServer_PostgreSQL::help_print(argc, argv); DBServer_PostgreSQL::help_print(argc, argv);
return 0; return 0;
} }
auto conf = uniset_init(argc, argv, "configure.xml"); auto conf = uniset_init(argc, argv);
auto dbs = DBServer_PostgreSQL::init_dbserver(argc, argv); auto dbs = DBServer_PostgreSQL::init_dbserver(argc, argv);
auto act = UniSetActivator::Instance(); auto act = UniSetActivator::Instance();
......
...@@ -32,16 +32,13 @@ ...@@ -32,16 +32,13 @@
#include "Configuration.h" #include "Configuration.h"
#include "Debug.h" #include "Debug.h"
#include "UniXML.h" #include "UniXML.h"
#include "DBLogSugar.h"
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
#define dblog if( ulog()->debugging(DBLogInfoLevel) ) (*(ulog().get()))[DBLogInfoLevel]
using namespace UniSetTypes; using namespace UniSetTypes;
using namespace std; using namespace std;
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
const Debug::type DBLEVEL = Debug::LEVEL1; DBServer_SQLite::DBServer_SQLite( ObjectId id, const std::string& prefix ):
// -------------------------------------------------------------------------- DBServer(id,prefix),
DBServer_SQLite::DBServer_SQLite( ObjectId id ):
DBServer(id),
db(new SQLiteInterface()),
PingTime(300000), PingTime(300000),
ReconnectTime(180000), ReconnectTime(180000),
connect_ok(false), connect_ok(false),
...@@ -55,35 +52,19 @@ DBServer_SQLite::DBServer_SQLite( ObjectId id ): ...@@ -55,35 +52,19 @@ DBServer_SQLite::DBServer_SQLite( ObjectId id ):
msg << "(DBServer_SQLite): init failed! Unknown ID!" << endl; msg << "(DBServer_SQLite): init failed! Unknown ID!" << endl;
throw Exception(msg.str()); throw Exception(msg.str());
} }
db = make_shared<SQLiteInterface>();
} }
DBServer_SQLite::DBServer_SQLite(): DBServer_SQLite::DBServer_SQLite( const std::string& prefix ):
DBServer(uniset_conf()->getDBServer()), DBServer_SQLite(uniset_conf()->getDBServer(),prefix)
db(new SQLiteInterface()),
PingTime(300000),
ReconnectTime(180000),
connect_ok(false),
activate(true),
qbufSize(200),
lastRemove(false)
{ {
// init();
if( getId() == DefaultObjectId )
{
ostringstream msg;
msg << "(DBServer_SQLite): init failed! Unknown ID!" << endl;
throw Exception(msg.str());
}
} }
//-------------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------------
DBServer_SQLite::~DBServer_SQLite() DBServer_SQLite::~DBServer_SQLite()
{ {
if( db != NULL ) if( db )
{
db->close(); db->close();
delete db;
db = 0;
}
} }
//-------------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------------
void DBServer_SQLite::sysCommand( const UniSetTypes::SystemMessage* sm ) void DBServer_SQLite::sysCommand( const UniSetTypes::SystemMessage* sm )
...@@ -127,26 +108,26 @@ void DBServer_SQLite::confirmInfo( const UniSetTypes::ConfirmMessage* cem ) ...@@ -127,26 +108,26 @@ void DBServer_SQLite::confirmInfo( const UniSetTypes::ConfirmMessage* cem )
<< " AND time='" << timeToString(cem->time, ":") << " '" << " AND time='" << timeToString(cem->time, ":") << " '"
<< " AND time_usec='" << cem->time_usec << " '"; << " AND time_usec='" << cem->time_usec << " '";
dblog << myname << "(update_confirm): " << data.str() << endl; dbinfo << myname << "(update_confirm): " << data.str() << endl;
if( !writeToBase(data.str()) ) if( !writeToBase(data.str()) )
{ {
ucrit << myname << "(update_confirm): db error: " << db->error() << endl; dbcrit << myname << "(update_confirm): db error: " << db->error() << endl;
} }
} }
catch( const Exception& ex ) catch( const Exception& ex )
{ {
ucrit << myname << "(update_confirm): " << ex << endl; dbcrit << myname << "(update_confirm): " << ex << endl;
} }
catch( const std::exception& ex ) catch( const std::exception& ex )
{ {
ucrit << myname << "(update_confirm): catch: " << ex.what() << endl; dbcrit << myname << "(update_confirm): catch: " << ex.what() << endl;
} }
} }
//-------------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------------
bool DBServer_SQLite::writeToBase( const string& query ) bool DBServer_SQLite::writeToBase( const string& query )
{ {
dblog << myname << "(writeToBase): " << query << endl; dbinfo << myname << "(writeToBase): " << query << endl;
// cout << "DBServer_SQLite: " << query << endl; // cout << "DBServer_SQLite: " << query << endl;
if( !db || !connect_ok ) if( !db || !connect_ok )
...@@ -165,7 +146,7 @@ bool DBServer_SQLite::writeToBase( const string& query ) ...@@ -165,7 +146,7 @@ bool DBServer_SQLite::writeToBase( const string& query )
qbuf.pop(); qbuf.pop();
ucrit << myname << "(writeToBase): DB not connected! buffer(" << qbufSize dbcrit << myname << "(writeToBase): DB not connected! buffer(" << qbufSize
<< ") overflow! lost query: " << qlost << endl; << ") overflow! lost query: " << qlost << endl;
} }
...@@ -191,7 +172,7 @@ void DBServer_SQLite::flushBuffer() ...@@ -191,7 +172,7 @@ void DBServer_SQLite::flushBuffer()
{ {
if( !db->insert(qbuf.front()) ) if( !db->insert(qbuf.front()) )
{ {
ucrit << myname << "(writeToBase): error: " << db->error() << dbcrit << myname << "(writeToBase): error: " << db->error() <<
" lost query: " << qbuf.front() << endl; " lost query: " << qbuf.front() << endl;
} }
...@@ -224,27 +205,27 @@ void DBServer_SQLite::sensorInfo( const UniSetTypes::SensorMessage* si ) ...@@ -224,27 +205,27 @@ void DBServer_SQLite::sensorInfo( const UniSetTypes::SensorMessage* si )
<< val << "','" // value << val << "','" // value
<< si->node << "')"; // node << si->node << "')"; // node
dblog << myname << "(insert_main_history): " << data.str() << endl; dbinfo << myname << "(insert_main_history): " << data.str() << endl;
if( !writeToBase(data.str()) ) if( !writeToBase(data.str()) )
{ {
ucrit << myname << "(insert) sensor msg error: " << db->error() << endl; dbcrit << myname << "(insert) sensor msg error: " << db->error() << endl;
} }
} }
catch( const Exception& ex ) catch( const Exception& ex )
{ {
ucrit << myname << "(insert_main_history): " << ex << endl; dbcrit << myname << "(insert_main_history): " << ex << endl;
} }
catch( const std::exception& ex ) catch( const std::exception& ex )
{ {
ucrit << myname << "(insert_main_history): catch:" << ex.what() << endl; dbcrit << myname << "(insert_main_history): catch:" << ex.what() << endl;
} }
} }
//-------------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------------
void DBServer_SQLite::init_dbserver() void DBServer_SQLite::initDBServer()
{ {
DBServer::init_dbserver(); DBServer::initDBServer();
dblog << myname << "(init): ..." << endl; dbinfo << myname << "(init): ..." << endl;
if( connect_ok ) if( connect_ok )
{ {
...@@ -271,7 +252,7 @@ void DBServer_SQLite::init_dbserver() ...@@ -271,7 +252,7 @@ void DBServer_SQLite::init_dbserver()
UniXML::iterator it(node); UniXML::iterator it(node);
dblog << myname << "(init): init connection.." << endl; dbinfo << myname << "(init): init connection.." << endl;
string dbfile(conf->getProp(node, "dbfile")); string dbfile(conf->getProp(node, "dbfile"));
tblMap[UniSetTypes::Message::SensorInfo] = "main_history"; tblMap[UniSetTypes::Message::SensorInfo] = "main_history";
...@@ -288,14 +269,14 @@ void DBServer_SQLite::init_dbserver() ...@@ -288,14 +269,14 @@ void DBServer_SQLite::init_dbserver()
else else
lastRemove = false; lastRemove = false;
dblog << myname << "(init): connect dbfile=" << dbfile dbinfo << myname << "(init): connect dbfile=" << dbfile
<< " pingTime=" << PingTime << " pingTime=" << PingTime
<< " ReconnectTime=" << ReconnectTime << endl; << " ReconnectTime=" << ReconnectTime << endl;
if( !db->connect(dbfile, false) ) if( !db->connect(dbfile, false) )
{ {
// ostringstream err; // ostringstream err;
ucrit << myname dbcrit << myname
<< "(init): DB connection error: " << "(init): DB connection error: "
<< db->error() << endl; << db->error() << endl;
// throw Exception( string(myname+"(init): не смогли создать соединение с БД "+db->error()) ); // throw Exception( string(myname+"(init): не смогли создать соединение с БД "+db->error()) );
...@@ -303,7 +284,7 @@ void DBServer_SQLite::init_dbserver() ...@@ -303,7 +284,7 @@ void DBServer_SQLite::init_dbserver()
} }
else else
{ {
dblog << myname << "(init): connect [OK]" << endl; dbinfo << myname << "(init): connect [OK]" << endl;
connect_ok = true; connect_ok = true;
askTimer(DBServer_SQLite::ReconnectTimer, 0); askTimer(DBServer_SQLite::ReconnectTimer, 0);
askTimer(DBServer_SQLite::PingTimer, PingTime); askTimer(DBServer_SQLite::PingTimer, PingTime);
...@@ -321,7 +302,7 @@ void DBServer_SQLite::createTables( SQLiteInterface* db ) ...@@ -321,7 +302,7 @@ void DBServer_SQLite::createTables( SQLiteInterface* db )
if(!it) if(!it)
{ {
ucrit << myname << ": section <Tables> not found.." << endl; dbcrit << myname << ": section <Tables> not found.." << endl;
throw Exception(); throw Exception();
} }
...@@ -329,25 +310,26 @@ void DBServer_SQLite::createTables( SQLiteInterface* db ) ...@@ -329,25 +310,26 @@ void DBServer_SQLite::createTables( SQLiteInterface* db )
{ {
if( it.getName() != "comment" ) if( it.getName() != "comment" )
{ {
dblog << myname << "(createTables): create " << it.getName() << endl; dbinfo << myname << "(createTables): create " << it.getName() << endl;
ostringstream query; ostringstream query;
query << "CREATE TABLE " << conf->getProp(it, "name") << "(" << conf->getProp(it, "create") << ")"; query << "CREATE TABLE " << conf->getProp(it, "name") << "(" << conf->getProp(it, "create") << ")";
if( !db->query(query.str()) ) if( !db->query(query.str()) )
ucrit << myname << "(createTables): error: \t\t" << db->error() << endl; dbcrit << myname << "(createTables): error: \t\t" << db->error() << endl;
} }
} }
} }
//-------------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------------
void DBServer_SQLite::timerInfo( const UniSetTypes::TimerMessage* tm ) void DBServer_SQLite::timerInfo( const UniSetTypes::TimerMessage* tm )
{ {
DBServer::timerInfo(tm);
switch( tm->id ) switch( tm->id )
{ {
case DBServer_SQLite::PingTimer: case DBServer_SQLite::PingTimer:
{ {
if( !db->ping() ) if( !db->ping() )
{ {
uwarn << myname << "(timerInfo): DB lost connection.." << endl; dbwarn << myname << "(timerInfo): DB lost connection.." << endl;
connect_ok = false; connect_ok = false;
askTimer(DBServer_SQLite::PingTimer, 0); askTimer(DBServer_SQLite::PingTimer, 0);
askTimer(DBServer_SQLite::ReconnectTimer, ReconnectTime); askTimer(DBServer_SQLite::ReconnectTimer, ReconnectTime);
...@@ -355,14 +337,14 @@ void DBServer_SQLite::timerInfo( const UniSetTypes::TimerMessage* tm ) ...@@ -355,14 +337,14 @@ void DBServer_SQLite::timerInfo( const UniSetTypes::TimerMessage* tm )
else else
{ {
connect_ok = true; connect_ok = true;
dblog << myname << "(timerInfo): DB ping ok" << endl; dbinfo << myname << "(timerInfo): DB ping ok" << endl;
} }
} }
break; break;
case DBServer_SQLite::ReconnectTimer: case DBServer_SQLite::ReconnectTimer:
{ {
dblog << myname << "(timerInfo): reconnect timer" << endl; dbinfo << myname << "(timerInfo): reconnect timer" << endl;
if( db->isConnection() ) if( db->isConnection() )
{ {
...@@ -374,16 +356,46 @@ void DBServer_SQLite::timerInfo( const UniSetTypes::TimerMessage* tm ) ...@@ -374,16 +356,46 @@ void DBServer_SQLite::timerInfo( const UniSetTypes::TimerMessage* tm )
} }
connect_ok = false; connect_ok = false;
uwarn << myname << "(timerInfo): DB no connection.." << endl; dbwarn << myname << "(timerInfo): DB no connection.." << endl;
} }
else else
init_dbserver(); initDBServer();
} }
break; break;
default: default:
uwarn << myname << "(timerInfo): Unknown TimerID=" << tm->id << endl; dbwarn << myname << "(timerInfo): Unknown TimerID=" << tm->id << endl;
break; break;
} }
} }
//-------------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------------
std::shared_ptr<DBServer_SQLite> DBServer_SQLite::init_dbserver( int argc, const char* const* argv, const std::string& prefix )
{
auto conf = uniset_conf();
ObjectId ID = conf->getDBServer();
string name = conf->getArgParam("--" + prefix + "-name", "");
if( !name.empty() )
{
ObjectId ID = conf->getObjectID(name);
if( ID == UniSetTypes::DefaultObjectId )
{
cerr << "(DBServer_SQLite): Unknown ObjectID for '" << name << endl;
return 0;
}
}
uinfo << "(DBServer_SQLite): name = " << name << "(" << ID << ")" << endl;
return make_shared<DBServer_SQLite>(ID, prefix);
}
// -----------------------------------------------------------------------------
void DBServer_SQLite::help_print( int argc, const char* const* argv )
{
cout << "Default: prefix='sqlite'" << endl;
cout << "--prefix-name objectID - ObjectID. Default: 'conf->getDBServer()'" << endl;
cout << DBServer::help_print() << endl;
}
// -----------------------------------------------------------------------------
...@@ -135,16 +135,21 @@ class DBServer_SQLite: ...@@ -135,16 +135,21 @@ class DBServer_SQLite:
public DBServer public DBServer
{ {
public: public:
DBServer_SQLite( UniSetTypes::ObjectId id ); DBServer_SQLite( UniSetTypes::ObjectId id, const std::string& prefix );
DBServer_SQLite(); DBServer_SQLite( const std::string& prefix );
~DBServer_SQLite(); virtual ~DBServer_SQLite();
static const Debug::type DBLogInfoLevel = Debug::LEVEL9; /*! глобальная функция для инициализации объекта */
static std::shared_ptr<DBServer_SQLite> init_dbserver( int argc, const char* const* argv, const std::string& prefix = "sqlite" );
/*! глобальная функция для вывода help-а */
static void help_print( int argc, const char* const* argv );
protected: protected:
typedef std::map<int, std::string> DBTableMap; typedef std::map<int, std::string> DBTableMap;
virtual void initDB( SQLiteInterface* db ) {}; virtual void initDBServer() override;
virtual void initDB( std::shared_ptr<SQLiteInterface>& db ) {};
virtual void initDBTableMap(DBTableMap& tblMap) {}; virtual void initDBTableMap(DBTableMap& tblMap) {};
virtual void timerInfo( const UniSetTypes::TimerMessage* tm ) override; virtual void timerInfo( const UniSetTypes::TimerMessage* tm ) override;
...@@ -153,7 +158,6 @@ class DBServer_SQLite: ...@@ -153,7 +158,6 @@ class DBServer_SQLite:
virtual void confirmInfo( const UniSetTypes::ConfirmMessage* cmsg ) override; virtual void confirmInfo( const UniSetTypes::ConfirmMessage* cmsg ) override;
bool writeToBase( const string& query ); bool writeToBase( const string& query );
virtual void init_dbserver();
void createTables( SQLiteInterface* db ); void createTables( SQLiteInterface* db );
inline const char* tblName(int key) inline const char* tblName(int key)
...@@ -169,7 +173,7 @@ class DBServer_SQLite: ...@@ -169,7 +173,7 @@ class DBServer_SQLite:
}; };
SQLiteInterface* db; std::shared_ptr<SQLiteInterface> db;
int PingTime; int PingTime;
int ReconnectTime; int ReconnectTime;
bool connect_ok; /*! признак наличия соеднинения с сервером БД */ bool connect_ok; /*! признак наличия соеднинения с сервером БД */
......
...@@ -17,57 +17,28 @@ int main(int argc, char** argv) ...@@ -17,57 +17,28 @@ int main(int argc, char** argv)
try try
{ {
if( argc > 1 && !strcmp(argv[1], "--help") ) if( argc > 1 && (!strcmp(argv[1], "--help") || !strcmp(argv[1], "-h")) )
{ {
short_usage(); cout << "--confile filename - configuration file. Default: configure.xml" << endl;
DBServer_SQLite::help_print(argc,argv);
return 0; return 0;
} }
auto conf = uniset_init(argc, argv, "configure.xml"); auto conf = uniset_init(argc, argv, "configure.xml");
ObjectId ID = conf->getDBServer(); auto db = DBServer_SQLite::init_dbserver(argc,argv);
// определяем ID объекта
string name = conf->getArgParam("--name");
if( !name.empty())
{
if( ID != UniSetTypes::DefaultObjectId )
{
uwarn << "(DBServer::main): переопределяем ID заданнй в "
<< conf->getConfFileName() << endl;
}
ID = conf->oind->getIdByName(conf->getServicesSection() + "/" + name);
if( ID == UniSetTypes::DefaultObjectId )
{
cerr << "(DBServer::main): идентификатор '" << name
<< "' не найден в конф. файле!"
<< " в секции " << conf->getServicesSection() << endl;
return 1;
}
}
else if( ID == UniSetTypes::DefaultObjectId )
{
cerr << "(DBServer::main): Не удалось определить ИДЕНТИФИКАТОР сервера" << endl;
short_usage();
return 1;
}
DBServer_SQLite dbs(ID);
auto act = UniSetActivator::Instance(); auto act = UniSetActivator::Instance();
act->add(dbs.get_ptr()); act->add(db);
act->run(false); act->run(false);
} }
catch( const std::exception& ex ) catch( const std::exception& ex )
{ {
cerr << "(DBServer::main): " << ex.what() << endl; cerr << "(DBServer_SQLite::main): " << ex.what() << endl;
} }
catch(...) catch(...)
{ {
cerr << "(DBServer::main): catch ..." << endl; cerr << "(DBServer_SQLite::main): catch ..." << endl;
} }
return 0; return 0;
......
#ifndef DBLogSugar_H_
#define DBLogSugar_H_
// "синтаксический сахар"..для логов
#ifndef dbinfo
#define dbinfo if( dblog->debugging(Debug::INFO) ) dblog->info()
#endif
#ifndef dbwarn
#define dbwarn if( dblog->debugging(Debug::WARN) ) dblog->warn()
#endif
#ifndef dbcrit
#define dbcrit if( dblog->debugging(Debug::CRIT) ) dblog->crit()
#endif
#ifndef dblog1
#define dblog1 if( dblog->debugging(Debug::LEVEL1) ) dblog->level1()
#endif
#ifndef dblog2
#define dblog2 if( dblog->debugging(Debug::LEVEL2) ) dblog->level2()
#endif
#ifndef dblog3
#define dblog3 if( dblog->debugging(Debug::LEVEL3) ) dblog->level3()
#endif
#ifndef dblog4
#define dblog4 if( dblog->debugging(Debug::LEVEL4) ) dblog->level4()
#endif
#ifndef dblog5
#define dblog5 if( dblog->debugging(Debug::LEVEL5) ) dblog->level5()
#endif
#ifndef dblog6
#define dblog6 if( dblog->debugging(Debug::LEVEL6) ) dblog->level6()
#endif
#ifndef dblog7
#define dblog7 if( dblog->debugging(Debug::LEVEL7) ) dblog->level7()
#endif
#ifndef dblog8
#define dblog8 if( dblog->debugging(Debug::LEVEL8) ) dblog->level8()
#endif
#ifndef dblog9
#define dblog9 if( dblog->debugging(Debug::LEVEL9) ) dblog->level9()
#endif
#ifndef dblogany
#define dblogany dblog->any()
#endif
#endif // end of DBLogSugar
...@@ -26,6 +26,9 @@ ...@@ -26,6 +26,9 @@
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
#include "UniSetTypes.h" #include "UniSetTypes.h"
#include "UniSetObject_LT.h" #include "UniSetObject_LT.h"
#include "LogServer.h"
#include "DebugStream.h"
#include "LogAgregator.h"
//------------------------------------------------------------------------------------------ //------------------------------------------------------------------------------------------
/*! /*!
\page ServicesPage \page ServicesPage
...@@ -50,17 +53,27 @@ class DBServer: ...@@ -50,17 +53,27 @@ class DBServer:
public UniSetObject_LT public UniSetObject_LT
{ {
public: public:
DBServer( UniSetTypes::ObjectId id ); DBServer( UniSetTypes::ObjectId id, const std::string& prefix="db" );
DBServer(); DBServer( const std::string& prefix="db" );
~DBServer(); ~DBServer();
static std::string help_print();
protected: protected:
virtual void processingMessage( UniSetTypes::VoidMessage* msg ) override; virtual void processingMessage( UniSetTypes::VoidMessage* msg ) override;
virtual void sysCommand( const UniSetTypes::SystemMessage* sm ) override;
virtual void confirmInfo( const UniSetTypes::ConfirmMessage* cmsg ) {} virtual void confirmInfo( const UniSetTypes::ConfirmMessage* cmsg ) {}
virtual bool activateObject() override; virtual bool activateObject() override;
virtual void init_dbserver() {}; virtual void initDBServer(){};
std::shared_ptr<LogAgregator> loga;
std::shared_ptr<DebugStream> dblog;
std::shared_ptr<LogServer> logserv;
std::string logserv_host = {""};
int logserv_port = {0};
private: private:
}; };
......
...@@ -32,11 +32,12 @@ ...@@ -32,11 +32,12 @@
#include "Configuration.h" #include "Configuration.h"
#include "Debug.h" #include "Debug.h"
#include "UniXML.h" #include "UniXML.h"
#include "DBLogSugar.h"
// ------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------
using namespace UniSetTypes; using namespace UniSetTypes;
using namespace std; using namespace std;
// ------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------
DBServer::DBServer(ObjectId id): DBServer::DBServer( ObjectId id, const std::string& prefix ):
UniSetObject_LT(id) UniSetObject_LT(id)
{ {
if( getId() == DefaultObjectId ) if( getId() == DefaultObjectId )
...@@ -52,25 +53,34 @@ DBServer::DBServer(ObjectId id): ...@@ -52,25 +53,34 @@ DBServer::DBServer(ObjectId id):
setID(id); setID(id);
} }
}
DBServer::DBServer(): auto conf = uniset_conf();
UniSetObject_LT(uniset_conf()->getDBServer())
{
if( getId() == DefaultObjectId )
{
ObjectId id = uniset_conf()->getDBServer();
if( id == DefaultObjectId ) dblog = make_shared<DebugStream>();
{ dblog->setLogName(myname);
ostringstream msg; conf->initLogStream(dblog,prefix+"-log");
msg << "(DBServer): Запуск невозможен! НЕ ОПРЕДЕЛЁН ObjectId !!!!!\n";
throw Exception(msg.str());
}
setID(id); loga = make_shared<LogAgregator>();
loga->add(dblog);
loga->add(ulog());
xmlNode* cnode = conf->getNode("LocalDBServer");
UniXML::iterator it(cnode);
logserv = make_shared<LogServer>(loga);
logserv->init( prefix+"-logserver", cnode );
if( findArgParam("--" + prefix + "-run-logserver", conf->getArgc(), conf->getArgv()) != -1 )
{
logserv_host = conf->getArg2Param("--" + prefix + "-logserver-host", it.getProp("logserverHost"), "localhost");
logserv_port = conf->getArgPInt("--" + prefix + "-logserver-port", it.getProp("logserverPort"), getId());
} }
} }
DBServer::DBServer( const std::string& prefix ):
DBServer(uniset_conf()->getDBServer(), prefix )
{
}
//-------------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------------
DBServer::~DBServer() DBServer::~DBServer()
{ {
...@@ -94,7 +104,40 @@ void DBServer::processingMessage( UniSetTypes::VoidMessage* msg ) ...@@ -94,7 +104,40 @@ void DBServer::processingMessage( UniSetTypes::VoidMessage* msg )
bool DBServer::activateObject() bool DBServer::activateObject()
{ {
UniSetObject_LT::activateObject(); UniSetObject_LT::activateObject();
init_dbserver(); initDBServer();
return true; return true;
} }
//-------------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------------
void DBServer::sysCommand( const UniSetTypes::SystemMessage* sm )
{
UniSetObject_LT::sysCommand(sm);
if( sm->command == SystemMessage::StartUp )
{
if( !logserv_host.empty() && logserv_port != 0 && !logserv->isRunning() )
{
dbinfo << myname << "(init): run log server " << logserv_host << ":" << logserv_port << endl;
logserv->run(logserv_host, logserv_port, true);
}
}
}
//--------------------------------------------------------------------------------------------
std::string DBServer::help_print()
{
ostringstream h;
h << " Logs: " << endl;
h << "--prefix-log-... - log control" << endl;
h << " add-levels ..." << endl;
h << " del-levels ..." << endl;
h << " set-levels ..." << endl;
h << " logfile filaname" << endl;
h << " no-debug " << endl;
h << " LogServer: " << endl;
h << "--prefix-run-logserver - run logserver. Default: localhost:id" << endl;
h << "--prefix-logserver-host ip - listen ip. Default: localhost" << endl;
h << "--prefix-logserver-port num - listen port. Default: ID" << endl;
h << LogServer::help_print("prefix-logserver") << endl;
return std::move( h.str() );
}
//--------------------------------------------------------------------------------------------
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