Browse Source

Kernel loop: move long blocking work out of it

Every pass of the mojo kernel loop ran these synchronously; each could
stall the loop (and get la_mojo killed by the watchdog):

- Report cleanup (validateReports -> deleteReportDate): deleteRDFDir
  ran "rm -f -R <whole day>" (seconds to minutes on an SD card), daily or
  every second while the disk is above preserve_empty. The day is now
  deleted in a background thread (one at a time; calls during it return
  false). ~sqliteDBC waits for a running deletion (max 60 s).
- MediaMTX (validateService -> restart): "systemctl restart" waited for
  the service to stop and start, every second if the config kept failing
  validation. Now "systemctl --no-block restart" (only queues the job),
  at most once per KH_MTX_RESTART_MIN_S (30 s).
- IP UART serial provider (hardwareManager::validate -> create_SOL): a
  blocking connect() to an address that doesn't answer took ~2 min (SYN
  retries). Now non-blocking with SERIAL_SOL_CONNECT_TIMEOUT_MS (5 s),
  the socket mode restored afterwards, and the socket closed on failure
  (it leaked).
- Ethernet2UART gateway nodes: hardwareManager::validate (kernel loop)
  validated and reconnected them again, although the node factory thread
  does it (deviceNode::validate). Connects of up to 5 s blocked the kernel
  loop, plus the wait for the node's connection lock.
  hardwareResource::selfValidating() (default false) is true for
  deviceETH2UART, and the hardware manager skips such resources.

Tested: the connect timeout on its own (extracted unchanged). A peer
that drops the SYN failed after 5002 ms ("Connection timed out") instead
of ~2 min; refused and accepted connects are immediate; the socket is
blocking again in every case.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0139veDo3XyavMuVhdnHcN16
pull/26/head
Claude 8 hours ago
parent
commit
0d043cd106
Failed to extract signature
  1. 46
      lib/App/common/SQLite_dataBinder.cpp
  2. 5
      lib/App/common/deviceNodeEthernet2Serial.h
  3. 4
      lib/App/common/hardwareManager.cpp
  4. 7
      lib/App/common/hardwareResource.h
  5. 46
      lib/App/common/hardwareResourceSerialProvider.cpp
  6. 4
      lib/App/common/hardwareResourceSerialProvider.h
  7. 15
      lib/App/common/kernelHelperMediaMTX.cpp
  8. 6
      lib/App/common/kernelHelperMediaMTX.h

46
lib/App/common/SQLite_dataBinder.cpp

@ -1,5 +1,12 @@
#include "SQLite_dataBinder.h"
#include <atomic>
#include <string>
#include <thread>
// A report day is being deleted in the background (deleteReportDate)
static std::atomic<bool> s_bReportDayDeleting(false);
#include "../../components/base/basicEvent.h"
#define LOG(X) m_pLog->Log("SDBC", this, X)
@ -109,6 +116,11 @@ sqliteDBC::sqliteDBC(config_setting_t * Settings) :
sqliteDBC::~sqliteDBC()
{
// A report day still being deleted in the background uses this object (deleteReportStat)
for (int i = 0; i < 600 && s_bReportDayDeleting; i++)
{
SLEEP(100);
};
if (m_pDataStorage)
{
delete(m_pDataStorage);
@ -2415,18 +2427,44 @@ uint32_t sqliteDBC::getFirstEventTS()
return rv;
}
/*
Called from the kernel loop (validateReports: daily cleanup, or every second while the disk is above
preserve_empty). deleteRDFDir() runs "rm -f -R <whole day>" - many seconds (minutes on a big SD card):
the kernel loop stalled and the watchdog killed la_mojo. The day is deleted in a background thread;
while it runs, further calls return false (the oldest day is still listed until it is done).
*/
bool sqliteDBC::deleteReportDate(uint32_t ts)
{
if (ts)
{
bool tFalse = false;
if (! s_bReportDayDeleting.compare_exchange_strong(tFalse, true))
{
return false; // a day is being deleted
};
REPORT_DIRINFO tRDF;// = {0};
fillRDF(ts, tRDF);
LOG("Delete RDF Dir");
if (deleteRDFDir(m_pDbReportBase, tRDF))
std::string tBase(m_pDbReportBase);
LOG("Delete RDF Dir (background)");
try
{
LOG("Dir Deleted OK");
return deleteReportStat(tRDF);
std::thread([this, tBase, tRDF]() mutable {
pthread_setname_np(pthread_self(), "ReportDelete");
if (deleteRDFDir((CSTR) tBase.c_str(), tRDF))
{
LOG("Dir Deleted OK");
deleteReportStat(tRDF);
};
s_bReportDayDeleting = false;
}).detach();
}
catch (const std::exception & e)
{
s_bReportDayDeleting = false;
LOG_ERROR("Can not start the report delete thread");
return false;
};
return true;
};
return false;
}

5
lib/App/common/deviceNodeEthernet2Serial.h

@ -121,6 +121,11 @@
{
return true;
}
// validated and reconnected by the node factory (deviceNode::validate) - not by the hardware manager
virtual bool selfValidating(void)
{
return true;
}
};
#endif

4
lib/App/common/hardwareManager.cpp

@ -451,6 +451,10 @@ bool hardwareManager::validate(void)
{
for (VECTOR_HW_RESOURCES::iterator idx = m_vResources.begin(); idx < m_vResources.end(); idx++)
{
if ((*idx)->selfValidating())
{
continue; // its node validates / reconnects it (node factory thread)
};
if (! (*idx)->validate())
{
// recreate Resource

7
lib/App/common/hardwareResource.h

@ -64,6 +64,13 @@ class hardwareResource : public basicObject
virtual bool create(uint32_t id, HARDWARE_PROVIDERS type);
// true: the resource is validated / reconnected by its owner (e.g. a deviceNode in the node factory
// thread) - the hardware manager (kernel loop) must not do it again: a gateway connect blocked the
// kernel loop for seconds, and two threads reconnected the same object
virtual bool selfValidating(void){
return false;
}
virtual bool validate(void){
return m_bValid;
}

46
lib/App/common/hardwareResourceSerialProvider.cpp

@ -229,6 +229,43 @@ bool hardwareResourceSerialProvider::pingDevice()
return RetVal;
}
#include <poll.h>
// connect() bounded by timeoutMs (the socket is left in blocking mode as before). false: errno set
static bool connectWithTimeout(int fd, struct sockaddr * addr, socklen_t len, int timeoutMs)
{
int tFlags = fcntl(fd, F_GETFL, 0);
fcntl(fd, F_SETFL, tFlags | O_NONBLOCK);
int tRc = connect(fd, addr, len);
if (tRc != 0 && errno == EINPROGRESS)
{
struct pollfd tPfd;
tPfd.fd = fd;
tPfd.events = POLLOUT;
do
{
tRc = poll(&tPfd, 1, timeoutMs);
}
while (tRc < 0 && errno == EINTR);
if (tRc == 0)
{
errno = ETIMEDOUT;
tRc = -1;
}
else if (tRc > 0)
{
int tErr = 0;
socklen_t tL = sizeof(tErr);
getsockopt(fd, SOL_SOCKET, SO_ERROR, &tErr, &tL);
errno = tErr;
tRc = (tErr == 0) ? 0 : -1;
};
};
int tErrno = errno;
fcntl(fd, F_SETFL, tFlags); // back to the caller's mode in every case
errno = tErrno;
return tRc == 0;
}
bool hardwareResourceSerialProvider::create_SOL()
{
@ -392,12 +429,15 @@ bool hardwareResourceSerialProvider::create_SOL()
tServerAddr.sin_addr.s_addr = inet_addr(m_sUartData.path);
tServerAddr.sin_port = htons(m_sUartData.port);
// connect the client socket to server socket
if (connect(m_iDeviceFD, (struct sockaddr *) &tServerAddr, sizeof(tServerAddr)) != 0)
// connect the client socket to server socket - with a timeout: a blocking connect() to an address
// that does not answer took ~2 min (SYN retries) inside hardwareManager::validate() = the kernel loop
if (! connectWithTimeout(m_iDeviceFD, (struct sockaddr *) &tServerAddr, sizeof(tServerAddr), SERIAL_SOL_CONNECT_TIMEOUT_MS))
{
char cBuffer[256];
sprintf(cBuffer, "ERROR connect to [%s:%d] (%s)", m_sUartData.path, m_sUartData.port, strerror(errno));
snprintf(cBuffer, sizeof(cBuffer), "ERROR connect to [%.64s:%d] (%s)", m_sUartData.path, m_sUartData.port, strerror(errno));
LOG_ERROR(cBuffer);
close(m_iDeviceFD); // was leaked
m_iDeviceFD = -1;
return false;
}
#ifdef DEBUG

4
lib/App/common/hardwareResourceSerialProvider.h

@ -43,6 +43,10 @@
// #define DEBUG_SERIAL_COMMUNICATION
#endif
#ifndef SERIAL_SOL_CONNECT_TIMEOUT_MS
#define SERIAL_SOL_CONNECT_TIMEOUT_MS 5000 // TCP connect to an IP UART (serial over LAN / Internet)
#endif
#if defined( HALF_DUPLEX ) || defined( SERIAL_PING_PONG )
class hardwareResourceSerialProvider : public hardwareResource, public basicTransport, public basicThread

15
lib/App/common/kernelHelperMediaMTX.cpp

@ -28,6 +28,7 @@ kernelHelperMediaMTX::kernelHelperMediaMTX(): basicThread() {
memset( m_sAppConfigFile, 0, 512 );
m_nLastLogSize = 0;
m_bRecordMode = false;
m_tLastRestart = 0;
if( loadConfig() ) m_bStatus = KH_STATUS_MTX_INIT;
}
@ -49,8 +50,20 @@ bool kernelHelperMediaMTX::create(){
return init();
}
/*
Called from the kernel loop (validateService, every second when the config does not validate).
"systemctl restart" waited for the service to stop and start (many seconds) - the kernel loop stalled
and the watchdog killed la_mojo. --no-block only queues the restart job; at most one restart per
KH_MTX_RESTART_MIN_S (a config that keeps failing validation restarted MediaMTX every second).
*/
bool kernelHelperMediaMTX::restart(){
int RetVal = system( "systemctl restart mediamtx.service" );
time_t tNow = time( NULL );
if ( m_tLastRestart != 0 && ( tNow - m_tLastRestart ) < KH_MTX_RESTART_MIN_S ) {
return true; // restarted a moment ago: the config is re-checked after the period
};
m_tLastRestart = tNow;
LOG( "Restart MediaMTX (queued)" );
int RetVal = system( "systemctl --no-block restart mediamtx.service" );
if ( RetVal == -1 ) return false;
return true;
}

6
lib/App/common/kernelHelperMediaMTX.h

@ -44,6 +44,11 @@ typedef std::map<uint64_t, StreamSegmentRecord *> M_StreamMap; // inodes -> info
typedef std::map<uint64_t, M_StreamMap *> M_VideoSegmentInfo; // stream_id -> map
// At most one MediaMTX restart per this period (a config that keeps failing validation restarted it every second)
#ifndef KH_MTX_RESTART_MIN_S
#define KH_MTX_RESTART_MIN_S 30
#endif
class kernelHelperMediaMTX: public basicThread {
private:
basicLogCollection * m_pLog;
@ -57,6 +62,7 @@ class kernelHelperMediaMTX: public basicThread {
char m_sRecordsBase[MAX_PATH_LEN];
off_t m_nLastLogSize;
bool m_bRecordMode;
time_t m_tLastRestart; // last restart() (rate limit)
bool loadConfig();
bool loadStreams();
StreamSegmentRecord * createSSR( uint32_t stream_id, uint32_t streamTSS, uint32_t streamTMS, CSTR path );

Loading…
Cancel
Save