diff --git a/lib/App/common/SQLite_dataBinder.cpp b/lib/App/common/SQLite_dataBinder.cpp index 651fbfb2..41a2b04f 100644 --- a/lib/App/common/SQLite_dataBinder.cpp +++ b/lib/App/common/SQLite_dataBinder.cpp @@ -97,6 +97,13 @@ sqliteDBC::sqliteDBC(config_setting_t * Settings) : m_pDataReports = NULL; m_pDataStatistics = NULL; m_nServerID = 1; + memset(&m_sCRepInfo, 0, sizeof(REPORT_DIRINFO)); + memset(&m_sPRepInfo, 0, sizeof(REPORT_DIRINFO)); + pthread_mutexattr_t tAttr; + pthread_mutexattr_init(&tAttr); + pthread_mutexattr_settype(&tAttr, PTHREAD_MUTEX_RECURSIVE); + pthread_mutex_init(&m_mReportLock, &tAttr); + pthread_mutexattr_destroy(&tAttr); } sqliteDBC::~sqliteDBC() @@ -122,6 +129,7 @@ sqliteDBC::~sqliteDBC() m_bRepIsConnected = false; m_bStaIsConnected = false; _instance = NULL; + pthread_mutex_destroy(&m_mReportLock); } bool sqliteDBC::connect(void) @@ -562,6 +570,7 @@ void sqliteDBC::initMemDB(uint32_t sid) CSTR sqliteDBC::getCurrentReportDir(void) { + ReportGuard tReportGuard(m_mReportLock); // see switchReportToCurrentDay() CSTR tV = NULL; if (m_sCRepInfo.ts) { @@ -851,9 +860,94 @@ bool sqliteDBC::addDeviceDraw(uint32_t DBID, uint8_t type, uint8_t lrf, void * t return false; } +/* + * Opens (creates if needed) the report of the given day: data/reports/YYYY/MM/DD/report.db + * SQLite_Connector::Connect() closes the currently open report under its own lock first. + * Caller must hold m_mReportLock. + */ +bool sqliteDBC::openDayReport(REPORT_DIRINFO & RDF) +{ + char tPath[CLOG]; + char tQBuf[1024]; + if (! checkRDFDir(m_pDbReportBase, RDF, true, getUserUid(web_access_user), getUserGid(web_access_group))) + { + LOG_ERROR("Cannot create report directory!"); + return false; + }; + snprintf(tPath, sizeof(tPath), "%s/%s/%s/%s/report.db", m_pDbReportBase, RDF.YEAR, RDF.MONTH, RDF.DAY); + LOG("Connect Report!"); + LOG(tPath); + if (m_bRepIsConnected) + { + LOG("Disconnect Report!"); + }; + m_bRepIsConnected = false; + if (! m_pDataReports->Connect(tPath, 0, true)) + { + LOG_ERROR("Cannot open day report!"); + return false; + }; + strncpy(m_pDbReport, tPath, CLOG - 1); + m_pDbReport[CLOG - 1] = (char) 0; + chown(m_pDbReport, getUserUid(web_access_user), getUserGid(web_access_group)); + chmod(m_pDbReport, DB_FILE_MODE); + m_pDataReports->SilentQuery( + "CREATE TABLE IF NOT EXISTS \"events\" ( \"id\" INTEGER NOT NULL, \"node_id\" INTEGER NOT NULL, \"uuid\" TEXT NOT NULL UNIQUE, \"ts\" INTEGER NOT NULL, \"ts_ms\" INTEGER NOT NULL, \"evt_type\" INTEGER NOT " + "NULL, \"lrf_id\" INTEGER, \"range_digital\" INTEGER, \"azimuth\" REAL, \"elevation\" REAL, \"range\" REAL, \"area\" REAL, \"lat\" REAL, \"lon\" REAL, \"alt\" REAL, \"ref_id\" INTEGER, \"ref_uuid\" " + "TEXT, PRIMARY KEY(\"id\" AUTOINCREMENT) )"); + m_pDataReports->SilentQuery("CREATE TABLE IF NOT EXISTS \"events_2_pictures\" ( \"evt_id\" INTEGER NOT NULL, \"picture_id\" INTEGER NOT NULL )"); + m_pDataReports->SilentQuery("CREATE TABLE IF NOT EXISTS \"events_2_videos\" ( \"evt_id\" INTEGER NOT NULL, \"video_id\" INTEGER NOT NULL, \"frame\" INTEGER DEFAULT 0, \"tss\" INTEGER, \"tms\" INTEGER )"); + m_pDataReports->SilentQuery( + "CREATE TABLE IF NOT EXISTS \"pictures\" ( \"id\" INTEGER NOT NULL, \"media_stream_id\" INTEGER NOT NULL, \"md5\" TEXT NOT NULL UNIQUE, \"uts\" INTEGER NOT NULL, \"uts_ms\" INTEGER NOT NULL, \"ext\" TEXT " + "NOT NULL, \"data\" BLOB COLLATE BINARY, PRIMARY KEY(\"id\" AUTOINCREMENT) )"); + m_pDataReports->SilentQuery( + "CREATE TABLE IF NOT EXISTS \"videos\" ( \"id\" INTEGER NOT NULL, \"media_stream_id\" INTEGER NOT NULL, \"md5\" TEXT NOT NULL UNIQUE, \"uts\" INTEGER NOT NULL, \"uts_ms\" INTEGER NOT NULL, \"ext\" TEXT NOT " + "NULL, \"fps\" INTEGER NOT NULL, \"flength\" INTEGER, PRIMARY KEY(\"id\" AUTOINCREMENT) )"); + memcpy(&m_sPRepInfo, &m_sCRepInfo, sizeof(REPORT_DIRINFO)); + memcpy(&m_sCRepInfo, &RDF, sizeof(REPORT_DIRINFO)); + m_bRepIsConnected = true; + LOG("Report Connected!"); + // Create the day record (no session yet) - session counters are updated on SESSION_START / SESSION_END + if (m_bStaIsConnected) + { + snprintf(tQBuf, sizeof(tQBuf), "INSERT INTO `days`(`year`,`month`,`day`,`session_count`,`session_closed`) VALUES(%s,%s,%s,0,1) ON CONFLICT(`year`,`month`,`day`) DO NOTHING", + m_sCRepInfo.YEAR, m_sCRepInfo.MONTH, m_sCRepInfo.DAY); + LOG(tQBuf); + m_pDataStatistics->SilentQuery(tQBuf); + }; + return true; +} + +/* + * Called by the kernel at local midnight (and on every SESSION_START): if the local day changed + * since the current report was opened, close it and open the new day's report directory. + */ +bool sqliteDBC::switchReportToCurrentDay(void) +{ + ReportGuard tGuard(m_mReportLock); + if (m_pDataReports == NULL) + { + return false; + }; + REPORT_DIRINFO tRR; // initialized by fillRDF + fillRDF(time(NULL), tRR); + if (m_bRepIsConnected && (tRR.ts <= m_sCRepInfo.ts)) + { + return true; // already today's report + }; + char tB[128]; + snprintf(tB, sizeof(tB), "Day report switch %s-%s-%s -> %s-%s-%s", m_sCRepInfo.YEAR, m_sCRepInfo.MONTH, m_sCRepInfo.DAY, tRR.YEAR, tRR.MONTH, tRR.DAY); + LOG(tB); + return openDayReport(tRR); +} + void sqliteDBC::updateStats(bool evt, bool video, uint8_t ses_status) { - if (m_bStaIsConnected && ( evt || video )) + ReportGuard tReportGuard(m_mReportLock); // see switchReportToCurrentDay() + // Session status changes are called as updateStats(false, false, SESSION_xxx): they must not be + // filtered out by the evt/video condition (they were, so the session counters and the new-day + // report switch on SESSION_START never ran). + if (m_bStaIsConnected && ( evt || video || ( ses_status != SESSION_CONTINUE ) )) { char tQBuf[1024]; switch (ses_status) @@ -876,47 +970,8 @@ void sqliteDBC::updateStats(bool evt, bool video, uint8_t ses_status) }; case SESSION_START: { - // Check New Day Reports - REPORT_DIRINFO tRR;// = {0}; initialized by fillRDF - fillRDF(time(NULL), tRR); - if( tRR.ts > m_sCRepInfo.ts ){ - // New Day Report - if (m_bRepIsConnected){ - m_bRepIsConnected = false; - LOG("Disconnect Report!"); - m_pDataReports->Disconnect(); - }; - memcpy( &m_sPRepInfo, &m_sCRepInfo, sizeof(REPORT_DIRINFO)); - memcpy( &m_sCRepInfo, &tRR, sizeof(REPORT_DIRINFO)); - if( checkRDFDir( m_pDbReportBase, m_sCRepInfo, true, getUserUid(web_access_user), getUserGid(web_access_group)) ){ - sprintf( m_pDbReport, "%s/%s/%s/%s/report.db", m_pDbReportBase, m_sCRepInfo.YEAR, m_sCRepInfo.MONTH, m_sCRepInfo.DAY ); - LOG("Connect Report!"); - LOG( m_pDbReport ); - if( m_pDataReports->Connect( m_pDbReport, 0, true ) ){ - chown(m_pDbReport, getUserUid(web_access_user), getUserGid(web_access_group)); - chmod(m_pDbReport, DB_FILE_MODE); - m_pDataReports->SilentQuery( - "CREATE TABLE IF NOT EXISTS \"events\" ( \"id\" INTEGER NOT NULL, \"node_id\" INTEGER NOT NULL, \"uuid\" TEXT NOT NULL UNIQUE, \"ts\" INTEGER NOT NULL, \"ts_ms\" INTEGER NOT NULL, \"evt_type\" INTEGER NOT " - "NULL, \"lrf_id\" INTEGER, \"range_digital\" INTEGER, \"azimuth\" REAL, \"elevation\" REAL, \"range\" REAL, \"area\" REAL, \"lat\" REAL, \"lon\" REAL, \"alt\" REAL, \"ref_id\" INTEGER, \"ref_uuid\" " - "TEXT, PRIMARY KEY(\"id\" AUTOINCREMENT) )"); - m_pDataReports->SilentQuery("CREATE TABLE IF NOT EXISTS \"events_2_pictures\" ( \"evt_id\" INTEGER NOT NULL, \"picture_id\" INTEGER NOT NULL )"); - m_pDataReports->SilentQuery("CREATE TABLE IF NOT EXISTS \"events_2_videos\" ( \"evt_id\" INTEGER NOT NULL, \"video_id\" INTEGER NOT NULL, \"frame\" INTEGER DEFAULT 0, \"tss\" INTEGER, \"tms\" INTEGER )"); - m_pDataReports->SilentQuery( - "CREATE TABLE IF NOT EXISTS \"pictures\" ( \"id\" INTEGER NOT NULL, \"media_stream_id\" INTEGER NOT NULL, \"md5\" TEXT NOT NULL UNIQUE, \"uts\" INTEGER NOT NULL, \"uts_ms\" INTEGER NOT NULL, \"ext\" TEXT " - "NOT NULL, \"data\" BLOB COLLATE BINARY, PRIMARY KEY(\"id\" AUTOINCREMENT) )"); - m_pDataReports->SilentQuery( - "CREATE TABLE IF NOT EXISTS \"videos\" ( \"id\" INTEGER NOT NULL, \"media_stream_id\" INTEGER NOT NULL, \"md5\" TEXT NOT NULL UNIQUE, \"uts\" INTEGER NOT NULL, \"uts_ms\" INTEGER NOT NULL, \"ext\" TEXT NOT " - "NULL, \"fps\" INTEGER NOT NULL, \"flength\" INTEGER, PRIMARY KEY(\"id\" AUTOINCREMENT) )"); - m_bRepIsConnected = true; - LOG("Report Connected!"); - // Create New Day Record - sprintf(tQBuf, "INSERT INTO `days`(`year`,`month`,`day`,`session_count`,`session_closed`) VALUES(%s,%s,%s,0,0) ON CONFLICT(`year`,`month`,`day`) DO UPDATE SET `session_count`=`session_count`+1, `session_closed`=0", - m_sCRepInfo.YEAR, m_sCRepInfo.MONTH, m_sCRepInfo.DAY); - LOG(tQBuf); - m_pDataStatistics->SilentQuery(tQBuf); - }; - }; - }; + // Close the previous day report and open today's one (if the local day changed) + switchReportToCurrentDay(); // Create New STAT record sprintf(tQBuf, "INSERT INTO `days`(`year`,`month`,`day`,`session_count`,`session_closed`) VALUES(%s,%s,%s,1,0) ON CONFLICT(`year`,`month`,`day`) DO UPDATE SET `session_count`=`session_count`+1, `session_closed`=0", m_sCRepInfo.YEAR, @@ -953,6 +1008,7 @@ void sqliteDBC::updateStats(bool evt, bool video, uint8_t ses_status) bool sqliteDBC::dropSession() { + ReportGuard tReportGuard(m_mReportLock); // see switchReportToCurrentDay() if (m_bRepIsConnected) { char tQBuf[1024]; @@ -1011,6 +1067,7 @@ bool sqliteDBC::dropSession() uint32_t sqliteDBC::addEvent(DBC_EVT_RECORD * ptr) { + ReportGuard tReportGuard(m_mReportLock); // see switchReportToCurrentDay() if (ptr == NULL) { return 0; @@ -1554,6 +1611,7 @@ bool sqliteDBC::addLRFWidthTable(uint32_t sensorID, PWIDTH_TABLE ptr) bool sqliteDBC::addPicture(DBC_SNAPSHOT_DATA * ptr, CSTR ext) { + ReportGuard tReportGuard(m_mReportLock); // see switchReportToCurrentDay() bool rVal = false; if (ptr != NULL) { @@ -1621,6 +1679,7 @@ uint32_t sqliteDBC::addResource(uint8_t type, CSTR devName, uint32_t auxID) bool sqliteDBC::addVideoEvent(uint32_t evtID, uint32_t videoID, uint32_t frame, uint32_t tss, uint32_t tms) { + ReportGuard tReportGuard(m_mReportLock); // see switchReportToCurrentDay() if (m_bRepIsConnected) { char tQBuf[2048]; @@ -1635,6 +1694,7 @@ bool sqliteDBC::addVideoEvent(uint32_t evtID, uint32_t videoID, uint32_t frame, uint32_t sqliteDBC::addVideoRecord(uint32_t streamID, CSTR md5, CSTR ext, uint32_t tss, uint32_t tms, uint32_t fps) { + ReportGuard tReportGuard(m_mReportLock); // see switchReportToCurrentDay() uint32_t RetVal = 0; if (m_bRepIsConnected) { @@ -2214,6 +2274,7 @@ DBC_LRF_INI * sqliteDBC::getINIData(uint32_t lrfID) bool sqliteDBC::getEventSessionStatus() { + ReportGuard tReportGuard(m_mReportLock); // see switchReportToCurrentDay() bool rv = false; if (m_bRepIsConnected) { @@ -2254,6 +2315,7 @@ bool sqliteDBC::getEventSessionStatus() */ uint32_t sqliteDBC::getLastEventTS() { + ReportGuard tReportGuard(m_mReportLock); // see switchReportToCurrentDay() uint32_t rv = 0; if (m_bRepIsConnected) { diff --git a/lib/App/common/SQLite_dataBinder.h b/lib/App/common/SQLite_dataBinder.h index b9452b52..8cc7c121 100644 --- a/lib/App/common/SQLite_dataBinder.h +++ b/lib/App/common/SQLite_dataBinder.h @@ -9,6 +9,8 @@ #include "dataBinder.h" #include "dataBinder_ReportAux.h" +#include + #define SESSION_CONTINUE 0x00 #define SESSION_START 0x01 #define SESSION_END 0x02 @@ -49,6 +51,19 @@ class sqliteDBC : public dataBinder REPORT_DIRINFO m_sCRepInfo; REPORT_DIRINFO m_sPRepInfo; + // Protects the current day report (m_pDataReports / m_sCRepInfo / m_bRepIsConnected) against + // a day switch from the kernel thread while the event thread writes to it. Recursive because + // report methods call each other (e.g. addEvent -> updateStats -> switchReportToCurrentDay). + pthread_mutex_t m_mReportLock; + class ReportGuard + { + public: + explicit ReportGuard(pthread_mutex_t & m) : m_rM(m) { pthread_mutex_lock(&m_rM); } + ~ReportGuard() { pthread_mutex_unlock(&m_rM); } + private: + pthread_mutex_t & m_rM; + }; + bool openDayReport(REPORT_DIRINFO & RDF); uint32_t m_nSiteID; uint32_t m_nServerID; uint32_t m_nServerNodeID; @@ -126,6 +141,7 @@ class sqliteDBC : public dataBinder virtual DBC_MODULE_EMBED_VIDEO_DATA * getEmbedVideoData(uint32_t ID); virtual DBC_LRF_INI * getINIData(uint32_t lrfID); virtual bool getEventSessionStatus(); + virtual bool switchReportToCurrentDay(void); virtual uint32_t getLastEventTS(); virtual uint32_t getFirstEventTS(); virtual DBC_LRF_DATA * getLRFData(uint32_t ID); diff --git a/lib/App/common/dataBinder.h b/lib/App/common/dataBinder.h index 162e13a4..51b8ff56 100644 --- a/lib/App/common/dataBinder.h +++ b/lib/App/common/dataBinder.h @@ -494,6 +494,13 @@ class dataBinder return false; } + // Closes the current day report and opens the report of the current local day + // (data/reports/YYYY/MM/DD). Returns true if the open report is (now) the current day's one. + virtual bool switchReportToCurrentDay(void) + { + return true; + } + virtual uint32_t getLastEventTS() { return 0; diff --git a/lib/App/mojo/mojoKernel.cpp b/lib/App/mojo/mojoKernel.cpp index 62c87295..650f687e 100644 --- a/lib/App/mojo/mojoKernel.cpp +++ b/lib/App/mojo/mojoKernel.cpp @@ -74,6 +74,9 @@ mojoKernel::mojoKernel(config_setting_t * ptr) : m_bApplicationFirstRun = false; m_bForceCloseSessionOnEndOfTheDay = false; m_mDateOfToday = getLocalDay(); + m_bDayChangePending = false; + m_tDayChangeDetected = 0; + m_nSessionDay = -1; m_pRPC = NULL; #ifndef LRF_PROXY_ONLY m_pMediaHelper = NULL; @@ -519,6 +522,7 @@ void mojoKernel::startSession() m_pEventHeap->broadcast(bEVT); }; m_bSessionStarted = true; + m_nSessionDay = getLocalDay(); #ifdef EMBED_AUTORESET m_nSessionCounter = 0; #endif @@ -1872,20 +1876,65 @@ void mojoKernel::handleVideo(VIDEO_SEGMENT_INFO * ptr) }; } +/* + * Called every second from the kernel thread. + * At local midnight the current day report must be closed and the next day's report opened + * (data/reports/YYYY/MM/DD). Previously the report only moved to the new day when the next + * session started, so everything after midnight was written into the previous day's report + * until the next alarm. + * + * Order of operations: + * 1. an open session that started on the previous day is closed (END event goes into the old + * report) - if a video segment with events is still recording, wait for it at most + * DAY_CHANGE_MAX_VIDEO_WAIT seconds so the video is stored next to its events; + * 2. once the END event is written (event thread), the report is switched to the new day. + * A session started after midnight already switched the report itself (SESSION_START). + */ +void mojoKernel::handleDayChange(void){ + int cd = getLocalDay(); + if ( cd < 0 ) return; + time_t now = time(NULL); + if ( !m_bDayChangePending ) { + if ( m_mDateOfToday == (unsigned long long) cd ) return; + m_bDayChangePending = true; + m_tDayChangeDetected = now; + LOG("Local day changed - closing day report"); + }; + bool bTimeOut = ( now - m_tDayChangeDetected ) >= DAY_CHANGE_MAX_VIDEO_WAIT; + + if ( m_bSessionStarted && ( m_nSessionDay != cd ) ) { + // Session belongs to the previous day - close it in the previous day's report + m_bForceCloseSessionOnEndOfTheDay = true; +#ifndef LRF_PROXY_ONLY + kernelModuleEmbedVideo * tMO = (kernelModuleEmbedVideo *) m_pModuleFactory->getModule(KERNEL_MODULE_EMBED_VIDEO); + if ( tMO && tMO->isProcessingVideoStream() ) { + if ( !bTimeOut ) return; // let the running recording finish into the old day + LOG_ERROR("Day change: video still recording - forcing session close"); + }; +#endif + stopSession( true ); + return; // switch on a next call, after the END event is written by the event thread + }; + + // Wait until the END of the previous session is stored in the old report + if ( !m_bSessionStarted && m_pDBC->getEventSessionStatus() && !bTimeOut ) return; + + if ( m_pDBC->switchReportToCurrentDay() ) { + m_mDateOfToday = cd; + m_bDayChangePending = false; + m_bForceCloseSessionOnEndOfTheDay = false; + LOG("Day report switched to the new day"); + } else { + LOG_ERROR("Day report switch failed - will retry"); + }; +} + bool mojoKernel::validateReports(void){ /// @todo Stephane needs to follow this function... if ( m_bKeepLocalReport ){ - if ( !m_bForceCloseSessionOnEndOfTheDay ) { - uint8_t cd = getLocalDay(); - if ( m_mDateOfToday != cd ) { - //New Day Started - m_mDateOfToday = cd; - if( m_bSessionStarted ){ - m_bForceCloseSessionOnEndOfTheDay = true; - }; - }; - }; + // Local midnight: close the day report and open the next day's report directory + handleDayChange(); DBC_SITE_DATA * tSiteData = m_pDBC->getSiteData(1); if (tSiteData){ diff --git a/lib/App/mojo/mojoKernel.h b/lib/App/mojo/mojoKernel.h index 0dd49630..a7205b50 100644 --- a/lib/App/mojo/mojoKernel.h +++ b/lib/App/mojo/mojoKernel.h @@ -20,6 +20,9 @@ #define MER_INC 2 #define NOTARGET_SESSION_CLOSE 120 // sec +// At local midnight an open session is closed in the old day's report. If a video segment with +// events is still being recorded, wait for it (so it is stored with its events) at most this long. +#define DAY_CHANGE_MAX_VIDEO_WAIT 90 // sec #define EMBED_AUTORESET 300 //sec #define PEREODIC_SENSORS_RESET @@ -81,6 +84,9 @@ class mojoKernel : public kernelPrototype basicMutex m_mSysInfoProtector; unsigned long long m_mDateOfToday; bool m_bForceCloseSessionOnEndOfTheDay; + bool m_bDayChangePending; // local day changed, report not switched yet + time_t m_tDayChangeDetected; // when the day change was detected + int m_nSessionDay; // local day-of-month the current session was started on bool m_bDebugMode; bool m_bKeepLocalReport; bool m_bWorkWithRemoteServer; @@ -121,6 +127,7 @@ class mojoKernel : public kernelPrototype void handleVideo(VIDEO_SEGMENT_INFO * ptr); bool validateReports(void); + void handleDayChange(void); bool createCronJob(uint8_t job, CSTR param_str = NULL, int param_int = 0); void cleanUpReportDir(uint32_t days); void backupReports(uint32_t days);