You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

853 lines
36 KiB

​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
12 months ago
​
​
​
​
​
​
​
​
​
​
12 months 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
15 hours ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
2 years 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
15 hours 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
15 hours 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
15 hours ago
​
​
​
​
​
​
​
​
​
​
1 year ago
​
12 months ago
​
​
​
​
1 year ago
​
​
​
1 year ago
​
​
​
​
​
​
12 months 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
15 hours 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
15 hours 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
15 hours ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
2 years ago
​
​
​
​
12 months ago
2 years ago
12 months ago
2 years 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
15 hours ago
12 months ago
12 months ago
12 months 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
15 hours ago
12 months 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
15 hours ago
​
​
​
2 years 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
15 hours ago
​
12 months ago
12 months ago
​
​
​
12 months ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
2 years 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
15 hours 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
15 hours 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
15 hours ago
​
​
​
​
​
​
​
​
​
​
​
12 months 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
15 hours ago
​
12 months 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
15 hours 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
15 hours 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
15 hours ago
12 months ago
​
12 months ago
​
2 years ago
​
​
12 months 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
15 hours ago
​
12 months ago
​
​
​
2 years 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
15 hours ago
2 years ago
2 years ago
2 years ago
​
​
​
​
​
​
​
​
2 years ago
2 years ago
​
​
​
​
​
​
​
​
​
​
​
​
2 years ago
​
2 years ago
​
​
​
​
​
​
​
​
​
2 years ago
​
​
​
​
​
​
​
​
​
​
​
​
2 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
2 years ago
​
2 years ago
​
​
2 years ago
​
2 years ago
​
​
2 years ago
​
​
​
​
​
2 years ago
​
​
​
​
  1. #include "servaSessionManager.h"
  2. #include "../common/serverMySQL_dataBinder.h"
  3. #include "../../components/base/basicEventHeap.h"
  4. #define LOG( X ) m_pLog->Log( "SSMN", this, X )
  5. #ifdef DEBUG
  6. #define LOG_ERROR( X ) {\
  7. char _tBfrErrMSG2w34[256];\
  8. sprintf( _tBfrErrMSG2w34, "In file %s[%d] in func:%s %s",__FILE__, __LINE__, __func__, X );\
  9. m_pLog->Log( "SSMN", this, _LOG_ERROR, _tBfrErrMSG2w34 );\
  10. }
  11. #else
  12. #define LOG_ERROR( X ) m_pLog->Log( "SSMN", this, _LOG_ERROR, X );
  13. #endif
  14. servaSessionManager *servaSessionManager::_instance = NULL;
  15. servaSessionManager *servaSessionManager::getInstance( config_setting_t * Settings ){
  16. if( _instance == NULL ){
  17. _instance = new servaSessionManager( Settings );
  18. };
  19. return _instance;
  20. };
  21. servaSessionManager::servaSessionManager( config_setting_t * Settings ){
  22. m_pLog = basicLogCollection::getInstance();
  23. m_pDBC = (serverDataBinder*) servaMySQLDBC::getInstance();
  24. m_bRepIsConnected = false;
  25. //Read System (loalfile) Settings
  26. m_pSettings = basicSettingsProvider::getInstance()->getSubNode( Settings, "SESSON_MNGR" );
  27. #ifdef DEBUG
  28. LOG("Getting Settings ...");
  29. #endif
  30. config_setting_t * pSetting;
  31. int tVal;
  32. const char * tBuf;
  33. char tBuffer[128];
  34. /*
  35. if(!config_setting_lookup_int(m_pSettings, "SESSION_TIMEOUT", &tVal )){
  36. pSetting = config_setting_add(m_pSettings, "SESSION_TIMEOUT", CONFIG_TYPE_INT);
  37. m_nSessionTO = DEFAULT_SESSION_TIMEOUT;
  38. config_setting_set_int( pSetting, m_nSessionTO );
  39. basicSettingsProvider::getInstance()->compromise();
  40. LOG("Session Timeout not set - using default");
  41. } else {
  42. m_nSessionTO = tVal;
  43. sprintf( tBuffer, "Session Timeout Read From Settings: %d sec.", m_nSessionTO );
  44. LOG( tBuffer );
  45. };
  46. */
  47. m_nSessionTO = m_pDBC->getSessionTimeOut();
  48. if(!config_setting_lookup_string(m_pSettings, "REPORTS_DIR_NAME", &tBuf )){
  49. pSetting = config_setting_add(m_pSettings, "REPORTS_DIR_NAME", CONFIG_TYPE_STRING);
  50. sprintf( m_pDbReportBase, "data/reports" );
  51. config_setting_set_string( pSetting, m_pDbReportBase );
  52. basicSettingsProvider::getInstance()->compromise();
  53. LOG("Reports Storage not set - using default");
  54. } else {
  55. sprintf( m_pDbReportBase, tBuf );
  56. };
  57. if(!config_setting_lookup_string(m_pSettings, "WEB_ACCESS_USER", &tBuf )){
  58. pSetting = config_setting_add(m_pSettings, "WEB_ACCESS_USER", CONFIG_TYPE_STRING);
  59. sprintf( web_access_user, "www-data" );
  60. config_setting_set_string( pSetting, web_access_user );
  61. basicSettingsProvider::getInstance()->compromise();
  62. LOG("Web Access User not set - using default");
  63. } else {
  64. sprintf( web_access_user, tBuf );
  65. };
  66. if(!config_setting_lookup_string(m_pSettings, "WEB_ACCESS_GROUP", &tBuf )){
  67. pSetting = config_setting_add(m_pSettings, "WEB_ACCESS_GROUP", CONFIG_TYPE_STRING);
  68. sprintf( web_access_group, "www-data" );
  69. config_setting_set_string( pSetting, web_access_group );
  70. basicSettingsProvider::getInstance()->compromise();
  71. LOG("Web Access Group not set - using default");
  72. } else {
  73. sprintf( web_access_group, tBuf );
  74. };
  75. basicSettingsProvider::getInstance()->validate();
  76. //if( !fileExist( DB_SHMEM_POINT )) {
  77. // bRecreateMemStructures = true;
  78. // mkdir( DB_SHMEM_POINT, STORAGE_DIR_MODE );// S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP | S_IWGRP | S_IXGRP | S_IROTH | S_IXOTH );
  79. // chown( DB_SHMEM_POINT, getUserUid(web_access_user), getUserGid(web_access_group) ); //To make Accessed from PHP
  80. // chmod( DB_SHMEM_POINT, STORAGE_DIR_MODE );
  81. //};
  82. };
  83. servaSessionManager::~servaSessionManager(){
  84. //Close all Ongoing Session since Application goes to die
  85. m_pDBC->closeAllOnGoingSessions();
  86. std::lock_guard<std::recursive_mutex> tGuard( m_mSessionProtector );
  87. for( M_SESSIONS::iterator idx = m_mSessions.begin(); idx != m_mSessions.end(); idx++ ) freeSession( (*idx).second );
  88. m_mSessions.clear();
  89. };
  90. void servaSessionManager::freeSession( SESSION_DATA *& sp ){
  91. if ( sp == NULL ) return;
  92. if ( sp->m_pDataReport ) delete( sp->m_pDataReport ); // closes the session's report.db
  93. free( sp );
  94. sp = NULL;
  95. };
  96. void servaSessionManager::closeReopened( SESSION_DATA *& sp ){
  97. // Reopened sessions are not in m_mSessions: just release them
  98. freeSession( sp );
  99. };
  100. uint64_t servaSessionManager::addEvent( uint64_t tack_id, uint64_t module_id, ARGUS_DATA_EVENT *ptr ){
  101. std::lock_guard<std::recursive_mutex> tGuard( m_mSessionProtector );
  102. uint64_t rV = 0;
  103. if( SESSION_DATA *sp = updateSession( tack_id, module_id ) ) {
  104. if( addEvent( sp, ptr ) ) rV = sp->db_id;
  105. };
  106. return rV;
  107. };
  108. bool servaSessionManager::addEvent( uint64_t sid, ARGUS_DATA_EVENT *ptr ){
  109. std::lock_guard<std::recursive_mutex> tGuard( m_mSessionProtector );
  110. if( SESSION_DATA *sp = validateSession( sid ) ) {
  111. return addEvent( sp, ptr );
  112. };
  113. return false;
  114. };
  115. bool servaSessionManager::addEvent( SESSION_DATA *sp, ARGUS_DATA_EVENT *ptr ){
  116. if ( ptr == NULL ) return false;
  117. if ( sp == NULL ) return false;
  118. if ( sp->m_pDataReport ) {
  119. char tQBuf[1024];
  120. switch ( ptr->TYPE ) {
  121. case EVT_LRF_END_SESSION_TO:
  122. case EVT_LRF_END_SESSION_MA:
  123. //No Technical events
  124. return false;
  125. sprintf( tQBuf, "INSERT INTO `events`(`session_id`,`module_id`,`ts`,`ts_ms`,`evt_type`) VALUES(%" PRIu64 ",%" PRIu64 ",%d,%d,%d)",
  126. sp->db_id,
  127. ptr->MODULE_ID,
  128. ptr->TS,
  129. ptr->MS,
  130. ptr->TYPE
  131. );
  132. break;
  133. case EVT_LRF_START_SESSION:
  134. //No Technical events
  135. return false;
  136. sprintf( tQBuf, "INSERT INTO `events`(`session_id`,`module_id`,`ts`,`ts_ms`,`evt_type`) VALUES(%" PRIu64 ",%" PRIu64 ",%d,%d,%d)",
  137. sp->db_id,
  138. ptr->MODULE_ID,
  139. ptr->TS,
  140. ptr->MS,
  141. ptr->TYPE
  142. );
  143. break;
  144. case EVT_FLT_LATF_CHK:
  145. case EVT_FLT_LATF_UP_DETEC:
  146. case EVT_FLT_LATF_BT_DETEC:
  147. case EVT_FLT_LATF_TRP_DET:
  148. case EVT_FLT_LATF_TRP_UPDT:
  149. case EVT_FLT_LATF_SUSP_START:
  150. case EVT_FLT_LATF_SUSP_NAK:
  151. case EVT_FLT_LATF_REGULAR:
  152. case EVT_FLT_LATF_DISABLED:
  153. case EVT_FLT_LATF_SUSP_DET:
  154. case EVT_FLT_LATF_DIFF_DET:
  155. case EVT_FLT_LATF_OP_DISABLED:
  156. case EVT_FLT_LATF_OP_TD:
  157. case EVT_FLT_LATF_OP_TG:
  158. case EVT_FLT_LATF_OP_EXP:
  159. case EVT_OP_ACK_MASK:
  160. case EVT_OP_NACK_MASK:
  161. case EVT_OP_ON_MASK:
  162. case EVT_OP_OFF_MASK:
  163. case EVT_CONNECTED:
  164. case EVT_DISCONNECTED:
  165. case EVT_COMMUNICATION_JAMED:
  166. case EVT_STUDY:
  167. case EVT_BUSY:
  168. case EVT_FLIP:
  169. case EVT_READY:
  170. case EVT_ERR_LRF_NO_IRQ:
  171. case EVT_ERR_LRF_NO_ZERO:
  172. case EVT_ERR_LRF_ANGLE:
  173. case EVT_ERR_LRF_VOLTAGE:
  174. case EVT_ERR_LRF_BROKEN:
  175. case EVT_LRF_VIS_CHANGED:
  176. case EVT_ERR_OVERFLOW:
  177. case EVT_SST_OVERFLOW:
  178. case EVT_VIDEO_FPS_DEGRADED:
  179. case EVT_VIDEO_FPS_RAISED:{
  180. //No Technical events
  181. return false;
  182. sprintf( tQBuf, "INSERT INTO `events`(`session_id`,`module_id`,`ts`,`ts_ms`,`evt_type`) VALUES(%" PRIu64 ",%" PRIu64 ",%d,%d,%d)",
  183. sp->db_id,
  184. ptr->MODULE_ID,
  185. ptr->TS,
  186. ptr->MS,
  187. ptr->TYPE
  188. );
  189. break;
  190. };
  191. case EVT_ROI_ACTIVE:
  192. case EVT_TARGET_3D_WHITE:
  193. case EVT_TARGET_3D_BLACK:{
  194. updateSessionStat( sp->db_id );
  195. sprintf( tQBuf, "INSERT INTO `events`(`session_id`,`module_id`,`ts`,`ts_ms`,`evt_type`,`azimuth`,`elevation`,`range`,`area`)" \
  196. " VALUES(%" PRIu64 ",%" PRIu64 ",%d,%d,%d,%0.2f,%0.2f,%0.2f,%0.2f)",
  197. sp->db_id,
  198. ptr->MODULE_ID,
  199. ptr->TS,
  200. ptr->MS,
  201. ptr->TYPE,
  202. ptr->AZIMUTH / 1000.0f,
  203. ptr->ELEVATION / 1000.0f,
  204. ptr->RANGE / 1000.0f,
  205. ptr->AREA / 100.0f
  206. );
  207. break;
  208. };
  209. case EVT_TARGET_2D_WHITE:
  210. case EVT_TARGET_2D_BLACK:{
  211. updateSessionStat( sp->db_id );
  212. sprintf( tQBuf, "INSERT INTO `events`(`session_id`,`module_id`,`ts`,`ts_ms`,`evt_type`,`azimuth`,`range`,`area`)" \
  213. " VALUES(%" PRIu64 ",%" PRIu64 ",%d,%d,%d,%0.2f,%0.2f,%0.2f)",
  214. sp->db_id,
  215. ptr->MODULE_ID,
  216. ptr->TS,
  217. ptr->MS,
  218. ptr->TYPE,
  219. ptr->AZIMUTH / 1000.0f,
  220. ptr->RANGE / 1000.0f,
  221. ptr->AREA / 100.0f
  222. );
  223. break;
  224. };
  225. default: return false;
  226. };
  227. #ifdef DEBUG_EXTRA
  228. LOG( tQBuf );
  229. #endif
  230. return sp->m_pDataReport->SilentQuery( tQBuf );
  231. };
  232. return false;
  233. };
  234. bool servaSessionManager::addVideo( DBC_RPC_MEDIA_INFO_EX *ptr ){//uint32_t module_id, uint32_t ts, uint16_t tsms, CSTR uuid, CSTR fmt, uint8_t fps ){
  235. std::lock_guard<std::recursive_mutex> tGuard( m_mSessionProtector );
  236. if ( ptr == NULL ){
  237. LOG_ERROR( "ExtInfo ptr is null!");
  238. return false;
  239. };
  240. char tB[64];
  241. sprintf( tB, "Session id: %" PRIu64, ptr->session_id );
  242. LOG( tB );
  243. // At Time of Video Addition the Session May be expired already!!
  244. // No neet to Validate session!
  245. bool bExpiredSession = false;
  246. SESSION_DATA *sp = validateSession( ptr->session_id );
  247. if ( sp == NULL ) {
  248. LOG("Session Allredy Closed");
  249. sp = reopenSession( ptr->session_id );
  250. if ( sp == NULL ) {
  251. LOG_ERROR( "Session Data ptr is null!");
  252. return false;
  253. };
  254. bExpiredSession = true;
  255. };
  256. if ( sp->m_pDataReport ) {
  257. char tName[MAX_PATH];
  258. sprintf(tName, "%s/%s.%s", sp->reportVaultPath, ptr->uuid, ptr->fmt );
  259. chown( tName, getUserUid(web_access_user), getUserGid(web_access_group) );
  260. chmod( tName, DB_FILE_MODE );
  261. updateSessionStat( ptr->session_id, false );
  262. char tQBuf[CTEXT];
  263. sprintf( tQBuf, "INSERT INTO `videos`(`session_id`,`module_id`,`uuid`,`ts`,`ts_ms`,`ext`,`fps`) VALUES(%" PRIu64 ", %d,'%s',%d,%d,'%s',%d)",
  264. ptr->session_id,
  265. ptr->module_id,
  266. ptr->uuid,
  267. ptr->ts,
  268. ptr->tms,
  269. ptr->fmt,
  270. ptr->fps
  271. );
  272. #ifdef DEBUG
  273. LOG( tQBuf );
  274. #endif
  275. bool rv = sp->m_pDataReport->SilentQuery( tQBuf );
  276. if( bExpiredSession ) closeReopened( sp );
  277. return rv;
  278. } else {
  279. LOG_ERROR( "Report DB is closed!");
  280. };
  281. if( bExpiredSession ) closeReopened( sp );
  282. return false;
  283. };
  284. bool servaSessionManager::create(){
  285. //Reset All Ongoing Session since Application was restarted (crashed?)
  286. return m_pDBC->closeAllOnGoingSessions();
  287. };
  288. SESSION_DATA *servaSessionManager::getActiveSessionByTrack( uint64_t tack_id ){
  289. std::lock_guard<std::recursive_mutex> tGuard( m_mSessionProtector );
  290. SESSION_DATA * rVal = NULL;
  291. try {
  292. m_mSessionProtector.lock();
  293. SESSION_DATA * tData = m_mSessions.at( tack_id );
  294. if ( tData ) {
  295. rVal = (SESSION_DATA *) malloc( sizeof(SESSION_DATA));
  296. if ( rVal ) memcpy( rVal, tData, sizeof(SESSION_DATA));
  297. };
  298. m_mSessionProtector.unlock();
  299. } catch ( ... ) {
  300. m_mSessionProtector.unlock();
  301. // No Session
  302. };
  303. return rVal;
  304. };
  305. CSTR servaSessionManager::getReportDir( uint64_t track_id, uint32_t ts ){
  306. char retVal[MAX_PATH];
  307. REPORT_DIRINFO tRDF;
  308. fillRDF( ts, tRDF );
  309. sprintf( retVal, "%s/%" PRIu64 "/%s/%s/%s", m_pDbReportBase, track_id, tRDF.YEAR, tRDF.MONTH, tRDF.DAY );
  310. #ifdef DEBUG_EXTRA
  311. LOG( retVal );
  312. #endif
  313. return strdup( retVal );
  314. };
  315. CSTR servaSessionManager::getSessionBase( uint64_t sid ){
  316. std::lock_guard<std::recursive_mutex> tGuard( m_mSessionProtector );
  317. CSTR rData = NULL;
  318. SESSION_DATA *sp = validateSession( sid );
  319. if ( sp ) return strdup( sp->reportVaultPath );
  320. //TODO: Get Session Base from Database then (not open/close session)
  321. sp = reopenSession( sid );
  322. if ( sp ) {
  323. rData = strdup( sp->reportVaultPath );
  324. closeReopened( sp );
  325. };
  326. return rData;
  327. };
  328. SESSION_DATA *servaSessionManager::reopenSession( uint64_t session_id ){
  329. SESSION_DATA * tData = NULL;
  330. // No Session -> Create one
  331. tData = m_pDBC->getSessionData( session_id );
  332. if ( tData ) {
  333. //Reopen just for fun :)
  334. tData->skeep_validation = true;
  335. // Create History Database if not exists
  336. char tBase[MAX_PATH];
  337. sprintf( tBase, "%s/%d", m_pDbReportBase, tData->track_id );
  338. if( fileExist( tBase ) == 0 ){
  339. if (!createAccessibleDir( tBase, STORAGE_DIR_MODE, getUserUid(web_access_user), getUserGid(web_access_group))){
  340. LOG_ERROR("Cannot create Base Report Dir!");
  341. #ifdef DEBUG
  342. char tB[1024];
  343. sprintf( tB, "Dir: %s, UID[%s]: %d GID[%s]: %d", tBase, web_access_user, getUserUid(web_access_user) ,web_access_group, getUserGid(web_access_group) );
  344. LOG( tB );
  345. #endif
  346. free( tData );
  347. return NULL;
  348. };
  349. };
  350. REPORT_DIRINFO tRDF;
  351. fillRDF( tData->sts, tRDF );
  352. if( checkRDFDir( tBase, tRDF, true, getUserUid(web_access_user), getUserGid(web_access_group), STORAGE_DIR_MODE ) ){
  353. #ifdef DEBUG
  354. LOG("Connect to Report Database ReopenSession");
  355. #endif
  356. sprintf( tData->reportVaultPath, "%s/%s/%s/%s", tBase, tRDF.YEAR, tRDF.MONTH, tRDF.DAY );
  357. //LOG( tData->reportVaultPath );
  358. char tName[MAX_PATH];
  359. sprintf( tName, "%s/report.db", tData->reportVaultPath );
  360. if( fileExist( tName ) ){
  361. //Allready have report file
  362. tData->m_pDataReport = new SQLite_Connector();
  363. if ( tData->m_pDataReport ) {
  364. if( !tData->m_pDataReport->Connect( tName, 0, true) ) {
  365. LOG_ERROR("Cannot Connect to RDB!");
  366. delete( tData->m_pDataReport );
  367. free( tData );
  368. tData = NULL;
  369. };
  370. } else {
  371. LOG_ERROR("Cannot Create Connector to RDB!");
  372. free( tData );
  373. tData = NULL;
  374. };
  375. } else {
  376. #ifdef DEBUG
  377. LOG("Create New Report Database");
  378. #endif
  379. //Create new report file
  380. tData->m_pDataReport = new SQLite_Connector();
  381. if ( tData->m_pDataReport ) {
  382. #ifdef DEBUG
  383. LOG( tName );
  384. #endif
  385. if( tData->m_pDataReport->Connect( tName, 0, true) ) {
  386. chown( tName, getUserUid(web_access_user), getUserGid(web_access_group) );
  387. chmod( tName, DB_FILE_MODE );
  388. tData->m_pDataReport->SilentQuery("CREATE TABLE IF NOT EXISTS \"events\" ( \"id\" INTEGER NOT NULL, \"session_id\" INTEGER NOT NULL, \"module_id\" INTEGER NOT NULL, \"ts\" INTEGER NOT NULL, \"ts_ms\" INTEGER NOT NULL, \"evt_type\" INTEGER NOT NULL, \"azimuth\" REAL, \"elevation\" REAL, \"range\" REAL, \"area\" REAL, PRIMARY KEY(\"id\" AUTOINCREMENT) )");
  389. tData->m_pDataReport->SilentQuery("CREATE TABLE IF NOT EXISTS \"videos\" ( \"id\" INTEGER NOT NULL, \"session_id\" INTEGER NOT NULL, \"module_id\" INTEGER NOT NULL, \"uuid\" TEXT NOT NULL UNIQUE, \"ts\" INTEGER NOT NULL, \"ts_ms\" INTEGER NOT NULL, \"ext\" TEXT NOT NULL, \"fps\" INTEGER NOT NULL, PRIMARY KEY(\"id\" AUTOINCREMENT) )");
  390. } else {
  391. LOG_ERROR("Cannot Connect to RDB!");
  392. delete( tData->m_pDataReport );
  393. free( tData );
  394. tData = NULL;
  395. };
  396. } else {
  397. LOG_ERROR("Cannot Create Connector to RDB!");
  398. free( tData );
  399. tData = NULL;
  400. };
  401. };
  402. } else {
  403. LOG_ERROR("The report Vault Dir can not be accessed!");
  404. free( tData );
  405. tData = NULL;
  406. };
  407. };
  408. // Not put into m_mSessions: the map holds the ACTIVE session of each track, and storing the
  409. // reopened one there overwrote (and leaked, never closed) the track's running session.
  410. return tData;
  411. };
  412. SESSION_DATA *servaSessionManager::updateSession( uint64_t tack_id, uint64_t module_id ){
  413. std::lock_guard<std::recursive_mutex> tGuard( m_mSessionProtector );
  414. SESSION_DATA * tData = NULL;
  415. try {
  416. m_mSessionProtector.lock();
  417. tData = m_mSessions.at( tack_id );
  418. m_mSessionProtector.unlock();
  419. #ifdef DEBUG
  420. LOG("Have Opened Session");
  421. #endif
  422. } catch ( ... ) {
  423. m_mSessionProtector.unlock();
  424. // No Session -> Create one
  425. tData = (SESSION_DATA*) malloc( sizeof(SESSION_DATA) );
  426. if ( tData ) {
  427. memset( tData, 0, sizeof(SESSION_DATA) );
  428. uint64_t cms = getMilliseconds();
  429. tData->lts = tData->sts = cms/1000;
  430. tData->sms = cms%1000;
  431. tData->track_id = tack_id;
  432. getUniqID_UUID( tData->uuid );
  433. // Set Side of event
  434. tData->src = ' ';
  435. DBC_IS_MODULE_DATA *tMData = m_pDBC->getModuleData( module_id );
  436. if ( tMData ) {
  437. DBC_IS_TRACK_DATA *tTData = m_pDBC->getTrackData( tack_id );
  438. if ( tTData ) {
  439. if (tTData->side == 'U') {
  440. if (tMData->side == 'F') {
  441. tData->src = 'L';
  442. } else {
  443. tData->src = 'R';
  444. };
  445. } else {
  446. if (tMData->side == 'F') {
  447. tData->src = 'R';
  448. } else {
  449. tData->src = 'L';
  450. };
  451. };
  452. free(tTData);
  453. };
  454. free(tMData);
  455. };
  456. // Create History Database if not exists
  457. char tBase[MAX_PATH];
  458. sprintf( tBase, "%s/%" PRIu64, m_pDbReportBase, tack_id );
  459. if( fileExist( tBase ) == 0 ){
  460. if (!createAccessibleDir( tBase, STORAGE_DIR_MODE, getUserUid(web_access_user), getUserGid(web_access_group))){
  461. LOG_ERROR("Cannot create Base Report Dir!");
  462. #ifdef DEBUG
  463. char tB[1024];
  464. sprintf( tB, "Dir: %s, UID[%s]: %d GID[%s]: %d", tBase, web_access_user, getUserUid(web_access_user) ,web_access_group, getUserGid(web_access_group) );
  465. LOG( tB );
  466. #endif
  467. free( tData );
  468. return NULL;
  469. };
  470. };
  471. REPORT_DIRINFO tRDF;
  472. fillRDF( tData->sts, tRDF );
  473. if( checkRDFDir( tBase, tRDF, true, getUserUid(web_access_user), getUserGid(web_access_group), STORAGE_DIR_MODE ) ){
  474. #ifdef DEBUG
  475. LOG("Connect to Report Database UpdateSession");
  476. #endif
  477. sprintf( tData->reportVaultPath, "%s/%s/%s/%s", tBase, tRDF.YEAR, tRDF.MONTH, tRDF.DAY );
  478. LOG( tData->reportVaultPath );
  479. char tName[MAX_PATH];
  480. sprintf( tName, "%s/report.db", tData->reportVaultPath );
  481. if( fileExist( tName ) ){
  482. //Allready have report file
  483. tData->m_pDataReport = new SQLite_Connector();
  484. if ( tData->m_pDataReport ) {
  485. if( !tData->m_pDataReport->Connect( tName, 0, true) ) {
  486. LOG_ERROR("Cannot Connect to RDB!");
  487. delete( tData->m_pDataReport );
  488. free( tData );
  489. tData = NULL;
  490. };
  491. } else {
  492. LOG_ERROR("Cannot Create Connector to RDB!");
  493. free( tData );
  494. tData = NULL;
  495. };
  496. } else {
  497. #ifdef DEBUG
  498. LOG("Create New Report Database");
  499. #endif
  500. //Create new report file
  501. tData->m_pDataReport = new SQLite_Connector();
  502. if ( tData->m_pDataReport ) {
  503. #ifdef DEBUG
  504. LOG( tName );
  505. #endif
  506. if( tData->m_pDataReport->Connect( tName, 0, true) ) {
  507. chown( tName, getUserUid(web_access_user), getUserGid(web_access_group) );
  508. chmod( tName, DB_FILE_MODE );
  509. tData->m_pDataReport->SilentQuery("CREATE TABLE IF NOT EXISTS \"events\" ( \"id\" INTEGER NOT NULL, \"session_id\" INTEGER NOT NULL, \"module_id\" INTEGER NOT NULL, \"ts\" INTEGER NOT NULL, \"ts_ms\" INTEGER NOT NULL, \"evt_type\" INTEGER NOT NULL, \"azimuth\" REAL, \"elevation\" REAL, \"range\" REAL, \"area\" REAL, PRIMARY KEY(\"id\" AUTOINCREMENT) )");
  510. tData->m_pDataReport->SilentQuery("CREATE TABLE IF NOT EXISTS \"videos\" ( \"id\" INTEGER NOT NULL, \"session_id\" INTEGER NOT NULL, \"module_id\" INTEGER NOT NULL, \"uuid\" TEXT NOT NULL UNIQUE, \"ts\" INTEGER NOT NULL, \"ts_ms\" INTEGER NOT NULL, \"ext\" TEXT NOT NULL, \"fps\" INTEGER NOT NULL, PRIMARY KEY(\"id\" AUTOINCREMENT) )");
  511. } else {
  512. LOG_ERROR("Cannot Connect to RDB!");
  513. delete( tData->m_pDataReport );
  514. free( tData );
  515. tData = NULL;
  516. };
  517. } else {
  518. LOG_ERROR("Cannot Create Connector to RDB!");
  519. free( tData );
  520. tData = NULL;
  521. };
  522. };
  523. } else {
  524. LOG_ERROR("The report Vault Dir can not be accessed!");
  525. free( tData );
  526. tData = NULL;
  527. };
  528. } else {
  529. LOG_ERROR("Cannot Allocate Session Data [malloc]!");
  530. };
  531. if ( tData ) {
  532. LOG("Session is New");
  533. if ( tData->db_id == 0 ) {
  534. DBC_IS_MODULE_DATA *tMData = m_pDBC->getModuleData( module_id );
  535. if ( tMData ) {
  536. DBC_IS_TRACK_DATA *tTData = m_pDBC->getTrackData( tack_id );
  537. if ( tTData ) {
  538. if ( tTData->side == 'U') {
  539. if (tMData->side == 'F') {
  540. tData->src = 'L';
  541. } else {
  542. tData->src = 'R';
  543. };
  544. } else {
  545. if (tMData->side == 'F') {
  546. tData->src = 'R';
  547. } else {
  548. tData->src = 'L';
  549. };
  550. };
  551. free(tTData);
  552. };
  553. free(tMData);
  554. };
  555. char tB[128];
  556. LOG("All Seems to be good!");
  557. sprintf( tB, "Session Source is: [%c]", tData->src );
  558. LOG( tB );
  559. tData->db_id = m_pDBC->sessionCreate( tData->track_id, tData->sts, tData->sms, tData->uuid, tData->src );
  560. if ( tData->db_id == 0 ) {
  561. LOG_ERROR("Cannot Create Session!");
  562. delete( tData->m_pDataReport );
  563. free( tData );
  564. tData = NULL;
  565. } else {
  566. LOG("Session Registered at Database");
  567. //Propogate Event ->Session Start
  568. SERVA_SESSION_EVT_DATA *tSData = (SERVA_SESSION_EVT_DATA*) malloc( sizeof(SERVA_SESSION_EVT_DATA));
  569. if ( tSData ) {
  570. tSData->side = tData->src;
  571. tSData->track_id = tData->track_id;
  572. EVENT_CONTAINER *tEvt = createBasicEvent( tack_id, EVT_CLASS_SYSTEM, EVT_SRV_SESSION_STARTED, NULL, NULL, tSData );
  573. if ( tEvt ) basicEventHeap::getInstance()->broadcast( tEvt );
  574. else free( tSData );
  575. };
  576. // Put Session into collection
  577. m_mSessionProtector.lock();
  578. m_mSessions[tack_id] = tData;
  579. m_mSessionProtector.unlock();
  580. };
  581. } else {
  582. LOG("Session is Old");
  583. char cSRC = ' ';
  584. DBC_IS_MODULE_DATA *tMData = m_pDBC->getModuleData( module_id );
  585. if ( tMData ) {
  586. DBC_IS_TRACK_DATA *tTData = m_pDBC->getTrackData( tack_id );
  587. if ( tTData ) {
  588. if (tTData->side == 'U') {
  589. if (tMData->side == 'F') {
  590. cSRC = 'L';
  591. } else {
  592. cSRC = 'R';
  593. };
  594. } else {
  595. if (tMData->side == 'F') {
  596. cSRC = 'R';
  597. } else {
  598. cSRC = 'L';
  599. };
  600. };
  601. free(tTData);
  602. };
  603. free(tMData);
  604. };
  605. if ( cSRC != ' ' ) {
  606. LOG("Have side info");
  607. if ( ( tData->src != 'B' ) && ( tData->src != cSRC ) ) {
  608. LOG("This is additional side!");
  609. tData->src = 'B'; // Change Status to 'B' = 'Both' (R+L)
  610. m_pDBC->updateSessionSource( tData->db_id, tData->src );
  611. // Create Event for other side
  612. // sending EVT_SRV_SESSION_STARTED - > to signalize SCADA
  613. // that another side of platform also become active
  614. SERVA_SESSION_EVT_DATA *tSData = (SERVA_SESSION_EVT_DATA*) malloc( sizeof(SERVA_SESSION_EVT_DATA));
  615. if ( tSData ) {
  616. tSData->side = tData->src;
  617. tSData->track_id = tData->track_id;
  618. EVENT_CONTAINER *tEvt = createBasicEvent( tack_id, EVT_CLASS_SYSTEM, EVT_SRV_SESSION_STARTED, NULL, NULL, tSData );
  619. if ( tEvt ) basicEventHeap::getInstance()->broadcast( tEvt );
  620. else free( tSData );
  621. };
  622. };
  623. };
  624. };
  625. };
  626. };
  627. return tData;
  628. };
  629. bool servaSessionManager::updateSessionStat( uint64_t session_id, bool evt ){
  630. std::lock_guard<std::recursive_mutex> tGuard( m_mSessionProtector );
  631. if( SESSION_DATA *tD = validateSession( session_id ) ){
  632. tD->lts = time( NULL );
  633. if ( evt ) {
  634. m_pDBC->sessionStatAddEvt( session_id );
  635. } else {
  636. m_pDBC->sessionStatAddVid( session_id );
  637. };
  638. return true;
  639. };
  640. return false;
  641. };
  642. bool servaSessionManager::validate(){
  643. uint32_t cts = time( NULL );
  644. M_SESSIONS::iterator dE;
  645. bool bMustDelete = false;
  646. m_mSessionProtector.lock();
  647. for( M_SESSIONS::iterator idx = m_mSessions.begin(); idx != m_mSessions.end(); idx++ ){
  648. if ( (*idx).second ) {
  649. #ifdef DEBUG_EXTRA
  650. char tB[128];
  651. sprintf( tB, "Validation %d %d %d", cts, (*idx).second->lts, m_nSessionTO );
  652. LOG( tB );
  653. #endif
  654. if ( !(*idx).second->skeep_validation ) {
  655. if (cts - (*idx).second->lts > m_nSessionTO ) {
  656. // Expire Session
  657. //m_pDBC->updateSessionStatus( (*idx).second->db_id, 1 );
  658. m_pDBC->sessionClose( (*idx).second->db_id );
  659. // Set Session to remove
  660. dE = idx;
  661. bMustDelete = true;
  662. //Propogate Event Session End
  663. EVENT_CONTAINER *tEvt = createBasicEvent( (*idx).second->track_id, EVT_CLASS_SYSTEM, EVT_SRV_SESSION_ENDED );
  664. if ( tEvt ) basicEventHeap::getInstance()->broadcast( tEvt );
  665. };
  666. };
  667. };
  668. };
  669. if ( bMustDelete ) {
  670. // Remove Session
  671. freeSession( (*dE).second );
  672. m_mSessions.erase( dE );
  673. };
  674. m_mSessionProtector.unlock();
  675. return true;
  676. };
  677. SESSION_DATA *servaSessionManager::validateSession( uint64_t sid ){
  678. std::lock_guard<std::recursive_mutex> tGuard( m_mSessionProtector );
  679. for( M_SESSIONS::iterator idx = m_mSessions.begin(); idx != m_mSessions.end(); idx++ )
  680. if( (*idx).second && (*idx).second->db_id == sid ) return (*idx).second;
  681. return NULL;
  682. };
  683. bool servaSessionManager::dropSession( uint64_t session_id ){
  684. std::lock_guard<std::recursive_mutex> tGuard( m_mSessionProtector );
  685. #ifdef DEBUG
  686. LOG("Drop Session!");
  687. #endif
  688. for( M_SESSIONS::iterator idx = m_mSessions.begin(); idx != m_mSessions.end(); idx++ ){
  689. if ( (*idx).second ) if ((*idx).second->db_id == session_id) return dropSession( idx );
  690. };
  691. return false;
  692. };
  693. bool servaSessionManager::dropSession( M_SESSIONS::iterator idx ){
  694. std::lock_guard<std::recursive_mutex> tGuard( m_mSessionProtector );
  695. freeSession( (*idx).second );
  696. m_mSessions.erase( idx );
  697. return true;
  698. };
  699. bool servaSessionManager::eraseSession( uint64_t session_id ){
  700. std::lock_guard<std::recursive_mutex> tGuard( m_mSessionProtector );
  701. // Erase just not important sessions
  702. // In case The session is Opened!
  703. #ifdef DEBUG
  704. LOG("Eraze Session!");
  705. #endif
  706. dropSession( session_id );
  707. SESSION_DATA * tData = m_pDBC->getSessionData( session_id );
  708. if ( tData ) {
  709. char tBase[MAX_PATH];
  710. sprintf( tBase, "%s/%d", m_pDbReportBase, tData->track_id );
  711. if( fileExist( tBase ) ){
  712. REPORT_DIRINFO tRDF;
  713. fillRDF( tData->sts, tRDF );
  714. sprintf( tData->reportVaultPath, "%s/%s/%s/%s", tBase, tRDF.YEAR, tRDF.MONTH, tRDF.DAY );
  715. #ifdef DEBUG_EXTRA
  716. LOG( tData->reportVaultPath );
  717. #endif
  718. if( fileExist( tData->reportVaultPath ) ){
  719. char tName[MAX_PATH];
  720. sprintf( tName, "%s/report.db", tData->reportVaultPath );
  721. if( fileExist( tName ) ){
  722. bool must_unlink = true;
  723. tData->m_pDataReport = new SQLite_Connector();
  724. if ( tData->m_pDataReport ) {
  725. if( tData->m_pDataReport->Connect( tName, 0, true) ) {
  726. char tB[1024];
  727. sprintf( tB, "DELETE FROM `events` WHERE `session_id`=%"PRIu64 , session_id );
  728. tData->m_pDataReport->SilentQuery( tB );
  729. sprintf( tB, "SELECT `uuid`, `ext` FROM `videos` WHERE `session_id`=%"PRIu64 , session_id );
  730. AAssoc *result = tData->m_pDataReport->Query( tB );
  731. if( result != NULL ) {
  732. if( result->size() > 0 ) {
  733. Assoc * cArr;
  734. for ( uint16_t idx = 0; idx < result->size(); idx++ ) {
  735. Assoc::iterator it;
  736. char fN[MAX_PATH], uA[65], uX[6];
  737. cArr = result->at(idx);
  738. it = cArr->find("uuid");
  739. if( it != cArr->end() ){
  740. strncpy( uA, it->second.c_str(), 64 );
  741. uA[64]=(char)0;
  742. };
  743. it = cArr->find("ext");
  744. if( it != cArr->end() ){
  745. strncpy( uX, it->second.c_str(), 5 );
  746. uX[5]=(char)0;
  747. };
  748. sprintf( fN,"%s/%s.%s", tData->reportVaultPath, uA, uX );
  749. if( fileExist( fN ) ) {
  750. #ifdef DEBUG_EXTRA
  751. LOG("Deleting ...");
  752. #endif
  753. unlink( fN );
  754. #ifdef DEBUG_EXTRA
  755. LOG("Deleted!");
  756. } else {
  757. LOG("Not Exists!");
  758. #endif
  759. };
  760. };
  761. };
  762. deleteResult( result );
  763. };
  764. sprintf( tB, "DELETE FROM `videos` WHERE `session_id`=%"PRIu64 , session_id );
  765. tData->m_pDataReport->SilentQuery( tB );
  766. //Check if still have othes Sessions
  767. sprintf( tB, "SELECT count( `id` ) as CNT FROM `events`" );
  768. result = tData->m_pDataReport->Query( tB );
  769. if( result!= NULL ) {
  770. if( result->size() > 0 ) {
  771. Assoc * cArr = result->at(0);
  772. Assoc::iterator it = cArr->find("CNT");
  773. if( it != cArr->end() ) if ( atoi( it->second.c_str() ) > 0 ) must_unlink = false;
  774. };
  775. deleteResult( result );
  776. };
  777. };
  778. delete( tData->m_pDataReport ); // close database
  779. };
  780. if ( must_unlink ){
  781. #ifdef DEBUG_EXTRA
  782. LOG("Remove Database!");
  783. LOG( tName );
  784. #endif
  785. unlink( tName );
  786. char tCMD[MAX_PATH];
  787. sprintf( tCMD, "rm -R -f %s", tData->reportVaultPath );
  788. #ifdef DEBUG_EXTRA
  789. LOG("Remove Folder!");
  790. LOG( tCMD );
  791. #endif
  792. system( tCMD );
  793. };
  794. } else {
  795. LOG_ERROR("Report Database Not Found!");
  796. };
  797. };
  798. };
  799. free( tData );
  800. //Delete Session Record
  801. m_pDBC->deleteSession( session_id );
  802. };
  803. return true;
  804. };