la_serva: fix memory/descriptor leaks, crashes and a DB-log deadlock #15

Merged
ClaudeAI merged 1 commits from fix/la-serva-memory-leaks into master 24 minutes ago
Collaborator

Summary

Fixes the memory and descriptor leaks found in the la_serva review (Projects/la_serva, Debug86), plus crashes, memory corruption and a deadlock on the database log.

Leaks that grew without bound

  • Dead module connections were never removed.
    • What it cost: each one kept 3 threads, 8 MB of socket buffers, a descriptor, and a database poll every 10 ms.
    • Why it happened: a module that loses power or its network leaves a half-open TCP connection, and the socket never reports it.
    • Fix: servaRPCHadnler drops a connection that sends nothing for RPC_IDLE_TIMEOUT_S (60 s; la_mojo sends a status about every second). Accepted sockets also get TCP keepalive (30 s idle, 3 probes of 10 s).
  • Client socket never closed.
    • The bug: the socket was only closed on an I/O error. When a handler was removed for any other reason (module disabled or not registered, idle), its descriptor leaked.
    • The consequence: once accept() hit EMFILE, the accept thread ended for good.
    • Fixes:
      • ~serverPort shuts down and closes the socket;
      • temporary accept() errors (EMFILE, ENFILE, ENOMEM, ECONNABORTED, EINTR, and others) no longer stop the server;
      • recv() == 0 always counts as a disconnect.
  • Reopened sessions overwrote the active one. servaSessionManager::reopenSession stored the reopened (expired) session in the per-track map, overwriting the track's active session. The active session's data and open report.db leaked, and it was never closed in MySQL. Reopened sessions are now kept outside the map and released by the caller.
  • Composer: servaVideoComposer leaked its session data, an open SQLite connection and both video queues on every composition.
  • servaKernel:
    • leaked a composer whose compose() failed;
    • never initialised or released the automatic composer, so it ran at most once;
    • leaked the media-info record of every encoded video.

Crashes and corruption

  • Iterators: vector::erase() was followed by reuse of the old iterator in 7 loops: the network server, the encoder and composer pools, and 4 Modbus loops.
  • transportSocket::_close:
    • It wrote the stop byte to the read end of the pipe, so the I/O threads only stopped at the 5 s select timeout, which blocked the accept thread on every disconnect.
    • It left closed pipe numbers set, so a second close could write into another connection's descriptor.
  • Session map locking: a recursive mutex is now held for each whole public operation (RPC, kernel and Modbus threads use the map).
  • Freeze on the first MySQL error with database logging enabled.
    • The cause: Query() logs while holding the non-recursive DB mutex, and the log service wrote to the database synchronously. That deadlocks on the same thread and also between two threads.
    • Fix:
      • the log service queues lines (at most 1000) and writes them with the new MySQL_Connector::TrySilentQuery, which never blocks and never logs;
      • reconnect retries per query are limited to 3 instead of looping forever while holding the mutex;
      • the log-line parser skips the UTC offset.
  • basicMutex::try_lock returned true when the lock was not taken. An uncontended try_lock kept the mutex and the caller never released it. No try_lock call in la_mojo or la_serva is actually reached today (basicEngine::setWM only uses it with hard == false, which no caller passes). The fix matters for other users such as objectLGS, transportSerial, videoNode and basicVideoAnalyzer.
  • Kernel restart (web commands):
    • the Modbus singleton was deleted but not reset;
    • the remote client kept the deleted kernel and refused to start again;
    • EXIT_CODE_RELOAD_SERVICES deleted the database object that every surviving component still used. It is now kept.
  • Overflows and smaller bugs:
    • life monitoring overflowed module_id[4] for platforms with more than 4 modules;
    • registerServA overflowed a 120-byte stack buffer, closed a popen() stream with fclose, and leaked the config;
    • 9 config strings in servaBackend were allocated one byte short;
    • the video chunk length is now checked against the packet;
    • "eased" events copied every field from itself, so all fields were 0;
    • networkServer freed libconfig's host string.

Minor

  • The Modbus action list and the sessions are freed at shutdown.
  • The session-start event payload is freed if the event cannot be created.
  • The once-a-second "No History Auto Delete!" log line now only appears in DEBUG_EXTRA builds.

Testing

  • Compile check: all 46 Debug86 sources pass g++ -fsyntax-only. With -Wall, the changed files have no new warnings (servaKernel.cpp went from 16 to 12). The changed shared files still compile in la_mojo.
  • Network test against the real networkServer / serverPort / transportSocket classes, under AddressSanitizer (no findings):
Case Before After
Client closes normally handler removed after 3 s after 40 ms
Server rejects the client socket never closed client sees the close after 28 ms
Client goes silent never removed dropped by the idle timeout
50 connect/close cycles 4 descriptors and 1 thread leaked, 10 s back to baseline, 1.1 s
  • basicMutex::try_lock: checked free, held by another thread, and free again after unlock.
  • Not run: the session manager, the composer and the MySQL logging need MySQL and real report files. On the server:
    • watch /proc/<pid>/task and /proc/<pid>/fd over a day with module outages;
    • try a kernel restart from the web UI and a MySQL restart.

Behaviour changes

  • Silent modules: a module that sends nothing for 60 s is disconnected and has to reconnect.
  • "Reload services": the database object and its connection are kept. Database settings from the local config file now take effect only on a full restart of the program.

Generated with Claude Code

https://claude.ai/code/session_0139veDo3XyavMuVhdnHcN16

## Summary Fixes the memory and descriptor leaks found in the la_serva review (`Projects/la_serva`, `Debug86`), plus crashes, memory corruption and a deadlock on the database log. ## Leaks that grew without bound - **Dead module connections were never removed.** - **What it cost:** each one kept 3 threads, 8 MB of socket buffers, a descriptor, and a database poll every 10 ms. - **Why it happened:** a module that loses power or its network leaves a half-open TCP connection, and the socket never reports it. - **Fix:** `servaRPCHadnler` drops a connection that sends nothing for `RPC_IDLE_TIMEOUT_S` (60 s; la_mojo sends a status about every second). Accepted sockets also get TCP keepalive (30 s idle, 3 probes of 10 s). - **Client socket never closed.** - **The bug:** the socket was only closed on an I/O error. When a handler was removed for any other reason (module disabled or not registered, idle), its descriptor leaked. - **The consequence:** once `accept()` hit `EMFILE`, the accept thread ended for good. - **Fixes:** - `~serverPort` shuts down and closes the socket; - temporary `accept()` errors (`EMFILE`, `ENFILE`, `ENOMEM`, `ECONNABORTED`, `EINTR`, and others) no longer stop the server; - `recv() == 0` always counts as a disconnect. - **Reopened sessions overwrote the active one.** `servaSessionManager::reopenSession` stored the reopened (expired) session in the per-track map, overwriting the track's active session. The active session's data and open `report.db` leaked, and it was never closed in MySQL. Reopened sessions are now kept outside the map and released by the caller. - **Composer:** `servaVideoComposer` leaked its session data, an open SQLite connection and both video queues on every composition. - **`servaKernel`:** - leaked a composer whose `compose()` failed; - never initialised or released the automatic composer, so it ran at most once; - leaked the media-info record of every encoded video. ## Crashes and corruption - **Iterators:** `vector::erase()` was followed by reuse of the old iterator in 7 loops: the network server, the encoder and composer pools, and 4 Modbus loops. - **`transportSocket::_close`:** - It wrote the stop byte to the read end of the pipe, so the I/O threads only stopped at the 5 s `select` timeout, which blocked the accept thread on every disconnect. - It left closed pipe numbers set, so a second close could write into another connection's descriptor. - **Session map locking:** a recursive mutex is now held for each whole public operation (RPC, kernel and Modbus threads use the map). - **Freeze on the first MySQL error with database logging enabled.** - **The cause:** `Query()` logs while holding the non-recursive DB mutex, and the log service wrote to the database synchronously. That deadlocks on the same thread and also between two threads. - **Fix:** - the log service queues lines (at most 1000) and writes them with the new `MySQL_Connector::TrySilentQuery`, which never blocks and never logs; - reconnect retries per query are limited to 3 instead of looping forever while holding the mutex; - the log-line parser skips the UTC offset. - **`basicMutex::try_lock` returned true when the lock was not taken.** An uncontended `try_lock` kept the mutex and the caller never released it. No `try_lock` call in la_mojo or la_serva is actually reached today (`basicEngine::setWM` only uses it with `hard == false`, which no caller passes). The fix matters for other users such as `objectLGS`, `transportSerial`, `videoNode` and `basicVideoAnalyzer`. - **Kernel restart (web commands):** - the Modbus singleton was deleted but not reset; - the remote client kept the deleted kernel and refused to start again; - `EXIT_CODE_RELOAD_SERVICES` deleted the database object that every surviving component still used. It is now kept. - **Overflows and smaller bugs:** - life monitoring overflowed `module_id[4]` for platforms with more than 4 modules; - `registerServA` overflowed a 120-byte stack buffer, closed a `popen()` stream with `fclose`, and leaked the config; - 9 config strings in `servaBackend` were allocated one byte short; - the video chunk length is now checked against the packet; - "eased" events copied every field from itself, so all fields were 0; - `networkServer` freed libconfig's host string. ## Minor - The Modbus action list and the sessions are freed at shutdown. - The session-start event payload is freed if the event cannot be created. - The once-a-second "No History Auto Delete!" log line now only appears in `DEBUG_EXTRA` builds. ## Testing - **Compile check:** all 46 `Debug86` sources pass `g++ -fsyntax-only`. With `-Wall`, the changed files have no new warnings (`servaKernel.cpp` went from 16 to 12). The changed shared files still compile in la_mojo. - **Network test** against the real `networkServer` / `serverPort` / `transportSocket` classes, under AddressSanitizer (no findings): | Case | Before | After | |---|---|---| | Client closes normally | handler removed after 3 s | after 40 ms | | Server rejects the client | socket never closed | client sees the close after 28 ms | | Client goes silent | never removed | dropped by the idle timeout | | 50 connect/close cycles | 4 descriptors and 1 thread leaked, 10 s | back to baseline, 1.1 s | - **`basicMutex::try_lock`:** checked free, held by another thread, and free again after unlock. - **Not run:** the session manager, the composer and the MySQL logging need MySQL and real report files. On the server: - watch `/proc/<pid>/task` and `/proc/<pid>/fd` over a day with module outages; - try a kernel restart from the web UI and a MySQL restart. ## Behaviour changes - **Silent modules:** a module that sends nothing for 60 s is disconnected and has to reconnect. - **"Reload services":** the database object and its connection are kept. Database settings from the local config file now take effect only on a full restart of the program. Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_0139veDo3XyavMuVhdnHcN16
ClaudeAI added 1 commit 24 minutes ago
7a450b0c02
la_serva: fix memory/descriptor leaks, crashes and a DB-log deadlock
ClaudeAI merged commit 07d312e680 into master 24 minutes ago
The pull request has been merged as 07d312e680.
Sign in to join this conversation.
No reviewers
No Label
No Milestone
No project
No Assignees
1 Participants
Notifications
Due Date

No due date set.

Dependencies

This pull request currently doesn't have any dependencies.

Loading…
There is no content yet.