From a77f34253ad48bf3069e2e122c93e396a9cadbca Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 09:04:07 +0000 Subject: [PATCH] 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 '' for N s - watchdog no longer fed", and the daemon kills the process as before. - wdStep() logs steps slower than 1 s ("Kernel step '' took N ms"). The feeder logs a step that runs longer than 5 s every 5 s ("Kernel loop busy in '' 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 ''", then killed (137). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0139veDo3XyavMuVhdnHcN16 --- lib/App/common/kernelPrototype.cpp | 144 ++++++++++++++++++++++++++++- lib/App/common/kernelPrototype.h | 37 ++++++++ lib/App/mojo/mojoKernel.cpp | 41 ++++---- 3 files changed, 203 insertions(+), 19 deletions(-) diff --git a/lib/App/common/kernelPrototype.cpp b/lib/App/common/kernelPrototype.cpp index 5d0ad771..5659c1ed 100644 --- a/lib/App/common/kernelPrototype.cpp +++ b/lib/App/common/kernelPrototype.cpp @@ -14,6 +14,16 @@ kernelPrototype * kernelPrototype::_instance = NULL; +#ifdef LINUX_KERNEL_WATCHDOG + #include +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() { return _instance; @@ -25,7 +35,12 @@ kernelPrototype::kernelPrototype(config_setting_t * ptr) : { m_pLog = basicLogCollection::getInstance(); #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; int connection_result; @@ -39,6 +54,10 @@ kernelPrototype::kernelPrototype(config_setting_t * ptr) : if (connection_result == -1) { LOG_ERROR("WD Connection Error"); + if (m_iWatchdogFd > -1) + { + close(m_iWatchdogFd); // was leaked + }; m_iWatchdogFd = -1; }; if (m_iWatchdogFd < 0) @@ -63,8 +82,11 @@ kernelPrototype::kernelPrototype(config_setting_t * ptr) : char tB[64]; sprintf(tB, "%d\n", gettid()); 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 m_pSettings = basicSettingsProvider::getInstance()->getSubNode(ptr, "KERNEL"); @@ -89,6 +111,7 @@ kernelPrototype::kernelPrototype(config_setting_t * ptr) : kernelPrototype::~kernelPrototype() { #ifdef LINUX_KERNEL_WATCHDOG + wdStop(); LOG("Closing WD!"); if (! (m_iWatchdogFd < 0)) { @@ -98,6 +121,121 @@ kernelPrototype::~kernelPrototype() #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) { m_mWMProtector.lock(); diff --git a/lib/App/common/kernelPrototype.h b/lib/App/common/kernelPrototype.h index 66c11aed..29d10d00 100644 --- a/lib/App/common/kernelPrototype.h +++ b/lib/App/common/kernelPrototype.h @@ -28,7 +28,26 @@ #include #include #include + + #include + #include +#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 +#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_RELOAD_SERVICES 1 @@ -51,6 +70,24 @@ class kernelPrototype : public basicThread, public basicEventHandler #ifdef LINUX_KERNEL_WATCHDOG int m_iWatchdogFd; + + private: + + std::thread * m_pWdThread; + std::atomic m_bWdRun; + std::atomic m_nWdProgressMs; // last wdStep() + std::atomic m_nWdStepStartMs; // start of the current step + std::atomic 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 /* basic */ basicLogCollection * m_pLog; diff --git a/lib/App/mojo/mojoKernel.cpp b/lib/App/mojo/mojoKernel.cpp index f52aa753..4d2b81ee 100644 --- a/lib/App/mojo/mojoKernel.cpp +++ b/lib/App/mojo/mojoKernel.cpp @@ -100,6 +100,11 @@ mojoKernel::mojoKernel(config_setting_t * ptr) : 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); stopSession(false); @@ -183,13 +188,7 @@ mojoKernel::~mojoKernel() } #ifdef LINUX_KERNEL_WATCHDOG 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!"); #endif // 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; m_bThreadStatus = TH_WORKING; 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){ + KWD_STEP("idle"); m_tTimeTSeconds = time(NULL); // Each Second if (m_tTimeTSeconds != tTimeTSeconds){ @@ -800,34 +806,33 @@ void mojoKernel::m_fThreadProc(void){ 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(); + KWD_STEP("validateFilters"); validateFilters(); + KWD_STEP("validateSession"); validateSession(); + KWD_STEP("validateReports"); validateReports(); - //?? + KWD_STEP("hardwareManager::validate"); if (! m_pHardwareManager->validate()){ LOG("Reload Mojo Node Due to Memory Consumption!"); m_bThreadStatus = TH_ENDED; setExitCause(EXIT_CODE_KERNEL_CLEAR); continue; }; + KWD_STEP("updateSysInfo"); m_mSysInfoProtector.lock(); m_pHardwareManager->updateSysInfo(&m_sSysInfo); m_mSysInfoProtector.unlock(); #ifndef LRF_PROXY_ONLY if ( m_pMediaHelper ) { + KWD_STEP("mediaHelper::validateService"); m_pMediaHelper->validateService(); }; #endif + KWD_STEP("remote server"); if (m_sSiteData.use_remote_server){ if (m_pRPC){ 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 if (tCMD != NULL) { m_pDBC->updateNodePushedCMD(tCMD->id, DBC_CMD_STARTED); @@ -1030,11 +1036,14 @@ void mojoKernel::m_fThreadProc(void){ free(tCMD); }; if ( m_pDBC ){ + KWD_STEP("cleanNodePushedCMD"); m_pDBC->cleanNodePushedCMD(); } }; SLEEP(SLEEP_KERNEL_INTERVAL); }; + KWD_STEP("exit"); // the destructor grants the shutdown its own deadline (wdExtend) + #undef KWD_STEP } void mojoKernel::loadFilters()