Browse Source

Kernel watchdog: feed from its own thread while the kernel loop makes progress

watchDogDaemon kills a client that misses its deadline (signal 9). The
mojo kernel loop sent "4000" (next update within 4 s) at the start of each
pass and then ran all validations in the same thread. A pass of about
3 s killed la_mojo, for example a gateway connect (5 s), rm -rf of a
report day, or a synchronous systemctl restart of MediaMTX.

kernelPrototype
- A feeder thread (wdStart) sends KERNEL_WD_FEED_MS (4 s) every second
  while the kernel loop reports progress (wdStep). A loop without progress
  for KERNEL_WD_STALL_MS (60 s) is a hang: the feeding stops, logged as
  "Kernel loop stalled in '<step>' for N s - watchdog no longer fed", and
  the daemon kills the process as before.
- wdStep() logs steps slower than 1 s ("Kernel step '<step>' took N
  ms"). The feeder logs a step that runs longer than 5 s every 5 s
  ("Kernel loop busy in '<step>' for N s"), so the step is named before
  any kill.
- wdExtend(): stops feeding and grants a one-time deadline.
- send(MSG_NOSIGNAL) instead of write(): a watchDogDaemon that restarted
  closed the socket, and the next write() killed la_mojo with SIGPIPE.
  A lost connection is logged and closed.
- The socket is closed when connect() fails (it leaked).
- The feeder is opt-in: servaKernel is unchanged.

mojoKernel
- The loop calls wdStart() and names each step: debug mode, filters,
  session, reports, hardwareManager::validate, updateSysInfo, media
  helper, remote server, kernel commands, cleanNodePushedCMD.
- ~mojoKernel grants KERNEL_WD_SHUTDOWN_MS (120 s) before deleting the
  factories / nodes / threads. Before, the 4 s of the last feed ran out
  and the daemon killed la_mojo in the middle of a reload / restart /
  exit. "-1" at the end goes through wdSend().

Tested with the real watchDogDaemon and a test kernel built on
kernelPrototype (stall limit 8 s for the test):
- old behaviour, one 6 s step: killed (137);
- new, normal passes: runs to the end;
- new, one 6 s step: not killed; logs "busy ... 5 s" and "took 6000 ms";
- new, a step that hangs: logs "stalled in '<step>'", then killed (137).

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
a77f34253a
Failed to extract signature
  1. 144
      lib/App/common/kernelPrototype.cpp
  2. 37
      lib/App/common/kernelPrototype.h
  3. 41
      lib/App/mojo/mojoKernel.cpp

144
lib/App/common/kernelPrototype.cpp

@ -14,6 +14,16 @@
kernelPrototype * kernelPrototype::_instance = NULL; kernelPrototype * kernelPrototype::_instance = NULL;
#ifdef LINUX_KERNEL_WATCHDOG
#include <time.h>
static uint64_t wdNowMs(void)
{
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
return (uint64_t) ts.tv_sec * 1000 + ts.tv_nsec / 1000000;
}
#endif
kernelPrototype * kernelPrototype::getInstance() kernelPrototype * kernelPrototype::getInstance()
{ {
return _instance; return _instance;
@ -25,7 +35,12 @@ kernelPrototype::kernelPrototype(config_setting_t * ptr) :
{ {
m_pLog = basicLogCollection::getInstance(); m_pLog = basicLogCollection::getInstance();
#ifdef LINUX_KERNEL_WATCHDOG #ifdef LINUX_KERNEL_WATCHDOG
m_iWatchdogFd = -1;
m_iWatchdogFd = -1;
m_pWdThread = NULL;
m_bWdRun = false;
m_nWdProgressMs = wdNowMs();
m_nWdStepStartMs = wdNowMs();
m_pWdStep = "init";
struct sockaddr_un server_addr; struct sockaddr_un server_addr;
int connection_result; int connection_result;
@ -39,6 +54,10 @@ kernelPrototype::kernelPrototype(config_setting_t * ptr) :
if (connection_result == -1) if (connection_result == -1)
{ {
LOG_ERROR("WD Connection Error"); LOG_ERROR("WD Connection Error");
if (m_iWatchdogFd > -1)
{
close(m_iWatchdogFd); // was leaked
};
m_iWatchdogFd = -1; m_iWatchdogFd = -1;
}; };
if (m_iWatchdogFd < 0) if (m_iWatchdogFd < 0)
@ -63,8 +82,11 @@ kernelPrototype::kernelPrototype(config_setting_t * ptr) :
char tB[64]; char tB[64];
sprintf(tB, "%d\n", gettid()); sprintf(tB, "%d\n", gettid());
LOG("PID SENT TO WD!"); LOG("PID SENT TO WD!");
// ToDo: Make Error Handling here!
write(m_iWatchdogFd, &tB, strlen(tB));
// MSG_NOSIGNAL: a daemon that restarted must not kill us with SIGPIPE
if (send(m_iWatchdogFd, tB, strlen(tB), MSG_NOSIGNAL) < 0)
{
LOG_ERROR("Watchdog: PID not sent");
};
}; };
#endif #endif
m_pSettings = basicSettingsProvider::getInstance()->getSubNode(ptr, "KERNEL"); m_pSettings = basicSettingsProvider::getInstance()->getSubNode(ptr, "KERNEL");
@ -89,6 +111,7 @@ kernelPrototype::kernelPrototype(config_setting_t * ptr) :
kernelPrototype::~kernelPrototype() kernelPrototype::~kernelPrototype()
{ {
#ifdef LINUX_KERNEL_WATCHDOG #ifdef LINUX_KERNEL_WATCHDOG
wdStop();
LOG("Closing WD!"); LOG("Closing WD!");
if (! (m_iWatchdogFd < 0)) if (! (m_iWatchdogFd < 0))
{ {
@ -98,6 +121,121 @@ kernelPrototype::~kernelPrototype()
#endif #endif
} }
#ifdef LINUX_KERNEL_WATCHDOG
bool kernelPrototype::wdSend(int64_t ms)
{
bool tOk = false;
m_mWdWrite.lock();
if (m_iWatchdogFd > -1)
{
char tB[32];
int tLen = snprintf(tB, sizeof(tB), "%lld\n", (long long) ms);
if (send(m_iWatchdogFd, tB, tLen, MSG_NOSIGNAL) == tLen)
{
tOk = true;
}
else
{
// Daemon gone (restarted / stopped): not monitored any more - and no SIGPIPE
LOG_ERROR("Watchdog connection lost - not monitored any more");
close(m_iWatchdogFd);
m_iWatchdogFd = -1;
};
};
m_mWdWrite.unlock();
return tOk;
}
void kernelPrototype::wdStep(const char * step)
{
uint64_t tNow = wdNowMs();
const char * tPrev = m_pWdStep.exchange(step);
uint64_t tTook = tNow - m_nWdStepStartMs.exchange(tNow);
m_nWdProgressMs = tNow;
if (tTook > KERNEL_WD_SLOW_STEP_MS && tPrev != NULL && strcmp(tPrev, "idle") != 0)
{
char tB[128];
snprintf(tB, sizeof(tB), "Kernel step '%s' took %llu ms", tPrev, (unsigned long long) tTook);
LOG_ERROR(tB);
};
}
void kernelPrototype::wdFeederProc(void)
{
pthread_setname_np(pthread_self(), "KernelWD");
uint64_t tLastSend = 0;
uint64_t tLastBusyLog = 0;
bool tStalled = false;
while (m_bWdRun)
{
uint64_t tNow = wdNowMs();
uint64_t tIdle = tNow - m_nWdProgressMs;
uint64_t tBusy = tNow - m_nWdStepStartMs;
const char * tStep = m_pWdStep;
if (tIdle < KERNEL_WD_STALL_MS)
{
if (tStalled)
{
LOG("Kernel loop running again - watchdog fed");
tStalled = false;
};
if (tNow - tLastSend >= 1000)
{
wdSend(KERNEL_WD_FEED_MS);
tLastSend = tNow;
};
if (tBusy >= KERNEL_WD_BUSY_LOG_MS && strcmp(tStep, "idle") != 0 && tNow - tLastBusyLog >= KERNEL_WD_BUSY_LOG_MS)
{
char tB[128];
snprintf(tB, sizeof(tB), "Kernel loop busy in '%s' for %llu s", tStep, (unsigned long long) (tBusy / 1000));
LOG_ERROR(tB);
tLastBusyLog = tNow;
};
}
else if (! tStalled)
{
// A hang: stop feeding, the daemon kills the process after the last deadline
char tB[160];
snprintf(tB, sizeof(tB), "Kernel loop stalled in '%s' for %llu s - watchdog no longer fed", tStep, (unsigned long long) (tIdle / 1000));
LOG_ERROR(tB);
tStalled = true;
};
SLEEP(100);
};
}
void kernelPrototype::wdStart(void)
{
if (m_iWatchdogFd < 0 || m_pWdThread != NULL)
{
return;
};
wdStep("start");
m_bWdRun = true;
m_pWdThread = new std::thread(&kernelPrototype::wdFeederProc, this);
}
void kernelPrototype::wdStop(void)
{
if (m_pWdThread != NULL)
{
m_bWdRun = false;
if (m_pWdThread->joinable())
{
m_pWdThread->join();
};
delete m_pWdThread;
m_pWdThread = NULL;
};
}
void kernelPrototype::wdExtend(uint32_t ms)
{
wdStop();
wdSend(ms);
}
#endif
void kernelPrototype::setWM(uint8_t mode) void kernelPrototype::setWM(uint8_t mode)
{ {
m_mWMProtector.lock(); m_mWMProtector.lock();

37
lib/App/common/kernelPrototype.h

@ -28,7 +28,26 @@
#include <linux/watchdog.h> #include <linux/watchdog.h>
#include <sys/socket.h> #include <sys/socket.h>
#include <sys/un.h> #include <sys/un.h>
#include <atomic>
#include <thread>
#endif
/*
Watchdog (watchDogDaemon, UNIX socket /srv/etc/watchdog): a client sends its PID, then "N\n" = next update
within N ms; without it the daemon kills the process (signal 9), "-1" ends the monitoring.
The kernel loop fed it itself ("4000" at the start of each pass): a pass of ~3 s (gateway connect, rm -rf of
a report day, systemctl restart ...) got la_mojo killed. Now a feeder thread sends KERNEL_WD_FEED_MS every
second as long as the kernel loop reports progress (wdStep); a loop without progress for KERNEL_WD_STALL_MS
is a hang: the feeding stops (logged with the step it hangs in) and the daemon kills the process.
*/
#define KERNEL_WD_FEED_MS 4000 // deadline sent every second
#ifndef KERNEL_WD_STALL_MS
#define KERNEL_WD_STALL_MS 60000 // kernel loop without progress this long = hung
#endif #endif
#define KERNEL_WD_SLOW_STEP_MS 1000 // steps slower than this are logged
#define KERNEL_WD_BUSY_LOG_MS 5000 // a step running longer is logged every 5 s (before the kill)
#define KERNEL_WD_SHUTDOWN_MS 120000 // deadline for the kernel shutdown (deleting factories / nodes / threads)
#define EXIT_CODE_KERNEL_CLEAR 0 #define EXIT_CODE_KERNEL_CLEAR 0
#define EXIT_CODE_RELOAD_SERVICES 1 #define EXIT_CODE_RELOAD_SERVICES 1
@ -51,6 +70,24 @@ class kernelPrototype : public basicThread, public basicEventHandler
#ifdef LINUX_KERNEL_WATCHDOG #ifdef LINUX_KERNEL_WATCHDOG
int m_iWatchdogFd; int m_iWatchdogFd;
private:
std::thread * m_pWdThread;
std::atomic<bool> m_bWdRun;
std::atomic<uint64_t> m_nWdProgressMs; // last wdStep()
std::atomic<uint64_t> m_nWdStepStartMs; // start of the current step
std::atomic<const char *> m_pWdStep; // current step (string literal)
basicMutex m_mWdWrite;
void wdFeederProc(void);
protected:
bool wdSend(int64_t ms); // "ms\n" to the daemon (-1 = stop monitoring); false if not connected
void wdStart(void); // start the feeder thread (the kernel loop must call wdStep())
void wdStop(void); // stop feeding (the last deadline sent stays)
void wdStep(const char * step); // kernel loop progress: a new step begins (string literal!)
void wdExtend(uint32_t ms); // stop feeding and grant ms (e.g. for the shutdown)
#endif #endif
/* basic */ /* basic */
basicLogCollection * m_pLog; basicLogCollection * m_pLog;

41
lib/App/mojo/mojoKernel.cpp

@ -100,6 +100,11 @@ mojoKernel::mojoKernel(config_setting_t * ptr) :
mojoKernel::~mojoKernel() mojoKernel::~mojoKernel()
{ {
#ifdef LINUX_KERNEL_WATCHDOG
// Deleting the factories / nodes / threads takes longer than one feed period: grant the shutdown its
// own deadline instead of the last 4 s (the daemon killed la_mojo in the middle of a reload / exit)
wdExtend(KERNEL_WD_SHUTDOWN_MS);
#endif
WaitFinish(true); WaitFinish(true);
stopSession(false); stopSession(false);
@ -183,13 +188,7 @@ mojoKernel::~mojoKernel()
} }
#ifdef LINUX_KERNEL_WATCHDOG #ifdef LINUX_KERNEL_WATCHDOG
LOG("Disable WD!"); LOG("Disable WD!");
if (m_iWatchdogFd > -1)
{
char tB[64];
sprintf(tB, "-1\n");
// ToDo: Make Error Handling here!
write(m_iWatchdogFd, &tB, strlen(tB));
};
wdSend(-1); // MSG_NOSIGNAL: no SIGPIPE if the daemon is gone
LOG("WatchDog turned Off!"); LOG("WatchDog turned Off!");
#endif #endif
// Events broadcast while the components were deleted must not reach the next kernel (restart) // Events broadcast while the components were deleted must not reach the next kernel (restart)
@ -786,7 +785,14 @@ void mojoKernel::m_fThreadProc(void){
time_t tTimeTSeconds = 0; time_t tTimeTSeconds = 0;
m_bThreadStatus = TH_WORKING; m_bThreadStatus = TH_WORKING;
pthread_setname_np( pthread_self(), "Kernel" ); pthread_setname_np( pthread_self(), "Kernel" );
#ifdef LINUX_KERNEL_WATCHDOG
wdStart(); // the watchdog is fed by its own thread while this loop reports progress (wdStep)
#define KWD_STEP(X) wdStep(X)
#else
#define KWD_STEP(X)
#endif
while (m_bThreadStatus < TH_ENDED){ while (m_bThreadStatus < TH_ENDED){
KWD_STEP("idle");
m_tTimeTSeconds = time(NULL); m_tTimeTSeconds = time(NULL);
// Each Second // Each Second
if (m_tTimeTSeconds != tTimeTSeconds){ if (m_tTimeTSeconds != tTimeTSeconds){
@ -800,34 +806,33 @@ void mojoKernel::m_fThreadProc(void){
continue; continue;
}; };
}; };
#ifdef LINUX_KERNEL_WATCHDOG
if (m_iWatchdogFd > -1){
char tB[64];
sprintf(tB, "4000\n");
// ToDo: Make Error Handling here!
write(m_iWatchdogFd, &tB, strlen(tB));
};
#endif
KWD_STEP("debug mode");
m_bDebugMode = m_pDBC->getAppDebugMode(); m_bDebugMode = m_pDBC->getAppDebugMode();
KWD_STEP("validateFilters");
validateFilters(); validateFilters();
KWD_STEP("validateSession");
validateSession(); validateSession();
KWD_STEP("validateReports");
validateReports(); validateReports();
//??
KWD_STEP("hardwareManager::validate");
if (! m_pHardwareManager->validate()){ if (! m_pHardwareManager->validate()){
LOG("Reload Mojo Node Due to Memory Consumption!"); LOG("Reload Mojo Node Due to Memory Consumption!");
m_bThreadStatus = TH_ENDED; m_bThreadStatus = TH_ENDED;
setExitCause(EXIT_CODE_KERNEL_CLEAR); setExitCause(EXIT_CODE_KERNEL_CLEAR);
continue; continue;
}; };
KWD_STEP("updateSysInfo");
m_mSysInfoProtector.lock(); m_mSysInfoProtector.lock();
m_pHardwareManager->updateSysInfo(&m_sSysInfo); m_pHardwareManager->updateSysInfo(&m_sSysInfo);
m_mSysInfoProtector.unlock(); m_mSysInfoProtector.unlock();
#ifndef LRF_PROXY_ONLY #ifndef LRF_PROXY_ONLY
if ( m_pMediaHelper ) { if ( m_pMediaHelper ) {
KWD_STEP("mediaHelper::validateService");
m_pMediaHelper->validateService(); m_pMediaHelper->validateService();
}; };
#endif #endif
KWD_STEP("remote server");
if (m_sSiteData.use_remote_server){ if (m_sSiteData.use_remote_server){
if (m_pRPC){ if (m_pRPC){
m_pRPC->validate(); m_pRPC->validate();
@ -848,6 +853,7 @@ void mojoKernel::m_fThreadProc(void){
}; };
}; };
}; };
KWD_STEP("kernel commands");
DBC_PUSHED_CMD * tCMD = m_pDBC->getNodePushedCMD(m_nServerNodeID); // Kernel DBC_PUSHED_CMD * tCMD = m_pDBC->getNodePushedCMD(m_nServerNodeID); // Kernel
if (tCMD != NULL) { if (tCMD != NULL) {
m_pDBC->updateNodePushedCMD(tCMD->id, DBC_CMD_STARTED); m_pDBC->updateNodePushedCMD(tCMD->id, DBC_CMD_STARTED);
@ -1030,11 +1036,14 @@ void mojoKernel::m_fThreadProc(void){
free(tCMD); free(tCMD);
}; };
if ( m_pDBC ){ if ( m_pDBC ){
KWD_STEP("cleanNodePushedCMD");
m_pDBC->cleanNodePushedCMD(); m_pDBC->cleanNodePushedCMD();
} }
}; };
SLEEP(SLEEP_KERNEL_INTERVAL); SLEEP(SLEEP_KERNEL_INTERVAL);
}; };
KWD_STEP("exit"); // the destructor grants the shutdown its own deadline (wdExtend)
#undef KWD_STEP
} }
void mojoKernel::loadFilters() void mojoKernel::loadFilters()

Loading…
Cancel
Save