 la_serva: fix memory/descriptor leaks, crashes and a DB-log deadlock
Leaks that grew without bound:
- Dead module connections were never removed (half-open TCP after a
module power loss / network drop): every one kept 3 threads, 8 MB of
socket buffers, a descriptor and a 10 ms DB poll. servaRPCHadnler now
drops a connection that sends nothing for RPC_IDLE_TIMEOUT_S (60 s;
la_mojo sends a status about every second), and accepted sockets get
TCP keepalive (30 s idle, 3 probes of 10 s).
- The client socket was only closed on an I/O error: a handler removed
for any other reason (module disabled / not registered, idle) leaked
its descriptor until accept() failed with EMFILE - which ended the
accept thread for good. ~serverPort now shuts down and closes it;
transient accept() errors (EMFILE, ENFILE, ENOMEM, ECONNABORTED,
EINTR, ...) no longer stop the server. recv() == 0 (peer closed) is
always a disconnect, whatever errno holds.
- servaSessionManager::reopenSession stored the reopened (expired)
session in the per-track map, overwriting the track's ACTIVE session:
its data and open report.db leaked and it was never closed in MySQL.
Reopened sessions are now kept outside the map and released by the
caller (addVideo, getSessionBase).
- servaVideoComposer leaked its session data, an open SQLite connection
and both video queues on every composition; servaKernel leaked a
composer whose compose() failed, never initialised / released the
automatic composer (it ran at most once) and leaked the media info
of every encoded video (processVideoFile success path).
Crashes / corruption:
- vector erase() with the old iterator reused (netServer client
cleanup, encoder / composer pools, 4 ModBus action loops).
- transportSocket::_close wrote the stop byte into the read end of the
pipe (threads only stopped at the 5 s select timeout, blocking the
accept thread on every disconnect) and left closed pipe numbers set
(a second _close could write into another connection's socket).
- Session map used without the lock from RPC, kernel and ModBus
threads: now a recursive mutex held for each public operation.
- Freeze on the first MySQL error with DB logging enabled: Query() logs
while holding the non-recursive DB mutex and the log service wrote
synchronously into the DB (same-thread and two-thread deadlock).
The DB log service now queues lines (max 1000) and writes them with
MySQL_Connector::TrySilentQuery (never blocks, never logs); reconnect
retries per query are bounded (3) instead of looping forever while
holding the mutex. The log line parser also skips the UTC offset.
- basicMutex::try_lock returned true when the lock was NOT taken: an
uncontended try_lock took the mutex and the caller never released it
(basicEngine, serial transport, ...).
- Kernel restart (web commands): the ModBus singleton was deleted but
not reset (next getInstance returned freed memory), the remote client
kept the deleted kernel and refused to start again, and
EXIT_CODE_RELOAD_SERVICES deleted the DB object every surviving
component still used. Now fixed / the DB object is kept.
- Life monitoring overflowed module_id[4] for platforms with > 4
modules; registerServA overflowed a 120-byte stack buffer, closed a
popen() stream with fclose and leaked the config; 9 config strings in
servaBackend were allocated one byte short; video chunk length is now
checked against the packet; "eased" events copied every field from
itself (all 0); networkServer freed libconfig's host string.
Minor: ModBus action list / sessions freed at shutdown, session-start
event payload freed if the event cannot be created, the per-second
"No History Auto Delete!" log line moved to DEBUG_EXTRA.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0139veDo3XyavMuVhdnHcN16
17 hours ago |
|
#include "servaLifeMonitoring.h"
#include "../../components/base/basicEvent.h"
#include "../../components/base/basicEventHeap.h"
#define LOG( X ) m_pLog->Log( "HELZ", this, X )
#ifdef DEBUG
#define LOG_ERROR( X ) {\
char _tBfrErrMSG2w34[256];\ sprintf( _tBfrErrMSG2w34, "In file %s[%d] in func:%s %s",__FILE__, __LINE__, __func__, X );\ m_pLog->Log( "HELZ", this, _LOG_ERROR, _tBfrErrMSG2w34 );\ }#else
#define LOG_ERROR( X ) m_pLog->Log( "HELZ", this, _LOG_ERROR, X );
#endif
servaLifeMonitoring *servaLifeMonitoring::_Instance = 0;
servaLifeMonitoring *servaLifeMonitoring::getInstance(){ if( _Instance == 0 ){ _Instance = new servaLifeMonitoring(); }; return _Instance;};
servaLifeMonitoring::servaLifeMonitoring():basicValidatable(),basicThread(){ m_pLog = basicLogCollection::getInstance(); m_pDBC = servaMySQLDBC::getInstance(); DBC_UINT64_LIST *tList = m_pDBC->listPlatforms('E'); if ( tList ) { if ( tList->size() ) { for ( DBC_UINT64_LIST::iterator idx = tList->begin(); idx != tList->end(); idx++ ) { DBC_UINT64_LIST *tML = m_pDBC->listPlatformModules( *idx ); if ( tML ) { if ( tML->size() ) { HEALTH_MONITORING_ZONE *tHZ = (HEALTH_MONITORING_ZONE*) malloc( sizeof( HEALTH_MONITORING_ZONE)); if (tHZ) { memset( tHZ, 0, sizeof(HEALTH_MONITORING_ZONE)); tHZ->platform_id = *idx; uint8_t cid = 0; tHZ->lvl = 255; // To clean prev State
tHZ->validated = false; // module_id[] has 4 entries: a platform with more modules overflowed the zone
for ( DBC_UINT64_LIST::iterator jdx = tML->begin(); jdx != tML->end() && cid < 4; jdx++ ) { tHZ->module_id[cid] = *jdx; tHZ->module_monitored[cid] = true; cid++; }; m_mMonitoringZonesProtector.lock(); m_vMonitoringZones.push_back( tHZ ); m_mMonitoringZonesProtector.unlock(); }; }; delete(tML); }; }; }; delete( tList ); }; m_nStartupTS = time(NULL); init();};
servaLifeMonitoring::~servaLifeMonitoring(){ waitThreadEnd( true ); m_mMonitoringZonesProtector.lock(); if ( m_vMonitoringZones.size() ) { for ( V_HEALTH_MONITORING_ZONES::iterator idx = m_vMonitoringZones.begin(); idx != m_vMonitoringZones.end(); idx++ ) { free( *idx ); }; m_vMonitoringZones.clear(); }; m_mMonitoringZonesProtector.unlock();};
bool servaLifeMonitoring::validateZone( HEALTH_MONITORING_ZONE *ptr ){ bool retVal = true; if ( ptr ) { uint8_t min_lvl = 0; uint64_t min_id = ptr->module_id[0]; for ( uint8_t i = 0; i < 4; i++ ) { if (ptr->module_monitored[i]) { if( ptr->module_status[i] > min_lvl ) { min_lvl = ptr->module_status[i]; min_id = ptr->module_id[i]; }; }; }; if( min_lvl != ptr->lvl ) { retVal = false; ptr->lvl = min_lvl; ptr->lvl_id = min_id; }; ptr->validated = false; }; return retVal;};
uint8_t servaLifeMonitoring::validateModule( uint64_t module_id ){ uint8_t retVal = 0; if ( module_id ) { uint32_t cts = time( NULL ); uint32_t mts = m_pDBC->getCloudLTS(ARGUS_OBJECT_MODULE, module_id ); uint8_t ms = m_pDBC->getCloudStatus( ARGUS_OBJECT_MODULE, module_id ); if ( mts ) { if ((cts - mts) > 30) { retVal = ARGUS_LIFE_STATUS_LVL_4; } else { //Online - Check Status
if( ms < ARGUS_CLOUD_STATUS_E_GENERIC ) { retVal = ARGUS_LIFE_STATUS_CLEAN; } else { switch ( ms ) { case ARGUS_CLOUD_STATUS_E_GENERIC: break; case ARGUS_CLOUD_STATUS_E_CAM_GENERIC: case ARGUS_CLOUD_STATUS_E_CAM_NC: case ARGUS_CLOUD_STATUS_E_CAM_NPTZ: case ARGUS_CLOUD_STATUS_E_CAM_NIM: retVal = ARGUS_LIFE_STATUS_LVL_1; break; case ARGUS_CLOUD_STATUS_E_SEN_GENERIC: case ARGUS_CLOUD_STATUS_E_US_LRF: case ARGUS_CLOUD_STATUS_E_BS_LRF: retVal = ARGUS_LIFE_STATUS_LVL_2; break; case ARGUS_CLOUD_STATUS_E_US_NC: case ARGUS_CLOUD_STATUS_E_BS_NC: retVal = ARGUS_LIFE_STATUS_LVL_3; break; default: retVal = ARGUS_LIFE_STATUS_LVL_3; }; }; }; } else { retVal = ARGUS_LIFE_STATUS_LVL_4; }; if ( retVal == ARGUS_LIFE_STATUS_LVL_4 ) { DBC_IS_MODULE_DATA *tData = m_pDBC->getModuleData( module_id ); if ( tData ) { if( !pingIP4( tData->ip4 ) ) {#ifdef DEBUG_EXTRA
LOG_ERROR("No Network Access to Platform!");#endif
retVal = ARGUS_LIFE_STATUS_LVL_5; }; free( tData ); }; }; }; return retVal;};
bool servaLifeMonitoring::validate(){ uint32_t cts = time(NULL); if ( ( cts - m_nStartupTS ) < LM_SKEEP_MONITORING_SECONDS ) return true; m_mMonitoringZonesProtector.lock(); for ( V_HEALTH_MONITORING_ZONES::iterator idx = m_vMonitoringZones.begin(); idx != m_vMonitoringZones.end(); idx++ ) { if (!validateZone(*idx)) {#ifdef DEBUG
LOG("Zone Health is Changed");#endif
MODULE_HEALTH_STATUS *tData = (MODULE_HEALTH_STATUS*) malloc(sizeof(MODULE_HEALTH_STATUS)); if ( tData ) { tData->status = (*idx)->lvl; tData->module_id = (*idx)->lvl_id; tData->platform_id = (*idx)->platform_id;#ifdef DEBUG
char tT[128]; sprintf( tT, "gen Event HEALTH %d", tData->status ); LOG( tT );#endif
EVENT_CONTAINER *tEvt = createBasicEvent(0, EVT_CLASS_SYSTEM, EVT_SRV_MODULE_HEALTH, NULL, NULL, tData ); if ( tEvt ) { basicEventHeap::getInstance()->broadcast( tEvt ); } else free( tData ); } else LOG_ERROR("No Data Fetched from DB");#ifdef DEBUG_EXTRA
} else { char tT[128]; sprintf( tT, "Zone Health is same %d",(*idx)->lvl ); LOG( tT );#endif
}; }; m_mMonitoringZonesProtector.unlock(); return true;};
void servaLifeMonitoring::m_fThreadProc( void ){ m_bThreadStatus = TH_WORKING; uint32_t ots = time(NULL); pthread_setname_np( pthread_self(), "LifeMonitoring" ); while( m_bThreadStatus < TH_ENDED ) { uint32_t cts = time(NULL); if ( ( cts - m_nStartupTS ) > LM_SKEEP_MONITORING_SECONDS ){ if ( ots != cts ) { ots = cts; // Taking to validate one record then return it to a queue
HEALTH_MONITORING_ZONE * tCWZ = NULL; m_mMonitoringZonesProtector.lock(); if ( m_vMonitoringZones.size() ) { tCWZ = m_vMonitoringZones.at(0); m_vMonitoringZones.erase(m_vMonitoringZones.begin()); }; m_mMonitoringZonesProtector.unlock(); if ( tCWZ ) { if ( !tCWZ->validated ) { for (uint8_t i = 0; i < 4; i++) { if (tCWZ->module_monitored[i]) tCWZ->module_status[i] = validateModule( tCWZ->module_id[i] ); }; }; m_mMonitoringZonesProtector.lock(); m_vMonitoringZones.push_back( tCWZ ); m_mMonitoringZonesProtector.unlock(); }; }; }; SLEEP( DEFAULT_THREAD_SLEEP_TIME ); };};
#undef LOG
#undef LOG_ERROR
|