la_mojo: one report database per hour (report_HH.db) #10

Merged
ClaudeAI merged 1 commits from feature/hourly-report-db into master 2 hours ago
  1. 76
      lib/App/common/SQLite_dataBinder.cpp
  2. 10
      lib/App/common/SQLite_dataBinder.h
  3. 6
      lib/App/common/dataBinder.h
  4. 76
      lib/App/mojo/mojoKernel.cpp
  5. 15
      lib/App/mojo/mojoKernel.h
  6. 9
      lib/components/base/basicFunctionality.cpp
  7. 2
      lib/components/base/basicFunctionality.h

76
lib/App/common/SQLite_dataBinder.cpp

@ -99,6 +99,7 @@ sqliteDBC::sqliteDBC(config_setting_t * Settings) :
m_nServerID = 1;
memset(&m_sCRepInfo, 0, sizeof(REPORT_DIRINFO));
memset(&m_sPRepInfo, 0, sizeof(REPORT_DIRINFO));
m_nCRepHour = -1;
pthread_mutexattr_t tAttr;
pthread_mutexattr_init(&tAttr);
pthread_mutexattr_settype(&tAttr, PTHREAD_MUTEX_RECURSIVE);
@ -450,7 +451,9 @@ bool sqliteDBC::connect(void)
#ifdef DEBUG
LOG("Last Session is Closed!");
#endif
fillRDF(time(NULL), m_sCRepInfo);
time_t tNow = time(NULL);
fillRDF(tNow, m_sCRepInfo);
m_nCRepHour = getLocalHour(tNow);
} else {
#ifdef DEBUG
LOG("Last Session is NOT Closed!");
@ -464,7 +467,9 @@ bool sqliteDBC::connect(void)
LOG_ERROR("Cannot Open Report!!");
return false;
};
sprintf(m_pDbReport, "%s/%s/%s/%s/report.db", m_pDbReportBase, m_sCRepInfo.YEAR, m_sCRepInfo.MONTH, m_sCRepInfo.DAY);
char tRepName[32];
snprintf(tRepName, sizeof(tRepName), REPORT_DB_NAME_FMT, m_nCRepHour < 0 ? 0 : m_nCRepHour);
sprintf(m_pDbReport, "%s/%s/%s/%s/%s", m_pDbReportBase, m_sCRepInfo.YEAR, m_sCRepInfo.MONTH, m_sCRepInfo.DAY, tRepName);
#ifdef DEBUG
LOG(m_pDbReport);
#endif
@ -570,7 +575,7 @@ void sqliteDBC::initMemDB(uint32_t sid)
CSTR sqliteDBC::getCurrentReportDir(void)
{
ReportGuard tReportGuard(m_mReportLock); // see switchReportToCurrentDay()
ReportGuard tReportGuard(m_mReportLock); // see switchReportToCurrentHour()
CSTR tV = NULL;
if (m_sCRepInfo.ts)
{
@ -861,12 +866,14 @@ bool sqliteDBC::addDeviceDraw(uint32_t DBID, uint8_t type, uint8_t lrf, void * t
}
/*
* 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.
* Opens (creates if needed) the report of the given day and local hour:
* data/reports/YYYY/MM/DD/report_HH.db (REPORT_DB_NAME_FMT)
* Pictures and videos stay in the day folder. SQLite_Connector::Connect() closes the
* currently open report under its own lock first. Caller must hold m_mReportLock.
*/
bool sqliteDBC::openDayReport(REPORT_DIRINFO & RDF)
bool sqliteDBC::openHourReport(REPORT_DIRINFO & RDF, int hour)
{
char tName[32];
char tPath[CLOG];
char tQBuf[1024];
if (! checkRDFDir(m_pDbReportBase, RDF, true, getUserUid(web_access_user), getUserGid(web_access_group)))
@ -874,7 +881,13 @@ bool sqliteDBC::openDayReport(REPORT_DIRINFO & RDF)
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);
if (hour < 0 || hour > 23)
{
LOG_ERROR("Invalid report hour!");
return false;
};
snprintf(tName, sizeof(tName), REPORT_DB_NAME_FMT, hour);
snprintf(tPath, sizeof(tPath), "%s/%s/%s/%s/%s", m_pDbReportBase, RDF.YEAR, RDF.MONTH, RDF.DAY, tName);
LOG("Connect Report!");
LOG(tPath);
if (m_bRepIsConnected)
@ -884,7 +897,7 @@ bool sqliteDBC::openDayReport(REPORT_DIRINFO & RDF)
m_bRepIsConnected = false;
if (! m_pDataReports->Connect(tPath, 0, true))
{
LOG_ERROR("Cannot open day report!");
LOG_ERROR("Cannot open hour report!");
return false;
};
strncpy(m_pDbReport, tPath, CLOG - 1);
@ -905,6 +918,7 @@ bool sqliteDBC::openDayReport(REPORT_DIRINFO & RDF)
"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_nCRepHour = hour;
m_bRepIsConnected = true;
LOG("Report Connected!");
// Create the day record (no session yet) - session counters are updated on SESSION_START / SESSION_END
@ -919,31 +933,39 @@ bool sqliteDBC::openDayReport(REPORT_DIRINFO & RDF)
}
/*
* 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.
* Called by the kernel when the local hour changes (and on every SESSION_START): if the local
* day or hour changed since the current report was opened, close it and open the current
* hour's report_HH.db (in a new day folder at midnight).
*/
bool sqliteDBC::switchReportToCurrentDay(void)
bool sqliteDBC::switchReportToCurrentHour(void)
{
ReportGuard tGuard(m_mReportLock);
if (m_pDataReports == NULL)
{
return false;
};
time_t tNow = time(NULL);
REPORT_DIRINFO tRR; // initialized by fillRDF
fillRDF(time(NULL), tRR);
if (m_bRepIsConnected && (tRR.ts <= m_sCRepInfo.ts))
fillRDF(tNow, tRR);
int tHour = getLocalHour(tNow);
// Same day and same hour (also when the hour repeats at the end of daylight saving time)
if (m_bRepIsConnected && (tRR.ts <= m_sCRepInfo.ts) && (tHour == m_nCRepHour))
{
return true; // already the current hour's report
};
if (m_bRepIsConnected && (tRR.ts < m_sCRepInfo.ts))
{
return true; // already today's report
return true; // clock moved back to a previous day - keep the open 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);
snprintf(tB, sizeof(tB), "Report switch %s-%s-%s %02d -> %s-%s-%s %02d", m_sCRepInfo.YEAR, m_sCRepInfo.MONTH, m_sCRepInfo.DAY, m_nCRepHour, tRR.YEAR, tRR.MONTH, tRR.DAY, tHour);
LOG(tB);
return openDayReport(tRR);
return openHourReport(tRR, tHour);
}
void sqliteDBC::updateStats(bool evt, bool video, uint8_t ses_status)
{
ReportGuard tReportGuard(m_mReportLock); // see switchReportToCurrentDay()
ReportGuard tReportGuard(m_mReportLock); // see switchReportToCurrentHour()
// 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).
@ -970,8 +992,8 @@ void sqliteDBC::updateStats(bool evt, bool video, uint8_t ses_status)
};
case SESSION_START:
{
// Close the previous day report and open today's one (if the local day changed)
switchReportToCurrentDay();
// Close the previous report and open the current hour's one (if the hour changed)
switchReportToCurrentHour();
// 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,
@ -1008,7 +1030,7 @@ void sqliteDBC::updateStats(bool evt, bool video, uint8_t ses_status)
bool sqliteDBC::dropSession()
{
ReportGuard tReportGuard(m_mReportLock); // see switchReportToCurrentDay()
ReportGuard tReportGuard(m_mReportLock); // see switchReportToCurrentHour()
if (m_bRepIsConnected)
{
char tQBuf[1024];
@ -1067,7 +1089,7 @@ bool sqliteDBC::dropSession()
uint32_t sqliteDBC::addEvent(DBC_EVT_RECORD * ptr)
{
ReportGuard tReportGuard(m_mReportLock); // see switchReportToCurrentDay()
ReportGuard tReportGuard(m_mReportLock); // see switchReportToCurrentHour()
if (ptr == NULL)
{
return 0;
@ -1611,7 +1633,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()
ReportGuard tReportGuard(m_mReportLock); // see switchReportToCurrentHour()
bool rVal = false;
if (ptr != NULL)
{
@ -1679,7 +1701,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()
ReportGuard tReportGuard(m_mReportLock); // see switchReportToCurrentHour()
if (m_bRepIsConnected)
{
char tQBuf[2048];
@ -1694,7 +1716,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()
ReportGuard tReportGuard(m_mReportLock); // see switchReportToCurrentHour()
uint32_t RetVal = 0;
if (m_bRepIsConnected)
{
@ -2274,7 +2296,7 @@ DBC_LRF_INI * sqliteDBC::getINIData(uint32_t lrfID)
bool sqliteDBC::getEventSessionStatus()
{
ReportGuard tReportGuard(m_mReportLock); // see switchReportToCurrentDay()
ReportGuard tReportGuard(m_mReportLock); // see switchReportToCurrentHour()
bool rv = false;
if (m_bRepIsConnected)
{
@ -2315,7 +2337,7 @@ bool sqliteDBC::getEventSessionStatus()
*/
uint32_t sqliteDBC::getLastEventTS()
{
ReportGuard tReportGuard(m_mReportLock); // see switchReportToCurrentDay()
ReportGuard tReportGuard(m_mReportLock); // see switchReportToCurrentHour()
uint32_t rv = 0;
if (m_bRepIsConnected)
{

10
lib/App/common/SQLite_dataBinder.h

@ -18,6 +18,9 @@
#define REMOVE_ONLY_SESSION_MARKS
// One report database per local hour inside the day folder: data/reports/YYYY/MM/DD/report_HH.db
#define REPORT_DB_NAME_FMT "report_%02d.db"
class sqliteDBC : public dataBinder
{
private:
@ -51,9 +54,10 @@ class sqliteDBC : public dataBinder
REPORT_DIRINFO m_sCRepInfo;
REPORT_DIRINFO m_sPRepInfo;
int m_nCRepHour; // local hour of the open report_HH.db (-1: none)
// 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).
// report methods call each other (e.g. addEvent -> updateStats -> switchReportToCurrentHour).
pthread_mutex_t m_mReportLock;
class ReportGuard
{
@ -63,7 +67,7 @@ class sqliteDBC : public dataBinder
private:
pthread_mutex_t & m_rM;
};
bool openDayReport(REPORT_DIRINFO & RDF);
bool openHourReport(REPORT_DIRINFO & RDF, int hour);
uint32_t m_nSiteID;
uint32_t m_nServerID;
uint32_t m_nServerNodeID;
@ -141,7 +145,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 bool switchReportToCurrentHour(void);
virtual uint32_t getLastEventTS();
virtual uint32_t getFirstEventTS();
virtual DBC_LRF_DATA * getLRFData(uint32_t ID);

6
lib/App/common/dataBinder.h

@ -494,9 +494,9 @@ 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)
// Closes the current report and opens the report of the current local hour
// (data/reports/YYYY/MM/DD/report_HH.db). Returns true if the open report is (now) the current one.
virtual bool switchReportToCurrentHour(void)
{
return true;
}

76
lib/App/mojo/mojoKernel.cpp

@ -15,6 +15,8 @@
#include "mojoKernel.h"
static int getLocalReportPeriod(void);
#include "../common/kernelEventFilterAPF.h"
#include "../common/kernelEventFilterBubble.h"
#include "../common/kernelEventFilterTrain.h"
@ -74,9 +76,10 @@ 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_nReportPeriod = getLocalReportPeriod();
m_bReportSwitchPending = false;
m_tReportSwitchDetected = 0;
m_nSessionPeriod = -1;
m_pRPC = NULL;
#ifndef LRF_PROXY_ONLY
m_pMediaHelper = NULL;
@ -522,7 +525,7 @@ void mojoKernel::startSession()
m_pEventHeap->broadcast(bEVT);
};
m_bSessionStarted = true;
m_nSessionDay = getLocalDay();
m_nSessionPeriod = getLocalReportPeriod();
#ifdef EMBED_AUTORESET
m_nSessionCounter = 0;
#endif
@ -1876,40 +1879,49 @@ void mojoKernel::handleVideo(VIDEO_SEGMENT_INFO * ptr)
};
}
/*
* Local "report period" = day-of-month * 100 + hour: changes every local hour (and at midnight).
*/
static int getLocalReportPeriod(void){
time_t t = time(NULL);
tm lt;
if ( localtime_r( &t, &lt ) == NULL ) return -1;
return lt.tm_mday * 100 + lt.tm_hour;
}
/*
* 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.
* Every local hour the current report (data/reports/YYYY/MM/DD/report_HH.db) is closed and
* the next hour's report is opened - at midnight in the next day's directory.
*
* Order of operations:
* 1. an open session that started on the previous day is closed (END event goes into the old
* 1. an open session that started in the previous hour 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).
* REPORT_SWITCH_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 hour.
* The next event opens a new session in the new report.
* A session started after the hour change already switched the report itself (SESSION_START).
*/
void mojoKernel::handleDayChange(void){
int cd = getLocalDay();
if ( cd < 0 ) return;
void mojoKernel::handleReportPeriodChange(void){
int cp = getLocalReportPeriod();
if ( cp < 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");
if ( !m_bReportSwitchPending ) {
if ( m_nReportPeriod == cp ) return;
m_bReportSwitchPending = true;
m_tReportSwitchDetected = now;
LOG("Local hour changed - closing hour report");
};
bool bTimeOut = ( now - m_tDayChangeDetected ) >= DAY_CHANGE_MAX_VIDEO_WAIT;
bool bTimeOut = ( now - m_tReportSwitchDetected ) >= REPORT_SWITCH_MAX_VIDEO_WAIT;
if ( m_bSessionStarted && ( m_nSessionDay != cd ) ) {
// Session belongs to the previous day - close it in the previous day's report
if ( m_bSessionStarted && ( m_nSessionPeriod != cp ) ) {
// Session belongs to the previous hour - close it in the previous hour'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");
if ( !bTimeOut ) return; // let the running recording finish into the old report
LOG_ERROR("Hour change: video still recording - forcing session close");
};
#endif
stopSession( true );
@ -1919,13 +1931,13 @@ void mojoKernel::handleDayChange(void){
// 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;
if ( m_pDBC->switchReportToCurrentHour() ) {
m_nReportPeriod = cp;
m_bReportSwitchPending = false;
m_bForceCloseSessionOnEndOfTheDay = false;
LOG("Day report switched to the new day");
LOG("Report switched to the new hour");
} else {
LOG_ERROR("Day report switch failed - will retry");
LOG_ERROR("Hour report switch failed - will retry");
};
}
@ -1933,8 +1945,8 @@ bool mojoKernel::validateReports(void){
/// @todo Stephane needs to follow this function...
if ( m_bKeepLocalReport ){
// Local midnight: close the day report and open the next day's report directory
handleDayChange();
// Every local hour: close the hour report and open the next one (next day's folder at midnight)
handleReportPeriodChange();
DBC_SITE_DATA * tSiteData = m_pDBC->getSiteData(1);
if (tSiteData){

15
lib/App/mojo/mojoKernel.h

@ -20,9 +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
// At each local hour change an open session is closed in the old hour'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 REPORT_SWITCH_MAX_VIDEO_WAIT 90 // sec
#define EMBED_AUTORESET 300 //sec
#define PEREODIC_SENSORS_RESET
@ -84,9 +84,10 @@ 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
int m_nReportPeriod; // local day*100+hour of the open report
bool m_bReportSwitchPending; // local hour changed, report not switched yet
time_t m_tReportSwitchDetected; // when the hour change was detected
int m_nSessionPeriod; // local day*100+hour the current session was started in
bool m_bDebugMode;
bool m_bKeepLocalReport;
bool m_bWorkWithRemoteServer;
@ -127,7 +128,7 @@ class mojoKernel : public kernelPrototype
void handleVideo(VIDEO_SEGMENT_INFO * ptr);
bool validateReports(void);
void handleDayChange(void);
void handleReportPeriodChange(void);
bool createCronJob(uint8_t job, CSTR param_str = NULL, int param_int = 0);
void cleanUpReportDir(uint32_t days);
void backupReports(uint32_t days);

9
lib/components/base/basicFunctionality.cpp

@ -53,6 +53,15 @@ int getLocalDay(){
};
}
int getLocalHour(time_t t){
if ( t == 0 ) t = time(NULL);
tm local_time;
if( localtime_r(&t, &local_time) == NULL ){
return -1;
};
return local_time.tm_hour;
}
int checkCmdExists(CSTR cmd)
{
FILE * fd = popen(cmd, "r");

2
lib/components/base/basicFunctionality.h

@ -72,6 +72,8 @@ CSTR strReplace(CSTR orig, CSTR rep, CSTR with);
int checkCmdExists(CSTR cmd);
int getLocalDay();
// Local hour of day (0..23) of time t (t == 0: now), -1 on error
int getLocalHour(time_t t = 0);
ssize_t readLine(int fd, char * buffer, size_t n);
ssize_t readLine(FILE * fd, char * buffer, size_t n);

Loading…
Cancel
Save