 la_serva: fix memory/descriptor leaks, crashes and a DB-log deadlock
Leaks that grew without bound:
- Dead module connections were never removed (half-open TCP after a
module power loss / network drop): every one kept 3 threads, 8 MB of
socket buffers, a descriptor and a 10 ms DB poll. servaRPCHadnler now
drops a connection that sends nothing for RPC_IDLE_TIMEOUT_S (60 s;
la_mojo sends a status about every second), and accepted sockets get
TCP keepalive (30 s idle, 3 probes of 10 s).
- The client socket was only closed on an I/O error: a handler removed
for any other reason (module disabled / not registered, idle) leaked
its descriptor until accept() failed with EMFILE - which ended the
accept thread for good. ~serverPort now shuts down and closes it;
transient accept() errors (EMFILE, ENFILE, ENOMEM, ECONNABORTED,
EINTR, ...) no longer stop the server. recv() == 0 (peer closed) is
always a disconnect, whatever errno holds.
- servaSessionManager::reopenSession stored the reopened (expired)
session in the per-track map, overwriting the track's ACTIVE session:
its 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 (addVideo, getSessionBase).
- 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 / released the
automatic composer (it ran at most once) and leaked the media info
of every encoded video (processVideoFile success path).
Crashes / corruption:
- vector erase() with the old iterator reused (netServer client
cleanup, encoder / composer pools, 4 ModBus action loops).
- transportSocket::_close wrote the stop byte into the read end of the
pipe (threads only stopped at the 5 s select timeout, blocking the
accept thread on every disconnect) and left closed pipe numbers set
(a second _close could write into another connection's socket).
- Session map used without the lock from RPC, kernel and ModBus
threads: now a recursive mutex held for each public operation.
- Freeze on the first MySQL error with DB logging enabled: Query() logs
while holding the non-recursive DB mutex and the log service wrote
synchronously into the DB (same-thread and two-thread deadlock).
The DB log service now queues lines (max 1000) and writes them with
MySQL_Connector::TrySilentQuery (never blocks, never logs); reconnect
retries per query are bounded (3) instead of looping forever while
holding the mutex. The log line parser also skips the UTC offset.
- basicMutex::try_lock returned true when the lock was NOT taken: an
uncontended try_lock took the mutex and the caller never released it
(basicEngine, serial transport, ...).
- Kernel restart (web commands): the ModBus singleton was deleted but
not reset (next getInstance returned freed memory), the remote client
kept the deleted kernel and refused to start again, and
EXIT_CODE_RELOAD_SERVICES deleted the DB object every surviving
component still used. Now fixed / the DB object is kept.
- Life monitoring overflowed module_id[4] for platforms with > 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; video chunk length is now
checked against the packet; "eased" events copied every field from
itself (all 0); networkServer freed libconfig's host string.
Minor: ModBus action list / sessions freed at shutdown, session-start
event payload freed if the event cannot be created, the per-second
"No History Auto Delete!" log line moved to DEBUG_EXTRA.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0139veDo3XyavMuVhdnHcN16
44 minutes ago  la_serva: fix memory/descriptor leaks, crashes and a DB-log deadlock
Leaks that grew without bound:
- Dead module connections were never removed (half-open TCP after a
module power loss / network drop): every one kept 3 threads, 8 MB of
socket buffers, a descriptor and a 10 ms DB poll. servaRPCHadnler now
drops a connection that sends nothing for RPC_IDLE_TIMEOUT_S (60 s;
la_mojo sends a status about every second), and accepted sockets get
TCP keepalive (30 s idle, 3 probes of 10 s).
- The client socket was only closed on an I/O error: a handler removed
for any other reason (module disabled / not registered, idle) leaked
its descriptor until accept() failed with EMFILE - which ended the
accept thread for good. ~serverPort now shuts down and closes it;
transient accept() errors (EMFILE, ENFILE, ENOMEM, ECONNABORTED,
EINTR, ...) no longer stop the server. recv() == 0 (peer closed) is
always a disconnect, whatever errno holds.
- servaSessionManager::reopenSession stored the reopened (expired)
session in the per-track map, overwriting the track's ACTIVE session:
its 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 (addVideo, getSessionBase).
- 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 / released the
automatic composer (it ran at most once) and leaked the media info
of every encoded video (processVideoFile success path).
Crashes / corruption:
- vector erase() with the old iterator reused (netServer client
cleanup, encoder / composer pools, 4 ModBus action loops).
- transportSocket::_close wrote the stop byte into the read end of the
pipe (threads only stopped at the 5 s select timeout, blocking the
accept thread on every disconnect) and left closed pipe numbers set
(a second _close could write into another connection's socket).
- Session map used without the lock from RPC, kernel and ModBus
threads: now a recursive mutex held for each public operation.
- Freeze on the first MySQL error with DB logging enabled: Query() logs
while holding the non-recursive DB mutex and the log service wrote
synchronously into the DB (same-thread and two-thread deadlock).
The DB log service now queues lines (max 1000) and writes them with
MySQL_Connector::TrySilentQuery (never blocks, never logs); reconnect
retries per query are bounded (3) instead of looping forever while
holding the mutex. The log line parser also skips the UTC offset.
- basicMutex::try_lock returned true when the lock was NOT taken: an
uncontended try_lock took the mutex and the caller never released it
(basicEngine, serial transport, ...).
- Kernel restart (web commands): the ModBus singleton was deleted but
not reset (next getInstance returned freed memory), the remote client
kept the deleted kernel and refused to start again, and
EXIT_CODE_RELOAD_SERVICES deleted the DB object every surviving
component still used. Now fixed / the DB object is kept.
- Life monitoring overflowed module_id[4] for platforms with > 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; video chunk length is now
checked against the packet; "eased" events copied every field from
itself (all 0); networkServer freed libconfig's host string.
Minor: ModBus action list / sessions freed at shutdown, session-start
event payload freed if the event cannot be created, the per-second
"No History Auto Delete!" log line moved to DEBUG_EXTRA.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0139veDo3XyavMuVhdnHcN16
44 minutes ago  la_serva: fix memory/descriptor leaks, crashes and a DB-log deadlock
Leaks that grew without bound:
- Dead module connections were never removed (half-open TCP after a
module power loss / network drop): every one kept 3 threads, 8 MB of
socket buffers, a descriptor and a 10 ms DB poll. servaRPCHadnler now
drops a connection that sends nothing for RPC_IDLE_TIMEOUT_S (60 s;
la_mojo sends a status about every second), and accepted sockets get
TCP keepalive (30 s idle, 3 probes of 10 s).
- The client socket was only closed on an I/O error: a handler removed
for any other reason (module disabled / not registered, idle) leaked
its descriptor until accept() failed with EMFILE - which ended the
accept thread for good. ~serverPort now shuts down and closes it;
transient accept() errors (EMFILE, ENFILE, ENOMEM, ECONNABORTED,
EINTR, ...) no longer stop the server. recv() == 0 (peer closed) is
always a disconnect, whatever errno holds.
- servaSessionManager::reopenSession stored the reopened (expired)
session in the per-track map, overwriting the track's ACTIVE session:
its 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 (addVideo, getSessionBase).
- 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 / released the
automatic composer (it ran at most once) and leaked the media info
of every encoded video (processVideoFile success path).
Crashes / corruption:
- vector erase() with the old iterator reused (netServer client
cleanup, encoder / composer pools, 4 ModBus action loops).
- transportSocket::_close wrote the stop byte into the read end of the
pipe (threads only stopped at the 5 s select timeout, blocking the
accept thread on every disconnect) and left closed pipe numbers set
(a second _close could write into another connection's socket).
- Session map used without the lock from RPC, kernel and ModBus
threads: now a recursive mutex held for each public operation.
- Freeze on the first MySQL error with DB logging enabled: Query() logs
while holding the non-recursive DB mutex and the log service wrote
synchronously into the DB (same-thread and two-thread deadlock).
The DB log service now queues lines (max 1000) and writes them with
MySQL_Connector::TrySilentQuery (never blocks, never logs); reconnect
retries per query are bounded (3) instead of looping forever while
holding the mutex. The log line parser also skips the UTC offset.
- basicMutex::try_lock returned true when the lock was NOT taken: an
uncontended try_lock took the mutex and the caller never released it
(basicEngine, serial transport, ...).
- Kernel restart (web commands): the ModBus singleton was deleted but
not reset (next getInstance returned freed memory), the remote client
kept the deleted kernel and refused to start again, and
EXIT_CODE_RELOAD_SERVICES deleted the DB object every surviving
component still used. Now fixed / the DB object is kept.
- Life monitoring overflowed module_id[4] for platforms with > 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; video chunk length is now
checked against the packet; "eased" events copied every field from
itself (all 0); networkServer freed libconfig's host string.
Minor: ModBus action list / sessions freed at shutdown, session-start
event payload freed if the event cannot be created, the per-second
"No History Auto Delete!" log line moved to DEBUG_EXTRA.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0139veDo3XyavMuVhdnHcN16
44 minutes ago  la_serva: fix memory/descriptor leaks, crashes and a DB-log deadlock
Leaks that grew without bound:
- Dead module connections were never removed (half-open TCP after a
module power loss / network drop): every one kept 3 threads, 8 MB of
socket buffers, a descriptor and a 10 ms DB poll. servaRPCHadnler now
drops a connection that sends nothing for RPC_IDLE_TIMEOUT_S (60 s;
la_mojo sends a status about every second), and accepted sockets get
TCP keepalive (30 s idle, 3 probes of 10 s).
- The client socket was only closed on an I/O error: a handler removed
for any other reason (module disabled / not registered, idle) leaked
its descriptor until accept() failed with EMFILE - which ended the
accept thread for good. ~serverPort now shuts down and closes it;
transient accept() errors (EMFILE, ENFILE, ENOMEM, ECONNABORTED,
EINTR, ...) no longer stop the server. recv() == 0 (peer closed) is
always a disconnect, whatever errno holds.
- servaSessionManager::reopenSession stored the reopened (expired)
session in the per-track map, overwriting the track's ACTIVE session:
its 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 (addVideo, getSessionBase).
- 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 / released the
automatic composer (it ran at most once) and leaked the media info
of every encoded video (processVideoFile success path).
Crashes / corruption:
- vector erase() with the old iterator reused (netServer client
cleanup, encoder / composer pools, 4 ModBus action loops).
- transportSocket::_close wrote the stop byte into the read end of the
pipe (threads only stopped at the 5 s select timeout, blocking the
accept thread on every disconnect) and left closed pipe numbers set
(a second _close could write into another connection's socket).
- Session map used without the lock from RPC, kernel and ModBus
threads: now a recursive mutex held for each public operation.
- Freeze on the first MySQL error with DB logging enabled: Query() logs
while holding the non-recursive DB mutex and the log service wrote
synchronously into the DB (same-thread and two-thread deadlock).
The DB log service now queues lines (max 1000) and writes them with
MySQL_Connector::TrySilentQuery (never blocks, never logs); reconnect
retries per query are bounded (3) instead of looping forever while
holding the mutex. The log line parser also skips the UTC offset.
- basicMutex::try_lock returned true when the lock was NOT taken: an
uncontended try_lock took the mutex and the caller never released it
(basicEngine, serial transport, ...).
- Kernel restart (web commands): the ModBus singleton was deleted but
not reset (next getInstance returned freed memory), the remote client
kept the deleted kernel and refused to start again, and
EXIT_CODE_RELOAD_SERVICES deleted the DB object every surviving
component still used. Now fixed / the DB object is kept.
- Life monitoring overflowed module_id[4] for platforms with > 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; video chunk length is now
checked against the packet; "eased" events copied every field from
itself (all 0); networkServer freed libconfig's host string.
Minor: ModBus action list / sessions freed at shutdown, session-start
event payload freed if the event cannot be created, the per-second
"No History Auto Delete!" log line moved to DEBUG_EXTRA.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0139veDo3XyavMuVhdnHcN16
44 minutes ago  la_serva: fix memory/descriptor leaks, crashes and a DB-log deadlock
Leaks that grew without bound:
- Dead module connections were never removed (half-open TCP after a
module power loss / network drop): every one kept 3 threads, 8 MB of
socket buffers, a descriptor and a 10 ms DB poll. servaRPCHadnler now
drops a connection that sends nothing for RPC_IDLE_TIMEOUT_S (60 s;
la_mojo sends a status about every second), and accepted sockets get
TCP keepalive (30 s idle, 3 probes of 10 s).
- The client socket was only closed on an I/O error: a handler removed
for any other reason (module disabled / not registered, idle) leaked
its descriptor until accept() failed with EMFILE - which ended the
accept thread for good. ~serverPort now shuts down and closes it;
transient accept() errors (EMFILE, ENFILE, ENOMEM, ECONNABORTED,
EINTR, ...) no longer stop the server. recv() == 0 (peer closed) is
always a disconnect, whatever errno holds.
- servaSessionManager::reopenSession stored the reopened (expired)
session in the per-track map, overwriting the track's ACTIVE session:
its 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 (addVideo, getSessionBase).
- 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 / released the
automatic composer (it ran at most once) and leaked the media info
of every encoded video (processVideoFile success path).
Crashes / corruption:
- vector erase() with the old iterator reused (netServer client
cleanup, encoder / composer pools, 4 ModBus action loops).
- transportSocket::_close wrote the stop byte into the read end of the
pipe (threads only stopped at the 5 s select timeout, blocking the
accept thread on every disconnect) and left closed pipe numbers set
(a second _close could write into another connection's socket).
- Session map used without the lock from RPC, kernel and ModBus
threads: now a recursive mutex held for each public operation.
- Freeze on the first MySQL error with DB logging enabled: Query() logs
while holding the non-recursive DB mutex and the log service wrote
synchronously into the DB (same-thread and two-thread deadlock).
The DB log service now queues lines (max 1000) and writes them with
MySQL_Connector::TrySilentQuery (never blocks, never logs); reconnect
retries per query are bounded (3) instead of looping forever while
holding the mutex. The log line parser also skips the UTC offset.
- basicMutex::try_lock returned true when the lock was NOT taken: an
uncontended try_lock took the mutex and the caller never released it
(basicEngine, serial transport, ...).
- Kernel restart (web commands): the ModBus singleton was deleted but
not reset (next getInstance returned freed memory), the remote client
kept the deleted kernel and refused to start again, and
EXIT_CODE_RELOAD_SERVICES deleted the DB object every surviving
component still used. Now fixed / the DB object is kept.
- Life monitoring overflowed module_id[4] for platforms with > 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; video chunk length is now
checked against the packet; "eased" events copied every field from
itself (all 0); networkServer freed libconfig's host string.
Minor: ModBus action list / sessions freed at shutdown, session-start
event payload freed if the event cannot be created, the per-second
"No History Auto Delete!" log line moved to DEBUG_EXTRA.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0139veDo3XyavMuVhdnHcN16
44 minutes ago  la_serva: fix memory/descriptor leaks, crashes and a DB-log deadlock
Leaks that grew without bound:
- Dead module connections were never removed (half-open TCP after a
module power loss / network drop): every one kept 3 threads, 8 MB of
socket buffers, a descriptor and a 10 ms DB poll. servaRPCHadnler now
drops a connection that sends nothing for RPC_IDLE_TIMEOUT_S (60 s;
la_mojo sends a status about every second), and accepted sockets get
TCP keepalive (30 s idle, 3 probes of 10 s).
- The client socket was only closed on an I/O error: a handler removed
for any other reason (module disabled / not registered, idle) leaked
its descriptor until accept() failed with EMFILE - which ended the
accept thread for good. ~serverPort now shuts down and closes it;
transient accept() errors (EMFILE, ENFILE, ENOMEM, ECONNABORTED,
EINTR, ...) no longer stop the server. recv() == 0 (peer closed) is
always a disconnect, whatever errno holds.
- servaSessionManager::reopenSession stored the reopened (expired)
session in the per-track map, overwriting the track's ACTIVE session:
its 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 (addVideo, getSessionBase).
- 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 / released the
automatic composer (it ran at most once) and leaked the media info
of every encoded video (processVideoFile success path).
Crashes / corruption:
- vector erase() with the old iterator reused (netServer client
cleanup, encoder / composer pools, 4 ModBus action loops).
- transportSocket::_close wrote the stop byte into the read end of the
pipe (threads only stopped at the 5 s select timeout, blocking the
accept thread on every disconnect) and left closed pipe numbers set
(a second _close could write into another connection's socket).
- Session map used without the lock from RPC, kernel and ModBus
threads: now a recursive mutex held for each public operation.
- Freeze on the first MySQL error with DB logging enabled: Query() logs
while holding the non-recursive DB mutex and the log service wrote
synchronously into the DB (same-thread and two-thread deadlock).
The DB log service now queues lines (max 1000) and writes them with
MySQL_Connector::TrySilentQuery (never blocks, never logs); reconnect
retries per query are bounded (3) instead of looping forever while
holding the mutex. The log line parser also skips the UTC offset.
- basicMutex::try_lock returned true when the lock was NOT taken: an
uncontended try_lock took the mutex and the caller never released it
(basicEngine, serial transport, ...).
- Kernel restart (web commands): the ModBus singleton was deleted but
not reset (next getInstance returned freed memory), the remote client
kept the deleted kernel and refused to start again, and
EXIT_CODE_RELOAD_SERVICES deleted the DB object every surviving
component still used. Now fixed / the DB object is kept.
- Life monitoring overflowed module_id[4] for platforms with > 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; video chunk length is now
checked against the packet; "eased" events copied every field from
itself (all 0); networkServer freed libconfig's host string.
Minor: ModBus action list / sessions freed at shutdown, session-start
event payload freed if the event cannot be created, the per-second
"No History Auto Delete!" log line moved to DEBUG_EXTRA.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0139veDo3XyavMuVhdnHcN16
44 minutes ago  la_serva: fix memory/descriptor leaks, crashes and a DB-log deadlock
Leaks that grew without bound:
- Dead module connections were never removed (half-open TCP after a
module power loss / network drop): every one kept 3 threads, 8 MB of
socket buffers, a descriptor and a 10 ms DB poll. servaRPCHadnler now
drops a connection that sends nothing for RPC_IDLE_TIMEOUT_S (60 s;
la_mojo sends a status about every second), and accepted sockets get
TCP keepalive (30 s idle, 3 probes of 10 s).
- The client socket was only closed on an I/O error: a handler removed
for any other reason (module disabled / not registered, idle) leaked
its descriptor until accept() failed with EMFILE - which ended the
accept thread for good. ~serverPort now shuts down and closes it;
transient accept() errors (EMFILE, ENFILE, ENOMEM, ECONNABORTED,
EINTR, ...) no longer stop the server. recv() == 0 (peer closed) is
always a disconnect, whatever errno holds.
- servaSessionManager::reopenSession stored the reopened (expired)
session in the per-track map, overwriting the track's ACTIVE session:
its 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 (addVideo, getSessionBase).
- 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 / released the
automatic composer (it ran at most once) and leaked the media info
of every encoded video (processVideoFile success path).
Crashes / corruption:
- vector erase() with the old iterator reused (netServer client
cleanup, encoder / composer pools, 4 ModBus action loops).
- transportSocket::_close wrote the stop byte into the read end of the
pipe (threads only stopped at the 5 s select timeout, blocking the
accept thread on every disconnect) and left closed pipe numbers set
(a second _close could write into another connection's socket).
- Session map used without the lock from RPC, kernel and ModBus
threads: now a recursive mutex held for each public operation.
- Freeze on the first MySQL error with DB logging enabled: Query() logs
while holding the non-recursive DB mutex and the log service wrote
synchronously into the DB (same-thread and two-thread deadlock).
The DB log service now queues lines (max 1000) and writes them with
MySQL_Connector::TrySilentQuery (never blocks, never logs); reconnect
retries per query are bounded (3) instead of looping forever while
holding the mutex. The log line parser also skips the UTC offset.
- basicMutex::try_lock returned true when the lock was NOT taken: an
uncontended try_lock took the mutex and the caller never released it
(basicEngine, serial transport, ...).
- Kernel restart (web commands): the ModBus singleton was deleted but
not reset (next getInstance returned freed memory), the remote client
kept the deleted kernel and refused to start again, and
EXIT_CODE_RELOAD_SERVICES deleted the DB object every surviving
component still used. Now fixed / the DB object is kept.
- Life monitoring overflowed module_id[4] for platforms with > 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; video chunk length is now
checked against the packet; "eased" events copied every field from
itself (all 0); networkServer freed libconfig's host string.
Minor: ModBus action list / sessions freed at shutdown, session-start
event payload freed if the event cannot be created, the per-second
"No History Auto Delete!" log line moved to DEBUG_EXTRA.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0139veDo3XyavMuVhdnHcN16
44 minutes ago  la_serva: fix memory/descriptor leaks, crashes and a DB-log deadlock
Leaks that grew without bound:
- Dead module connections were never removed (half-open TCP after a
module power loss / network drop): every one kept 3 threads, 8 MB of
socket buffers, a descriptor and a 10 ms DB poll. servaRPCHadnler now
drops a connection that sends nothing for RPC_IDLE_TIMEOUT_S (60 s;
la_mojo sends a status about every second), and accepted sockets get
TCP keepalive (30 s idle, 3 probes of 10 s).
- The client socket was only closed on an I/O error: a handler removed
for any other reason (module disabled / not registered, idle) leaked
its descriptor until accept() failed with EMFILE - which ended the
accept thread for good. ~serverPort now shuts down and closes it;
transient accept() errors (EMFILE, ENFILE, ENOMEM, ECONNABORTED,
EINTR, ...) no longer stop the server. recv() == 0 (peer closed) is
always a disconnect, whatever errno holds.
- servaSessionManager::reopenSession stored the reopened (expired)
session in the per-track map, overwriting the track's ACTIVE session:
its 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 (addVideo, getSessionBase).
- 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 / released the
automatic composer (it ran at most once) and leaked the media info
of every encoded video (processVideoFile success path).
Crashes / corruption:
- vector erase() with the old iterator reused (netServer client
cleanup, encoder / composer pools, 4 ModBus action loops).
- transportSocket::_close wrote the stop byte into the read end of the
pipe (threads only stopped at the 5 s select timeout, blocking the
accept thread on every disconnect) and left closed pipe numbers set
(a second _close could write into another connection's socket).
- Session map used without the lock from RPC, kernel and ModBus
threads: now a recursive mutex held for each public operation.
- Freeze on the first MySQL error with DB logging enabled: Query() logs
while holding the non-recursive DB mutex and the log service wrote
synchronously into the DB (same-thread and two-thread deadlock).
The DB log service now queues lines (max 1000) and writes them with
MySQL_Connector::TrySilentQuery (never blocks, never logs); reconnect
retries per query are bounded (3) instead of looping forever while
holding the mutex. The log line parser also skips the UTC offset.
- basicMutex::try_lock returned true when the lock was NOT taken: an
uncontended try_lock took the mutex and the caller never released it
(basicEngine, serial transport, ...).
- Kernel restart (web commands): the ModBus singleton was deleted but
not reset (next getInstance returned freed memory), the remote client
kept the deleted kernel and refused to start again, and
EXIT_CODE_RELOAD_SERVICES deleted the DB object every surviving
component still used. Now fixed / the DB object is kept.
- Life monitoring overflowed module_id[4] for platforms with > 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; video chunk length is now
checked against the packet; "eased" events copied every field from
itself (all 0); networkServer freed libconfig's host string.
Minor: ModBus action list / sessions freed at shutdown, session-start
event payload freed if the event cannot be created, the per-second
"No History Auto Delete!" log line moved to DEBUG_EXTRA.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0139veDo3XyavMuVhdnHcN16
44 minutes ago  la_serva: fix memory/descriptor leaks, crashes and a DB-log deadlock
Leaks that grew without bound:
- Dead module connections were never removed (half-open TCP after a
module power loss / network drop): every one kept 3 threads, 8 MB of
socket buffers, a descriptor and a 10 ms DB poll. servaRPCHadnler now
drops a connection that sends nothing for RPC_IDLE_TIMEOUT_S (60 s;
la_mojo sends a status about every second), and accepted sockets get
TCP keepalive (30 s idle, 3 probes of 10 s).
- The client socket was only closed on an I/O error: a handler removed
for any other reason (module disabled / not registered, idle) leaked
its descriptor until accept() failed with EMFILE - which ended the
accept thread for good. ~serverPort now shuts down and closes it;
transient accept() errors (EMFILE, ENFILE, ENOMEM, ECONNABORTED,
EINTR, ...) no longer stop the server. recv() == 0 (peer closed) is
always a disconnect, whatever errno holds.
- servaSessionManager::reopenSession stored the reopened (expired)
session in the per-track map, overwriting the track's ACTIVE session:
its 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 (addVideo, getSessionBase).
- 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 / released the
automatic composer (it ran at most once) and leaked the media info
of every encoded video (processVideoFile success path).
Crashes / corruption:
- vector erase() with the old iterator reused (netServer client
cleanup, encoder / composer pools, 4 ModBus action loops).
- transportSocket::_close wrote the stop byte into the read end of the
pipe (threads only stopped at the 5 s select timeout, blocking the
accept thread on every disconnect) and left closed pipe numbers set
(a second _close could write into another connection's socket).
- Session map used without the lock from RPC, kernel and ModBus
threads: now a recursive mutex held for each public operation.
- Freeze on the first MySQL error with DB logging enabled: Query() logs
while holding the non-recursive DB mutex and the log service wrote
synchronously into the DB (same-thread and two-thread deadlock).
The DB log service now queues lines (max 1000) and writes them with
MySQL_Connector::TrySilentQuery (never blocks, never logs); reconnect
retries per query are bounded (3) instead of looping forever while
holding the mutex. The log line parser also skips the UTC offset.
- basicMutex::try_lock returned true when the lock was NOT taken: an
uncontended try_lock took the mutex and the caller never released it
(basicEngine, serial transport, ...).
- Kernel restart (web commands): the ModBus singleton was deleted but
not reset (next getInstance returned freed memory), the remote client
kept the deleted kernel and refused to start again, and
EXIT_CODE_RELOAD_SERVICES deleted the DB object every surviving
component still used. Now fixed / the DB object is kept.
- Life monitoring overflowed module_id[4] for platforms with > 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; video chunk length is now
checked against the packet; "eased" events copied every field from
itself (all 0); networkServer freed libconfig's host string.
Minor: ModBus action list / sessions freed at shutdown, session-start
event payload freed if the event cannot be created, the per-second
"No History Auto Delete!" log line moved to DEBUG_EXTRA.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0139veDo3XyavMuVhdnHcN16
44 minutes ago |
|
#include "servaRemoteClientHandler.h"
#include "servaRemoteClient.h"
#include "servaKernel.h"
#define LOG( X ) m_pLog->Log( "RPCH", this, X )
#ifdef DEBUG
#define LOG_ERROR( X ) {\
char _tBfrErrMSG234[256];\ sprintf( _tBfrErrMSG234, "In file %s[%d] in func:%s %s",__FILE__, __LINE__, __func__, X );\ m_pLog->Log( "RPCH", this, _LOG_ERROR, _tBfrErrMSG234 );\ }#else
#define LOG_ERROR( X ) m_pLog->Log( "RPCH", this, _LOG_ERROR, X );
#endif
servaRPCHadnler::servaRPCHadnler( int SocketFD, networkServiceEngine *ptr ):basicThread(),networkClientHandler( SocketFD, ptr ),protocolParser(){ m_pEngine = ptr; m_pMaster = (servaRemoteClient *)ptr; m_pLog = basicLogCollection::getInstance(); m_dMojoDBID = 0; m_dTrackDBID = 0; m_nInbondSerial = 0; m_nOutbondSerial = 0; m_dSessionDBID = 0; m_bClientStructsArePacked = true; // Hope the Client as We are
m_bTrainOnTrack = false; m_tLastRx = time( NULL ); memset( m_cRemoteIP, 0, sizeof( m_cRemoteIP ) ); memset( m_cRemoteIdentity, 0, sizeof( m_cRemoteIdentity ) ); m_nPreTrainCloudStatus = m_nCloudStatus = ARGUS_CLOUD_STATUS_NA; m_pDBC = servaMySQLDBC::getInstance(); m_pSM = servaSessionManager::getInstance(); m_pEventHeap = basicEventHeap::getInstance(); m_pPort = new serverPort( SocketFD ); if ( m_pPort ) { if ( m_pPort->create() ) { setTransport(m_pPort); init(); } else { delete( m_pPort ); m_pPort = NULL; }; };};
bool servaRPCHadnler::setTrainPresense( bool st ){ if( m_dSessionDBID ){ //m_pSM->setTrainStatus( m_dSessionDBID, st );
}; if( !st && ( m_nPreTrainCloudStatus != ARGUS_CLOUD_STATUS_NA ) ){ m_nCloudStatus = m_nPreTrainCloudStatus; } else { m_nPreTrainCloudStatus = m_nCloudStatus; m_nCloudStatus = ARGUS_CLOUD_STATUS_TRAIN; }; return m_pDBC->setCloudStatus(ARGUS_OBJECT_MODULE, m_dMojoDBID, m_nCloudStatus );};
servaRPCHadnler::~servaRPCHadnler(){ waitThreadEnd( true ); if( m_pPort ) delete( m_pPort );};
bool servaRPCHadnler::attachEngine( networkServiceEngine *ptr ){ m_pEngine = ptr; m_pMaster = (servaRemoteClient *) ptr; return true;};
bool servaRPCHadnler::dispatchEvent( EVENT_CONTAINER *Evt ){ //LOG("EVT");
return true;};
bool servaRPCHadnler::getStatus( void ){ if ( m_pPort ) { if( getConnectionStatus() != CS_DISCONNECTED ) return true; }; return false;};
bool servaRPCHadnler::setRemotePeerIP( CSTR ptr ){ if ( ptr == NULL ) return false;#ifdef DEBUG
char tB[64]; sprintf(tB,"Remote Peer: %s", ptr ); LOG( tB );#endif
strncpy( m_cRemoteIP, ptr, sizeof( m_cRemoteIP ) - 1 ); m_cRemoteIP[sizeof( m_cRemoteIP ) - 1] = (char)0; return true;};
/********************PROTOCOL**************************/
int servaRPCHadnler::packetChecker( U8 *Buffer, size_t BufferSize ){ char tB[64]; if ( Buffer[0] == ARGUS_START_CLIENT_FLAG ) { if( BufferSize > ARGUS_DATA_MSG_MIN_SIZE ){ uint32_t SIZE = Buffer[5]; SIZE = ( SIZE << 8 ) | Buffer[6]; SIZE = ( SIZE << 8 ) | Buffer[7]; SIZE = ( SIZE << 8 ) | Buffer[8]; if ( ( SIZE + ARGUS_HEADER_SIZE + ARGUS_CHECKSUM_SIZE ) <= BufferSize ) { uint16_t tCRC = checksum16( Buffer, SIZE + ARGUS_HEADER_SIZE ); uint16_t cCRC = Buffer[SIZE + ARGUS_HEADER_SIZE]; cCRC = ( cCRC << 8 ) | Buffer[SIZE + ARGUS_HEADER_SIZE+1]; if ( tCRC == cCRC ) return 0; } else return 1; // to grou
} else return 1; //to grow
}; return -1; // to skip
};
protocolPackage *servaRPCHadnler::packetExtractor(U8 *Buffer, size_t BufferSize){ protocolPackage *tPack = (protocolPackage*) malloc( sizeof(protocolPackage)); if ( tPack ) { tPack->m_nCode = Buffer[ARGUS_HEADER_SIZE]; tPack->m_nSize = Buffer[5]; tPack->m_nSize = ( tPack->m_nSize << 8 ) | Buffer[6]; tPack->m_nSize = ( tPack->m_nSize << 8 ) | Buffer[7]; tPack->m_nSize = ( tPack->m_nSize << 8 ) | Buffer[8]; tPack->m_nSize = tPack->m_nSize + ARGUS_HEADER_SIZE + ARGUS_CHECKSUM_SIZE; tPack->m_pData = (U8 *) malloc( tPack->m_nSize ); if ( tPack->m_pData ) { memcpy( tPack->m_pData, Buffer, tPack->m_nSize ); } else { free( tPack ); tPack = NULL; }; }; return tPack;};
bool servaRPCHadnler::packetHandler( protocolPackage *Package ){ m_tLastRx = time( NULL ); // the peer is alive
m_nInbondSerial = Package->m_pData[1]; m_nInbondSerial = ( m_nInbondSerial << 8 ) | Package->m_pData[2]; m_nInbondSerial = ( m_nInbondSerial << 8 ) | Package->m_pData[3]; m_nInbondSerial = ( m_nInbondSerial << 8 ) | Package->m_pData[4];#ifdef DEBUG_EXTRA
char bB[129]; sprintf(bB, "Code: %02X PackSize: %d", Package->m_nCode, Package->m_nSize ); LOG( bB );#endif
switch( Package->m_nCode ){ case ARGUS_DATA_MSG_REGISTER:{ if ( Package->m_nSize == ARGUS_RPC_REG_V1_SIZE ) {#ifdef DEBUG
LOG("Old Type Registration!");#endif
m_bClientStructsArePacked = false; //Old Clients - No packed Structs
//Only Identity Transfered
strncpy( m_cRemoteIdentity, (char*)(Package->m_pData + ARGUS_PAYLOAD_START), 32 ); } else { ARGUS_DATA_MOJO_REGISTRATION *tM = (ARGUS_DATA_MOJO_REGISTRATION *)(Package->m_pData + ARGUS_PAYLOAD_START); //To Have ability connect via tonel IPv4 address transfered also
strncpy( m_cRemoteIdentity, tM->identity, 32); strncpy( m_cRemoteIP, tM->peer, 22); }; m_cRemoteIdentity[32] = (char)0;#ifdef DEBUG
char tB[128]; sprintf(tB,"Registration request from[%s][%s]", m_cRemoteIP, m_cRemoteIdentity ); LOG(tB);#endif
m_dMojoDBID = m_pMaster->requestMojoRegistration( m_cRemoteIP, m_cRemoteIdentity ); if ( m_dMojoDBID ) { char WM = m_pMaster->getMojoWorkMode( m_dMojoDBID ); if ( WM == 'E') { m_dTrackDBID = m_pDBC->getTrackIdByMojo( m_dMojoDBID );#ifdef DEBUG
sprintf(tB,"Module:[%" PRIu64 "] Track:[%" PRIu64 "]", m_dMojoDBID, m_dTrackDBID ); LOG(tB);#endif
m_mCloudProtector.lock(); m_nCloudStatus = ARGUS_CLOUD_STATUS_ONLINE; m_mCloudProtector.unlock(); m_pDBC->setCloudStatus( ARGUS_OBJECT_MODULE, m_dMojoDBID, ARGUS_CLOUD_STATUS_REG ); DBC_REG_MODULE_DATA tData = {0}; tData.id = m_dMojoDBID; tData.track_id = m_dTrackDBID; peer_send_reg_ack( &tData ); } else {#ifdef DEBUG
LOG("Module is Disabled!");#endif
peer_send_byte_status( ARGUS_DATA_MSG_DISABLED ); setConnectionStatus( CS_DISCONNECTED ); }; } else {#ifdef DEBUG
LOG("Module Not Registered with System");#endif
peer_send_byte_status( ARGUS_DATA_MSG_ACCESS_DENIED ); setConnectionStatus( CS_DISCONNECTED ); }; break; }; case ARGUS_DATA_MSG_INFO:{ size_t tSize = sizeof( ARGUS_DATA_MOJO_INFO ) + ARGUS_PAYLOAD_START + ARGUS_CHECKSUM_SIZE; if( Package->m_nSize != tSize ) { m_bClientStructsArePacked = false; ARGUS_DATA_MOJO_INFO_EASED *tINFO = (ARGUS_DATA_MOJO_INFO_EASED *) (Package->m_pData+ARGUS_PAYLOAD_START);#ifdef DEBUG
LOG("Module Info Received!"); char tB[128]; sprintf( tB, "Upper Sensor Node: %d", tINFO->UPPER_ID ); LOG( tB ); sprintf( tB, "Bottom Sensor Node: %d", tINFO->BOTTOM_ID ); LOG( tB ); sprintf( tB, "Camera Node: %d", tINFO->CAM_ID); LOG( tB ); sprintf( tB, "Camera Stream ID: %d", tINFO->CAM_STREAM_ID ); LOG( tB ); //for ( uint8_t i = 0; i < Package->m_nSize; i++ ) {
// if ( Package->m_pData[i] > 31 && Package->m_pData[i] < 128 ) {
// sprintf(tB, "Data[%d]: 0x%02X [%c]", i, Package->m_pData[i], (char)Package->m_pData[i] );
// } else {
// sprintf(tB, "Data[%d]: 0x%02X", i, Package->m_pData[i] );
// }
// LOG( tB );
//};
#endif
//ToDo: Module SW must wait to register onto Server untill all Nodes are loadded
if( tINFO->CAM_ID == 0 ) { tINFO->CAM_ID = 4; LOG_ERROR( "Wrong Camrea Info From Module[1]!"); }; m_pDBC->updateModuleData( m_dMojoDBID, tINFO->UPPER_ID, tINFO->BOTTOM_ID, tINFO->CAM_ID, tINFO->CAM_STREAM_ID, tINFO->TLS_VERSION, tINFO->LLS_VERSION ); } else { ARGUS_DATA_MOJO_INFO *tINFO = (ARGUS_DATA_MOJO_INFO *) (Package->m_pData+ARGUS_PAYLOAD_START);#ifdef DEBUG
LOG("Module Info Received!"); char tB[128]; sprintf( tB, "Upper Sensor Node: %d", tINFO->UPPER_ID ); LOG( tB ); sprintf( tB, "Bottom Sensor Node: %d", tINFO->BOTTOM_ID ); LOG( tB ); sprintf( tB, "Camera Node: %d", tINFO->CAM_ID); LOG( tB ); sprintf( tB, "Camera Stream ID: %d", tINFO->CAM_STREAM_ID ); LOG( tB ); //for ( uint8_t i = 0; i < Package->m_nSize; i++ ) {
// if ( Package->m_pData[i] > 31 && Package->m_pData[i] < 128 ) {
// sprintf(tB, "Data[%d]: 0x%02X [%c]", i, Package->m_pData[i], (char)Package->m_pData[i] );
// } else {
// sprintf(tB, "Data[%d]: 0x%02X", i, Package->m_pData[i] );
// }
// LOG( tB );
//};
#endif
//ToDo: Module SW must wait to register onto Server untill all Nodes are loadded
if( tINFO->CAM_ID == 0 ) { tINFO->CAM_ID = 4; LOG_ERROR( "Wrong Camrea Info From Module[2]!"); }; m_pDBC->updateModuleData( m_dMojoDBID, tINFO->UPPER_ID, tINFO->BOTTOM_ID, tINFO->CAM_ID, tINFO->CAM_STREAM_ID, tINFO->TLS_VERSION, tINFO->LLS_VERSION ); }; peer_send_byte_status( ARGUS_DATA_MSG_INFO ); break; }; case ARGUS_DATA_MSG_KEEP_ALIVE: case ARGUS_DATA_MSG_STAT:{ size_t tSize = sizeof( ARGUS_DATA_MOJO_STATUS ) + ARGUS_PAYLOAD_START + ARGUS_CHECKSUM_SIZE; if( Package->m_nSize != tSize ) { m_bClientStructsArePacked = false; ARGUS_DATA_MOJO_STATUS_EASED *tSTATUS = (ARGUS_DATA_MOJO_STATUS_EASED *)(Package->m_pData + ARGUS_PAYLOAD_START); m_mCloudProtector.lock();
m_nCloudStatus = ( tSTATUS->STATUSES.system == SYSTEM_STATUS_NA )?ARGUS_CLOUD_STATUS_NA:0; m_nCloudStatus |= (( tSTATUS->STATUSES.system & SYSTEM_STATUS_TRAIN ) == 0 )?ARGUS_CLOUD_STATUS_TRAIN:0; m_nCloudStatus |= ( tSTATUS->CPU_LOAD > 95 )?ARGUS_CLOUD_STATUS_E_CPU:0; m_nCloudStatus |= ( tSTATUS->CPU_TEMP > 95 )?ARGUS_CLOUD_STATUS_E_TEMPERATURE:0; m_nCloudStatus |= ( tSTATUS->MEMO_UTI > 95 )?ARGUS_CLOUD_STATUS_E_MEM:0; m_nCloudStatus |= ( tSTATUS->DISK_UTI > 95 )?ARGUS_CLOUD_STATUS_E_DISK:0;
m_nCloudStatus |= ( tSTATUS->STATUSES.camera == CAMERA_STATUS_NA )?ARGUS_CLOUD_STATUS_E_CAM_GENERIC:0; m_nCloudStatus |= (( tSTATUS->STATUSES.camera & CAMERA_STATUS_OK ) == 0 )?ARGUS_CLOUD_STATUS_E_CAM_NC:0; m_nCloudStatus |= (( tSTATUS->STATUSES.camera & CAMERA_STATUS_STREAM_OK ) == 0 )?ARGUS_CLOUD_STATUS_E_CAM_NIM:0; m_nCloudStatus |= (( tSTATUS->STATUSES.camera & CAMERA_STATUS_PTZ_OK ) == 0 )?ARGUS_CLOUD_STATUS_E_CAM_NPTZ:0;
m_nCloudStatus |= ( tSTATUS->STATUSES.b_sensor == SENOR_STATUS_NA )?ARGUS_CLOUD_STATUS_E_SEN_GENERIC:0; m_nCloudStatus |= ( tSTATUS->STATUSES.b_sensor == SENOR_STATUS_CONNECTING )?ARGUS_CLOUD_STATUS_E_BS_NC:0; m_nCloudStatus |= ( tSTATUS->STATUSES.b_sensor == SENOR_STATUS_DETECTION_ERR )?ARGUS_CLOUD_STATUS_E_BS_LRF:0;
m_nCloudStatus |= ( tSTATUS->STATUSES.u_sensor == SENOR_STATUS_NA )?ARGUS_CLOUD_STATUS_E_SEN_GENERIC:0; m_nCloudStatus |= ( tSTATUS->STATUSES.u_sensor == SENOR_STATUS_CONNECTING )?ARGUS_CLOUD_STATUS_E_US_NC:0; m_nCloudStatus |= ( tSTATUS->STATUSES.u_sensor == SENOR_STATUS_DETECTION_ERR )?ARGUS_CLOUD_STATUS_E_US_LRF:0;
m_mCloudProtector.unlock(); } else { ARGUS_DATA_MOJO_STATUS *tSTATUS = (ARGUS_DATA_MOJO_STATUS *)(Package->m_pData + ARGUS_PAYLOAD_START); m_mCloudProtector.lock();
m_nCloudStatus = ( tSTATUS->STATUSES.system == SYSTEM_STATUS_NA )?ARGUS_CLOUD_STATUS_NA:0; m_nCloudStatus |= (( tSTATUS->STATUSES.system & SYSTEM_STATUS_TRAIN ) == 0 )?ARGUS_CLOUD_STATUS_TRAIN:0; m_nCloudStatus |= ( tSTATUS->CPU_LOAD > 95 )?ARGUS_CLOUD_STATUS_E_CPU:0; m_nCloudStatus |= ( tSTATUS->CPU_TEMP > 95 )?ARGUS_CLOUD_STATUS_E_TEMPERATURE:0; m_nCloudStatus |= ( tSTATUS->MEMO_UTI > 95 )?ARGUS_CLOUD_STATUS_E_MEM:0; m_nCloudStatus |= ( tSTATUS->DISK_UTI > 95 )?ARGUS_CLOUD_STATUS_E_DISK:0;
m_nCloudStatus |= ( tSTATUS->STATUSES.camera == CAMERA_STATUS_NA )?ARGUS_CLOUD_STATUS_E_CAM_GENERIC:0; m_nCloudStatus |= (( tSTATUS->STATUSES.camera & CAMERA_STATUS_OK ) == 0 )?ARGUS_CLOUD_STATUS_E_CAM_NC:0; m_nCloudStatus |= (( tSTATUS->STATUSES.camera & CAMERA_STATUS_STREAM_OK ) == 0 )?ARGUS_CLOUD_STATUS_E_CAM_NIM:0; m_nCloudStatus |= (( tSTATUS->STATUSES.camera & CAMERA_STATUS_PTZ_OK ) == 0 )?ARGUS_CLOUD_STATUS_E_CAM_NPTZ:0;
m_nCloudStatus |= ( tSTATUS->STATUSES.b_sensor == SENOR_STATUS_NA )?ARGUS_CLOUD_STATUS_E_SEN_GENERIC:0; m_nCloudStatus |= ( tSTATUS->STATUSES.b_sensor == SENOR_STATUS_CONNECTING )?ARGUS_CLOUD_STATUS_E_BS_NC:0; m_nCloudStatus |= ( tSTATUS->STATUSES.b_sensor == SENOR_STATUS_DETECTION_ERR )?ARGUS_CLOUD_STATUS_E_BS_LRF:0;
m_nCloudStatus |= ( tSTATUS->STATUSES.u_sensor == SENOR_STATUS_NA )?ARGUS_CLOUD_STATUS_E_SEN_GENERIC:0; m_nCloudStatus |= ( tSTATUS->STATUSES.u_sensor == SENOR_STATUS_CONNECTING )?ARGUS_CLOUD_STATUS_E_US_NC:0; m_nCloudStatus |= ( tSTATUS->STATUSES.u_sensor == SENOR_STATUS_DETECTION_ERR )?ARGUS_CLOUD_STATUS_E_US_LRF:0;
m_mCloudProtector.unlock(); }; peer_send_byte_status( ARGUS_DATA_MSG_STAT ); break; }; case ARGUS_DATA_MSG_EVT:{ peer_send_byte_status( ARGUS_DATA_MSG_EVT ); // make instant ACK to module
size_t tSize = sizeof( ARGUS_DATA_EVENT ) + ARGUS_PAYLOAD_START + ARGUS_CHECKSUM_SIZE; ARGUS_DATA_EVENT tData = {0}; if( Package->m_nSize != tSize ){ m_bClientStructsArePacked = false; ARGUS_DATA_EVENT_EASED *tPtr = (ARGUS_DATA_EVENT_EASED *) (Package->m_pData+ARGUS_PAYLOAD_START); // was tData.X = tData.X: every field except AREA stayed 0
tData.AREA = tPtr->AREA; tData.AZIMUTH = tPtr->AZIMUTH; tData.ELEVATION = tPtr->ELEVATION; tData.MODULE_ID = tPtr->MODULE_ID; tData.MS = tPtr->MS; tData.RANGE = tPtr->RANGE; tData.REF_ID = tPtr->REF_ID; tData.SRC = tPtr->SRC; tData.TS = tPtr->TS; tData.TYPE = tPtr->TYPE; memcpy( tData.UUID, tPtr->UUID, sizeof( tData.UUID ) ); } else { memcpy( &tData, Package->m_pData+ARGUS_PAYLOAD_START, sizeof(ARGUS_DATA_EVENT) ); }; switch ( tData.TYPE ) { case EVT_ROI_ACTIVE: case EVT_TARGET_3D_WHITE: case EVT_TARGET_3D_BLACK: case EVT_TARGET_2D_WHITE: case EVT_TARGET_2D_BLACK:{#ifdef DEBUG_EXTRA
char tB[128]; sprintf(tB, "EVT[%d] SRC[%d] %d.%d", tData.TYPE, tData.SRC, tData.TS, tData.MS ); LOG( tB ); sprintf(tB, "AZ[%d] RANGE[%d] ELV[%d] AREA[%d]", tData.AZIMUTH, tData.RANGE, tData.ELEVATION, tData.AREA ); LOG( tB ); strncpy( tB, tData.UUID, 64 ); tB[64] = (char)0; LOG( tB );#endif
tData.MODULE_ID = m_dMojoDBID; if ( m_dSessionDBID ) { if ( m_pSM->validateSession( m_dSessionDBID ) ) { m_pSM->addEvent( m_dSessionDBID, &tData ); } else { m_dSessionDBID = m_pSM->addEvent( m_dTrackDBID, m_dMojoDBID, &tData ); }; } else { m_dSessionDBID = m_pSM->addEvent( m_dTrackDBID, m_dMojoDBID, &tData ); }; break; }; case EVT_FLT_LATF_TRP_DET: case EVT_FLT_LATF_TRP_UPDT: case EVT_FLT_LATF_OP_TD:{ // Train Presence
setTrainPresense( TRAIN_ON_TRACK ); break; }; case EVT_FLT_LATF_TRP_EXP:{ //Train is Gone
setTrainPresense( TRAIN_IS_GONE ); break; }; }; break; }; case ARGUS_DATA_MSG_REQ_TIME_SYNC:{ peer_send_byte_status( ARGUS_DATA_MSG_REQ_TIME_SYNC ); break; }; case ARGUS_DATA_MSG_TIME_SYNC:{#ifdef DEBUG_EXTRA
LOG( "Time Synchronization Request" );#endif
ARGUS_DATA_TIME_SYNC_REQ *tTSR = ( ARGUS_DATA_TIME_SYNC_REQ *) (Package->m_pData+ARGUS_PAYLOAD_START); ARGUS_DATA_TIME_SYNC_ACK tTSA; tTSA.STS = tTSR->STS; tTSA.ATS = getMilliseconds(); peer_send_time_sync_ack( &tTSA ); break; }; case ARGUS_DATA_MSG_VIDEO_INFO:{#ifdef DEBUG
LOG( "Received Video Record Info" );#endif
m_pVideoHelper.clear(); CSTR BASE = m_pSM->getSessionBase( m_dSessionDBID ); if( BASE ){ ARGUS_DATA_VIDEO_INFO tData = {0}; size_t tSize = sizeof( ARGUS_DATA_VIDEO_INFO ) + ARGUS_PAYLOAD_START + ARGUS_CHECKSUM_SIZE; if( Package->m_nSize != tSize ){ m_bClientStructsArePacked = false; ARGUS_DATA_VIDEO_INFO_EASED *tPtr = (ARGUS_DATA_VIDEO_INFO_EASED *)(Package->m_pData + ARGUS_PAYLOAD_START); tData.DATA_SIZE = tPtr->DATA_SIZE; tData.DMS = tPtr->DMS; tData.DTS = tPtr->DTS; strncpy( tData.FMT, tPtr->FMT, 6 ); tData.FPS = tPtr->FPS; tData.HEIGHT = tPtr->HEIGHT; tData.REF_ID = tPtr->REF_ID; tData.WIDTH = tPtr->WIDTH; } else { memcpy( &tData, Package->m_pData + ARGUS_PAYLOAD_START, sizeof( ARGUS_DATA_VIDEO_INFO )); }; if (m_pVideoHelper.init( BASE, m_dMojoDBID, m_dSessionDBID, &tData )) { LOG("Helper Init Ok"); peer_send_vinfo_ack( m_pVideoHelper.getReferenceID() ); } else { LOG("Helper Init Failure"); peer_send_vinfo_ack( 0 ); }; free( BASE ); } else { LOG("Helper Init Failure (NO SESSION)"); peer_send_vinfo_ack( 0 ); }; break; }; case ARGUS_DATA_MSG_VIDEO_DATA:{ // payload after the message code, without the checksum
size_t tAvail = ( Package->m_nSize > ARGUS_HEADER_SIZE + 1 + ARGUS_CHECKSUM_SIZE ) ? Package->m_nSize - ARGUS_HEADER_SIZE - 1 - ARGUS_CHECKSUM_SIZE : 0; uint32_t tt = m_pVideoHelper.saveNextChunk( Package->m_pData+ARGUS_HEADER_SIZE+1, tAvail );#ifdef DEBUG_EXTRA
char tK[128]; sprintf( tK, "Saved %d Bytes of Video!", tt ); LOG( tK );#endif
peer_send_vdata_ack( tt ); break; }; case ARGUS_DATA_MSG_RESTART_SW:{ LOG("Module Restarts control Software"); break; }; case ARGUS_DATA_MSG_RESTART_PLATFORM:{ LOG("Module Restart HOST OS"); break; }; }; return true;};
void servaRPCHadnler::m_fThreadProc( void ){ time_t tTimeTSeconds = 0; time_t cTimeTSeconds = 0; uint32_t tSecondsCounter = 0;
m_bThreadStatus = TH_WORKING;#ifdef DEBUG
LOG("Connector Thread Started");#endif
pthread_setname_np( pthread_self(), "RPC Handler" ); while ( m_bThreadStatus < TH_ENDED ) { // seconds Counter (for internal purposes)
cTimeTSeconds = time( NULL ); //Process each second
if ( cTimeTSeconds != tTimeTSeconds ) { tSecondsCounter++; tTimeTSeconds = cTimeTSeconds; // Dead connection: mark it disconnected, the network server then removes this handler
// (and ~serverPort closes the socket)
if ( ( cTimeTSeconds - m_tLastRx ) > RPC_IDLE_TIMEOUT_S && getConnectionStatus() != CS_DISCONNECTED ) { char tB[160]; snprintf( tB, sizeof( tB ), "No data from [%s][%s] for %d s - dropping the connection", m_cRemoteIP, m_cRemoteIdentity, RPC_IDLE_TIMEOUT_S ); LOG_ERROR( tB ); setConnectionStatus( CS_DISCONNECTED ); }; // update clowd status
m_mCloudProtector.lock(); m_pDBC->setCloudStatus( ARGUS_OBJECT_MODULE, m_dMojoDBID, m_nCloudStatus ); m_mCloudProtector.unlock(); }; DBC_RPC_WEB_CMD *tCMD = m_pDBC->fetchWebCmd( m_dMojoDBID ); if ( tCMD ) { //LOG( "Have Web CMD!");
//To Do -> Check with EASED Structs in Proto
ARGUS_DATA_RPC RPC_PACK; RPC_PACK.CMD = tCMD->cmd; RPC_PACK.NODE_ID = tCMD->aux_id; strncpy( RPC_PACK.DATA, tCMD->param, 64 ); //if( peer_send_rpc( &RPC_PACK ) ) m_pDBC->updateWebCmdStatus( tCMD->id, 200 ); // Set Finished
if( peer_send_rpc( &RPC_PACK ) ) m_pDBC->removeWebCmd( tCMD->id ); // Instant Clear
free( tCMD ); }; SLEEP(DEFAULT_THREAD_SLEEP_TIME); };#ifdef DEBUG_EXTRA
LOG("Connector Thread Ended!");#endif
};
bool servaRPCHadnler::peer_send_vdata_ack( uint8_t status ){ uint8_t Buffer[64]; Buffer[ARGUS_HEADER_SIZE] = ARGUS_DATA_MSG_VIDEO_DATA; Buffer[ARGUS_HEADER_SIZE+1] = status; m_nOutbondSerial++; return m_pPort->sendData( Buffer, argus_rpc_finishupPackage( Buffer, m_nOutbondSerial, ARGUS_HEADER_SIZE+2 ) );};
bool servaRPCHadnler::peer_send_vinfo_ack( uint64_t pid ){ uint8_t Buffer[64]; Buffer[ARGUS_HEADER_SIZE] = ARGUS_DATA_MSG_VIDEO_INFO; Buffer[ARGUS_HEADER_SIZE+1] = ( pid >> 56 ) & 0xff; Buffer[ARGUS_HEADER_SIZE+2] = ( pid >> 48 ) & 0xff; Buffer[ARGUS_HEADER_SIZE+3] = ( pid >> 40 ) & 0xff; Buffer[ARGUS_HEADER_SIZE+4] = ( pid >> 32 ) & 0xff; Buffer[ARGUS_HEADER_SIZE+5] = ( pid >> 24 ) & 0xff; Buffer[ARGUS_HEADER_SIZE+6] = ( pid >> 16 ) & 0xff; Buffer[ARGUS_HEADER_SIZE+7] = ( pid >> 8 ) & 0xff; Buffer[ARGUS_HEADER_SIZE+8] = pid & 0xff; m_nOutbondSerial++; return m_pPort->sendData( Buffer, argus_rpc_finishupPackage( Buffer, m_nOutbondSerial, ARGUS_HEADER_SIZE+9 ) );};
bool servaRPCHadnler::peer_send_byte_status( uint8_t status ){ uint8_t Buffer[64]; Buffer[ARGUS_HEADER_SIZE] = status; m_nOutbondSerial++; return m_pPort->sendData( Buffer, argus_rpc_finishupPackage( Buffer, m_nOutbondSerial, ARGUS_HEADER_SIZE+1 ) );};
bool servaRPCHadnler::peer_send_reg_ack( DBC_REG_MODULE_DATA *ptr ){ if ( ptr == NULL ) { return peer_send_byte_status( ARGUS_DATA_MSG_ACCESS_DENIED ); } else { uint8_t tBuffer[128]; tBuffer[ARGUS_HEADER_SIZE] = ARGUS_DATA_MSG_REGISTER; m_nOutbondSerial++; uint16_t i = 0; for(; i < sizeof(DBC_REG_MODULE_DATA); i++) tBuffer[ARGUS_HEADER_SIZE+1+i] = ((uint8_t*)ptr)[i]; return m_pPort->sendData(tBuffer, argus_rpc_finishupPackage(tBuffer, m_nOutbondSerial, ARGUS_HEADER_SIZE+1+i )); }};
bool servaRPCHadnler::peer_send_req_draw( uint8_t sensor, uint8_t draw_type, bool getexisted ){ if ( sensor == ARGUS_RPC_MOJO_ITSELF ) return false; uint8_t Buffer[64]; Buffer[ARGUS_HEADER_SIZE] = ARGUS_DATA_MSG_GET_DRAW; Buffer[ARGUS_HEADER_SIZE+1] = sensor; if( !getexisted ) { Buffer[ARGUS_HEADER_SIZE+2] = draw_type | 0x80; } else { Buffer[ARGUS_HEADER_SIZE+2] = draw_type; }; return m_pPort->sendData( Buffer, argus_rpc_finishupPackage( Buffer, m_nOutbondSerial, ARGUS_HEADER_SIZE+3 ) );};
bool servaRPCHadnler::peer_send_ack_evt( uint64_t evt_dbid, CSTR uuid ){ uint8_t Buffer[128]; Buffer[ARGUS_HEADER_SIZE] = ARGUS_DATA_MSG_EVT; Buffer[ARGUS_HEADER_SIZE+1] = ( evt_dbid >> 56 ) & 0xFF; Buffer[ARGUS_HEADER_SIZE+2] = ( evt_dbid >> 48 ) & 0xFF; Buffer[ARGUS_HEADER_SIZE+3] = ( evt_dbid >> 40 ) & 0xFF; Buffer[ARGUS_HEADER_SIZE+4] = ( evt_dbid >> 32 ) & 0xFF; Buffer[ARGUS_HEADER_SIZE+5] = ( evt_dbid >> 24 ) & 0xFF; Buffer[ARGUS_HEADER_SIZE+6] = ( evt_dbid >> 16 ) & 0xFF; Buffer[ARGUS_HEADER_SIZE+7] = ( evt_dbid >> 8 ) & 0xFF; Buffer[ARGUS_HEADER_SIZE+8] = evt_dbid & 0xFF; Buffer[ARGUS_HEADER_SIZE+9] = strlen( uuid ); uint8_t i = 0; for( ; i< Buffer[ARGUS_HEADER_SIZE+9]; i++ ) Buffer[ARGUS_HEADER_SIZE+10+i] = (uint8_t)uuid[i]; return m_pPort->sendData(Buffer, argus_rpc_finishupPackage( Buffer, m_nOutbondSerial, ARGUS_HEADER_SIZE+11+i ));};
bool servaRPCHadnler::peer_send_rpc( ARGUS_DATA_RPC *ptr ){ uint8_t tBuffer[1024]; tBuffer[ARGUS_HEADER_SIZE] = ARGUS_DATA_MSG_RPC; uint16_t i = 0; for(; i < sizeof(ARGUS_DATA_RPC); i++) tBuffer[ARGUS_HEADER_SIZE+1+i] = ((uint8_t*)ptr)[i]; return m_pPort->sendData(tBuffer, argus_rpc_finishupPackage(tBuffer, m_nOutbondSerial, ARGUS_HEADER_SIZE+1+i ));};
bool servaRPCHadnler::peer_send_time_sync_ack( ARGUS_DATA_TIME_SYNC_ACK *ptr ){ uint8_t tBuffer[1024]; tBuffer[ARGUS_HEADER_SIZE] = ARGUS_DATA_MSG_TIME_SYNC; uint16_t i = 0; for(; i < sizeof(ARGUS_DATA_TIME_SYNC_ACK); i++) tBuffer[ARGUS_HEADER_SIZE+1+i] = ((uint8_t*)ptr)[i]; return m_pPort->sendData(tBuffer, argus_rpc_finishupPackage(tBuffer, m_nOutbondSerial, ARGUS_HEADER_SIZE+1+i ));};
servaVideoTransferHelper::servaVideoTransferHelper(){ m_pLog = basicLogCollection::getInstance(); m_pEventHeap = basicEventHeap::getInstance(); m_pFD = NULL; clear();};
servaVideoTransferHelper::~servaVideoTransferHelper(){ clear();};
bool servaVideoTransferHelper::init( CSTR base, uint64_t MID, uint64_t SID, ARGUS_DATA_VIDEO_INFO *ptr ){ m_nRemoteRefID = 0; if ( ptr ) { memcpy( &m_sIn, ptr, sizeof(ARGUS_DATA_VIDEO_INFO) ); if ( ptr->REF_ID ) { servaMySQLDBC * m_pDBC = servaMySQLDBC::getInstance(); CSTR tUUID = getUniqID_UUID(); //m_pDBC->getMediaUUID( ptr->REF_ID );
if ( tUUID ) {#ifdef DEBUG
char tB[256]; sprintf(tB, "Update VideoData: %s, %d.%d, [%dx%d@%d] <%s>", tUUID, m_sIn.DTS, m_sIn.DMS, m_sIn.WIDTH, m_sIn.HEIGHT, m_sIn.FPS, m_sIn.FMT); LOG( tB );#endif
sprintf( m_cCurrentFile, "%s/%s.%s", base, tUUID, m_sIn.FMT ); m_pFD = fopen( m_cCurrentFile, "wb" ); free( tUUID ); m_nRemoteRefID = ptr->REF_ID; return true; }; } else { //ToDo Set File Access to web user
CSTR tUUID = getUniqID_UUID(); if ( tUUID ) {#ifdef DEBUG
char tB[256]; sprintf(tB, "VideoData: %s, %d.%d, [%dx%d@%d] <%s>", tUUID, m_sIn.DTS, m_sIn.DMS, m_sIn.WIDTH, m_sIn.HEIGHT, m_sIn.FPS, m_sIn.FMT); LOG( tB );#endif
servaMySQLDBC * m_pDBC = servaMySQLDBC::getInstance(); //servaSessionManager * m_pSM = servaSessionManager::getInstance();
if ( m_nRemoteRefID = m_pDBC->addMediaQueueRecord( tUUID, MID, SID, m_sIn.DTS, m_sIn.DMS, m_sIn.WIDTH, m_sIn.HEIGHT, m_sIn.FPS, m_sIn.FMT ) ) { sprintf( m_cCurrentFile, "%s/%s.%s", base, tUUID, m_sIn.FMT ); m_pFD = fopen( m_cCurrentFile, "wb" ); free( tUUID ); return true; }; free( tUUID ); }; } }; memset( m_cCurrentFile, 0, MAX_PATH ); memset( &m_sIn, 0, sizeof(ARGUS_DATA_VIDEO_INFO) ); return false;};
void servaVideoTransferHelper::clear(){ if( m_pFD ) fclose( m_pFD ); m_pFD = NULL; m_nRemoteRefID = 0; m_nSAVED = 0; m_bOPerc = 0; memset( m_cCurrentFile, 0, MAX_PATH ); memset( &m_sIn, 0, sizeof(ARGUS_DATA_VIDEO_INFO) );};
uint32_t servaVideoTransferHelper::saveNextChunk( uint8_t *ptr, size_t avail ){ if ( ptr && avail >= 12 ){ uint64_t tDBID = ptr[0]; tDBID = ( tDBID << 8 ) | ptr[1]; tDBID = ( tDBID << 8 ) | ptr[2]; tDBID = ( tDBID << 8 ) | ptr[3]; tDBID = ( tDBID << 8 ) | ptr[4]; tDBID = ( tDBID << 8 ) | ptr[5]; tDBID = ( tDBID << 8 ) | ptr[6]; tDBID = ( tDBID << 8 ) | ptr[7]; uint32_t chusz = ptr[8]; chusz = ( chusz << 8 ) | ptr[9]; chusz = ( chusz << 8 ) | ptr[10]; chusz = ( chusz << 8 ) | ptr[11]; if ( chusz > avail - 12 ) { // the length field claims more data than the packet holds
LOG_ERROR("Video chunk size exceeds the packet"); return 0; }; if ( m_pFD ) { if ( chusz ) { int rv = fwrite( ptr+12, 1, chusz, m_pFD ); if ( rv != chusz ) { fclose( m_pFD ); m_pFD = NULL; unlink( m_cCurrentFile ); return 0; }; m_nSAVED += chusz; if ( chusz < ARGUS_RPC_DEFAULT_MEDIA_CHUNK ) { LOG("Video File Reception Done"); fclose( m_pFD ); m_pFD = NULL; servaKernel::getInstance()->updateEncodeStatus(tDBID, MEDIA_STORED, 100); } else { if ( m_sIn.DATA_SIZE ) { uint8_t perc = (uint8_t)((m_nSAVED * 100) / m_sIn.DATA_SIZE); if ( m_bOPerc != perc ) { m_bOPerc = perc; servaKernel::getInstance()->updateEncodeStatus(tDBID, MEDIA_TRANSFERING, perc ); }; } else servaKernel::getInstance()->updateEncodeStatus( tDBID, MEDIA_TRANSFERING, 50 ); }; return chusz; }; }; }; return 0;};
#undef LOG
#undef LOG_ERROR
|