Commit 7e0114b5 authored by Pavel Vainerman's avatar Pavel Vainerman

(LogServer): реализовал поддержку режима чтения только указанных(regexp) логов..…

(LogServer): реализовал поддержку режима чтения только указанных(regexp) логов.. (thank`s за идею hd@nio14) (UniSetTypes): небольшая оптимизация.. (uniset-log): переделал работу с аргументами командной строки (LogServer): сделал для вывода списка возможность задать фильтр..(т.е. выводиться не полный список) И другие мелкие правки: make style
parent de16881f
...@@ -128,7 +128,7 @@ static bool quiet = false; ...@@ -128,7 +128,7 @@ static bool quiet = false;
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
{ {
......
...@@ -36,7 +36,7 @@ static char* checkArg( int ind, int argc, char* argv[] ); ...@@ -36,7 +36,7 @@ static char* checkArg( int ind, int argc, char* argv[] );
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
int main( int argc, char** argv ) int main( int argc, char** argv )
{ {
// std::ios::sync_with_stdio(false); // std::ios::sync_with_stdio(false);
int optindex = 0; int optindex = 0;
int opt = 0; int opt = 0;
int verb = 0; int verb = 0;
......
...@@ -97,7 +97,7 @@ static char* checkArg( int ind, int argc, char* argv[] ); ...@@ -97,7 +97,7 @@ static char* checkArg( int ind, int argc, char* argv[] );
int main( int argc, char** argv ) int main( int argc, char** argv )
{ {
// std::ios::sync_with_stdio(false); // std::ios::sync_with_stdio(false);
Command cmd = cmdNOP; Command cmd = cmdNOP;
int optindex = 0; int optindex = 0;
int opt = 0; int opt = 0;
......
...@@ -33,7 +33,7 @@ static void print_help() ...@@ -33,7 +33,7 @@ static void print_help()
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
int main( int argc, char** argv ) int main( int argc, char** argv )
{ {
// std::ios::sync_with_stdio(false); // std::ios::sync_with_stdio(false);
int optindex = 0; int optindex = 0;
int opt = 0; int opt = 0;
int verb = 0; int verb = 0;
......
...@@ -34,7 +34,7 @@ static void print_help() ...@@ -34,7 +34,7 @@ static void print_help()
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
int main( int argc, char** argv ) int main( int argc, char** argv )
{ {
// std::ios::sync_with_stdio(false); // std::ios::sync_with_stdio(false);
int optindex = 0; int optindex = 0;
int opt = 0; int opt = 0;
int verb = 0; int verb = 0;
......
...@@ -83,7 +83,7 @@ static char* checkArg( int ind, int argc, char* argv[] ); ...@@ -83,7 +83,7 @@ static char* checkArg( int ind, int argc, char* argv[] );
int main( int argc, char** argv ) int main( int argc, char** argv )
{ {
// std::ios::sync_with_stdio(false); // std::ios::sync_with_stdio(false);
Command cmd = cmdNOP; Command cmd = cmdNOP;
int optindex = 0; int optindex = 0;
int opt = 0; int opt = 0;
......
...@@ -21,7 +21,7 @@ static void short_usage() ...@@ -21,7 +21,7 @@ static void short_usage()
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
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
{ {
......
...@@ -25,7 +25,7 @@ struct ExtInfo: ...@@ -25,7 +25,7 @@ struct ExtInfo:
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
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
{ {
......
...@@ -9,7 +9,7 @@ using namespace std; ...@@ -9,7 +9,7 @@ using namespace std;
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
int main( int argc, const char** argv ) int main( int argc, const char** argv )
{ {
// std::ios::sync_with_stdio(false); // std::ios::sync_with_stdio(false);
try try
{ {
......
...@@ -13,7 +13,7 @@ static void short_usage() ...@@ -13,7 +13,7 @@ static void short_usage()
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
int main(int argc, const char** argv) int main(int argc, const char** argv)
{ {
// std::ios::sync_with_stdio(false); // std::ios::sync_with_stdio(false);
try try
{ {
......
...@@ -14,6 +14,7 @@ static struct option longopts[] = ...@@ -14,6 +14,7 @@ static struct option longopts[] =
{ {
{ "help", no_argument, 0, 'h' }, { "help", no_argument, 0, 'h' },
{ "verbose", no_argument, 0, 'v' }, { "verbose", no_argument, 0, 'v' },
{ "filter", required_argument, 0, 'f' },
{ "iaddr", required_argument, 0, 'i' }, { "iaddr", required_argument, 0, 'i' },
{ "port", required_argument, 0, 'p' }, { "port", required_argument, 0, 'p' },
{ "add", required_argument, 0, 'a' }, { "add", required_argument, 0, 'a' },
...@@ -21,9 +22,9 @@ static struct option longopts[] = ...@@ -21,9 +22,9 @@ static struct option longopts[] =
{ "set", required_argument, 0, 's' }, { "set", required_argument, 0, 's' },
{ "off", required_argument, 0, 'o' }, { "off", required_argument, 0, 'o' },
{ "on", required_argument, 0, 'e' }, { "on", required_argument, 0, 'e' },
{ "list", no_argument, 0, 'l' }, { "list", optional_argument, 0, 'l' },
{ "rotate", required_argument, 0, 'r' }, { "rotate", optional_argument, 0, 'r' },
{ "logname", required_argument, 0, 'n' }, { "logfilter", required_argument, 0, 'n' },
{ "command-only", no_argument, 0, 'b' }, { "command-only", no_argument, 0, 'b' },
{ "timeout", required_argument, 0, 'w' }, { "timeout", required_argument, 0, 'w' },
{ "reconnect-delay", required_argument, 0, 'x' }, { "reconnect-delay", required_argument, 0, 'x' },
...@@ -36,7 +37,6 @@ static void print_help() ...@@ -36,7 +37,6 @@ static void print_help()
printf("-v, --verbose - Print all messages to stdout\n"); printf("-v, --verbose - Print all messages to stdout\n");
printf("[-i|--iaddr] addr - LogServer ip or hostname.\n"); printf("[-i|--iaddr] addr - LogServer ip or hostname.\n");
printf("[-p|--port] port - LogServer port.\n"); printf("[-p|--port] port - LogServer port.\n");
printf("[-n|--logname] name - Send command only for 'logname'.\n");
printf("[-b|--command-only] - Send command and break. (No read logs).\n"); printf("[-b|--command-only] - Send command and break. (No read logs).\n");
printf("[-w|--timeout] msec - Timeout for wait data. Default: 0 - endless waiting\n"); printf("[-w|--timeout] msec - Timeout for wait data. Default: 0 - endless waiting\n");
printf("[-x|--reconnect-delay] msec - Pause for repeat connect to LogServer. Default: 5000 msec.\n"); printf("[-x|--reconnect-delay] msec - Pause for repeat connect to LogServer. Default: 5000 msec.\n");
...@@ -44,15 +44,20 @@ static void print_help() ...@@ -44,15 +44,20 @@ static void print_help()
printf("\n"); printf("\n");
printf("Commands:\n"); printf("Commands:\n");
printf("[--add | -a] info,warn,crit,... - Add log levels.\n"); printf("[--add | -a] info,warn,crit,... [logfilter] - Add log levels.\n");
printf("[--del | -d] info,warn,crit,... - Delete log levels.\n"); printf("[--del | -d] info,warn,crit,... [logfilter] - Delete log levels.\n");
printf("[--set | -s] info,warn,crit,... - Set log levels.\n"); printf("[--set | -s] info,warn,crit,... [logfilter] - Set log levels.\n");
printf("--off, -o - Off the write log file (if enabled).\n"); printf("--off, -o [logfilter] - Off the write log file (if enabled).\n");
printf("--on, -e - On(enable) the write log file (if before disabled).\n"); printf("--on, -e [logfilter] - On(enable) the write log file (if before disabled).\n");
printf("--rotate, -r - rotate log file.\n"); printf("--rotate, -r [logfilter] - rotate log file.\n");
printf("--list, -l - List of managed logs.\n"); printf("--list, -l [logfilter] - List of managed logs.\n");
printf("--filter, -f logfilter - ('filter mode'). View log only from 'logfilter'(regexp)\n");
printf("\n");
printf("Note: 'logfilter' - regexp for name of log. Default: ALL logs.\n");
} }
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
static char* checkArg( int i, int argc, char* argv[] );
// --------------------------------------------------------------------------
int main( int argc, char** argv ) int main( int argc, char** argv )
{ {
// std::ios::sync_with_stdio(false); // нельзя отключать.. тогда "обмен с сервером" рассинхронизируется // std::ios::sync_with_stdio(false); // нельзя отключать.. тогда "обмен с сервером" рассинхронизируется
...@@ -67,13 +72,13 @@ int main( int argc, char** argv ) ...@@ -67,13 +72,13 @@ int main( int argc, char** argv )
int data = 0; int data = 0;
string sdata(""); string sdata("");
int cmdonly = 0; int cmdonly = 0;
string logname(""); string logfilter("");
timeout_t tout = 0; timeout_t tout = 0;
timeout_t rdelay = 5000; timeout_t rdelay = 5000;
try try
{ {
while( (opt = getopt_long(argc, argv, "hvla:p:i:d:s:n:eorbx:w:", longopts, &optindex)) != -1 ) while( (opt = getopt_long(argc, argv, "hvlf:a:p:i:d:s:n:eorbx:w:", longopts, &optindex)) != -1 )
{ {
switch (opt) switch (opt)
{ {
...@@ -85,6 +90,12 @@ int main( int argc, char** argv ) ...@@ -85,6 +90,12 @@ int main( int argc, char** argv )
{ {
cmd = LogServerTypes::cmdAddLevel; cmd = LogServerTypes::cmdAddLevel;
sdata = string(optarg); sdata = string(optarg);
char* arg2 = checkArg(optind, argc, argv);
if( arg2 )
logfilter = string(arg2);
else
logfilter = "";
} }
break; break;
...@@ -92,6 +103,12 @@ int main( int argc, char** argv ) ...@@ -92,6 +103,12 @@ int main( int argc, char** argv )
{ {
cmd = LogServerTypes::cmdDelLevel; cmd = LogServerTypes::cmdDelLevel;
sdata = string(optarg); sdata = string(optarg);
char* arg2 = checkArg(optind, argc, argv);
if( arg2 )
logfilter = string(arg2);
else
logfilter = "";
} }
break; break;
...@@ -99,34 +116,75 @@ int main( int argc, char** argv ) ...@@ -99,34 +116,75 @@ int main( int argc, char** argv )
{ {
cmd = LogServerTypes::cmdSetLevel; cmd = LogServerTypes::cmdSetLevel;
sdata = string(optarg); sdata = string(optarg);
char* arg2 = checkArg(optind, argc, argv);
if( arg2 )
logfilter = string(arg2);
else
logfilter = "";
} }
break; break;
case 'l': case 'l':
{
cmd = LogServerTypes::cmdList; cmd = LogServerTypes::cmdList;
cmdonly = 1; cmdonly = 1;
break; char* arg2 = checkArg(optind, argc, argv);
if( arg2 )
logfilter = string(arg2);
else
logfilter = "";
}
break;
case 'o': case 'o':
{
cmd = LogServerTypes::cmdOffLogFile; cmd = LogServerTypes::cmdOffLogFile;
break; char* arg2 = checkArg(optind, argc, argv);
if( arg2 )
logfilter = string(arg2);
else
logfilter = "";
}
break;
case 'f':
{
cmd = LogServerTypes::cmdFilterMode;
logfilter = string(optarg);
}
break;
case 'e': case 'e':
{
cmd = LogServerTypes::cmdOnLogFile; cmd = LogServerTypes::cmdOnLogFile;
break; char* arg2 = checkArg(optind, argc, argv);
if( arg2 )
logfilter = string(arg2);
else
logfilter = "";
}
break;
case 'r': case 'r':
{
cmd = LogServerTypes::cmdRotate; cmd = LogServerTypes::cmdRotate;
break; char* arg2 = checkArg(optind, argc, argv);
if( arg2 )
logfilter = string(arg2);
else
logfilter = "";
}
break;
case 'i': case 'i':
addr = string(optarg); addr = string(optarg);
break; break;
case 'n':
logname = string(optarg);
break;
case 'b': case 'b':
cmdonly = 1; cmdonly = 1;
break; break;
...@@ -149,7 +207,7 @@ int main( int argc, char** argv ) ...@@ -149,7 +207,7 @@ int main( int argc, char** argv )
case '?': case '?':
default: default:
printf("? argumnet\n"); printf("Unknown argumnet\n");
return 0; return 0;
} }
} }
...@@ -174,7 +232,7 @@ int main( int argc, char** argv ) ...@@ -174,7 +232,7 @@ int main( int argc, char** argv )
cout << "SEND COMMAND: '" << (LogServerTypes::Command)cmd << " data='" << sdata << "'(" << (int)data << ")" << endl; cout << "SEND COMMAND: '" << (LogServerTypes::Command)cmd << " data='" << sdata << "'(" << (int)data << ")" << endl;
} }
lr.readlogs( addr, port, (LogServerTypes::Command)cmd, data, logname, verb ); lr.readlogs( addr, port, (LogServerTypes::Command)cmd, data, logfilter, verb );
} }
catch( const SystemError& err ) catch( const SystemError& err )
{ {
...@@ -192,3 +250,11 @@ int main( int argc, char** argv ) ...@@ -192,3 +250,11 @@ int main( int argc, char** argv )
return 0; return 0;
} }
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
char* checkArg( int i, int argc, char* argv[] )
{
if( i < argc && (argv[i])[0] != '-' )
return argv[i];
return 0;
}
// --------------------------------------------------------------------------
...@@ -114,7 +114,7 @@ int main( int argc, char** argv ) ...@@ -114,7 +114,7 @@ int main( int argc, char** argv )
} }
auto la2 = make_shared<LogAgregator>("la2"); auto la2 = make_shared<LogAgregator>("la2");
auto dlog3 = la2->create("dlog3"); auto dlog3 = la2->create("dlog3");
auto dlog4 = la2->create("dlog4"); auto dlog4 = la2->create("dlog4");
la->add(la2); la->add(la2);
...@@ -127,18 +127,20 @@ int main( int argc, char** argv ) ...@@ -127,18 +127,20 @@ int main( int argc, char** argv )
} }
auto la3 = make_shared<LogAgregator>("la3"); auto la3 = make_shared<LogAgregator>("la3");
auto dlog5 = la3->create("dlog5"); auto dlog5 = la3->create("dlog5");
auto dlog6 = la3->create("dlog6"); auto dlog6 = la3->create("dlog6");
la->add(la3); la->add(la3);
#if 0 #if 0
cout << la << endl; cout << la << endl;
cout << "************ " << endl; cout << "************ " << endl;
auto lst = la->getLogList(); auto lst = la->getLogList();
for( const auto& l: lst )
for( const auto& l : lst )
cout << l.name << endl; cout << l.name << endl;
return 0; return 0;
#endif #endif
......
...@@ -40,13 +40,13 @@ void TestGen::timerInfo( const TimerMessage* tm ) ...@@ -40,13 +40,13 @@ void TestGen::timerInfo( const TimerMessage* tm )
{ {
if( tm->id == 1 ) if( tm->id == 1 )
{ {
askTimer(1,0); askTimer(1, 0);
askTimer(2,3000); askTimer(2, 3000);
} }
else if( tm->id == 2 ) else if( tm->id == 2 )
{ {
askTimer(1,2000); askTimer(1, 2000);
askTimer(2,0); askTimer(2, 0);
} }
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
...@@ -58,6 +58,6 @@ void TestGen::sigterm( int signo ) ...@@ -58,6 +58,6 @@ void TestGen::sigterm( int signo )
void TestGen::sysCommand( const UniSetTypes::SystemMessage* sm ) void TestGen::sysCommand( const UniSetTypes::SystemMessage* sm )
{ {
if( sm->command == SystemMessage::StartUp ) if( sm->command == SystemMessage::StartUp )
askTimer(1,2000); askTimer(1, 2000);
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
...@@ -13,7 +13,7 @@ ...@@ -13,7 +13,7 @@
Name: libuniset2 Name: libuniset2
Version: 2.1 Version: 2.1
Release: alt3 Release: alt4
Summary: UniSet - library for building distributed industrial control systems Summary: UniSet - library for building distributed industrial control systems
...@@ -455,6 +455,10 @@ mv -f %buildroot%python_sitelibdir_noarch/* %buildroot%python_sitelibdir/%oname ...@@ -455,6 +455,10 @@ mv -f %buildroot%python_sitelibdir_noarch/* %buildroot%python_sitelibdir/%oname
# .. # ..
%changelog %changelog
* Mon Jun 01 2015 Pavel Vainerman <pv@altlinux.ru> 2.1-alt4
- (LogServer): added suppport "filter mode"
- (LogAgregator): refactoring, change show loglist format
* Sun May 31 2015 Pavel Vainerman <pv@altlinux.ru> 2.1-alt3 * Sun May 31 2015 Pavel Vainerman <pv@altlinux.ru> 2.1-alt3
- (LogAgregator): - (LogAgregator):
- added support agregator hierarchy - added support agregator hierarchy
......
...@@ -62,7 +62,7 @@ IOControl::IOControl( UniSetTypes::ObjectId id, UniSetTypes::ObjectId icID, ...@@ -62,7 +62,7 @@ IOControl::IOControl( UniSetTypes::ObjectId id, UniSetTypes::ObjectId icID,
iolog->setLogName(myname); iolog->setLogName(myname);
conf->initLogStream(iolog, prefix + "-log"); conf->initLogStream(iolog, prefix + "-log");
loga = make_shared<LogAgregator>(myname+"-loga"); loga = make_shared<LogAgregator>(myname + "-loga");
loga->add(iolog); loga->add(iolog);
loga->add(ulog()); loga->add(ulog());
loga->add(dlog()); loga->add(dlog());
......
...@@ -51,7 +51,7 @@ MBExchange::MBExchange( UniSetTypes::ObjectId objId, UniSetTypes::ObjectId shmId ...@@ -51,7 +51,7 @@ MBExchange::MBExchange( UniSetTypes::ObjectId objId, UniSetTypes::ObjectId shmId
mblog->setLogName(myname); mblog->setLogName(myname);
conf->initLogStream(mblog, prefix + "-log"); conf->initLogStream(mblog, prefix + "-log");
loga = make_shared<LogAgregator>(myname+"-loga"); loga = make_shared<LogAgregator>(myname + "-loga");
loga->add(mblog); loga->add(mblog);
loga->add(ulog()); loga->add(ulog());
loga->add(dlog()); loga->add(dlog());
......
...@@ -100,8 +100,9 @@ std::shared_ptr<ModbusClient> MBTCPMaster::initMB( bool reopen ) ...@@ -100,8 +100,9 @@ std::shared_ptr<ModbusClient> MBTCPMaster::initMB( bool reopen )
mbinfo << myname << "(init): ipaddr=" << iaddr << " port=" << port << endl; mbinfo << myname << "(init): ipaddr=" << iaddr << " port=" << port << endl;
auto l = loga->create(myname+"-exchangelog"); auto l = loga->create(myname + "-exchangelog");
mbtcp->setLog(l); mbtcp->setLog(l);
if( ic ) if( ic )
ic->logAgregator()->add(loga); ic->logAgregator()->add(loga);
} }
......
...@@ -104,6 +104,7 @@ MBTCPMultiMaster::MBTCPMultiMaster( UniSetTypes::ObjectId objId, UniSetTypes::Ob ...@@ -104,6 +104,7 @@ MBTCPMultiMaster::MBTCPMultiMaster( UniSetTypes::ObjectId objId, UniSetTypes::Ob
auto l = loga->create(sinf.myname); auto l = loga->create(sinf.myname);
sinf.mbtcp->setLog(l); sinf.mbtcp->setLog(l);
if( ic ) if( ic )
ic->logAgregator()->add(loga); ic->logAgregator()->add(loga);
......
...@@ -131,8 +131,9 @@ std::shared_ptr<ModbusClient> RTUExchange::initMB( bool reopen ) ...@@ -131,8 +131,9 @@ std::shared_ptr<ModbusClient> RTUExchange::initMB( bool reopen )
if( defSpeed != ComPort::ComSpeed0 ) if( defSpeed != ComPort::ComSpeed0 )
mbrtu->setSpeed(defSpeed); mbrtu->setSpeed(defSpeed);
auto l = loga->create(myname+"-exchangelog"); auto l = loga->create(myname + "-exchangelog");
mbrtu->setLog(l); mbrtu->setLog(l);
if( ic ) if( ic )
ic->logAgregator()->add(loga); ic->logAgregator()->add(loga);
......
...@@ -39,7 +39,7 @@ MBSlave::MBSlave( UniSetTypes::ObjectId objId, UniSetTypes::ObjectId shmId, cons ...@@ -39,7 +39,7 @@ MBSlave::MBSlave( UniSetTypes::ObjectId objId, UniSetTypes::ObjectId shmId, cons
mblog->setLogName(myname); mblog->setLogName(myname);
conf->initLogStream(mblog, prefix + "-log"); conf->initLogStream(mblog, prefix + "-log");
loga = make_shared<LogAgregator>(myname+"-loga"); loga = make_shared<LogAgregator>(myname + "-loga");
loga->add(mblog); loga->add(mblog);
loga->add(ulog()); loga->add(ulog());
loga->add(dlog()); loga->add(dlog());
......
...@@ -156,7 +156,7 @@ void MBTCPMultiSlave::execute_tcp() ...@@ -156,7 +156,7 @@ void MBTCPMultiSlave::execute_tcp()
return; return;
} }
auto l = loga->create(myname+"-exchangelog"); auto l = loga->create(myname + "-exchangelog");
sslot->setLog(l); sslot->setLog(l);
for( auto && i : cmap ) for( auto && i : cmap )
......
...@@ -28,7 +28,7 @@ UNetExchange::UNetExchange( UniSetTypes::ObjectId objId, UniSetTypes::ObjectId s ...@@ -28,7 +28,7 @@ UNetExchange::UNetExchange( UniSetTypes::ObjectId objId, UniSetTypes::ObjectId s
unetlog->setLogName(myname); unetlog->setLogName(myname);
conf->initLogStream(unetlog, prefix + "-log"); conf->initLogStream(unetlog, prefix + "-log");
loga = make_shared<LogAgregator>(myname+"-loga"); loga = make_shared<LogAgregator>(myname + "-loga");
loga->add(unetlog); loga->add(unetlog);
loga->add(ulog()); loga->add(ulog());
loga->add(dlog()); loga->add(dlog());
......
...@@ -3,10 +3,10 @@ ...@@ -3,10 +3,10 @@
/* /*
DO NOT EDIT THIS FILE. IT IS AUTOGENERATED FILE. DO NOT EDIT THIS FILE. IT IS AUTOGENERATED FILE.
ALL YOUR CHANGES WILL BE LOST. ALL YOUR CHANGES WILL BE LOST.
НЕ РЕДАКТИРУЙТЕ ЭТОТ ФАЙЛ. ЭТОТ ФАЙЛ СОЗДАН АВТОМАТИЧЕСКИ. НЕ РЕДАКТИРУЙТЕ ЭТОТ ФАЙЛ. ЭТОТ ФАЙЛ СОЗДАН АВТОМАТИЧЕСКИ.
ВСЕ ВАШИ ИЗМЕНЕНИЯ БУДУТ ПОТЕРЯНЫ. ВСЕ ВАШИ ИЗМЕНЕНИЯ БУДУТ ПОТЕРЯНЫ.
*/ */
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
// generate timestamp: 2015-05-31+03:00 // generate timestamp: 2015-05-31+03:00
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
...@@ -28,11 +28,11 @@ class UObject_SK: ...@@ -28,11 +28,11 @@ class UObject_SK:
public LT_Object public LT_Object
{ {
public: public:
UObject_SK( UniSetTypes::ObjectId id, xmlNode* node=UniSetTypes::uniset_conf()->getNode("UObject"), const std::string& argprefix="" ); UObject_SK( UniSetTypes::ObjectId id, xmlNode* node = UniSetTypes::uniset_conf()->getNode("UObject"), const std::string& argprefix = "" );
UObject_SK(); UObject_SK();
virtual ~UObject_SK(); virtual ~UObject_SK();
long getValue( UniSetTypes::ObjectId sid ); long getValue( UniSetTypes::ObjectId sid );
void setValue( UniSetTypes::ObjectId sid, long value ); void setValue( UniSetTypes::ObjectId sid, long value );
void askSensor( UniSetTypes::ObjectId sid, UniversalIO::UIOCommand, UniSetTypes::ObjectId node = UniSetTypes::uniset_conf()->getLocalNode() ); void askSensor( UniSetTypes::ObjectId sid, UniversalIO::UIOCommand, UniSetTypes::ObjectId node = UniSetTypes::uniset_conf()->getLocalNode() );
...@@ -40,105 +40,111 @@ class UObject_SK: ...@@ -40,105 +40,111 @@ class UObject_SK:
virtual bool setMsg( UniSetTypes::ObjectId code, bool state = true ); virtual bool setMsg( UniSetTypes::ObjectId code, bool state = true );
inline std::shared_ptr<DebugStream> log(){ return mylog; } inline std::shared_ptr<DebugStream> log()
inline std::shared_ptr<LogAgregator> logAgregator(){ return loga; } {
return mylog;
}
inline std::shared_ptr<LogAgregator> logAgregator()
{
return loga;
}
void init_dlog( std::shared_ptr<DebugStream> d ); void init_dlog( std::shared_ptr<DebugStream> d );
// "синтаксический сахар"..для логов // "синтаксический сахар"..для логов
#ifndef myinfo #ifndef myinfo
#define myinfo if( log()->debugging(Debug::INFO) ) log()->info() #define myinfo if( log()->debugging(Debug::INFO) ) log()->info()
#endif #endif
#ifndef mywarn #ifndef mywarn
#define mywarn if( log()->debugging(Debug::WARN) ) log()->warn() #define mywarn if( log()->debugging(Debug::WARN) ) log()->warn()
#endif #endif
#ifndef mycrit #ifndef mycrit
#define mycrit if( log()->debugging(Debug::CRIT) ) log()->crit() #define mycrit if( log()->debugging(Debug::CRIT) ) log()->crit()
#endif #endif
#ifndef mylog1 #ifndef mylog1
#define mylog1 if( log()->debugging(Debug::LEVEL1) ) log()->level1() #define mylog1 if( log()->debugging(Debug::LEVEL1) ) log()->level1()
#endif #endif
#ifndef mylog2 #ifndef mylog2
#define mylog2 if( log()->debugging(Debug::LEVEL2) ) log()->level2() #define mylog2 if( log()->debugging(Debug::LEVEL2) ) log()->level2()
#endif #endif
#ifndef mylog3 #ifndef mylog3
#define mylog3 if( log()->debugging(Debug::LEVEL3) ) log()->level3() #define mylog3 if( log()->debugging(Debug::LEVEL3) ) log()->level3()
#endif #endif
#ifndef mylog4 #ifndef mylog4
#define mylog4 if( log()->debugging(Debug::LEVEL4) ) log()->level4() #define mylog4 if( log()->debugging(Debug::LEVEL4) ) log()->level4()
#endif #endif
#ifndef mylog5 #ifndef mylog5
#define mylog5 if( log()->debugging(Debug::LEVEL5) ) log()->level5() #define mylog5 if( log()->debugging(Debug::LEVEL5) ) log()->level5()
#endif #endif
#ifndef mylog6 #ifndef mylog6
#define mylog6 if( log()->debugging(Debug::LEVEL6) ) log()->level6() #define mylog6 if( log()->debugging(Debug::LEVEL6) ) log()->level6()
#endif #endif
#ifndef mylog7 #ifndef mylog7
#define mylog7 if( log()->debugging(Debug::LEVEL7) ) log()->level7() #define mylog7 if( log()->debugging(Debug::LEVEL7) ) log()->level7()
#endif #endif
#ifndef mylog8 #ifndef mylog8
#define mylog8 if( log()->debugging(Debug::LEVEL8) ) log()->level8() #define mylog8 if( log()->debugging(Debug::LEVEL8) ) log()->level8()
#endif #endif
#ifndef mylog9 #ifndef mylog9
#define mylog9 if( log()->debugging(Debug::LEVEL9) ) log()->level9() #define mylog9 if( log()->debugging(Debug::LEVEL9) ) log()->level9()
#endif #endif
#ifndef mylogany #ifndef mylogany
#define mylogany log()->any() #define mylogany log()->any()
#endif #endif
// Вспомогательные функции для удобства логирования // Вспомогательные функции для удобства логирования
// ------------------------------------------------------------ // ------------------------------------------------------------
/*!< вывод в строку значение всех входов и выходов в формате /*!< вывод в строку значение всех входов и выходов в формате
ObjectName: ObjectName:
in_xxx = val in_xxx = val
in_xxx2 = val in_xxx2 = val
out_zzz = val out_zzz = val
... ...
*/ */
std::string dumpIO(); std::string dumpIO();
/*!< Вывод в строку названия входа/выхода в формате: in_xxx(SensorName) /*!< Вывод в строку названия входа/выхода в формате: in_xxx(SensorName)
\param id - идентификатор датчика \param id - идентификатор датчика
\param showLinkName - TRUE - выводить SensorName, FALSE - не выводить \param showLinkName - TRUE - выводить SensorName, FALSE - не выводить
*/ */
std::string str( UniSetTypes::ObjectId id, bool showLinkName=true ); std::string str( UniSetTypes::ObjectId id, bool showLinkName = true );
/*!< Вывод значения входа/выхода в формате: in_xxx(SensorName)=val /*!< Вывод значения входа/выхода в формате: in_xxx(SensorName)=val
\param id - идентификатор датчика \param id - идентификатор датчика
\param showLinkName - TRUE - выводить SensorName, FALSE - не выводить \param showLinkName - TRUE - выводить SensorName, FALSE - не выводить
*/ */
std::string strval( UniSetTypes::ObjectId id, bool showLinkName=true ); std::string strval( UniSetTypes::ObjectId id, bool showLinkName = true );
// ------------------------------------------------------------ // ------------------------------------------------------------
// Используемые идентификаторы // Используемые идентификаторы
// Используемые идентификаторы сообщений // Используемые идентификаторы сообщений
// Текущее значение // Текущее значение
// --- public variables --- // --- public variables ---
// --- end of public variables --- // --- end of public variables ---
protected: protected:
// --- protected variables --- // --- protected variables ---
// ---- end of protected variables ---- // ---- end of protected variables ----
virtual void callback() override; virtual void callback() override;
virtual void processingMessage( UniSetTypes::VoidMessage* msg ) override; virtual void processingMessage( UniSetTypes::VoidMessage* msg ) override;
virtual void sysCommand( const UniSetTypes::SystemMessage* sm ){}; virtual void sysCommand( const UniSetTypes::SystemMessage* sm ) {};
virtual void askSensors( UniversalIO::UIOCommand cmd ){} virtual void askSensors( UniversalIO::UIOCommand cmd ) {}
virtual void sensorInfo( const UniSetTypes::SensorMessage* sm ) override{} virtual void sensorInfo( const UniSetTypes::SensorMessage* sm ) override {}
virtual void timerInfo( const UniSetTypes::TimerMessage* tm ) override{} virtual void timerInfo( const UniSetTypes::TimerMessage* tm ) override {}
virtual void sigterm( int signo ) override; virtual void sigterm( int signo ) override;
virtual bool activateObject() override; virtual bool activateObject() override;
virtual void testMode( bool state ); virtual void testMode( bool state );
...@@ -158,7 +164,7 @@ class UObject_SK: ...@@ -158,7 +164,7 @@ class UObject_SK:
int resetMsgTime; int resetMsgTime;
// Выполнение очередного шага программы // Выполнение очередного шага программы
virtual void step(){} virtual void step() {}
int sleep_msec; /*!< пауза между итерациями */ int sleep_msec; /*!< пауза между итерациями */
bool active; bool active;
...@@ -170,22 +176,28 @@ class UObject_SK: ...@@ -170,22 +176,28 @@ class UObject_SK:
PassiveTimer ptHeartBeat; /*! < период "сердцебиения" */ PassiveTimer ptHeartBeat; /*! < период "сердцебиения" */
UniSetTypes::ObjectId idHeartBeat; /*! < идентификатор датчика (AI) "сердцебиения" */ UniSetTypes::ObjectId idHeartBeat; /*! < идентификатор датчика (AI) "сердцебиения" */
int maxHeartBeat; /*! < сохраняемое значение */ int maxHeartBeat; /*! < сохраняемое значение */
xmlNode* confnode; xmlNode* confnode;
/*! получить числовое свойство из конф. файла по привязанной confnode */ /*! получить числовое свойство из конф. файла по привязанной confnode */
int getIntProp(const std::string& name) { return UniSetTypes::uniset_conf()->getIntProp(confnode, name); } int getIntProp(const std::string& name)
{
return UniSetTypes::uniset_conf()->getIntProp(confnode, name);
}
/*! получить текстовое свойство из конф. файла по привязанной confnode */ /*! получить текстовое свойство из конф. файла по привязанной confnode */
inline const std::string getProp(const std::string& name) { return UniSetTypes::uniset_conf()->getProp(confnode, name); } inline const std::string getProp(const std::string& name)
{
return UniSetTypes::uniset_conf()->getProp(confnode, name);
}
int smReadyTimeout; /*!< время ожидания готовности SM */ int smReadyTimeout; /*!< время ожидания готовности SM */
std::atomic_bool activated; std::atomic_bool activated;
int activateTimeout; /*!< время ожидания готовности UniSetObject к работе */ int activateTimeout; /*!< время ожидания готовности UniSetObject к работе */
PassiveTimer ptStartUpTimeout; /*!< время на блокировку обработки WatchDog, если недавно был StartUp */ PassiveTimer ptStartUpTimeout; /*!< время на блокировку обработки WatchDog, если недавно был StartUp */
int askPause; /*!< пауза между неудачными попытками заказать датчики */ int askPause; /*!< пауза между неудачными попытками заказать датчики */
IOController_i::SensorInfo si; IOController_i::SensorInfo si;
bool forceOut; /*!< флаг принудительного обноления "выходов" */ bool forceOut; /*!< флаг принудительного обноления "выходов" */
std::shared_ptr<LogAgregator> loga; std::shared_ptr<LogAgregator> loga;
std::shared_ptr<DebugStream> mylog; std::shared_ptr<DebugStream> mylog;
std::shared_ptr<LogServer> logserv; std::shared_ptr<LogServer> logserv;
...@@ -194,15 +206,15 @@ class UObject_SK: ...@@ -194,15 +206,15 @@ class UObject_SK:
private: private:
// --- private variables --- // --- private variables ---
// --- end of private variables --- // --- end of private variables ---
// предыдущее значение (для работы UpdateValue()) // предыдущее значение (для работы UpdateValue())
// Используемые идентификаторы сообщений // Используемые идентификаторы сообщений
bool end_private; // вспомогательное поле (для внутреннего использования при генерировании кода) bool end_private; // вспомогательное поле (для внутреннего использования при генерировании кода)
}; };
......
...@@ -6,10 +6,10 @@ ...@@ -6,10 +6,10 @@
/* /*
DO NOT EDIT THIS FILE. IT IS AUTOGENERATED FILE. DO NOT EDIT THIS FILE. IT IS AUTOGENERATED FILE.
ALL YOUR CHANGES WILL BE LOST. ALL YOUR CHANGES WILL BE LOST.
НЕ РЕДАКТИРУЙТЕ ЭТОТ ФАЙЛ. ЭТОТ ФАЙЛ СОЗДАН АВТОМАТИЧЕСКИ. НЕ РЕДАКТИРУЙТЕ ЭТОТ ФАЙЛ. ЭТОТ ФАЙЛ СОЗДАН АВТОМАТИЧЕСКИ.
ВСЕ ВАШИ ИЗМЕНЕНИЯ БУДУТ ПОТЕРЯНЫ. ВСЕ ВАШИ ИЗМЕНЕНИЯ БУДУТ ПОТЕРЯНЫ.
*/ */
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
// generate timestamp: 2015-05-31+03:00 // generate timestamp: 2015-05-31+03:00
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
...@@ -31,26 +31,26 @@ using namespace UniSetTypes; ...@@ -31,26 +31,26 @@ using namespace UniSetTypes;
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
UObject_SK::UObject_SK(): UObject_SK::UObject_SK():
// Инициализация идентификаторов (имена берутся из конф. файла) // Инициализация идентификаторов (имена берутся из конф. файла)
// Используемые идентификаторы сообщений (имена берутся из конф. файла) // Используемые идентификаторы сообщений (имена берутся из конф. файла)
// variables // variables
active(false), active(false),
idHeartBeat(DefaultObjectId), idHeartBeat(DefaultObjectId),
maxHeartBeat(10), maxHeartBeat(10),
confnode(0), confnode(0),
smReadyTimeout(0), smReadyTimeout(0),
activated(false), activated(false),
askPause(2000), askPause(2000),
forceOut(false), forceOut(false),
end_private(false) end_private(false)
{ {
ucrit << "UObject: init failed!!!!!!!!!!!!!!!" << endl; ucrit << "UObject: init failed!!!!!!!!!!!!!!!" << endl;
throw Exception( string(myname+": init failed!!!") ); throw Exception( string(myname + ": init failed!!!") );
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
// ( val, confval, default val ) // ( val, confval, default val )
...@@ -58,41 +58,42 @@ static const std::string init3_str( const std::string& s1, const std::string& s2 ...@@ -58,41 +58,42 @@ static const std::string init3_str( const std::string& s1, const std::string& s2
{ {
if( !s1.empty() ) if( !s1.empty() )
return s1; return s1;
if( !s2.empty() ) if( !s2.empty() )
return s2; return s2;
return s3; return s3;
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
UObject_SK::UObject_SK( ObjectId id, xmlNode* cnode, const std::string& _argprefix ): UObject_SK::UObject_SK( ObjectId id, xmlNode* cnode, const std::string& _argprefix ):
UniSetObject(id), UniSetObject(id),
argprefix( (_argprefix.empty() ? myname+"-" : _argprefix) ), argprefix( (_argprefix.empty() ? myname + "-" : _argprefix) ),
// Инициализация идентификаторов (имена берутся из конф. файла) // Инициализация идентификаторов (имена берутся из конф. файла)
// Используемые идентификаторы сообщений (имена берутся из конф. файла) // Используемые идентификаторы сообщений (имена берутся из конф. файла)
// variables // variables
sleep_msec(150), sleep_msec(150),
active(true), active(true),
idHeartBeat(DefaultObjectId), idHeartBeat(DefaultObjectId),
maxHeartBeat(10), maxHeartBeat(10),
confnode(cnode), confnode(cnode),
smReadyTimeout(0), smReadyTimeout(0),
activated(false), activated(false),
askPause(uniset_conf()->getPIntProp(cnode,"askPause",2000)), askPause(uniset_conf()->getPIntProp(cnode, "askPause", 2000)),
forceOut(false), forceOut(false),
end_private(false) end_private(false)
{ {
auto conf = uniset_conf(); auto conf = uniset_conf();
if( UniSetTypes::findArgParam("--print-id-list",uniset_conf()->getArgc(),uniset_conf()->getArgv()) != -1 ) if( UniSetTypes::findArgParam("--print-id-list", uniset_conf()->getArgc(), uniset_conf()->getArgv()) != -1 )
{ {
// abort(); // abort();
} }
...@@ -103,15 +104,15 @@ end_private(false) ...@@ -103,15 +104,15 @@ end_private(false)
throw SystemError( err.str() ); throw SystemError( err.str() );
} }
mylog = make_shared<DebugStream>(); mylog = make_shared<DebugStream>();
mylog->setLogName(myname); mylog->setLogName(myname);
{ {
ostringstream s; ostringstream s;
s << argprefix << "log"; s << argprefix << "log";
conf->initLogStream(mylog,s.str()); conf->initLogStream(mylog, s.str());
} }
loga = make_shared<LogAgregator>(myname+"-loga"); loga = make_shared<LogAgregator>(myname + "-loga");
loga->add(mylog); loga->add(mylog);
loga->add(ulog()); loga->add(ulog());
...@@ -128,13 +129,15 @@ end_private(false) ...@@ -128,13 +129,15 @@ end_private(false)
logserv_host = conf->getArg2Param("--" + argprefix + "logserver-host", it.getProp("logserverHost"), "localhost"); logserv_host = conf->getArg2Param("--" + argprefix + "logserver-host", it.getProp("logserverHost"), "localhost");
logserv_port = conf->getArgPInt("--" + argprefix + "logserver-port", it.getProp("logserverPort"), getId()); logserv_port = conf->getArgPInt("--" + argprefix + "logserver-port", it.getProp("logserverPort"), getId());
} }
forceOut = conf->getArgPInt("--" + argprefix + "force-out",it.getProp("forceOut"),false);
string heart = conf->getArgParam("--" + argprefix + "heartbeat-id",it.getProp("heartbeat_id")); forceOut = conf->getArgPInt("--" + argprefix + "force-out", it.getProp("forceOut"), false);
string heart = conf->getArgParam("--" + argprefix + "heartbeat-id", it.getProp("heartbeat_id"));
if( !heart.empty() ) if( !heart.empty() )
{ {
idHeartBeat = conf->getSensorID(heart); idHeartBeat = conf->getSensorID(heart);
if( idHeartBeat == DefaultObjectId ) if( idHeartBeat == DefaultObjectId )
{ {
ostringstream err; ostringstream err;
...@@ -142,35 +145,38 @@ end_private(false) ...@@ -142,35 +145,38 @@ end_private(false)
throw SystemError(err.str()); throw SystemError(err.str());
} }
int heartbeatTime = conf->getArgPInt("--" + argprefix + "heartbeat-time",it.getProp("heartbeatTime"),conf->getHeartBeatTime()); int heartbeatTime = conf->getArgPInt("--" + argprefix + "heartbeat-time", it.getProp("heartbeatTime"), conf->getHeartBeatTime());
if( heartbeatTime>0 )
if( heartbeatTime > 0 )
ptHeartBeat.setTiming(heartbeatTime); ptHeartBeat.setTiming(heartbeatTime);
else else
ptHeartBeat.setTiming(UniSetTimer::WaitUpTime); ptHeartBeat.setTiming(UniSetTimer::WaitUpTime);
maxHeartBeat = conf->getArgPInt("--" + argprefix + "heartbeat-max",it.getProp("heartbeat_max"), 10); maxHeartBeat = conf->getArgPInt("--" + argprefix + "heartbeat-max", it.getProp("heartbeat_max"), 10);
} }
// Инициализация значений // Инициализация значений
sleep_msec = conf->getArgPInt("--" + argprefix + "sleep-msec","150", 150); sleep_msec = conf->getArgPInt("--" + argprefix + "sleep-msec", "150", 150);
string s_resetTime(""); string s_resetTime("");
if( s_resetTime.empty() ) if( s_resetTime.empty() )
s_resetTime = "500"; s_resetTime = "500";
resetMsgTime = uni_atoi(init3_str(conf->getArgParam("--" + argprefix + "resetMsgTime"),conf->getProp(cnode,"resetMsgTime"),s_resetTime)); resetMsgTime = uni_atoi(init3_str(conf->getArgParam("--" + argprefix + "resetMsgTime"), conf->getProp(cnode, "resetMsgTime"), s_resetTime));
ptResetMsg.setTiming(resetMsgTime); ptResetMsg.setTiming(resetMsgTime);
smReadyTimeout = conf->getArgInt("--" + argprefix + "sm-ready-timeout",""); smReadyTimeout = conf->getArgInt("--" + argprefix + "sm-ready-timeout", "");
if( smReadyTimeout == 0 ) if( smReadyTimeout == 0 )
smReadyTimeout = 60000; smReadyTimeout = 60000;
else if( smReadyTimeout < 0 ) else if( smReadyTimeout < 0 )
smReadyTimeout = UniSetTimer::WaitUpTime; smReadyTimeout = UniSetTimer::WaitUpTime;
smTestID = conf->getSensorID(init3_str(conf->getArgParam("--" + argprefix + "sm-test-id"),conf->getProp(cnode,"smTestID"),"")); smTestID = conf->getSensorID(init3_str(conf->getArgParam("--" + argprefix + "sm-test-id"), conf->getProp(cnode, "smTestID"), ""));
activateTimeout = conf->getArgPInt("--" + argprefix + "activate-timeout", 20000); activateTimeout = conf->getArgPInt("--" + argprefix + "activate-timeout", 20000);
...@@ -178,7 +184,7 @@ end_private(false) ...@@ -178,7 +184,7 @@ end_private(false)
ptStartUpTimeout.setTiming(msec); ptStartUpTimeout.setTiming(msec);
// ===================== <variables> ===================== // ===================== <variables> =====================
// ===================== end of <variables> ===================== // ===================== end of <variables> =====================
} }
...@@ -191,17 +197,17 @@ UObject_SK::~UObject_SK() ...@@ -191,17 +197,17 @@ UObject_SK::~UObject_SK()
void UObject_SK::updateValues() void UObject_SK::updateValues()
{ {
// Опрашиваем все входы... // Опрашиваем все входы...
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
void UObject_SK::updatePreviousValues() void UObject_SK::updatePreviousValues()
{ {
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
void UObject_SK::checkSensors() void UObject_SK::checkSensors()
{ {
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
bool UObject_SK::setMsg( UniSetTypes::ObjectId _code, bool _state ) bool UObject_SK::setMsg( UniSetTypes::ObjectId _code, bool _state )
...@@ -209,24 +215,24 @@ bool UObject_SK::setMsg( UniSetTypes::ObjectId _code, bool _state ) ...@@ -209,24 +215,24 @@ bool UObject_SK::setMsg( UniSetTypes::ObjectId _code, bool _state )
if( _code == UniSetTypes::DefaultObjectId ) if( _code == UniSetTypes::DefaultObjectId )
{ {
mycrit << myname << "(setMsg): попытка послать сообщение с DefaultObjectId" << endl; mycrit << myname << "(setMsg): попытка послать сообщение с DefaultObjectId" << endl;
return false; return false;
} }
mylog8 << myname << "(setMsg): " << ( _state ? "SEND " : "RESET " ) << endl; mylog8 << myname << "(setMsg): " << ( _state ? "SEND " : "RESET " ) << endl;
// взводим автоматический сброс
if( _state )
ptResetMsg.reset();
// взводим автоматический сброс
if( _state )
ptResetMsg.reset();
mylog8 << myname << "(setMsg): not found MessgeOID?!!" << endl;
mylog8 << myname << "(setMsg): not found MessgeOID?!!" << endl;
return false; return false;
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
void UObject_SK::resetMsg() void UObject_SK::resetMsg()
{ {
// reset messages // reset messages
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
...@@ -236,28 +242,28 @@ void UObject_SK::testMode( bool _state ) ...@@ -236,28 +242,28 @@ void UObject_SK::testMode( bool _state )
return; return;
// отключаем все выходы // отключаем все выходы
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
std::string UObject_SK::dumpIO() std::string UObject_SK::dumpIO()
{ {
ostringstream s; ostringstream s;
s << myname << ": " << endl; s << myname << ": " << endl;
return s.str(); return s.str();
} }
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
std::string UObject_SK::str( UniSetTypes::ObjectId id, bool showLinkName ) std::string UObject_SK::str( UniSetTypes::ObjectId id, bool showLinkName )
{ {
ostringstream s; ostringstream s;
return ""; return "";
} }
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
std::string UObject_SK::strval( UniSetTypes::ObjectId id, bool showLinkName ) std::string UObject_SK::strval( UniSetTypes::ObjectId id, bool showLinkName )
{ {
ostringstream s; ostringstream s;
return ""; return "";
} }
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
...@@ -278,19 +284,19 @@ void UObject_SK::processingMessage( UniSetTypes::VoidMessage* _msg ) ...@@ -278,19 +284,19 @@ void UObject_SK::processingMessage( UniSetTypes::VoidMessage* _msg )
{ {
case Message::SensorInfo: case Message::SensorInfo:
preSensorInfo( reinterpret_cast<SensorMessage*>(_msg) ); preSensorInfo( reinterpret_cast<SensorMessage*>(_msg) );
break; break;
case Message::Timer: case Message::Timer:
preTimerInfo( reinterpret_cast<TimerMessage*>(_msg) ); preTimerInfo( reinterpret_cast<TimerMessage*>(_msg) );
break; break;
case Message::SysCommand: case Message::SysCommand:
preSysCommand( reinterpret_cast<SystemMessage*>(_msg) ); preSysCommand( reinterpret_cast<SystemMessage*>(_msg) );
break; break;
default: default:
break; break;
} }
} }
catch( const Exception& ex ) catch( const Exception& ex )
{ {
...@@ -304,11 +310,13 @@ void UObject_SK::preSysCommand( const SystemMessage* _sm ) ...@@ -304,11 +310,13 @@ void UObject_SK::preSysCommand( const SystemMessage* _sm )
{ {
case SystemMessage::WatchDog: case SystemMessage::WatchDog:
uinfo << myname << "(preSysCommand): WatchDog" << endl; uinfo << myname << "(preSysCommand): WatchDog" << endl;
if( !active || !ptStartUpTimeout.checkTime() ) if( !active || !ptStartUpTimeout.checkTime() )
{ {
uwarn << myname << "(preSysCommand): игнорируем WatchDog, потому-что только-что стартанули" << endl; uwarn << myname << "(preSysCommand): игнорируем WatchDog, потому-что только-что стартанули" << endl;
break; break;
} }
case SystemMessage::StartUp: case SystemMessage::StartUp:
{ {
if( !logserv_host.empty() && logserv_port != 0 && !logserv->isRunning() ) if( !logserv_host.empty() && logserv_port != 0 && !logserv->isRunning() )
...@@ -328,21 +336,22 @@ void UObject_SK::preSysCommand( const SystemMessage* _sm ) ...@@ -328,21 +336,22 @@ void UObject_SK::preSysCommand( const SystemMessage* _sm )
active = true; active = true;
break; break;
} }
case SystemMessage::FoldUp: case SystemMessage::FoldUp:
case SystemMessage::Finish: case SystemMessage::Finish:
preAskSensors(UniversalIO::UIODontNotify); preAskSensors(UniversalIO::UIODontNotify);
askSensors(UniversalIO::UIODontNotify); askSensors(UniversalIO::UIODontNotify);
break; break;
case SystemMessage::LogRotate: case SystemMessage::LogRotate:
{ {
// переоткрываем логи // переоткрываем логи
mylogany << myname << "(preSysCommand): logRotate" << endl; mylogany << myname << "(preSysCommand): logRotate" << endl;
string fname( log()->getLogFile() ); string fname( log()->getLogFile() );
if( !fname.empty() ) if( !fname.empty() )
{ {
mylog->logFile(fname.c_str(),true); mylog->logFile(fname.c_str(), true);
mylogany << myname << "(preSysCommand): ***************** mylog LOG ROTATE *****************" << endl; mylogany << myname << "(preSysCommand): ***************** mylog LOG ROTATE *****************" << endl;
} }
} }
...@@ -351,7 +360,7 @@ void UObject_SK::preSysCommand( const SystemMessage* _sm ) ...@@ -351,7 +360,7 @@ void UObject_SK::preSysCommand( const SystemMessage* _sm )
default: default:
break; break;
} }
sysCommand(_sm); sysCommand(_sm);
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
...@@ -364,7 +373,7 @@ void UObject_SK::sigterm( int signo ) ...@@ -364,7 +373,7 @@ void UObject_SK::sigterm( int signo )
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
bool UObject_SK::activateObject() bool UObject_SK::activateObject()
{ {
// блокирование обработки Startup // блокирование обработки Startup
// пока не пройдёт инициализация датчиков // пока не пройдёт инициализация датчиков
// см. preSysCommand() // см. preSysCommand()
{ {
...@@ -390,24 +399,24 @@ void UObject_SK::waitSM( int wait_msec, ObjectId _testID ) ...@@ -390,24 +399,24 @@ void UObject_SK::waitSM( int wait_msec, ObjectId _testID )
if( _testID == DefaultObjectId ) if( _testID == DefaultObjectId )
return; return;
uinfo << myname << "(waitSM): waiting SM ready " uinfo << myname << "(waitSM): waiting SM ready "
<< wait_msec << " msec" << wait_msec << " msec"
<< " testID=" << _testID << endl; << " testID=" << _testID << endl;
if( !ui->waitReady(_testID,wait_msec) ) if( !ui->waitReady(_testID, wait_msec) )
{ {
ostringstream err; ostringstream err;
err << myname err << myname
<< "(waitSM): Не дождались готовности(exist) SharedMemory к работе в течение " << "(waitSM): Не дождались готовности(exist) SharedMemory к работе в течение "
<< wait_msec << " мсек"; << wait_msec << " мсек";
ucrit << err.str() << endl; ucrit << err.str() << endl;
// terminate(); // terminate();
// abort(); // abort();
raise(SIGTERM); raise(SIGTERM);
terminate(); terminate();
// throw SystemError(err.str()); // throw SystemError(err.str());
} }
...@@ -419,37 +428,39 @@ void UObject_SK::callback() ...@@ -419,37 +428,39 @@ void UObject_SK::callback()
{ {
if( !active ) if( !active )
return; return;
try try
{ {
// проверка таймеров // проверка таймеров
checkTimers(this); checkTimers(this);
if( resetMsgTime>0 && trResetMsg.hi(ptResetMsg.checkTime()) ) if( resetMsgTime > 0 && trResetMsg.hi(ptResetMsg.checkTime()) )
{ {
// cout << myname << ": ********* reset messages *********" << endl; // cout << myname << ": ********* reset messages *********" << endl;
resetMsg(); resetMsg();
} }
// обработка сообщений (таймеров и т.п.) // обработка сообщений (таймеров и т.п.)
for( unsigned int i=0; i<20; i++ ) for( unsigned int i = 0; i < 20; i++ )
{ {
if( !receiveMessage(msg) ) if( !receiveMessage(msg) )
break; break;
processingMessage(&msg); processingMessage(&msg);
updateOutputs(forceOut); updateOutputs(forceOut);
// updatePreviousValues(); // updatePreviousValues();
} }
// Выполнение шага программы // Выполнение шага программы
step(); step();
// "сердцебиение" // "сердцебиение"
if( idHeartBeat!=DefaultObjectId && ptHeartBeat.checkTime() ) if( idHeartBeat != DefaultObjectId && ptHeartBeat.checkTime() )
{ {
try try
{ {
ui->setValue(idHeartBeat,maxHeartBeat); ui->setValue(idHeartBeat, maxHeartBeat);
ptHeartBeat.reset(); ptHeartBeat.reset();
} }
catch( const Exception& ex ) catch( const Exception& ex )
...@@ -464,46 +475,46 @@ void UObject_SK::callback() ...@@ -464,46 +475,46 @@ void UObject_SK::callback()
} }
catch( const Exception& ex ) catch( const Exception& ex )
{ {
ucrit << myname << "(execute): " << ex << endl; ucrit << myname << "(execute): " << ex << endl;
} }
catch( const CORBA::SystemException& ex ) catch( const CORBA::SystemException& ex )
{ {
ucrit << myname << "(execute): СORBA::SystemException: " ucrit << myname << "(execute): СORBA::SystemException: "
<< ex.NP_minorString() << endl; << ex.NP_minorString() << endl;
}
catch( const std::exception& ex )
{
ucrit << myname << "(execute): catch " << ex.what() << endl;
} }
catch( const std::exception&ex )
{
ucrit << myname << "(execute): catch " << ex.what() << endl;
}
if( !active ) if( !active )
return; return;
msleep( sleep_msec ); msleep( sleep_msec );
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
void UObject_SK::setValue( UniSetTypes::ObjectId _sid, long _val ) void UObject_SK::setValue( UniSetTypes::ObjectId _sid, long _val )
{ {
ui->setValue(_sid,_val);
ui->setValue(_sid, _val);
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
void UObject_SK::updateOutputs( bool _force ) void UObject_SK::updateOutputs( bool _force )
{ {
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
void UObject_SK::preSensorInfo( const UniSetTypes::SensorMessage* _sm ) void UObject_SK::preSensorInfo( const UniSetTypes::SensorMessage* _sm )
{ {
sensorInfo(_sm); sensorInfo(_sm);
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
void UObject_SK::askSensor( UniSetTypes::ObjectId _sid, UniversalIO::UIOCommand _cmd, UniSetTypes::ObjectId _node ) void UObject_SK::askSensor( UniSetTypes::ObjectId _sid, UniversalIO::UIOCommand _cmd, UniSetTypes::ObjectId _node )
{ {
ui->askRemoteSensor(_sid,_cmd,_node,getId()); ui->askRemoteSensor(_sid, _cmd, _node, getId());
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
long UObject_SK::getValue( UniSetTypes::ObjectId _sid ) long UObject_SK::getValue( UniSetTypes::ObjectId _sid )
...@@ -516,7 +527,7 @@ long UObject_SK::getValue( UniSetTypes::ObjectId _sid ) ...@@ -516,7 +527,7 @@ long UObject_SK::getValue( UniSetTypes::ObjectId _sid )
} }
catch( const Exception& ex ) catch( const Exception& ex )
{ {
ucrit << myname << "(getValue): " << ex << endl; ucrit << myname << "(getValue): " << ex << endl;
throw; throw;
} }
} }
...@@ -525,33 +536,35 @@ long UObject_SK::getValue( UniSetTypes::ObjectId _sid ) ...@@ -525,33 +536,35 @@ long UObject_SK::getValue( UniSetTypes::ObjectId _sid )
void UObject_SK::preAskSensors( UniversalIO::UIOCommand _cmd ) void UObject_SK::preAskSensors( UniversalIO::UIOCommand _cmd )
{ {
PassiveTimer ptAct(activateTimeout); PassiveTimer ptAct(activateTimeout);
while( !activated && !ptAct.checkTime() ) while( !activated && !ptAct.checkTime() )
{ {
cout << myname << "(preAskSensors): wait activate..." << endl; cout << myname << "(preAskSensors): wait activate..." << endl;
msleep(300); msleep(300);
if( activated ) if( activated )
break; break;
} }
if( !activated ) if( !activated )
ucrit << myname ucrit << myname
<< "(preAskSensors): ************* don`t activated?! ************" << endl; << "(preAskSensors): ************* don`t activated?! ************" << endl;
for( ;; ) for( ;; )
{ {
try try
{ {
return; return;
} }
catch( const Exception& ex ) catch( const Exception& ex )
{ {
ucrit << myname << "(preAskSensors): " << ex << endl; ucrit << myname << "(preAskSensors): " << ex << endl;
}
catch( const std::exception& ex )
{
ucrit << myname << "(execute): catch " << ex.what() << endl;
} }
catch( const std::exception&ex )
{
ucrit << myname << "(execute): catch " << ex.what() << endl;
}
msleep(askPause); msleep(askPause);
} }
......
...@@ -137,16 +137,28 @@ class DebugStream : public std::ostream ...@@ -137,16 +137,28 @@ class DebugStream : public std::ostream
} }
// имя лог файла можно установить отдельно, но не вклчать запись.. // имя лог файла можно установить отдельно, но не вклчать запись..
inline void setLogFile( const std::string& n ){ fname = n; } inline void setLogFile( const std::string& n )
{
fname = n;
}
// включена ли запись лог-файла // включена ли запись лог-файла
inline bool isOnLogFile(){ return isWriteLogFile; } inline bool isOnLogFile()
{
return isWriteLogFile;
}
// включить запись лог файла // включить запись лог файла
inline void onLogFile( bool truncate=false ){ logFile(fname,truncate); } inline void onLogFile( bool truncate = false )
{
logFile(fname, truncate);
}
// отключить запись логфайла // отключить запись логфайла
inline void offLogFile(){ logFile(""); } inline void offLogFile()
{
logFile("");
}
/// Returns true if t is part of the current debug level. /// Returns true if t is part of the current debug level.
inline bool debugging(Debug::type t = Debug::ANY) const inline bool debugging(Debug::type t = Debug::ANY) const
......
...@@ -3,6 +3,7 @@ ...@@ -3,6 +3,7 @@
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
#include <string> #include <string>
#include <memory> #include <memory>
#include <regex>
#include <list> #include <list>
#include <vector> #include <vector>
#include <unordered_map> #include <unordered_map>
...@@ -111,17 +112,17 @@ class LogAgregator: ...@@ -111,17 +112,17 @@ class LogAgregator:
{ {
public: public:
const std::string sep= {"/"}; /*< раздедитель для имён подчинённых агрегаторов */ const std::string sep = {"/"}; /*< раздедитель для имён подчинённых агрегаторов */
explicit LogAgregator( const std::string& name, Debug::type t ); explicit LogAgregator( const std::string& name, Debug::type t );
explicit LogAgregator( const std::string& name="" ); explicit LogAgregator( const std::string& name = "" );
virtual ~LogAgregator(); virtual ~LogAgregator();
virtual void logFile( const std::string& f, bool truncate = false ) override; virtual void logFile( const std::string& f, bool truncate = false ) override;
void add( std::shared_ptr<LogAgregator> log, const std::string& lname="" ); void add( std::shared_ptr<LogAgregator> log, const std::string& lname = "" );
void add( std::shared_ptr<DebugStream> log, const std::string& lname="" ); void add( std::shared_ptr<DebugStream> log, const std::string& lname = "" );
std::shared_ptr<DebugStream> create( const std::string& logname ); std::shared_ptr<DebugStream> create( const std::string& logname );
...@@ -132,16 +133,12 @@ class LogAgregator: ...@@ -132,16 +133,12 @@ class LogAgregator:
void offLogFile( const std::string& logname ); void offLogFile( const std::string& logname );
void onLogFile( const std::string& logname ); void onLogFile( const std::string& logname );
// найти лог..
std::shared_ptr<DebugStream> getLog( const std::string& logname ); std::shared_ptr<DebugStream> getLog( const std::string& logname );
friend std::ostream& operator<<(std::ostream& os, LogAgregator& la );
friend std::ostream& operator<<(std::ostream& os, std::shared_ptr<LogAgregator> la );
static std::vector<std::string> split_first( const std::string& lname, const std::string s = "/" );
struct iLog struct iLog
{ {
iLog( std::shared_ptr<DebugStream>& l, const std::string& nm ):log(l),name(nm){} iLog( std::shared_ptr<DebugStream>& l, const std::string& nm ): log(l), name(nm) {}
std::shared_ptr<DebugStream> log; std::shared_ptr<DebugStream> log;
std::string name; std::string name;
...@@ -155,6 +152,11 @@ class LogAgregator: ...@@ -155,6 +152,11 @@ class LogAgregator:
std::list<iLog> getLogList(); std::list<iLog> getLogList();
std::list<iLog> getLogList( const std::string& regexp_str ); std::list<iLog> getLogList( const std::string& regexp_str );
friend std::ostream& operator<<(std::ostream& os, LogAgregator& la );
friend std::ostream& operator<<(std::ostream& os, std::shared_ptr<LogAgregator> la );
static std::vector<std::string> splitFirst( const std::string& lname, const std::string s = "/" );
protected: protected:
void logOnEvent( const std::string& s ); void logOnEvent( const std::string& s );
void addLog( std::shared_ptr<DebugStream> l, const std::string& lname ); void addLog( std::shared_ptr<DebugStream> l, const std::string& lname );
...@@ -164,13 +166,13 @@ class LogAgregator: ...@@ -164,13 +166,13 @@ class LogAgregator:
std::shared_ptr<DebugStream> findLog( const std::string& lname ); std::shared_ptr<DebugStream> findLog( const std::string& lname );
// вывод в виде "дерева" // вывод в виде "дерева"
std::ostream& print_tree(std::ostream& os, const std::string& g_tab=""); std::ostream& printTree(std::ostream& os, const std::string& g_tab = "");
// получить список с именами (длинными) и с указателями на логи // получить список с именами (длинными) и с указателями на логи
std::list<iLog> makeLogNameList( const std::string& prefix ); std::list<iLog> makeLogNameList( const std::string& prefix );
private: private:
typedef std::unordered_map<std::string,std::shared_ptr<DebugStream>> LogMap; typedef std::unordered_map<std::string, std::shared_ptr<DebugStream>> LogMap;
LogMap lmap; LogMap lmap;
}; };
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
......
...@@ -17,7 +17,8 @@ namespace LogServerTypes ...@@ -17,7 +17,8 @@ namespace LogServerTypes
cmdRotate, /*!< пересоздать файл с логами */ cmdRotate, /*!< пересоздать файл с логами */
cmdOffLogFile, /*!< отключить запись файла логов (если включена) */ cmdOffLogFile, /*!< отключить запись файла логов (если включена) */
cmdOnLogFile, /*!< включить запись файла логов (если была отключена) */ cmdOnLogFile, /*!< включить запись файла логов (если была отключена) */
cmdList /*!< вывести список контролируемых логов */ cmdList, /*!< вывести список контролируемых логов */
cmdFilterMode /*!< включить режим работы "фильтр" - вывод только от интересующих логов, заданных в lognmae (regexp) */
// cmdSetLogFile // cmdSetLogFile
}; };
...@@ -33,7 +34,7 @@ namespace LogServerTypes ...@@ -33,7 +34,7 @@ namespace LogServerTypes
Command cmd; Command cmd;
unsigned int data; unsigned int data;
static const size_t MAXLOGNAME = 20; static const size_t MAXLOGNAME = 30;
char logname[MAXLOGNAME + 1]; // +1 reserverd for '\0' char logname[MAXLOGNAME + 1]; // +1 reserverd for '\0'
void setLogName( const std::string& name ); void setLogName( const std::string& name );
......
...@@ -68,6 +68,7 @@ class LogSession: ...@@ -68,6 +68,7 @@ class LogSession:
std::string caddr; std::string caddr;
std::shared_ptr<DebugStream> log; std::shared_ptr<DebugStream> log;
std::shared_ptr<LogAgregator> alog; std::shared_ptr<LogAgregator> alog;
sigc::connection conn;
// PassiveTimer ptSessionTimeout; // PassiveTimer ptSessionTimeout;
FinalSlot slFin; FinalSlot slFin;
......
#include <memory> #include <memory>
#include <iomanip> #include <iomanip>
#include <regex>
#include <sstream> #include <sstream>
#include "DebugExtBuf.h" #include "DebugExtBuf.h"
#include "LogAgregator.h" #include "LogAgregator.h"
...@@ -8,7 +7,7 @@ ...@@ -8,7 +7,7 @@
using namespace std; using namespace std;
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
LogAgregator::LogAgregator( const std::string& name ): LogAgregator::LogAgregator( const std::string& name ):
LogAgregator(name,Debug::ANY) LogAgregator(name, Debug::ANY)
{ {
} }
// ------------------------------------------------------------------------ // ------------------------------------------------------------------------
...@@ -63,43 +62,26 @@ std::shared_ptr<DebugStream> LogAgregator::create( const std::string& logname ) ...@@ -63,43 +62,26 @@ std::shared_ptr<DebugStream> LogAgregator::create( const std::string& logname )
void LogAgregator::add( std::shared_ptr<DebugStream> l, const std::string& lname ) void LogAgregator::add( std::shared_ptr<DebugStream> l, const std::string& lname )
{ {
auto lag = std::dynamic_pointer_cast<LogAgregator>(l); auto lag = std::dynamic_pointer_cast<LogAgregator>(l);
if( lag ) if( lag )
addLogAgregator(lag, (lname.empty() ? l->getLogName(): lname) ); addLogAgregator(lag, (lname.empty() ? l->getLogName() : lname) );
else else
addLog(l,(lname.empty() ? l->getLogName(): lname)); addLog(l, (lname.empty() ? l->getLogName() : lname));
} }
// ------------------------------------------------------------------------ // ------------------------------------------------------------------------
void LogAgregator::add( std::shared_ptr<LogAgregator> loga, const std::string& lname ) void LogAgregator::add( std::shared_ptr<LogAgregator> loga, const std::string& lname )
{ {
addLogAgregator(loga, (lname.empty() ? loga->getLogName(): lname) ); addLogAgregator(loga, (lname.empty() ? loga->getLogName() : lname) );
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
void LogAgregator::addLogAgregator( std::shared_ptr<LogAgregator> la, const std::string& lname ) void LogAgregator::addLogAgregator( std::shared_ptr<LogAgregator> la, const std::string& lname )
{ {
auto i = lmap.find(lname); auto i = lmap.find(lname);
if( i != lmap.end() ) if( i != lmap.end() )
return; return;
addLog(la,lname); addLog(la, lname);
#if 0
auto lst = la->getLogList();
for( auto&& l: lst )
{
auto lag = std::dynamic_pointer_cast<LogAgregator>(l.log);
if( lag )
{
std::ostringstream s;
s << lname << sep << lag->getLogName();
addLogAgregator(lag,s.str()); // рекурсия..
}
else
{
std::ostringstream s;
s << lname << sep << l.log->getLogName();
addLog(l.log,s.str());
}
}
#endif
} }
// ------------------------------------------------------------------------ // ------------------------------------------------------------------------
void LogAgregator::addLog( std::shared_ptr<DebugStream> l, const std::string& lname ) void LogAgregator::addLog( std::shared_ptr<DebugStream> l, const std::string& lname )
...@@ -161,7 +143,7 @@ std::shared_ptr<DebugStream> LogAgregator::getLog( const std::string& logname ) ...@@ -161,7 +143,7 @@ std::shared_ptr<DebugStream> LogAgregator::getLog( const std::string& logname )
return findLog(logname); return findLog(logname);
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
std::ostream& LogAgregator::print_tree( std::ostream& os, const std::string& g_tab ) std::ostream& LogAgregator::printTree( std::ostream& os, const std::string& g_tab )
{ {
ostringstream s; ostringstream s;
s << " ." << g_tab; s << " ." << g_tab;
...@@ -170,17 +152,22 @@ std::ostream& LogAgregator::print_tree( std::ostream& os, const std::string& g_t ...@@ -170,17 +152,22 @@ std::ostream& LogAgregator::print_tree( std::ostream& os, const std::string& g_t
os << g_tab << getLogName() << sep << endl; // << setw(6) << " " << "[ " << Debug::str(DebugStream::level()) << " ]" << endl; os << g_tab << getLogName() << sep << endl; // << setw(6) << " " << "[ " << Debug::str(DebugStream::level()) << " ]" << endl;
std::list<std::shared_ptr<DebugStream>> lst; std::list<std::shared_ptr<DebugStream>> lst;
for( const auto& l: lmap )
for( const auto& l : lmap )
lst.push_back(l.second); lst.push_back(l.second);
lst.sort([](const std::shared_ptr<DebugStream>& a, const std::shared_ptr<DebugStream>& b) { return a->getLogName() < b->getLogName(); }); lst.sort([](const std::shared_ptr<DebugStream>& a, const std::shared_ptr<DebugStream>& b)
{
return a->getLogName() < b->getLogName();
});
for( auto&& l: lst ) for( auto && l : lst )
{ {
auto ag = dynamic_pointer_cast<LogAgregator>(l); auto ag = dynamic_pointer_cast<LogAgregator>(l);
if( ag ) if( ag )
{ {
ag->print_tree(os,s_tab); ag->printTree(os, s_tab);
} }
else else
os << s_tab << l->getLogName() << " [ " << Debug::str(l->level()) << " ]" << endl; os << s_tab << l->getLogName() << " [ " << Debug::str(l->level()) << " ]" << endl;
...@@ -191,7 +178,7 @@ std::ostream& LogAgregator::print_tree( std::ostream& os, const std::string& g_t ...@@ -191,7 +178,7 @@ std::ostream& LogAgregator::print_tree( std::ostream& os, const std::string& g_t
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
std::ostream& operator<<( std::ostream& os, LogAgregator& la ) std::ostream& operator<<( std::ostream& os, LogAgregator& la )
{ {
la.print_tree(os); la.printTree(os,"");
return os; return os;
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
...@@ -200,26 +187,28 @@ std::ostream& operator<<(std::ostream& os, std::shared_ptr<LogAgregator> la ) ...@@ -200,26 +187,28 @@ std::ostream& operator<<(std::ostream& os, std::shared_ptr<LogAgregator> la )
return os << *(la.get()); return os << *(la.get());
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
std::vector<std::string> LogAgregator::split_first( const std::string& lname, const std::string s ) std::vector<std::string> LogAgregator::splitFirst( const std::string& lname, const std::string s )
{ {
string::size_type pos = lname.find(s); string::size_type pos = lname.find(s);
if( pos == string::npos ) if( pos == string::npos )
{ {
vector<string> v{lname,""}; vector<string> v{lname, ""};
return std::move(v); return std::move(v);
} }
vector<string> v={lname.substr(0, pos), lname.substr(pos+1, lname.length()) }; vector<string> v = {lname.substr(0, pos), lname.substr(pos + 1, lname.length()) };
return std::move(v); return std::move(v);
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
std::shared_ptr<DebugStream> LogAgregator::findLog( const std::string& lname ) std::shared_ptr<DebugStream> LogAgregator::findLog( const std::string& lname )
{ {
auto v = split_first(lname,sep); auto v = splitFirst(lname, sep);
if( v[1].empty() ) if( v[1].empty() )
{ {
auto l = lmap.find(lname); auto l = lmap.find(lname);
if( l == lmap.end() ) if( l == lmap.end() )
return nullptr; return nullptr;
...@@ -227,10 +216,12 @@ std::shared_ptr<DebugStream> LogAgregator::findLog( const std::string& lname ) ...@@ -227,10 +216,12 @@ std::shared_ptr<DebugStream> LogAgregator::findLog( const std::string& lname )
} }
auto l = lmap.find(v[0]); auto l = lmap.find(v[0]);
if( l == lmap.end() ) if( l == lmap.end() )
return nullptr; return nullptr;
auto ag = dynamic_pointer_cast<LogAgregator>(l->second); auto ag = dynamic_pointer_cast<LogAgregator>(l->second);
if( !ag ) if( !ag )
return l->second; return l->second;
...@@ -246,7 +237,8 @@ std::list<LogAgregator::iLog> LogAgregator::getLogList( const std::string& regex ...@@ -246,7 +237,8 @@ std::list<LogAgregator::iLog> LogAgregator::getLogList( const std::string& regex
std::regex rule(regex_str); std::regex rule(regex_str);
auto lst = getLogList(); auto lst = getLogList();
for( const auto& i: lst )
for( const auto& i : lst )
{ {
if( std::regex_match(i.name, rule) ) if( std::regex_match(i.name, rule) )
{ {
...@@ -265,7 +257,10 @@ std::list<LogAgregator::iLog> LogAgregator::getLogList( const std::string& regex ...@@ -265,7 +257,10 @@ std::list<LogAgregator::iLog> LogAgregator::getLogList( const std::string& regex
std::list<LogAgregator::iLog> LogAgregator::getLogList() std::list<LogAgregator::iLog> LogAgregator::getLogList()
{ {
std::list<LogAgregator::iLog> lst = makeLogNameList(""); std::list<LogAgregator::iLog> lst = makeLogNameList("");
lst.sort([](const LogAgregator::iLog& a, const LogAgregator::iLog& b) { return a.name < b.name; }); lst.sort([](const LogAgregator::iLog & a, const LogAgregator::iLog & b)
{
return a.name < b.name;
});
return std::move(lst); return std::move(lst);
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
...@@ -278,17 +273,18 @@ std::list<LogAgregator::iLog> LogAgregator::makeLogNameList( const std::string& ...@@ -278,17 +273,18 @@ std::list<LogAgregator::iLog> LogAgregator::makeLogNameList( const std::string&
string p(s.str()); string p(s.str());
string p2(p+sep); string p2(p + sep);
for( auto&& l : lmap ) for( auto && l : lmap )
{ {
auto ag = dynamic_pointer_cast<LogAgregator>(l.second); auto ag = dynamic_pointer_cast<LogAgregator>(l.second);
if( ag ) if( ag )
lst.splice(lst.end(), ag->makeLogNameList(p2)); lst.splice(lst.end(), ag->makeLogNameList(p2));
else else
{ {
std::string nm(p2+l.second->getLogName()); std::string nm(p2 + l.second->getLogName());
LogAgregator::iLog il(l.second,std::move(nm) ); LogAgregator::iLog il(l.second, std::move(nm) );
lst.push_back( std::move(il) ); lst.push_back( std::move(il) );
} }
} }
...@@ -299,6 +295,7 @@ std::list<LogAgregator::iLog> LogAgregator::makeLogNameList( const std::string& ...@@ -299,6 +295,7 @@ std::list<LogAgregator::iLog> LogAgregator::makeLogNameList( const std::string&
void LogAgregator::offLogFile( const std::string& logname ) void LogAgregator::offLogFile( const std::string& logname )
{ {
auto l = findLog(logname); auto l = findLog(logname);
if( l ) if( l )
l->offLogFile(); l->offLogFile();
} }
...@@ -306,7 +303,9 @@ void LogAgregator::offLogFile( const std::string& logname ) ...@@ -306,7 +303,9 @@ void LogAgregator::offLogFile( const std::string& logname )
void LogAgregator::onLogFile( const std::string& logname ) void LogAgregator::onLogFile( const std::string& logname )
{ {
auto l = findLog(logname); auto l = findLog(logname);
if( l ) if( l )
l->onLogFile(); l->onLogFile();
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
...@@ -205,8 +205,8 @@ void LogReader::readlogs( const std::string& _addr, ost::tpport_t _port, LogServ ...@@ -205,8 +205,8 @@ void LogReader::readlogs( const std::string& _addr, ost::tpport_t _port, LogServ
log << buf; log << buf;
// if( msg.cmd == LogServerTypes::cmdList ) // if( msg.cmd == LogServerTypes::cmdList )
// break; // break;
} }
else else
break; break;
......
...@@ -28,6 +28,9 @@ std::ostream& LogServerTypes::operator<<(std::ostream& os, LogServerTypes::Comma ...@@ -28,6 +28,9 @@ std::ostream& LogServerTypes::operator<<(std::ostream& os, LogServerTypes::Comma
case LogServerTypes::cmdList: case LogServerTypes::cmdList:
return os << "cmdList"; return os << "cmdList";
case LogServerTypes::cmdFilterMode:
return os << "cmdFilterMode";
default: default:
return os << "Unknown"; return os << "Unknown";
} }
......
...@@ -46,11 +46,12 @@ LogSession::LogSession( ost::TCPSocket& server, std::shared_ptr<DebugStream>& _l ...@@ -46,11 +46,12 @@ LogSession::LogSession( ost::TCPSocket& server, std::shared_ptr<DebugStream>& _l
//slog.addLevel(Debug::ANY); //slog.addLevel(Debug::ANY);
if( log ) if( log )
log->signal_stream_event().connect( sigc::mem_fun(this, &LogSession::logOnEvent) ); conn = log->signal_stream_event().connect( sigc::mem_fun(this, &LogSession::logOnEvent) );
else else
slog.crit() << "LOG NULL!!" << endl; slog.crit() << "LOG NULL!!" << endl;
auto ag = dynamic_pointer_cast<LogAgregator>(log); auto ag = dynamic_pointer_cast<LogAgregator>(log);
if( ag ) if( ag )
alog = ag; alog = ag;
} }
...@@ -124,7 +125,7 @@ void LogSession::run() ...@@ -124,7 +125,7 @@ void LogSession::run()
{ {
if( cmdLogName == "ALL" || log->getLogFile() == cmdLogName ) if( cmdLogName == "ALL" || log->getLogFile() == cmdLogName )
{ {
LogAgregator::iLog llog(log,log->getLogName()); LogAgregator::iLog llog(log, log->getLogName());
loglist.push_back(llog); loglist.push_back(llog);
} }
} }
...@@ -136,14 +137,23 @@ void LogSession::run() ...@@ -136,14 +137,23 @@ void LogSession::run()
ostringstream s; ostringstream s;
s << "List of managed logs:" << endl; s << "List of managed logs:" << endl;
s << "=====================" << endl; s << "=====================" << endl;
if( !alog ) if( !alog )
{ {
s << log->getLogName() << endl; s << log->getLogName() << endl;
} }
else else
{ {
s << alog << endl; if( !cmdLogName.empty() )
{
auto lst = alog->getLogList(cmdLogName);
for( const auto& l: lst )
s << l.name << " [ " << Debug::str(l.log->level()) << " ]" << endl;
}
else
s << alog << endl;
} }
s << "=====================" << endl << endl; s << "=====================" << endl << endl;
if( isPending(Socket::pendingOutput, cmdTimeout) ) if( isPending(Socket::pendingOutput, cmdTimeout) )
...@@ -158,8 +168,15 @@ void LogSession::run() ...@@ -158,8 +168,15 @@ void LogSession::run()
return; return;
} }
if( msg.cmd == LogServerTypes::cmdFilterMode )
{
// отлючаем старый обработчик
if( conn )
conn.disconnect();
}
// обрабатываем команды только если нашли подходящие логи // обрабатываем команды только если нашли подходящие логи
for( auto&& l : loglist ) for( auto && l : loglist )
{ {
// Обработка команд.. // Обработка команд..
// \warning Работа с логом ведётся без mutex-а, хотя он разделяется отдельными потоками // \warning Работа с логом ведётся без mutex-а, хотя он разделяется отдельными потоками
...@@ -179,18 +196,22 @@ void LogSession::run() ...@@ -179,18 +196,22 @@ void LogSession::run()
case LogServerTypes::cmdRotate: case LogServerTypes::cmdRotate:
l.log->onLogFile(true); l.log->onLogFile(true);
break; break;
case LogServerTypes::cmdList: // обработали выше (в начале) case LogServerTypes::cmdList: // обработали выше (в начале)
break; break;
case LogServerTypes::cmdOffLogFile: case LogServerTypes::cmdOffLogFile:
l.log->offLogFile(); l.log->offLogFile();
break; break;
case LogServerTypes::cmdOnLogFile: case LogServerTypes::cmdOnLogFile:
l.log->onLogFile(); l.log->onLogFile();
break; break;
case LogServerTypes::cmdFilterMode:
l.log->signal_stream_event().connect( sigc::mem_fun(this, &LogSession::logOnEvent) );
break;
default: default:
slog.warn() << peername << "(run): Unknown command '" << msg.cmd << "'" << endl; slog.warn() << peername << "(run): Unknown command '" << msg.cmd << "'" << endl;
......
...@@ -213,7 +213,7 @@ UniSetTypes::IDList UniSetTypes::explode( const string& str, char sep ) ...@@ -213,7 +213,7 @@ UniSetTypes::IDList UniSetTypes::explode( const string& str, char sep )
} }
while( pos != string::npos ); while( pos != string::npos );
return l; return std::move(l);
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
std::vector<std::string> UniSetTypes::explode_str( const string& str, char sep ) std::vector<std::string> UniSetTypes::explode_str( const string& str, char sep )
...@@ -236,7 +236,7 @@ std::vector<std::string> UniSetTypes::explode_str( const string& str, char sep ) ...@@ -236,7 +236,7 @@ std::vector<std::string> UniSetTypes::explode_str( const string& str, char sep )
} }
while( pos != string::npos ); while( pos != string::npos );
return v; return std::move(v);
} }
// ------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------
bool UniSetTypes::is_digit( const std::string& s ) bool UniSetTypes::is_digit( const std::string& s )
......
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