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.

623 lines
25 KiB

​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
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
12 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
12 hours ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
2 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
2 years 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
12 hours 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
12 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
12 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
12 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
12 hours ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  1. //----------------------------------------------------------------------------
  2. // Dr.Frucht Systems Ltd.
  3. // Copyright � 2000-2022. All Rights Reserved.
  4. // Version 1.0 11/19/2022
  5. // Last modification: 11/19/2022
  6. // PROJECT:
  7. // SUBSYSTEM:
  8. // FILE: mojoKernel.cpp
  9. // AUTHOR: gagua
  10. // OVERVIEW
  11. // ~~~~~~~~
  12. // LRF_Kernel.cpp
  13. //----------------------------------------------------------------------------
  14. //
  15. #include "servaKernel.h"
  16. #include "../data/json/json_tool.h"
  17. #include <strings.h>
  18. #include <sys/time.h>
  19. #include <time.h>
  20. #include <json/value.h>
  21. #include <json/writer.h>
  22. #include <json/reader.h>
  23. //#include "../common/kernelEventFilterAPF.h"
  24. //#include "../common/kernelEventFilterTrain.h"
  25. //#include "../common/kernelModuleEmbedVideo.h"
  26. #include "../common/serverMySQL_dataBinder.h"
  27. #include "servaModBusManager.h"
  28. #define LOG( X ) kernelPrototype::m_pLog->Log( "KRNL", this, X )
  29. #ifdef DEBUG
  30. #define LOG_ERROR( X ) {\
  31. char _tBfrErrMSG234[256];\
  32. sprintf( _tBfrErrMSG234, "In file %s[%d] in func:%s %s",__FILE__, __LINE__, __func__, X );\
  33. kernelPrototype::m_pLog->Log( "KRNL", this, _LOG_ERROR, _tBfrErrMSG234 );\
  34. }
  35. #else
  36. #define LOG_ERROR( X ) kernelPrototype::m_pLog->Log( "KRNL", this, _LOG_ERROR, X );
  37. #endif
  38. servaKernel *servaKernel::_instance = NULL;
  39. servaKernel *servaKernel::getInstance( config_setting_t *ptr ){
  40. if ( _instance == NULL ) {
  41. _instance = new servaKernel( ptr );
  42. };
  43. return _instance;
  44. };
  45. servaKernel::servaKernel( config_setting_t *ptr ):kernelPrototype( ptr ){
  46. //m_pEventHeap = basicEventHeap::getInstance();
  47. // memset( &m_sSysInfo, 0, sizeof( DBC_SYS_LOAD_INFO ));
  48. //m_pShadow = NULL;
  49. //m_pSystemAnchor = NULL;
  50. // m_bSessionStarted = false;
  51. // m_bWorkWithRemoteServer = false;
  52. // m_bKeepLocalReport = true;
  53. // m_bMediaMode = 0;
  54. m_pLifeMonitor = servaLifeMonitoring::getInstance();
  55. m_pSM = NULL;
  56. m_pRPC = NULL;//??
  57. m_pModBus = NULL;
  58. m_pVideoComposer = NULL; // was never initialised: automatic composing ran at most once, or never
  59. memset( &m_sServaConfig, 0, sizeof( DBC_SERVA_CONFIG ));
  60. setWM( WM_NONE );
  61. };
  62. servaKernel::~servaKernel(){
  63. WaitFinish( true );
  64. //stopSession( false );
  65. //while(1){
  66. // char tB[200];
  67. // sprintf( tB, "[%d] Seconds Till System Restart", timeout );
  68. // LOG( "BopBop!" );
  69. // SLEEP(1000);
  70. //};
  71. if ( m_pModBus ) {
  72. delete( (servaModBusManager *) m_pModBus );
  73. m_pModBus = NULL;
  74. };
  75. // Running encoders / composers belong to this kernel (their destructors stop and join the threads);
  76. // before, they were left running when the kernel was restarted
  77. for ( V_MEDIA_ENCODERS::iterator idx = m_vEncodersPool.begin(); idx != m_vEncodersPool.end(); idx++ ) delete( *idx );
  78. m_vEncodersPool.clear();
  79. for ( V_VIDEO_COMPOSERS::iterator idx = m_vComposersPool.begin(); idx != m_vComposersPool.end(); idx++ ) delete( *idx );
  80. m_vComposersPool.clear();
  81. if ( m_pVideoComposer ) {
  82. delete( m_pVideoComposer );
  83. m_pVideoComposer = NULL;
  84. };
  85. #ifdef LINUX_KERNEL_WATCHDOG
  86. LOG("Disable WD!");
  87. if( m_iWatchdogFd > -1 ) {
  88. char tB[64];
  89. sprintf( tB, "-1\n" );
  90. //ToDo: Make Error Handling here!
  91. write( m_iWatchdogFd, &tB, strlen( tB ) );
  92. };
  93. LOG("WatchDog turned Off!");
  94. #endif
  95. _instance = NULL;
  96. };
  97. bool servaKernel::create(){
  98. if( m_pSettings != NULL ) {
  99. config_setting_t * pSetting;
  100. int tVal;
  101. const char * tBuf;
  102. char tBuffer[128];
  103. LOG("Getting Settings ...");
  104. /*if( !config_setting_lookup_string( m_pSettings, MOJO_KERNEL_TAG_SERVER_IDENTITY, &tBuf ) ){
  105. char * tVar;
  106. char * tTS;
  107. tTS = getTStr(NULL);
  108. tVar = MD5String(tTS);
  109. free(tTS);
  110. sprintf( m_sIdentity, tVar );
  111. pSetting = config_setting_add( m_pSettings, MOJO_KERNEL_TAG_SERVER_IDENTITY, CONFIG_TYPE_STRING );
  112. config_setting_set_string( pSetting, tVar );
  113. free( tVar );
  114. basicSettingsProvider::getInstance()->compromise();
  115. LOG("Server Identity not defined - generating new!");
  116. } else {
  117. sprintf( m_sIdentity, tBuf );
  118. sprintf( tBuffer, "Server Identity Read From Settings: %s", tBuf );
  119. LOG( tBuffer );
  120. };
  121. if( !config_setting_lookup_int( m_pSettings, MOJO_KERNEL_TAG_SITE_ID, &tVal ) ){
  122. tVal = m_nInstanceID = 1;
  123. pSetting = config_setting_add( m_pSettings, MOJO_KERNEL_TAG_SITE_ID, CONFIG_TYPE_INT );
  124. config_setting_set_int( pSetting, tVal );
  125. basicSettingsProvider::getInstance()->compromise();
  126. LOG("Site ID not defined - using [1] as number!");
  127. } else {
  128. m_nInstanceID = tVal;
  129. sprintf( tBuffer, "App Instance ID Read From Settings: %d", m_nInstanceID );
  130. LOG( tBuffer );
  131. };*/
  132. basicSettingsProvider::getInstance()->validate();
  133. } else {
  134. LOG_ERROR("Failed Read Config Settings!");
  135. return false;
  136. };
  137. LOG("Register Server ... ");
  138. registerServA();
  139. m_pSM = servaSessionManager::getInstance( m_pSettings );
  140. if ( m_pSM ){
  141. cleanUpMess();
  142. if ( m_pSM->create() ) {
  143. LOG("Session Manager Created");
  144. servaModBusManager * tModBus = servaModBusManager::getInstance();
  145. if( tModBus ){
  146. LOG("Have ModBus Instance");
  147. if( tModBus->create() ){
  148. LOG("Modbus Created");
  149. m_pModBus = (void *) tModBus;
  150. } else delete( tModBus );
  151. };
  152. /* Test Composer */
  153. //servaVideoComposer *tVC = new servaVideoComposer( 49 );
  154. //if ( tVC ) {
  155. // tVC->compose();
  156. //};
  157. m_pRPC = servaRemoteClient::getInstance(this);
  158. if ( m_pRPC ) {
  159. if( m_pRPC->start() ) return init();
  160. };
  161. };
  162. };
  163. return false;
  164. };
  165. void servaKernel::m_fThreadProc( void ){
  166. time_t tTimeTSeconds = 0;
  167. time_t cTimeTSeconds = 0;
  168. m_bThreadStatus = TH_WORKING;
  169. LOG("ServA Started!");
  170. while ( m_bThreadStatus < TH_ENDED ) {
  171. if( DBC_RPC_WEB_CMD * tCMD = m_pDBC->fetchWebCmd( 0 ) ) {
  172. m_pDBC->updateWebCmdStatus( tCMD->id, DBC_CMD_STARTED );
  173. switch( tCMD->cmd ){
  174. case CMD_KRNL_RELOAD:{
  175. LOG("Reload ServA Node!");
  176. m_bThreadStatus = TH_ENDED;
  177. setExitCause( EXIT_CODE_RELOAD_SERVICES );
  178. break;
  179. };
  180. case CMD_KRNL_RESTART:{
  181. LOG("Restart ServA Node!");
  182. m_bThreadStatus = TH_ENDED;
  183. setExitCause( EXIT_CODE_KERNEL_CLEAR );
  184. break;
  185. };
  186. case CMD_KRNL_FACTORY_RESET:{
  187. LOG("Restart ServA -> Factory Reset!");
  188. m_bThreadStatus = TH_ENDED;
  189. setExitCause( EXIT_CODE_FACTORY_RESET );
  190. break;
  191. };
  192. case CMD_NODES_RELOAD:{
  193. //if( m_pNodeFactory != NULL ) {
  194. // m_pNodeFactory->reloadNodes();
  195. //};
  196. break;
  197. };
  198. case CMD_NODE_RELOAD:{
  199. uint32_t tNodeID = atoi( tCMD->param );
  200. //if( m_pNodeFactory != NULL ) {
  201. // m_pNodeFactory->reloadNode( tNodeID );
  202. //};
  203. break;
  204. };
  205. case CMD_KRNL_PNP:{
  206. //if( m_pHardwareManager!= NULL ) {
  207. // LOG_ERROR( "Restart and Detect HardWare!" );
  208. // // Must be shutdowned all service that uses hardware prior to detection!
  209. // m_bThreadStatus = TH_ENDED;
  210. // setExitCause( EXIT_CODE_DETECT_HARDWARE ); // Go -> Detect Hardware in BACKEND
  211. //};
  212. break;
  213. };
  214. case CMD_KRNL_UPDATE_IDENT:{
  215. //LOG("Restart Mojo -> Update Ident!");
  216. //sprintf( m_sIdentity, tCMD->PARAM );
  217. //config_setting_remove ( m_pSettings, MOJO_KERNEL_TAG_SERVER_IDENTITY );
  218. //config_setting_t *pSetting = config_setting_add( m_pSettings, MOJO_KERNEL_TAG_SERVER_IDENTITY, CONFIG_TYPE_STRING );
  219. //config_setting_set_string( pSetting, tCMD->PARAM );
  220. //basicSettingsProvider::getInstance()->compromise();
  221. //basicSettingsProvider::getInstance()->validate();
  222. //m_pDBC->updateServerIdentity( m_nServerID, m_sIdentity );
  223. m_bThreadStatus = TH_ENDED;
  224. setExitCause( EXIT_CODE_KERNEL_CLEAR );
  225. break;
  226. };
  227. case CMD_KRNL_REPLACE_DATABASE:{
  228. LOG("Restart Mojo -> Replace Database!");
  229. //CSTR tNAME = m_pDBC->getDataParam( 0 );
  230. //CSTR tUSER = m_pDBC->getDataParam( 1 );
  231. //CSTR tGROUP = m_pDBC->getDataParam( 2 );
  232. //if ( tNAME ) {
  233. // char tB[256];
  234. // sprintf( tB,"./data/%s.db", tCMD->PARAM );
  235. // if ( fileExist( tB )) {
  236. // LOG("Restart Mojo -> Close Database!");
  237. //Closing Database
  238. // delete( m_pDBC );
  239. // m_pDBC = NULL;
  240. // LOG("Restart Mojo -> Delete Database!");
  241. // //unlink( tNAME );
  242. // LOG("Restart Mojo -> Copy Database!");
  243. // fileCopy( tB, tNAME );
  244. // LOG("Restart Mojo -> Chown Database!");
  245. // ch_chown( tNAME, tUSER, tGROUP );
  246. // LOG("Restart Mojo -> Delete Old Database!");
  247. // unlink( tB );
  248. // m_bThreadStatus = TH_ENDED;
  249. // LOG("Restart Mojo -> Exit!");
  250. // setExitCause( EXIT_CODE_NO_DATABASE );//EXIT_CODE_RELOAD_SERVICES );
  251. // m_bThreadStatus = TH_ENDED;
  252. // } else {
  253. // LOG_ERROR("New Database Does not Exists!");
  254. // };
  255. //free( tNAME );
  256. //free( tUSER );
  257. //free( tGROUP );
  258. //};
  259. break;
  260. };
  261. case CMD_KRNL_SYNC_TIME:{
  262. uint32_t uts = atoi( tCMD->param );
  263. if( uts ){
  264. #if ( __GLIBC__ < 3 ) && ( __GLIBC_MINOR__ < 31 )
  265. time_t ts = (time_t)uts;
  266. if( stime( &ts ) == 0 ){
  267. // Restert Server;
  268. m_bThreadStatus = TH_ENDED;
  269. setExitCause( EXIT_CODE_KERNEL_CLEAR );
  270. };
  271. #else
  272. timespec ts;
  273. ts.tv_sec = (time_t)uts;
  274. ts.tv_nsec = 0;
  275. if( clock_settime( CLOCK_REALTIME, &ts ) == 0 ){
  276. // Restert Server;
  277. m_bThreadStatus = TH_ENDED;
  278. setExitCause( EXIT_CODE_KERNEL_CLEAR );
  279. };
  280. #endif
  281. };
  282. break;
  283. };
  284. case CMD_KRNL_SYSTEM_TASK:{
  285. break;
  286. };
  287. case CMD_KRNL_PURGE_SESSION:{
  288. if ( tCMD->aux_id ) {
  289. LOG("Purge Session");
  290. if (m_pSM) m_pSM->eraseSession( tCMD->aux_id );
  291. };
  292. break;
  293. };
  294. case CMD_KRNL_SET_SESSION_HZL:{
  295. uint8_t tLVL = atoi( tCMD->param );
  296. if ( tCMD->aux_id ) {
  297. LOG("Life Session Hazard Level Updated by Operator");
  298. /* Actual DataBase change done in WebApp Here we just making internal Event */
  299. SESSION_RATE_DATA *tData = (SESSION_RATE_DATA *) malloc( sizeof( SESSION_RATE_DATA ) );
  300. if ( tData ) {
  301. tData->level = tLVL;
  302. tData->track_id = tCMD->aux_id;
  303. EVENT_CONTAINER * tEvt = createBasicEvent( 0, EVT_CLASS_SYSTEM, EVT_SRV_SESSION_RATED, NULL, NULL, tData );
  304. if ( tEvt ) {
  305. basicEventHeap::getInstance()->broadcast( tEvt );
  306. } else {
  307. free( tData );
  308. };
  309. };
  310. };
  311. break;
  312. };
  313. case CMD_KRNL_TEST_MODBUS:{
  314. MODBUS_TEST_DATA *tData = (MODBUS_TEST_DATA *) malloc( sizeof( MODBUS_TEST_DATA ) );
  315. if ( tData ) {
  316. tData->id = tCMD->aux_id;
  317. tData->c_OutBits = atoi( tCMD->param );
  318. EVENT_CONTAINER * tEvt = createBasicEvent( 0, EVT_CLASS_SYSTEM, EVT_SRV_MODBUS_TEST_M, NULL, NULL, tData );
  319. if ( tEvt ) {
  320. basicEventHeap::getInstance()->broadcast( tEvt );
  321. } else {
  322. free( tData );
  323. };
  324. };
  325. break;
  326. };
  327. case CMD_KRN_COMPOSE_SESSION_VIDEOS:{
  328. uint64_t session_id = tCMD->aux_id;
  329. if ( session_id ) {
  330. char tB[256];
  331. sprintf( tB, "Ordered Compose of session %lld", session_id );
  332. LOG( tB );
  333. servaVideoComposer *tCMP = new servaVideoComposer( session_id );
  334. if ( tCMP ) {
  335. if ( tCMP->compose() ) {
  336. m_vComposersPool.push_back(tCMP);
  337. } else {
  338. LOG("Disengage Composer!");
  339. delete( tCMP ); // was leaked
  340. };
  341. };
  342. };
  343. break;
  344. };
  345. case CMD_KRN_SCADA_SNOOZE_POST_MESSAGE:{
  346. uint64_t message_id = tCMD->aux_id;
  347. if ( message_id ) {
  348. #ifdef DEBUG
  349. char tB[256];
  350. sprintf( tB, "Ordered Snooze %lld SCADA Message", message_id );
  351. LOG( tB );
  352. #endif
  353. MODBUS_POST_DATA *tData = m_pDBC->getScadaPostData( message_id );
  354. if ( tData ) {
  355. m_pDBC->updateScadaPostStatus( message_id, 1 );
  356. EVENT_CONTAINER * tEvt = createBasicEvent( 0, EVT_CLASS_SYSTEM, EVT_SRV_MODBUS_S_POSTBOX, NULL, NULL, tData );
  357. if ( tEvt ) {
  358. basicEventHeap::getInstance()->broadcast( tEvt );
  359. } else {
  360. free( tData );
  361. };
  362. };
  363. };
  364. break;
  365. };
  366. case CMD_KRN_SCADA_DISMISS_POST_MESSAGE:{
  367. uint64_t message_id = tCMD->aux_id;
  368. if ( message_id ) {
  369. #ifdef DEBUG
  370. char tB[256];
  371. sprintf( tB, "Ordered Dismiss %lld SCADA Message", message_id );
  372. LOG( tB );
  373. #endif
  374. MODBUS_POST_DATA *tData = m_pDBC->getScadaPostData( message_id );
  375. if ( tData ) {
  376. m_pDBC->deleteScadaPost( message_id );
  377. EVENT_CONTAINER * tEvt = createBasicEvent( 0, EVT_CLASS_SYSTEM, EVT_SRV_MODBUS_D_POSTBOX, NULL, NULL, tData );
  378. if ( tEvt ) {
  379. basicEventHeap::getInstance()->broadcast( tEvt );
  380. } else {
  381. free( tData );
  382. };
  383. };
  384. };
  385. break;
  386. };
  387. //Debug Functionality from Platform View
  388. case CMD_KRN_SCADA_DISMISS_ALRM_PLATFORM:{
  389. uint64_t platform_id = tCMD->aux_id;
  390. if( platform_id ) {
  391. #ifdef DEBUG
  392. char tB[256];
  393. sprintf( tB, "Ordered Dismiss %lld SCADA Platform ALARMS", platform_id );
  394. LOG( tB );
  395. #endif
  396. EVENT_CONTAINER * tEvt = createBasicEvent( platform_id, EVT_CLASS_SYSTEM, EVT_SRV_MODBUS_CLEAR_S );
  397. if ( tEvt ) {
  398. basicEventHeap::getInstance()->broadcast( tEvt );
  399. } else {
  400. // free( tData );
  401. };
  402. };
  403. break;
  404. };
  405. case CMD_KRN_SCADA_DISMISS_TOTT_PLATFORM:{
  406. uint64_t platform_id = tCMD->aux_id;
  407. if( platform_id ) {
  408. #ifdef DEBUG
  409. char tB[256];
  410. sprintf( tB, "Ordered Dismiss %lld SCADA Platform ALL", platform_id );
  411. LOG( tB );
  412. #endif
  413. EVENT_CONTAINER * tEvt = createBasicEvent( platform_id, EVT_CLASS_SYSTEM, EVT_SRV_MODBUS_CLEAR_P );
  414. if ( tEvt ) {
  415. basicEventHeap::getInstance()->broadcast( tEvt );
  416. } else {
  417. //free( tData );
  418. };
  419. };
  420. break;
  421. };
  422. };
  423. m_pDBC->updateWebCmdStatus( tCMD->id, DBC_CMD_READY_TO_CLEAN );
  424. free( tCMD );
  425. };
  426. cTimeTSeconds = time( NULL );
  427. if( cTimeTSeconds != tTimeTSeconds ){ //Each Second
  428. tTimeTSeconds = cTimeTSeconds;
  429. #ifdef LINUX_KERNEL_WATCHDOG
  430. if( m_iWatchdogFd > -1 ) {
  431. char tB[64];
  432. sprintf( tB, "2000\n" );
  433. //ToDo: Make Error Handling here!
  434. write( m_iWatchdogFd, &tB, strlen( tB ) );
  435. };
  436. #endif
  437. m_pDBC->cleanWebCmd();
  438. updateStatus();
  439. if ( m_vEncodersPool.size() ) {
  440. for ( V_MEDIA_ENCODERS::iterator idx = m_vEncodersPool.begin(); idx < m_vEncodersPool.end(); ) {
  441. if ( (*idx)->getStatus() == ENCODER_FINISHED ) {
  442. handleEncodedVideo( *idx ); // deletes the encoder
  443. idx = m_vEncodersPool.erase( idx ); // erase() invalidates idx: continue with the returned one
  444. } else idx++;
  445. };
  446. };
  447. if ( m_vComposersPool.size() ) {
  448. for ( V_VIDEO_COMPOSERS::iterator idx = m_vComposersPool.begin(); idx< m_vComposersPool.end(); ) {
  449. if ( (*idx)->isFinished() ) {
  450. delete( *idx );
  451. idx = m_vComposersPool.erase( idx );
  452. } else idx++;
  453. };
  454. };
  455. if ( m_sServaConfig.encoderLimit ) {
  456. if (m_vEncodersPool.size() < m_sServaConfig.encoderLimit) {
  457. if (uint64_t new_id = m_pDBC->getRecentMediaId()) {
  458. LOG("New Encoder!");
  459. if ( processVideoFile( new_id ) ) {
  460. updateEncodeStatus( new_id, MEDIA_ENCODE_PROGRESS, 0 );
  461. } else {
  462. LOG_ERROR("Cannot Encode Queued Video -> Removing Task!");
  463. m_pDBC->removeRemoteMediaInfo( new_id );
  464. };
  465. };
  466. };
  467. } else LOG_ERROR("Video Encoders Disabled??");
  468. if ( m_pSM ) m_pSM->validate();
  469. if ( m_pLifeMonitor ) m_pLifeMonitor->validate();
  470. if ( m_pModBus ) ((servaModBusManager *)m_pModBus)->validate();
  471. //m_pHardwareManager->updateSysInfo( &m_sSysInfo );
  472. // The automatic composer was never released after it finished, so it ran only once
  473. if ( m_pVideoComposer != NULL && m_pVideoComposer->isFinished() ) {
  474. delete( m_pVideoComposer );
  475. m_pVideoComposer = NULL;
  476. };
  477. if ( m_pVideoComposer == NULL ) {
  478. uint64_t tSID = m_pDBC->getSessionWithUnmergedVideo( m_sServaConfig.composerProceedDelay );
  479. if ( tSID ) {
  480. m_pVideoComposer = new servaVideoComposer( tSID );
  481. if ( m_pVideoComposer ) {
  482. if( !m_pVideoComposer->compose() ){
  483. delete( m_pVideoComposer );
  484. m_pVideoComposer = NULL;
  485. };
  486. };
  487. };
  488. };
  489. };
  490. SLEEP(SLEEP_KERNEL_INTERVAL);
  491. };
  492. };
  493. void servaKernel::updateEncodeStatus( uint64_t dbid, uint8_t status, uint8_t perc ){
  494. m_pDBC->updateEncodeStatus( dbid, status, perc );
  495. };
  496. bool servaKernel::processVideoFile( uint64_t dbid ){
  497. if ( dbid == 0 ) return false;
  498. DBC_RPC_MEDIA_INFO *NFO = m_pDBC->getRemoteMediaInfo( dbid );
  499. if ( NFO ) {
  500. if ( strcmp( NFO->fmt, "mp4" ) == 0 ) {
  501. #ifdef DEBUG
  502. LOG("Skip Convertion of MP4");
  503. #endif
  504. DBC_RPC_MEDIA_INFO_EX *tP = m_pDBC->getRemoteMediaInfoEx( dbid );
  505. if ( tP ) {
  506. if( !m_pSM->addVideo( tP )){
  507. LOG_ERROR("Cannot Add to session Media Info!");
  508. };
  509. #ifdef DEBUG
  510. LOG("Delete Extended Info");
  511. #endif
  512. free( tP );
  513. } else {
  514. LOG_ERROR("Cannot get Extended Encoder Queue Media Info!");
  515. };
  516. free( NFO );
  517. return false;
  518. };
  519. servaMediaEncoder *ptr = new servaMediaEncoder(dbid);
  520. if ( ptr ) {
  521. #ifdef DEBUG
  522. LOG("Encoder Constructed!");
  523. #endif
  524. char tA[MAX_PATH];
  525. char tB[MAX_PATH];
  526. //Todo -> Instead GetSessionBase -> calc Base based on TS of video
  527. CSTR BASE = m_pSM->getSessionBase( NFO->session_id );
  528. if( BASE ){
  529. sprintf( tA,"%s/%s.%s", BASE, NFO->uuid, NFO->fmt );
  530. LOG(tA);
  531. sprintf( tB,"%s/%s.mp4", BASE, NFO->uuid );
  532. LOG(tB);
  533. free(BASE);
  534. if ( ptr->create( tA, tB, NFO->fps ) ) {
  535. #ifdef DEBUG
  536. LOG("Encoder Created!");
  537. #endif
  538. m_vEncodersPool.push_back( ptr );
  539. free( NFO ); // was leaked on this (the normal) path
  540. return true;
  541. };
  542. };
  543. delete( ptr );
  544. };
  545. free( NFO );
  546. } else LOG("No Video Info!!");
  547. return false;
  548. };
  549. void servaKernel::handleEncodedVideo( servaMediaEncoder *ptr ){
  550. if ( ptr ) {
  551. m_pDBC->updateEncodeFormat( ptr->getDBID(), ptr->getDstFormat() );
  552. DBC_RPC_MEDIA_INFO_EX *tP = m_pDBC->getRemoteMediaInfoEx( ptr->getDBID() );
  553. if ( tP ) {
  554. if( m_pSM->addVideo( tP )){
  555. m_pDBC->removeRemoteMediaInfo( ptr->getDBID() );
  556. } else {
  557. LOG_ERROR("Cannot Add to session Media Info!");
  558. };
  559. LOG("Delete Extended Info");
  560. free( tP );
  561. } else {
  562. LOG_ERROR("Cannot get Extended Encoder Queue Media Info!");
  563. };
  564. LOG("Delete Encoder");
  565. delete( ptr );
  566. LOG("Done");
  567. };
  568. };
  569. bool servaKernel::dispatchEvent( EVENT_CONTAINER *Evt ){
  570. if ( Evt == NULL ) return false;
  571. /*
  572. switch ( Evt->m_eClass ) {
  573. case EVT_CLASS_VIDEO:{
  574. switch ( Evt->m_eType ) {
  575. case EVT_SRV_VIDEO_CHUNK:{
  576. SERVA_VIDEO_TRANSFER_INFO *tData = ( SERVA_VIDEO_TRANSFER_INFO * ) Evt->m_pEvtData;
  577. if ( tData ){
  578. if ( tData->status == MEDIA_STORED ) {
  579. updateEncodeStatus(tData->db_id, tData->status, tData->perc);
  580. };
  581. };
  582. return false; // Kernel is Final Destination for that Event
  583. };
  584. };
  585. break;
  586. };
  587. };*/
  588. return true;
  589. };
  590. //Todo -> Startup Cleanup Media Encoder Queue (with ability to finish unfinishing jobs -> Drop just unsucessful transfers
  591. // Make Treshold of Running Encoders to a server
  592. #undef LOG
  593. #undef LOG_ERROR