From a81bb8dc2c2d611dd77f981434b7dfbc8b6a39fc Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 01:30:39 +0000 Subject: [PATCH] Event heap: fix hangs on shutdown (signal / web exit) and dispatch deadlocks Why the shutdown could hang: the event heap was never stopped, and its thread called every handler's dispatchEvent() while holding the handler list mutex. ~mojoKernel deletes the node / module factories, filters, media helper ... - all of them event handlers - while the heap kept calling into them (half-destroyed objects, destroyed mutexes); the deleting thread then waited forever in removeHandler() for the mutex the dispatch thread held. A dispatchEvent() that created or deleted a handler deadlocked the dispatch thread itself (non-recursive mutex). basicEventHeap: - Handlers are called without the list locked (snapshot + "still registered" check per handler); removeHandler() waits until the handler is no longer being called (5 s cap, logged), except when called from that very dispatchEvent(). - New pause() / resume() / flush() / clearQueue() and destroyInstance() (stops the thread; leaves it alone if a handler is stuck instead of hanging); existingInstance(); getInstance() is thread-safe. basicEventHandler: - detachEvents(): stop delivery first thing in a destructor (the base destructor runs only after the derived members are gone); basicEventHandler(false) + attachEvents(): register at the end of the constructor (registration in the base constructor lets the heap call into an object whose members are not built yet). Defaults unchanged. - Removal never creates a new heap (late destructors after exit). la_mojo: - ~mojoKernel: deliver queued events (2 s), pause the heap before deleting the components, drop what was queued during the teardown; the next kernel (restart) resumes it. - mojoBackend: destroyInstance() before the log is deleted at exit. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0139veDo3XyavMuVhdnHcN16 --- lib/App/mojo/mojoBackend.cpp | 3 + lib/App/mojo/mojoKernel.cpp | 11 + lib/components/base/basicEventHandler.cpp | 26 +- lib/components/base/basicEventHandler.h | 16 +- lib/components/base/basicEventHeap.cpp | 302 +++++++++++++++++----- lib/components/base/basicEventHeap.h | 74 +++--- 6 files changed, 340 insertions(+), 92 deletions(-) diff --git a/lib/App/mojo/mojoBackend.cpp b/lib/App/mojo/mojoBackend.cpp index bea0ea0c..233120cf 100644 --- a/lib/App/mojo/mojoBackend.cpp +++ b/lib/App/mojo/mojoBackend.cpp @@ -648,6 +648,9 @@ int main(int argc, char * argv[]) unlink(gsCFG_PID_FILE); LOG("PID File Deleted"); + // Stop the event dispatch thread before the log (and the process) goes away; it was never stopped + basicEventHeap::destroyInstance(); + LOG("Event Heap Stopped"); delete(m_pLog); return 0; } diff --git a/lib/App/mojo/mojoKernel.cpp b/lib/App/mojo/mojoKernel.cpp index a3f0d2e2..f52aa753 100644 --- a/lib/App/mojo/mojoKernel.cpp +++ b/lib/App/mojo/mojoKernel.cpp @@ -64,6 +64,7 @@ mojoKernel::mojoKernel(config_setting_t * ptr) : kernelPrototype(ptr) { m_pEventHeap = basicEventHeap::getInstance(); + m_pEventHeap->resume(); // paused by the previous kernel's destructor (restart) memset(&m_sSysInfo, 0, sizeof(DBC_SYS_LOAD_INFO)); m_pShadow = NULL; m_pSystemAnchor = NULL; @@ -102,6 +103,14 @@ mojoKernel::~mojoKernel() WaitFinish(true); stopSession(false); + // Deliver what is queued (session end, ...), then stop dispatching BEFORE the components are + // deleted: every node / module / filter is an event handler, and the heap kept calling + // dispatchEvent() on objects being destroyed - the shutdown could hang (signal, web exit) + m_pEventHeap->flush(2000); + if (! m_pEventHeap->pause()) + { + LOG_ERROR("Event heap did not pause - a handler is stuck in dispatchEvent()"); + }; #ifndef LRF_PROXY_ONLY if ( m_pMediaHelper ) { delete( m_pMediaHelper ); @@ -183,6 +192,8 @@ mojoKernel::~mojoKernel() }; LOG("WatchDog turned Off!"); #endif + // Events broadcast while the components were deleted must not reach the next kernel (restart) + m_pEventHeap->clearQueue(); _instance = NULL; } diff --git a/lib/components/base/basicEventHandler.cpp b/lib/components/base/basicEventHandler.cpp index cb31a60b..73e5b3f0 100644 --- a/lib/components/base/basicEventHandler.cpp +++ b/lib/components/base/basicEventHandler.cpp @@ -5,11 +5,35 @@ // Constructor implementation basicEventHandler::basicEventHandler() { + m_bEventsAttached = false; + attachEvents(); +} + +basicEventHandler::basicEventHandler(bool attach) +{ + m_bEventsAttached = false; + if ( attach ) attachEvents(); +} + +void basicEventHandler::attachEvents(void) +{ + if ( m_bEventsAttached ) return; + m_bEventsAttached = true; basicEventHeap::getInstance()->addHandler( this, true ); } +void basicEventHandler::detachEvents(void) +{ + if ( ! m_bEventsAttached ) return; + m_bEventsAttached = false; + // Only an existing heap: after basicEventHeap::destroyInstance() (application exit) a late + // destructor must not create a new heap and dispatch thread + basicEventHeap * tHeap = basicEventHeap::existingInstance(); + if ( tHeap ) tHeap->removeHandler( this ); +} + // Destructor implementation basicEventHandler::~basicEventHandler() { - basicEventHeap::getInstance()->removeHandler( this ); + detachEvents(); } diff --git a/lib/components/base/basicEventHandler.h b/lib/components/base/basicEventHandler.h index f9ea7485..742ab20e 100644 --- a/lib/components/base/basicEventHandler.h +++ b/lib/components/base/basicEventHandler.h @@ -11,13 +11,27 @@ */ class basicEventHandler { + private: + + bool m_bEventsAttached; + public: - // Constructor + // Constructor: registers the object for events at once. The heap may then call dispatchEvent() + // before the derived constructors have built their members; a class whose dispatchEvent() uses + // its members can pass attach = false and call attachEvents() at the end of its own constructor. basicEventHandler(); + explicit basicEventHandler(bool attach); + void attachEvents(void); // Destructor virtual ~basicEventHandler(); + // Stops event delivery to this object (returns once a running dispatchEvent() finished). + // ~basicEventHandler does it too, but only after the derived destructors have destroyed their + // members - a class whose dispatchEvent() uses its members should call this first thing in its + // own destructor. Safe to call more than once. + void detachEvents(void); + virtual bool dispatchEvent(EVENT_CONTAINER * Evt) { if ( Evt == NULL ) return false; diff --git a/lib/components/base/basicEventHeap.cpp b/lib/components/base/basicEventHeap.cpp index 649c512b..639c4d3a 100644 --- a/lib/components/base/basicEventHeap.cpp +++ b/lib/components/base/basicEventHeap.cpp @@ -2,16 +2,21 @@ #include "basicEventHandler.h" +#include +#include + #define LOG(X) m_pLog->Log("basicEventHeap", this, X) #define LOG_ERROR(X) m_pLog->Log("basicEventHeap", this, _LOG_ERROR, X) basicEventHeap * basicEventHeap::_instance = 0; +std::mutex basicEventHeap::_instanceLock; /** * Returns the single instance of the object. */ basicEventHeap * basicEventHeap::getInstance() { + std::lock_guard tLock(_instanceLock); if (0 == _instance) { _instance = new basicEventHeap; @@ -19,100 +24,207 @@ basicEventHeap * basicEventHeap::getInstance() return _instance; } -void basicEventHeap::addHandler(basicEventHandler * handler, bool atBottom) +basicEventHeap * basicEventHeap::existingInstance() { - m_pHandlerMutex->lock(); - if( atBottom ) { - m_vHandlers.push_back( handler ); - } else { - m_vHandlers.insert( m_vHandlers.begin(), handler ); - }; - m_pHandlerMutex->unlock(); + std::lock_guard tLock(_instanceLock); + return _instance; } -void basicEventHeap::removeHandler(basicEventHandler * handler) +void basicEventHeap::destroyInstance() { - m_pHandlerMutex->lock(); - for (V_EVT_HANDLER::iterator idx = m_vHandlers.begin(); idx != m_vHandlers.end(); idx++) + if (existingInstance()) { - if ((*idx) == handler) + // A handler stuck in dispatchEvent(): deleting would wait for that thread forever (the + // basicThread destructor joins it) - leave the object to the process exit instead of hanging + if (! _instance->pause()) { - m_vHandlers.erase(idx); - break; + _instance->m_pLog->Log("basicEventHeap", _instance, _LOG_ERROR, "Dispatch thread does not stop - not waiting for it"); + return; }; + basicEventHeap * tHeap; + { + std::lock_guard tLock(_instanceLock); + tHeap = _instance; + _instance = 0; + } + delete (tHeap); }; - m_pHandlerMutex->unlock(); } -void basicEventHeap::moveHandlerBottom( basicEventHandler * handler ){ - m_pHandlerMutex->lock(); - for (V_EVT_HANDLER::iterator idx = m_vHandlers.begin(); idx != m_vHandlers.end(); idx++) +basicEventHeap::basicEventHeap() +{ + m_pLog = basicLogCollection::getInstance(); + m_pDispatchingMutex = new basicMutex(); + m_pCurrentHandler = NULL; + m_bPaused = false; + m_bInDispatch = false; + m_tDispatchThread = pthread_t(); + basicThread::init(); +} + +basicEventHeap::~basicEventHeap() +{ + pause(); + waitThreadEnd(true); + clearQueue(); { - if ((*idx) == handler) - { - m_vHandlers.erase(idx); - break; - }; + std::lock_guard tLock(m_mHandlers); + m_vHandlers.clear(); + } + delete (m_pDispatchingMutex); +} + +bool basicEventHeap::isDispatchThread(void) +{ + return (m_bThreadStatus >= TH_WORKING) && pthread_equal(pthread_self(), m_tDispatchThread); +} + +bool basicEventHeap::isRegistered(basicEventHandler * handler) +{ + return std::find(m_vHandlers.begin(), m_vHandlers.end(), handler) != m_vHandlers.end(); +} + +void basicEventHeap::addHandler(basicEventHandler * handler, bool atBottom) +{ + std::lock_guard tLock(m_mHandlers); + if (atBottom) + { + m_vHandlers.push_back(handler); + } + else + { + m_vHandlers.insert(m_vHandlers.begin(), handler); }; - m_vHandlers.push_back( handler ); - m_pHandlerMutex->unlock(); } -void basicEventHeap::moveHandlerTop( basicEventHandler * handler ){ - m_pHandlerMutex->lock(); - for (V_EVT_HANDLER::iterator idx = m_vHandlers.begin(); idx != m_vHandlers.end(); idx++) +/* + Called from ~basicEventHandler (any thread). Before, the dispatch thread held the handler list + locked while calling dispatchEvent(): a handler deleted from another thread (shutdown: ~mojoKernel + deleting the node / module factories) waited for that lock while the dispatch thread called into + the half-destroyed object - the shutdown hung; a dispatchEvent() that created or deleted a handler + deadlocked the dispatch thread itself (non-recursive mutex). + Now the list is not locked during dispatchEvent(): this waits until the handler is no longer being + called (unless called from that very call, which cannot be waited for). +*/ +void basicEventHeap::removeHandler(basicEventHandler * handler) +{ + std::unique_lock tLock(m_mHandlers); + V_EVT_HANDLER::iterator idx = std::find(m_vHandlers.begin(), m_vHandlers.end(), handler); + if (idx != m_vHandlers.end()) + { + m_vHandlers.erase(idx); + }; + if (m_pCurrentHandler == handler && ! isDispatchThread()) { - if ((*idx) == handler) + if (! m_cvDispatch.wait_for(tLock, std::chrono::milliseconds(EVENT_HEAP_WAIT_DISPATCH_MS), [&] { return m_pCurrentHandler != handler; })) { - m_vHandlers.erase(idx); - break; + LOG_ERROR("removeHandler: handler still busy in dispatchEvent() - continuing anyway"); }; }; - m_vHandlers.insert( m_vHandlers.begin(), handler ); - m_pHandlerMutex->unlock(); +} + +void basicEventHeap::moveHandlerBottom(basicEventHandler * handler) +{ + std::lock_guard tLock(m_mHandlers); + V_EVT_HANDLER::iterator idx = std::find(m_vHandlers.begin(), m_vHandlers.end(), handler); + if (idx != m_vHandlers.end()) + { + m_vHandlers.erase(idx); + }; + m_vHandlers.push_back(handler); +} + +void basicEventHeap::moveHandlerTop(basicEventHandler * handler) +{ + std::lock_guard tLock(m_mHandlers); + V_EVT_HANDLER::iterator idx = std::find(m_vHandlers.begin(), m_vHandlers.end(), handler); + if (idx != m_vHandlers.end()) + { + m_vHandlers.erase(idx); + }; + m_vHandlers.insert(m_vHandlers.begin(), handler); } void basicEventHeap::m_fThreadProc(void) { - basicEventHandler * mpHandler = NULL; - EVENT_CONTAINER * mpEvent = NULL; - m_bThreadStatus = TH_WORKING; - pthread_setname_np( pthread_self(), "EventHeap" ); + { + std::lock_guard tLock(m_mHandlers); + m_tDispatchThread = pthread_self(); + } + m_bThreadStatus = TH_WORKING; + pthread_setname_np(pthread_self(), "EventHeap"); while (m_bThreadStatus < TH_ENDED) { - if (m_bThreadStatus == TH_WORKING) + // Enter a dispatch round only while not paused (pause() waits for m_bInDispatch == false) + V_EVT_HANDLER tHandlers; { - mpEvent = NULL; - m_pDispatchingMutex->lock(); - if (! m_vEventQueue.empty()) + std::lock_guard tLock(m_mHandlers); + if (m_bPaused) { - mpEvent = m_vEventQueue.front(); - m_vEventQueue.pop(); + m_bInDispatch = false; + } + else + { + m_bInDispatch = true; + tHandlers = m_vHandlers; // snapshot: the list may change while handlers are called }; - m_pDispatchingMutex->unlock(); - if (mpEvent != NULL) + } + if (! m_bInDispatch) + { + SLEEP(1); + continue; + }; + EVENT_CONTAINER * mpEvent = NULL; + m_pDispatchingMutex->lock(); + if (! m_vEventQueue.empty()) + { + mpEvent = m_vEventQueue.front(); + m_vEventQueue.pop(); + }; + m_pDispatchingMutex->unlock(); + if (mpEvent != NULL) + { + for (V_EVT_HANDLER::iterator idx = tHandlers.begin(); idx != tHandlers.end(); idx++) { - m_pHandlerMutex->lock(); - for (V_EVT_HANDLER::iterator idx = m_vHandlers.begin(); idx < m_vHandlers.end(); idx++) + basicEventHandler * mpHandler = (*idx); { - mpHandler = (*idx); - if (mpHandler != NULL) + // skip handlers removed since the snapshot (they may be deleted already) + std::lock_guard tLock(m_mHandlers); + if (mpHandler == NULL || ! isRegistered(mpHandler)) { - if (! mpHandler->dispatchEvent(mpEvent)) - { - break; // Stop Propogation if false - } + continue; } - }; - m_pHandlerMutex->unlock(); - utilizeBasicEvent(mpEvent); - } - else - { - SLEEP(1); - } + m_pCurrentHandler = mpHandler; + } + bool tPropagate = mpHandler->dispatchEvent(mpEvent); + { + std::lock_guard tLock(m_mHandlers); + m_pCurrentHandler = NULL; + } + m_cvDispatch.notify_all(); // a removeHandler() may wait for this handler + if (! tPropagate) + { + break; // Stop Propogation if false + } + }; + utilizeBasicEvent(mpEvent); + }; + { + std::lock_guard tLock(m_mHandlers); + m_bInDispatch = false; + } + m_cvDispatch.notify_all(); // pause() may wait for the end of the round + if (mpEvent == NULL) + { + SLEEP(1); }; }; + { + std::lock_guard tLock(m_mHandlers); + m_bInDispatch = false; + m_pCurrentHandler = NULL; + } + m_cvDispatch.notify_all(); } void basicEventHeap::broadcast(EVENT_CONTAINER * Evt) @@ -125,5 +237,73 @@ void basicEventHeap::broadcast(EVENT_CONTAINER * Evt) }; } +bool basicEventHeap::flush(uint32_t timeoutMs) +{ + if (isDispatchThread()) + { + return false; // a handler cannot wait for its own dispatch + }; + uint32_t tWaited = 0; + while (tWaited < timeoutMs) + { + m_pDispatchingMutex->lock(); + bool tEmpty = m_vEventQueue.empty(); + m_pDispatchingMutex->unlock(); + if (tEmpty) + { + std::lock_guard tLock(m_mHandlers); + if (! m_bInDispatch || m_bPaused || m_bThreadStatus >= TH_ENDED) + { + return true; + } + }; + if (m_bPaused || m_bThreadStatus >= TH_ENDED) + { + return false; // nothing will be delivered + }; + SLEEP(5); + tWaited += 5; + }; + LOG_ERROR("flush: events still queued after the timeout"); + return false; +} + +bool basicEventHeap::pause(void) +{ + std::unique_lock tLock(m_mHandlers); + m_bPaused = true; + if (isDispatchThread() || m_bThreadStatus >= TH_ENDED) + { + return true; // the current round ends when the caller returns + }; + if (! m_cvDispatch.wait_for(tLock, std::chrono::milliseconds(EVENT_HEAP_WAIT_DISPATCH_MS), [&] { return ! m_bInDispatch; })) + { + LOG_ERROR("pause: a dispatchEvent() is still running - continuing anyway"); + return false; + }; + return true; +} + +void basicEventHeap::resume(void) +{ + std::lock_guard tLock(m_mHandlers); + m_bPaused = false; +} + +size_t basicEventHeap::clearQueue(void) +{ + size_t tCount = 0; + m_pDispatchingMutex->lock(); + while (! m_vEventQueue.empty()) + { + EVENT_CONTAINER * tEvt = m_vEventQueue.front(); + m_vEventQueue.pop(); + utilizeBasicEvent(tEvt); + tCount++; + }; + m_pDispatchingMutex->unlock(); + return tCount; +} + #undef LOG #undef LOG_ERROR diff --git a/lib/components/base/basicEventHeap.h b/lib/components/base/basicEventHeap.h index 34764859..e37c099a 100644 --- a/lib/components/base/basicEventHeap.h +++ b/lib/components/base/basicEventHeap.h @@ -7,11 +7,25 @@ #include "basicMutex.h" #include "basicThread.h" +#include +#include + typedef std::vector V_EVT_HANDLER; +// How long removeHandler() / pause() wait for a running dispatchEvent() before giving up (logged) +#define EVENT_HEAP_WAIT_DISPATCH_MS 5000 + /** * @Description Singleton class to manage Events in the System * + * Handlers are called WITHOUT the handler list locked, so a dispatchEvent() may create or delete + * handlers (add/removeHandler) and another thread may delete a handler while events are dispatched: + * removeHandler() returns only once the heap no longer calls that handler. + * + * Shutdown: pause() stops the dispatching (after the running dispatch finished) so objects can be + * deleted safely, resume() continues, clearQueue() drops what was not delivered, + * destroyInstance() stops the thread for good. + * * @author Gagua */ class basicEventHeap : public basicThread @@ -19,22 +33,44 @@ class basicEventHeap : public basicThread private: basicLogCollection * m_pLog; - basicMutex * m_pDispatchingMutex; - basicMutex * m_pHandlerMutex; - // EventHandlerRing *m_pRing; - V_EVT_HANDLER m_vHandlers; - pEventQueue m_vEventQueue; + basicMutex * m_pDispatchingMutex; // event queue + + std::mutex m_mHandlers; // m_vHandlers, m_pCurrentHandler, m_bPaused, m_bInDispatch + std::condition_variable m_cvDispatch; // signalled when a handler call or a dispatch round ends + V_EVT_HANDLER m_vHandlers; + basicEventHandler * m_pCurrentHandler; // handler being called right now (NULL if none) + bool m_bPaused; + bool m_bInDispatch; // an event is being dispatched + pthread_t m_tDispatchThread; + + pEventQueue m_vEventQueue; + + bool isDispatchThread(void); + bool isRegistered(basicEventHandler * handler); // m_mHandlers held public: static basicEventHeap * getInstance(); - + // The instance if it exists, NULL otherwise (never creates one) + static basicEventHeap * existingInstance(); + // Stops the dispatch thread and drops undelivered events (end of the application) + static void destroyInstance(); virtual ~basicEventHeap(); + void addHandler(basicEventHandler * handler, bool atBottom = false); void removeHandler(basicEventHandler * handler); void broadcast(EVENT_CONTAINER * Evt); - void moveHandlerBottom( basicEventHandler * handler ); - void moveHandlerTop( basicEventHandler * handler ); + void moveHandlerBottom(basicEventHandler * handler); + void moveHandlerTop(basicEventHandler * handler); + + // Waits (up to timeoutMs) until every queued event is delivered; false on timeout + bool flush(uint32_t timeoutMs = 2000); + // Stops dispatching; returns once the running dispatch round ended (false on timeout) + bool pause(void); + void resume(void); + // Releases all events still queued (not delivered); returns how many + size_t clearQueue(void); + protected: basicEventHeap(); @@ -43,27 +79,7 @@ class basicEventHeap : public basicThread private: static basicEventHeap * _instance; + static std::mutex _instanceLock; // getInstance() may be called from several threads at once }; -// Constructor implementation -inline basicEventHeap::basicEventHeap() -{ - m_pLog = basicLogCollection::getInstance(); - // m_pRing = new EventHandlerRing(); - m_pDispatchingMutex = new basicMutex(); - m_pHandlerMutex = new basicMutex(); - basicThread::init(); -} - -// Destructor implementation -inline basicEventHeap::~basicEventHeap() -{ - waitThreadEnd(true); - m_vHandlers.clear(); - // while (m_pRing->count) m_pRing->pop(); - // delete( m_pRing ); - delete(m_pDispatchingMutex); - delete(m_pHandlerMutex); -} - #endif // __BASICEVENTHEAP_H_INCL__ -- 2.39.5