Commit 90a08483 authored by Pavel Vainerman's avatar Pavel Vainerman

(Log): перевёл LogServer и LogAgregator на использование (только)

shared_ptr.
parent 3bf24d0d
...@@ -65,7 +65,7 @@ int main( int argc, char* argv[], char* envp[] ) ...@@ -65,7 +65,7 @@ int main( int argc, char* argv[], char* envp[] )
if( verb ) if( verb )
cout << "(init): listen " << addr << ":" << port << endl; cout << "(init): listen " << addr << ":" << port << endl;
DebugStream log; auto log = make_shared<DebugStream>();
LogServer ls(log); LogServer ls(log);
ls.run(addr,port,true); ls.run(addr,port,true);
...@@ -78,7 +78,7 @@ int main( int argc, char* argv[], char* envp[] ) ...@@ -78,7 +78,7 @@ int main( int argc, char* argv[], char* envp[] )
if( r > 0 ) if( r > 0 )
{ {
buf[r] = '\0'; buf[r] = '\0';
log << buf; (*(log.get())) << buf;
} }
} }
} }
......
...@@ -74,8 +74,8 @@ int main( int argc, char* argv[], char* envp[] ) ...@@ -74,8 +74,8 @@ int main( int argc, char* argv[], char* envp[] )
/* Parent. */ /* Parent. */
close(cp[1]); close(cp[1]);
DebugStream zlog; auto zlog = make_shared<DebugStream>();
zlog.addLevel(Debug::ANY); zlog->addLevel(Debug::ANY);
LogServer ls(zlog); LogServer ls(zlog);
...@@ -90,7 +90,7 @@ int main( int argc, char* argv[], char* envp[] ) ...@@ -90,7 +90,7 @@ int main( int argc, char* argv[], char* envp[] )
if( r > 0 ) if( r > 0 )
{ {
buf[r] = '\0'; buf[r] = '\0';
zlog << buf; (*(zlog.get())) << buf;
} }
} }
......
...@@ -23,24 +23,28 @@ static struct option longopts[] = { ...@@ -23,24 +23,28 @@ static struct option longopts[] = {
{ "rotate", required_argument, 0, 'r' }, { "rotate", required_argument, 0, 'r' },
{ "logname", required_argument, 0, 'l' }, { "logname", required_argument, 0, 'l' },
{ "command-only", no_argument, 0, 'b' }, { "command-only", no_argument, 0, 'b' },
{ "timeout", required_argument, 0, 'w' },
{ "reconnect-delay", required_argument, 0, 'x' },
{ NULL, 0, 0, 0 } { NULL, 0, 0, 0 }
}; };
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
static void print_help() static void print_help()
{ {
printf("-h, --help - this message\n"); printf("-h, --help - this message\n");
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("[-l|--logname] name - Send command only for 'logname'.\n"); printf("[-l|--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("[-x|--reconnect-delay] msec - Pause for repeat connect to LogServer. Default: 5000 msec.\n");
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,... - Add log levels.\n");
printf("[--del | -d] info,warn,crit,... - Delete log levels.\n"); printf("[--del | -d] info,warn,crit,... - Delete log levels.\n");
printf("[--set | -s] info,wanr,crit,... - Set log levels.\n"); printf("[--set | -s] info,warn,crit,... - Set log levels.\n");
printf("--off, -o - Off the write log file (if enabled).\n"); printf("--off, -o - Off the write log file (if enabled).\n");
printf("--on, -n - On the write log file (if before disabled).\n"); printf("--on, -n - On the write log file (if before disabled).\n");
printf("--rotate, -r - rotate log file.\n"); printf("--rotate, -r - rotate log file.\n");
...@@ -59,10 +63,12 @@ int main( int argc, char **argv ) ...@@ -59,10 +63,12 @@ int main( int argc, char **argv )
string sdata(""); string sdata("");
int cmdonly = 0; int cmdonly = 0;
string logname(""); string logname("");
timeout_t tout = 0;
timeout_t rdelay = 5000;
try try
{ {
while( (opt = getopt_long(argc, argv, "hva:p:i:d:s:l:onrb",longopts,&optindex)) != -1 ) while( (opt = getopt_long(argc, argv, "hva:p:i:d:s:l:onrbx:w:",longopts,&optindex)) != -1 )
{ {
switch (opt) switch (opt)
{ {
...@@ -114,6 +120,14 @@ int main( int argc, char **argv ) ...@@ -114,6 +120,14 @@ int main( int argc, char **argv )
port = uni_atoi(optarg); port = uni_atoi(optarg);
break; break;
case 'x':
rdelay = uni_atoi(optarg);
break;
case 'w':
tout = uni_atoi(optarg);
break;
case 'v': case 'v':
verb = 1; verb = 1;
break; break;
...@@ -134,6 +148,8 @@ int main( int argc, char **argv ) ...@@ -134,6 +148,8 @@ int main( int argc, char **argv )
LogReader lr; LogReader lr;
lr.setCommandOnlyMode(cmdonly); lr.setCommandOnlyMode(cmdonly);
lr.setinTimeout(tout);
lr.setReconnectDelay(rdelay);
if( !sdata.empty() ) if( !sdata.empty() )
{ {
......
...@@ -81,14 +81,29 @@ int main( int argc, char **argv ) ...@@ -81,14 +81,29 @@ int main( int argc, char **argv )
// dlog.addLevel( Debug::type(Debug::CRIT | Debug::WARN | Debug::INFO) ); // dlog.addLevel( Debug::type(Debug::CRIT | Debug::WARN | Debug::INFO) );
} }
LogAgregator la; auto la = make_shared<LogAgregator>();
auto dlog = make_shared<DebugStream>(); auto dlog = make_shared<DebugStream>();
dlog->setLogName("dlog"); dlog->setLogName("dlog");
la.add(dlog); la->add(dlog);
auto dlog2 = la.create("dlog2"); auto dlog2 = la->create("dlog2");
if( la->getLog("dlog") == nullptr )
{
cerr << "Not found 'dlog'" << endl;
return 1;
}
if( la->getLog("dlog2") == nullptr )
{
cerr << "Not found 'dlog2'" << endl;
return 1;
}
LogServer ls(la); LogServer ls(la);
// LogServer ls(cout); // LogServer ls(cout);
...@@ -96,7 +111,7 @@ int main( int argc, char **argv ) ...@@ -96,7 +111,7 @@ int main( int argc, char **argv )
dlog2->addLevel(Debug::ANY); dlog2->addLevel(Debug::ANY);
ls.run( addr, port, true ); ls.run( addr, port, true );
#if 0 ls.setSessionLog(Debug::ANY);
unsigned int i=0; unsigned int i=0;
while( true ) while( true )
...@@ -112,7 +127,6 @@ int main( int argc, char **argv ) ...@@ -112,7 +127,6 @@ int main( int argc, char **argv )
msleep(delay); msleep(delay);
} }
#endif
} }
catch( SystemError& err ) catch( SystemError& err )
{ {
......
...@@ -409,6 +409,7 @@ mv -f %buildroot%python_sitelibdir_noarch/* %buildroot%python_sitelibdir/%oname ...@@ -409,6 +409,7 @@ mv -f %buildroot%python_sitelibdir_noarch/* %buildroot%python_sitelibdir/%oname
* Fri Jan 23 2015 Pavel Vainerman <pv@altlinux.ru> 2.0-alt13 * Fri Jan 23 2015 Pavel Vainerman <pv@altlinux.ru> 2.0-alt13
- refactoring ulog and dlog: Objects converted to shared_ptr<DebugStream> - refactoring ulog and dlog: Objects converted to shared_ptr<DebugStream>
for subsequent use LogAgregator. for subsequent use LogAgregator.
- modify interface for LogReader,LogSession,LogServer
* Fri Jan 23 2015 Pavel Vainerman <pv@altlinux.ru> 2.0-alt12 * Fri Jan 23 2015 Pavel Vainerman <pv@altlinux.ru> 2.0-alt12
- refactoring LogAgregator,LogServer,LogSesson --> use shared_ptr - refactoring LogAgregator,LogServer,LogSesson --> use shared_ptr
......
...@@ -2,6 +2,7 @@ ...@@ -2,6 +2,7 @@
#include <string> #include <string>
#include <error.h> #include <error.h>
#include <errno.h> #include <errno.h>
#include <memory>
#include <Debug.h> #include <Debug.h>
#include <UniSetActivator.h> #include <UniSetActivator.h>
#include <ThreadCreator.h> #include <ThreadCreator.h>
...@@ -26,37 +27,11 @@ using namespace UniSetExtensions; ...@@ -26,37 +27,11 @@ using namespace UniSetExtensions;
const unsigned int MaxAddNum = 10; const unsigned int MaxAddNum = 10;
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
static void help_print( int argc, const char* argv[] ); static void help_print( int argc, const char* argv[] );
static LogServer* run_logserver( const std::string& cnamem, DebugStream& log ); static std::shared_ptr<LogServer> run_logserver( const std::string& cnamem, std::shared_ptr<LogAgregator>& log );
static LogServer* logserver = 0;
#ifdef UNISET_ENABLE_IO #ifdef UNISET_ENABLE_IO
std::list< ThreadCreator<IOControl>* > lst_iothr; std::list< ThreadCreator<IOControl>* > lst_iothr;
#endif #endif
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
void activator_terminate( int signo )
{
if( logserver )
{
try
{
delete logserver;
logserver = 0;
}
catch(...){}
}
#ifdef UNISET_IO_ENABLE
for( auto& i: lst_iothr )
{
try
{
i->stop();
}
catch(...){}
}
#endif
}
// --------------------------------------------------------------------------
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);
...@@ -77,7 +52,7 @@ int main( int argc, const char **argv ) ...@@ -77,7 +52,7 @@ int main( int argc, const char **argv )
dlog()->logFile( logname ); dlog()->logFile( logname );
auto act = UniSetActivator::Instance(); auto act = UniSetActivator::Instance();
act->signal_terminate_event().connect( &activator_terminate ); //act->signal_terminate_event().connect( &activator_terminate );
// ------------ SharedMemory ---------------- // ------------ SharedMemory ----------------
auto shm = SharedMemory::init_smemory(argc,argv); auto shm = SharedMemory::init_smemory(argc,argv);
if( !shm ) if( !shm )
...@@ -212,11 +187,11 @@ int main( int argc, const char **argv ) ...@@ -212,11 +187,11 @@ int main( int argc, const char **argv )
i->start(); i->start();
#endif #endif
LogAgregator la; auto la = make_shared<LogAgregator>();
la.add(ulog()); la->add(ulog());
la.add(dlog()); la->add(dlog());
logserver = run_logserver("smplus",la); auto logserver = run_logserver("smplus",la);
if( logserver == 0 ) if( logserver == 0 )
{ {
cerr << "(smemory-plus): run logserver for 'smplus' FAILED" << endl; cerr << "(smemory-plus): run logserver for 'smplus' FAILED" << endl;
...@@ -280,7 +255,7 @@ void help_print( int argc, const char* argv[] ) ...@@ -280,7 +255,7 @@ void help_print( int argc, const char* argv[] )
cout << "--logfile - Use logfile. Default: smemory-plus.log" << endl; cout << "--logfile - Use logfile. Default: smemory-plus.log" << endl;
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
LogServer* run_logserver( const std::string& cname, DebugStream& log ) std::shared_ptr<LogServer> run_logserver( const std::string& cname, std::shared_ptr<LogAgregator>& log )
{ {
auto conf = uniset_conf(); auto conf = uniset_conf();
auto xml = conf->getConfXML(); auto xml = conf->getConfXML();
...@@ -294,7 +269,7 @@ LogServer* run_logserver( const std::string& cname, DebugStream& log ) ...@@ -294,7 +269,7 @@ LogServer* run_logserver( const std::string& cname, DebugStream& log )
UniXML::iterator it(cnode); UniXML::iterator it(cnode);
LogServer* ls = new LogServer( log ); auto ls = make_shared<LogServer>( log );
timeout_t sessTimeout = conf->getArgPInt("--" + cname + "-session-timeout",it.getProp("sessTimeout"),3600000); timeout_t sessTimeout = conf->getArgPInt("--" + cname + "-session-timeout",it.getProp("sessTimeout"),3600000);
timeout_t cmdTimeout = conf->getArgPInt("--" + cname + "-cmd-timeout",it.getProp("cmdTimeout"),2000); timeout_t cmdTimeout = conf->getArgPInt("--" + cname + "-cmd-timeout",it.getProp("cmdTimeout"),2000);
...@@ -308,16 +283,14 @@ LogServer* run_logserver( const std::string& cname, DebugStream& log ) ...@@ -308,16 +283,14 @@ LogServer* run_logserver( const std::string& cname, DebugStream& log )
if( host.empty() ) if( host.empty() )
{ {
cerr << "(init_ulogserver): " << cname << ": unknown host.." << endl; cerr << "(init_ulogserver): " << cname << ": unknown host.." << endl;
delete ls; return nullptr;
return 0;
} }
ost::tpport_t port = conf->getArgPInt("--" + cname + "-port",it.getProp("port"),0); ost::tpport_t port = conf->getArgPInt("--" + cname + "-port",it.getProp("port"),0);
if( port == 0 ) if( port == 0 )
{ {
cerr << "(init_ulogserver): " << cname << ": unknown port.." << endl; cerr << "(init_ulogserver): " << cname << ": unknown port.." << endl;
delete ls; return nullptr;
return 0;
} }
cout << "logserver: " << host << ":" << port << endl; cout << "logserver: " << host << ":" << port << endl;
......
...@@ -22,24 +22,24 @@ ...@@ -22,24 +22,24 @@
#include "DebugStream.h" #include "DebugStream.h"
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
class UObject_SK: class UObject_SK:
public UniSetObject, public UniSetObject,
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();
bool alarm( UniSetTypes::ObjectId sid, bool state ); bool alarm( UniSetTypes::ObjectId sid, bool state );
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() );
void updateValues(); void updateValues();
void setMsg( UniSetTypes::ObjectId code, bool state ); void setMsg( UniSetTypes::ObjectId code, bool state );
std::shared_ptr<DebugStream> mylog; std::shared_ptr<DebugStream> mylog;
void init_dlog( std::shared_ptr<DebugStream> d ); void init_dlog( std::shared_ptr<DebugStream> d );
// "синтаксический сахар"..для логов // "синтаксический сахар"..для логов
#define myinfo if( mylog->debugging(Debug::INFO) ) mylog->any() #define myinfo if( mylog->debugging(Debug::INFO) ) mylog->any()
...@@ -57,91 +57,91 @@ class UObject_SK: ...@@ -57,91 +57,91 @@ class UObject_SK:
#define mylogany mylog->any() #define mylogany mylog->any()
// Используемые идентификаторы // Используемые идентификаторы
// Используемые идентификаторы сообщений // Используемые идентификаторы сообщений
// Текущее значение // Текущее значение
// --- 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 ) override; virtual void sysCommand( const UniSetTypes::SystemMessage* sm ) override;
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 );
void updatePreviousValues(); void updatePreviousValues();
void checkSensors(); void checkSensors();
void updateOutputs( bool force ); void updateOutputs( bool force );
void preAskSensors( UniversalIO::UIOCommand cmd ); void preAskSensors( UniversalIO::UIOCommand cmd );
void preSensorInfo( const UniSetTypes::SensorMessage* sm ); void preSensorInfo( const UniSetTypes::SensorMessage* sm );
void preTimerInfo( const UniSetTypes::TimerMessage* tm ); void preTimerInfo( const UniSetTypes::TimerMessage* tm );
void waitSM( int wait_msec, UniSetTypes::ObjectId testID = UniSetTypes::DefaultObjectId ); void waitSM( int wait_msec, UniSetTypes::ObjectId testID = UniSetTypes::DefaultObjectId );
void resetMsg(); void resetMsg();
Trigger trResetMsg; Trigger trResetMsg;
PassiveTimer ptResetMsg; PassiveTimer ptResetMsg;
int resetMsgTime; int resetMsgTime;
// Выполнение очередного шага программы // Выполнение очередного шага программы
virtual void step(){} virtual void step(){}
int sleep_msec; /*!< пауза между итерациями */ int sleep_msec; /*!< пауза между итерациями */
bool active; bool active;
UniSetTypes::ObjectId smTestID; /*!< идентификатор датчика для тестирования готовности SM */ UniSetTypes::ObjectId smTestID; /*!< идентификатор датчика для тестирования готовности SM */
// управление датчиком "сердцебиения" // управление датчиком "сердцебиения"
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; /*!< флаг принудительного обноления "выходов" */
private: private:
// --- private variables --- // --- private variables ---
// --- end of private variables --- // --- end of private variables ---
// предыдущее значение (для работы UpdateValue()) // предыдущее значение (для работы UpdateValue())
// Используемые идентификаторы сообщений // Используемые идентификаторы сообщений
bool end_private; // вспомогательное поле (для внутреннего использования при генерировании кода) bool end_private; // вспомогательное поле (для внутреннего использования при генерировании кода)
}; };
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
......
...@@ -27,12 +27,20 @@ class LogReader ...@@ -27,12 +27,20 @@ class LogReader
inline void setCommandOnlyMode( bool s ){ cmdonly = s; } inline void setCommandOnlyMode( bool s ){ cmdonly = s; }
inline void setinTimeout( timeout_t msec ){ inTimeout = msec; }
inline void setoutTimeout( timeout_t msec ){ outTimeout = msec; }
inline void setReconnectDelay( timeout_t msec ){ reconDelay = msec; }
protected: protected:
void connect( const std::string& addr, ost::tpport_t port, timeout_t tout=TIMEOUT_INF ); void connect( const std::string& addr, ost::tpport_t port, timeout_t tout=TIMEOUT_INF );
void connect( ost::InetAddress addr, ost::tpport_t port, timeout_t tout=TIMEOUT_INF ); void connect( ost::InetAddress addr, ost::tpport_t port, timeout_t tout=TIMEOUT_INF );
void disconnect(); void disconnect();
timeout_t inTimeout;
timeout_t outTimeout;
timeout_t reconDelay;
private: private:
UTCPStream* tcp; UTCPStream* tcp;
std::string iaddr; std::string iaddr;
......
...@@ -10,6 +10,7 @@ ...@@ -10,6 +10,7 @@
#include "DebugStream.h" #include "DebugStream.h"
#include "ThreadCreator.h" #include "ThreadCreator.h"
class LogSession; class LogSession;
class LogAgregator;
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
/*! \page pgLogServer Лог сервер /*! \page pgLogServer Лог сервер
Лог сервер предназначен для возможности удалённого чтения логов (DebugStream). Лог сервер предназначен для возможности удалённого чтения логов (DebugStream).
...@@ -49,13 +50,14 @@ class LogServer ...@@ -49,13 +50,14 @@ class LogServer
{ {
public: public:
LogServer( std::shared_ptr<DebugStream>& log ); LogServer( std::shared_ptr<DebugStream> log );
LogServer( std::ostream& os ); LogServer( std::shared_ptr<LogAgregator> log );
~LogServer(); ~LogServer();
inline void setSessionTimeout( timeout_t msec ){ sessTimeout = msec; } inline void setSessionTimeout( timeout_t msec ){ sessTimeout = msec; }
inline void setCmdTimeout( timeout_t msec ){ cmdTimeout = msec; } inline void setCmdTimeout( timeout_t msec ){ cmdTimeout = msec; }
inline void setOutTimeout( timeout_t msec ){ outTimeout = msec; } inline void setOutTimeout( timeout_t msec ){ outTimeout = msec; }
inline void setSessionLog( Debug::type t ){ sessLogLevel = t; }
void run( const std::string& addr, ost::tpport_t port, bool thread=true ); void run( const std::string& addr, ost::tpport_t port, bool thread=true );
...@@ -74,6 +76,7 @@ class LogServer ...@@ -74,6 +76,7 @@ class LogServer
timeout_t sessTimeout; timeout_t sessTimeout;
timeout_t cmdTimeout; timeout_t cmdTimeout;
timeout_t outTimeout; timeout_t outTimeout;
Debug::type sessLogLevel;
std::atomic_bool cancelled; std::atomic_bool cancelled;
DebugStream mylog; DebugStream mylog;
......
...@@ -25,6 +25,10 @@ class LogSession: ...@@ -25,6 +25,10 @@ class LogSession:
inline std::string getClientAddress(){ return caddr; } inline std::string getClientAddress(){ return caddr; }
inline void setSessionLogLevel( Debug::type t ){ slog.level(t); }
inline void addSessionLogLevel( Debug::type t ){ slog.addLevel(t); }
inline void delSessionLogLevel( Debug::type t ){ slog.delLevel(t); }
protected: protected:
virtual void run(); virtual void run();
virtual void final(); virtual void final();
......
...@@ -10,6 +10,9 @@ using namespace std; ...@@ -10,6 +10,9 @@ using namespace std;
using namespace UniSetTypes; using namespace UniSetTypes;
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
LogReader::LogReader(): LogReader::LogReader():
inTimeout(10000),
outTimeout(6000),
reconDelay(5000),
tcp(0), tcp(0),
iaddr(""), iaddr(""),
cmdonly(false) cmdonly(false)
...@@ -111,9 +114,6 @@ void LogReader::readlogs( const std::string& _addr, ost::tpport_t _port, LogServ ...@@ -111,9 +114,6 @@ void LogReader::readlogs( const std::string& _addr, ost::tpport_t _port, LogServ
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
void LogReader::readlogs( const std::string& _addr, ost::tpport_t _port, LogServerTypes::lsMessage& msg, bool verbose ) void LogReader::readlogs( const std::string& _addr, ost::tpport_t _port, LogServerTypes::lsMessage& msg, bool verbose )
{ {
timeout_t inTimeout = 10000;
timeout_t outTimeout = 6000;
timeout_t reconDelay = 5000;
char buf[100001]; char buf[100001];
if( verbose ) if( verbose )
...@@ -121,6 +121,12 @@ void LogReader::readlogs( const std::string& _addr, ost::tpport_t _port, LogServ ...@@ -121,6 +121,12 @@ void LogReader::readlogs( const std::string& _addr, ost::tpport_t _port, LogServ
bool send_ok = false; bool send_ok = false;
if( inTimeout == 0 )
inTimeout = TIMEOUT_INF;
if( outTimeout == 0 )
outTimeout = TIMEOUT_INF;
while( true ) while( true )
{ {
if( !isConnection() ) if( !isConnection() )
......
...@@ -3,6 +3,7 @@ ...@@ -3,6 +3,7 @@
#include "UniSetTypes.h" #include "UniSetTypes.h"
#include "Exceptions.h" #include "Exceptions.h"
#include "LogSession.h" #include "LogSession.h"
#include "LogAgregator.h"
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
using namespace std; using namespace std;
using namespace UniSetTypes; using namespace UniSetTypes;
...@@ -30,24 +31,18 @@ LogServer::~LogServer() ...@@ -30,24 +31,18 @@ LogServer::~LogServer()
delete tcp; delete tcp;
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
LogServer::LogServer( std::ostream& os ): LogServer::LogServer( std::shared_ptr<LogAgregator> log ):
timeout(TIMEOUT_INF), LogServer(static_pointer_cast<DebugStream>(log))
sessTimeout(3600000),
cmdTimeout(2000),
outTimeout(2000),
cancelled(false),
thr(0),
tcp(0),
elog(nullptr),
oslog(&os)
{ {
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
LogServer::LogServer( std::shared_ptr<DebugStream>& log ): LogServer::LogServer( std::shared_ptr<DebugStream> log ):
timeout(TIMEOUT_INF), timeout(TIMEOUT_INF),
sessTimeout(3600000), sessTimeout(3600000),
cmdTimeout(2000), cmdTimeout(2000),
outTimeout(2000), outTimeout(2000),
sessLogLevel(Debug::NONE),
cancelled(false), cancelled(false),
thr(0), thr(0),
tcp(0), tcp(0),
...@@ -61,6 +56,7 @@ timeout(TIMEOUT_INF), ...@@ -61,6 +56,7 @@ timeout(TIMEOUT_INF),
sessTimeout(3600000), sessTimeout(3600000),
cmdTimeout(2000), cmdTimeout(2000),
outTimeout(2000), outTimeout(2000),
sessLogLevel(Debug::NONE),
cancelled(false), cancelled(false),
thr(0), thr(0),
tcp(0), tcp(0),
...@@ -111,6 +107,7 @@ void LogServer::work() ...@@ -111,6 +107,7 @@ void LogServer::work()
while( !cancelled && tcp->isPendingConnection(timeout) ) while( !cancelled && tcp->isPendingConnection(timeout) )
{ {
auto s = make_shared<LogSession>(*tcp, elog, sessTimeout, cmdTimeout, outTimeout); auto s = make_shared<LogSession>(*tcp, elog, sessTimeout, cmdTimeout, outTimeout);
s->setSessionLogLevel(sessLogLevel);
{ {
uniset_rwmutex_wrlock l(mutSList); uniset_rwmutex_wrlock l(mutSList);
slist.push_back(s); slist.push_back(s);
......
...@@ -36,7 +36,10 @@ delayTime(_delay), ...@@ -36,7 +36,10 @@ delayTime(_delay),
cancelled(false) cancelled(false)
{ {
//slog.addLevel(Debug::ANY); //slog.addLevel(Debug::ANY);
log->signal_stream_event().connect( sigc::mem_fun(this, &LogSession::logOnEvent) ); if( log )
log->signal_stream_event().connect( sigc::mem_fun(this, &LogSession::logOnEvent) );
else
slog.crit() << "LOG NULL!!" << endl;
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
void LogSession::logOnEvent( const std::string& s ) void LogSession::logOnEvent( const std::string& s )
...@@ -65,6 +68,10 @@ void LogSession::run() ...@@ -65,6 +68,10 @@ void LogSession::run()
if( slog.debugging(Debug::INFO) ) if( slog.debugging(Debug::INFO) )
slog[Debug::INFO] << peername << "(run): run thread of sessions.." << endl; slog[Debug::INFO] << peername << "(run): run thread of sessions.." << endl;
if( !log )
slog.crit() << peername << "(run): LOG NULL!!" << endl;
ptSessionTimeout.setTiming(sessTimeout); ptSessionTimeout.setTiming(sessTimeout);
setKeepAlive(true); setKeepAlive(true);
......
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