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[] )
if( verb )
cout << "(init): listen " << addr << ":" << port << endl;
DebugStream log;
auto log = make_shared<DebugStream>();
LogServer ls(log);
ls.run(addr,port,true);
......@@ -78,7 +78,7 @@ int main( int argc, char* argv[], char* envp[] )
if( r > 0 )
{
buf[r] = '\0';
log << buf;
(*(log.get())) << buf;
}
}
}
......
......@@ -74,8 +74,8 @@ int main( int argc, char* argv[], char* envp[] )
/* Parent. */
close(cp[1]);
DebugStream zlog;
zlog.addLevel(Debug::ANY);
auto zlog = make_shared<DebugStream>();
zlog->addLevel(Debug::ANY);
LogServer ls(zlog);
......@@ -90,7 +90,7 @@ int main( int argc, char* argv[], char* envp[] )
if( r > 0 )
{
buf[r] = '\0';
zlog << buf;
(*(zlog.get())) << buf;
}
}
......
......@@ -23,24 +23,28 @@ static struct option longopts[] = {
{ "rotate", required_argument, 0, 'r' },
{ "logname", required_argument, 0, 'l' },
{ "command-only", no_argument, 0, 'b' },
{ "timeout", required_argument, 0, 'w' },
{ "reconnect-delay", required_argument, 0, 'x' },
{ NULL, 0, 0, 0 }
};
// --------------------------------------------------------------------------
static void print_help()
{
printf("-h, --help - this message\n");
printf("-v, --verbose - Print all messages to stdout\n");
printf("[-i|--iaddr] addr - LogServer ip or hostname.\n");
printf("[-p|--port] port - LogServer port.\n");
printf("[-l|--logname] name - Send command only for 'logname'.\n");
printf("[-b|--command-only] - Send command and break. (No read logs).\n");
printf("-h, --help - this message\n");
printf("-v, --verbose - Print all messages to stdout\n");
printf("[-i|--iaddr] addr - LogServer ip or hostname.\n");
printf("[-p|--port] port - LogServer port.\n");
printf("[-l|--logname] name - Send command only for 'logname'.\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("Commands:\n");
printf("[--add | -a] info,warn,crit,... - Add 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("--on, -n - On the write log file (if before disabled).\n");
printf("--rotate, -r - rotate log file.\n");
......@@ -59,10 +63,12 @@ int main( int argc, char **argv )
string sdata("");
int cmdonly = 0;
string logname("");
timeout_t tout = 0;
timeout_t rdelay = 5000;
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)
{
......@@ -114,6 +120,14 @@ int main( int argc, char **argv )
port = uni_atoi(optarg);
break;
case 'x':
rdelay = uni_atoi(optarg);
break;
case 'w':
tout = uni_atoi(optarg);
break;
case 'v':
verb = 1;
break;
......@@ -134,6 +148,8 @@ int main( int argc, char **argv )
LogReader lr;
lr.setCommandOnlyMode(cmdonly);
lr.setinTimeout(tout);
lr.setReconnectDelay(rdelay);
if( !sdata.empty() )
{
......
......@@ -81,14 +81,29 @@ int main( int argc, char **argv )
// dlog.addLevel( Debug::type(Debug::CRIT | Debug::WARN | Debug::INFO) );
}
LogAgregator la;
auto la = make_shared<LogAgregator>();
auto dlog = make_shared<DebugStream>();
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(cout);
......@@ -96,7 +111,7 @@ int main( int argc, char **argv )
dlog2->addLevel(Debug::ANY);
ls.run( addr, port, true );
#if 0
ls.setSessionLog(Debug::ANY);
unsigned int i=0;
while( true )
......@@ -112,7 +127,6 @@ int main( int argc, char **argv )
msleep(delay);
}
#endif
}
catch( SystemError& err )
{
......
......@@ -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
- refactoring ulog and dlog: Objects converted to shared_ptr<DebugStream>
for subsequent use LogAgregator.
- modify interface for LogReader,LogSession,LogServer
* Fri Jan 23 2015 Pavel Vainerman <pv@altlinux.ru> 2.0-alt12
- refactoring LogAgregator,LogServer,LogSesson --> use shared_ptr
......
......@@ -2,6 +2,7 @@
#include <string>
#include <error.h>
#include <errno.h>
#include <memory>
#include <Debug.h>
#include <UniSetActivator.h>
#include <ThreadCreator.h>
......@@ -26,37 +27,11 @@ using namespace UniSetExtensions;
const unsigned int MaxAddNum = 10;
// --------------------------------------------------------------------------
static void help_print( int argc, const char* argv[] );
static LogServer* run_logserver( const std::string& cnamem, DebugStream& log );
static LogServer* logserver = 0;
static std::shared_ptr<LogServer> run_logserver( const std::string& cnamem, std::shared_ptr<LogAgregator>& log );
#ifdef UNISET_ENABLE_IO
std::list< ThreadCreator<IOControl>* > lst_iothr;
#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 )
{
std::ios::sync_with_stdio(false);
......@@ -77,7 +52,7 @@ int main( int argc, const char **argv )
dlog()->logFile( logname );
auto act = UniSetActivator::Instance();
act->signal_terminate_event().connect( &activator_terminate );
//act->signal_terminate_event().connect( &activator_terminate );
// ------------ SharedMemory ----------------
auto shm = SharedMemory::init_smemory(argc,argv);
if( !shm )
......@@ -212,11 +187,11 @@ int main( int argc, const char **argv )
i->start();
#endif
LogAgregator la;
la.add(ulog());
la.add(dlog());
auto la = make_shared<LogAgregator>();
la->add(ulog());
la->add(dlog());
logserver = run_logserver("smplus",la);
auto logserver = run_logserver("smplus",la);
if( logserver == 0 )
{
cerr << "(smemory-plus): run logserver for 'smplus' FAILED" << endl;
......@@ -280,7 +255,7 @@ void help_print( int argc, const char* argv[] )
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 xml = conf->getConfXML();
......@@ -294,7 +269,7 @@ LogServer* run_logserver( const std::string& cname, DebugStream& log )
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 cmdTimeout = conf->getArgPInt("--" + cname + "-cmd-timeout",it.getProp("cmdTimeout"),2000);
......@@ -308,16 +283,14 @@ LogServer* run_logserver( const std::string& cname, DebugStream& log )
if( host.empty() )
{
cerr << "(init_ulogserver): " << cname << ": unknown host.." << endl;
delete ls;
return 0;
return nullptr;
}
ost::tpport_t port = conf->getArgPInt("--" + cname + "-port",it.getProp("port"),0);
if( port == 0 )
{
cerr << "(init_ulogserver): " << cname << ": unknown port.." << endl;
delete ls;
return 0;
return nullptr;
}
cout << "logserver: " << host << ":" << port << endl;
......
......@@ -22,24 +22,24 @@
#include "DebugStream.h"
// -----------------------------------------------------------------------------
class UObject_SK:
public UniSetObject,
public LT_Object
public UniSetObject,
public LT_Object
{
public:
UObject_SK( UniSetTypes::ObjectId id, xmlNode* node=UniSetTypes::uniset_conf()->getNode("UObject"), const std::string& argprefix="" );
UObject_SK();
virtual ~UObject_SK();
bool alarm( UniSetTypes::ObjectId sid, bool state );
long getValue( UniSetTypes::ObjectId sid );
void setValue( UniSetTypes::ObjectId sid, long value );
void askSensor( UniSetTypes::ObjectId sid, UniversalIO::UIOCommand, UniSetTypes::ObjectId node = UniSetTypes::uniset_conf()->getLocalNode() );
void updateValues();
void setMsg( UniSetTypes::ObjectId code, bool state );
std::shared_ptr<DebugStream> mylog;
void init_dlog( std::shared_ptr<DebugStream> d );
public:
UObject_SK( UniSetTypes::ObjectId id, xmlNode* node=UniSetTypes::uniset_conf()->getNode("UObject"), const std::string& argprefix="" );
UObject_SK();
virtual ~UObject_SK();
bool alarm( UniSetTypes::ObjectId sid, bool state );
long getValue( UniSetTypes::ObjectId sid );
void setValue( UniSetTypes::ObjectId sid, long value );
void askSensor( UniSetTypes::ObjectId sid, UniversalIO::UIOCommand, UniSetTypes::ObjectId node = UniSetTypes::uniset_conf()->getLocalNode() );
void updateValues();
void setMsg( UniSetTypes::ObjectId code, bool state );
std::shared_ptr<DebugStream> mylog;
void init_dlog( std::shared_ptr<DebugStream> d );
// "синтаксический сахар"..для логов
#define myinfo if( mylog->debugging(Debug::INFO) ) mylog->any()
......@@ -57,91 +57,91 @@ class UObject_SK:
#define mylogany mylog->any()
// Используемые идентификаторы
// Используемые идентификаторы сообщений
// Текущее значение
// --- public variables ---
// --- end of public variables ---
protected:
// --- protected variables ---
// ---- end of protected variables ----
virtual void callback() override;
virtual void processingMessage( UniSetTypes::VoidMessage* msg ) override;
virtual void sysCommand( const UniSetTypes::SystemMessage* sm ) override;
virtual void askSensors( UniversalIO::UIOCommand cmd ){}
virtual void sensorInfo( const UniSetTypes::SensorMessage* sm ) override{}
virtual void timerInfo( const UniSetTypes::TimerMessage* tm ) override{}
virtual void sigterm( int signo ) override;
virtual bool activateObject() override;
virtual void testMode( bool state );
void updatePreviousValues();
void checkSensors();
void updateOutputs( bool force );
void preAskSensors( UniversalIO::UIOCommand cmd );
void preSensorInfo( const UniSetTypes::SensorMessage* sm );
void preTimerInfo( const UniSetTypes::TimerMessage* tm );
void waitSM( int wait_msec, UniSetTypes::ObjectId testID = UniSetTypes::DefaultObjectId );
void resetMsg();
Trigger trResetMsg;
PassiveTimer ptResetMsg;
int resetMsgTime;
// Выполнение очередного шага программы
virtual void step(){}
int sleep_msec; /*!< пауза между итерациями */
bool active;
UniSetTypes::ObjectId smTestID; /*!< идентификатор датчика для тестирования готовности SM */
// управление датчиком "сердцебиения"
PassiveTimer ptHeartBeat; /*! < период "сердцебиения" */
UniSetTypes::ObjectId idHeartBeat; /*! < идентификатор датчика (AI) "сердцебиения" */
int maxHeartBeat; /*! < сохраняемое значение */
xmlNode* confnode;
/*! получить числовое свойство из конф. файла по привязанной confnode */
int getIntProp(const std::string& name) { return UniSetTypes::uniset_conf()->getIntProp(confnode, name); }
/*! получить текстовое свойство из конф. файла по привязанной confnode */
inline const std::string getProp(const std::string& name) { return UniSetTypes::uniset_conf()->getProp(confnode, name); }
int smReadyTimeout; /*!< время ожидания готовности SM */
std::atomic_bool activated;
int activateTimeout; /*!< время ожидания готовности UniSetObject к работе */
PassiveTimer ptStartUpTimeout; /*!< время на блокировку обработки WatchDog, если недавно был StartUp */
int askPause; /*!< пауза между неудачными попытками заказать датчики */
IOController_i::SensorInfo si;
bool forceOut; /*!< флаг принудительного обноления "выходов" */
private:
// --- private variables ---
// --- end of private variables ---
// предыдущее значение (для работы UpdateValue())
// Используемые идентификаторы сообщений
bool end_private; // вспомогательное поле (для внутреннего использования при генерировании кода)
// Используемые идентификаторы
// Используемые идентификаторы сообщений
// Текущее значение
// --- public variables ---
// --- end of public variables ---
protected:
// --- protected variables ---
// ---- end of protected variables ----
virtual void callback() override;
virtual void processingMessage( UniSetTypes::VoidMessage* msg ) override;
virtual void sysCommand( const UniSetTypes::SystemMessage* sm ) override;
virtual void askSensors( UniversalIO::UIOCommand cmd ){}
virtual void sensorInfo( const UniSetTypes::SensorMessage* sm ) override{}
virtual void timerInfo( const UniSetTypes::TimerMessage* tm ) override{}
virtual void sigterm( int signo ) override;
virtual bool activateObject() override;
virtual void testMode( bool state );
void updatePreviousValues();
void checkSensors();
void updateOutputs( bool force );
void preAskSensors( UniversalIO::UIOCommand cmd );
void preSensorInfo( const UniSetTypes::SensorMessage* sm );
void preTimerInfo( const UniSetTypes::TimerMessage* tm );
void waitSM( int wait_msec, UniSetTypes::ObjectId testID = UniSetTypes::DefaultObjectId );
void resetMsg();
Trigger trResetMsg;
PassiveTimer ptResetMsg;
int resetMsgTime;
// Выполнение очередного шага программы
virtual void step(){}
int sleep_msec; /*!< пауза между итерациями */
bool active;
UniSetTypes::ObjectId smTestID; /*!< идентификатор датчика для тестирования готовности SM */
// управление датчиком "сердцебиения"
PassiveTimer ptHeartBeat; /*! < период "сердцебиения" */
UniSetTypes::ObjectId idHeartBeat; /*! < идентификатор датчика (AI) "сердцебиения" */
int maxHeartBeat; /*! < сохраняемое значение */
xmlNode* confnode;
/*! получить числовое свойство из конф. файла по привязанной confnode */
int getIntProp(const std::string& name) { return UniSetTypes::uniset_conf()->getIntProp(confnode, name); }
/*! получить текстовое свойство из конф. файла по привязанной confnode */
inline const std::string getProp(const std::string& name) { return UniSetTypes::uniset_conf()->getProp(confnode, name); }
int smReadyTimeout; /*!< время ожидания готовности SM */
std::atomic_bool activated;
int activateTimeout; /*!< время ожидания готовности UniSetObject к работе */
PassiveTimer ptStartUpTimeout; /*!< время на блокировку обработки WatchDog, если недавно был StartUp */
int askPause; /*!< пауза между неудачными попытками заказать датчики */
IOController_i::SensorInfo si;
bool forceOut; /*!< флаг принудительного обноления "выходов" */
private:
// --- private variables ---
// --- end of private variables ---
// предыдущее значение (для работы UpdateValue())
// Используемые идентификаторы сообщений
bool end_private; // вспомогательное поле (для внутреннего использования при генерировании кода)
};
// -----------------------------------------------------------------------------
......
......@@ -27,12 +27,20 @@ class LogReader
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:
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 disconnect();
timeout_t inTimeout;
timeout_t outTimeout;
timeout_t reconDelay;
private:
UTCPStream* tcp;
std::string iaddr;
......
......@@ -10,6 +10,7 @@
#include "DebugStream.h"
#include "ThreadCreator.h"
class LogSession;
class LogAgregator;
// -------------------------------------------------------------------------
/*! \page pgLogServer Лог сервер
Лог сервер предназначен для возможности удалённого чтения логов (DebugStream).
......@@ -49,13 +50,14 @@ class LogServer
{
public:
LogServer( std::shared_ptr<DebugStream>& log );
LogServer( std::ostream& os );
LogServer( std::shared_ptr<DebugStream> log );
LogServer( std::shared_ptr<LogAgregator> log );
~LogServer();
inline void setSessionTimeout( timeout_t msec ){ sessTimeout = msec; }
inline void setCmdTimeout( timeout_t msec ){ cmdTimeout = 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 );
......@@ -74,6 +76,7 @@ class LogServer
timeout_t sessTimeout;
timeout_t cmdTimeout;
timeout_t outTimeout;
Debug::type sessLogLevel;
std::atomic_bool cancelled;
DebugStream mylog;
......
......@@ -25,6 +25,10 @@ class LogSession:
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:
virtual void run();
virtual void final();
......
......@@ -10,6 +10,9 @@ using namespace std;
using namespace UniSetTypes;
// -------------------------------------------------------------------------
LogReader::LogReader():
inTimeout(10000),
outTimeout(6000),
reconDelay(5000),
tcp(0),
iaddr(""),
cmdonly(false)
......@@ -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 )
{
timeout_t inTimeout = 10000;
timeout_t outTimeout = 6000;
timeout_t reconDelay = 5000;
char buf[100001];
if( verbose )
......@@ -121,6 +121,12 @@ void LogReader::readlogs( const std::string& _addr, ost::tpport_t _port, LogServ
bool send_ok = false;
if( inTimeout == 0 )
inTimeout = TIMEOUT_INF;
if( outTimeout == 0 )
outTimeout = TIMEOUT_INF;
while( true )
{
if( !isConnection() )
......
......@@ -3,6 +3,7 @@
#include "UniSetTypes.h"
#include "Exceptions.h"
#include "LogSession.h"
#include "LogAgregator.h"
// -------------------------------------------------------------------------
using namespace std;
using namespace UniSetTypes;
......@@ -30,24 +31,18 @@ LogServer::~LogServer()
delete tcp;
}
// -------------------------------------------------------------------------
LogServer::LogServer( std::ostream& os ):
timeout(TIMEOUT_INF),
sessTimeout(3600000),
cmdTimeout(2000),
outTimeout(2000),
cancelled(false),
thr(0),
tcp(0),
elog(nullptr),
oslog(&os)
LogServer::LogServer( std::shared_ptr<LogAgregator> log ):
LogServer(static_pointer_cast<DebugStream>(log))
{
}
// -------------------------------------------------------------------------
LogServer::LogServer( std::shared_ptr<DebugStream>& log ):
LogServer::LogServer( std::shared_ptr<DebugStream> log ):
timeout(TIMEOUT_INF),
sessTimeout(3600000),
cmdTimeout(2000),
outTimeout(2000),
sessLogLevel(Debug::NONE),
cancelled(false),
thr(0),
tcp(0),
......@@ -61,6 +56,7 @@ timeout(TIMEOUT_INF),
sessTimeout(3600000),
cmdTimeout(2000),
outTimeout(2000),
sessLogLevel(Debug::NONE),
cancelled(false),
thr(0),
tcp(0),
......@@ -111,6 +107,7 @@ void LogServer::work()
while( !cancelled && tcp->isPendingConnection(timeout) )
{
auto s = make_shared<LogSession>(*tcp, elog, sessTimeout, cmdTimeout, outTimeout);
s->setSessionLogLevel(sessLogLevel);
{
uniset_rwmutex_wrlock l(mutSList);
slist.push_back(s);
......
......@@ -36,7 +36,10 @@ delayTime(_delay),
cancelled(false)
{
//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 )
......@@ -65,6 +68,10 @@ void LogSession::run()
if( slog.debugging(Debug::INFO) )
slog[Debug::INFO] << peername << "(run): run thread of sessions.." << endl;
if( !log )
slog.crit() << peername << "(run): LOG NULL!!" << endl;
ptSessionTimeout.setTiming(sessTimeout);
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