 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
22 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
22 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
22 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
22 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
22 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
22 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
22 hours ago |
|
#include "mysql_class.h"
#define LOG(X) m_pLog->Log("MYDB", this, X)
#define LOG_ERROR(X) m_pLog->Log("MYDB", this, _LOG_ERROR, X)
/* Default Constructor */
MySQL_Connector::MySQL_Connector() : m_mAccessMutex(){ m_pLog = basicLogCollection::getInstance(); m_pDBLink = NULL; m_pDBName = NULL; m_pDBHost = NULL; m_pDBUser = NULL; m_pDBPassword = NULL; m_nPort = 0; m_bIsConnected = false;}
MySQL_Connector::MySQL_Connector(CSTR DBHost, CSTR DBUser, CSTR DBPassword, uint16_t Port) : m_mAccessMutex(){ m_pLog = basicLogCollection::getInstance(); m_pDBLink = mysql_init(NULL); m_pDBName = NULL; m_pDBHost = (CSTR) malloc(strlen((const char *) DBHost) + 1); strcpy(m_pDBHost, DBHost); m_pDBUser = (CSTR) malloc(strlen((const char *) DBUser) + 1); strcpy(m_pDBUser, DBUser); m_pDBPassword = (CSTR) malloc(strlen((const char *) DBPassword) + 1); strcpy(m_pDBPassword, DBPassword); m_nPort = Port; m_bIsConnected = false; /* CLIENT_COMPRESS | CLIENT_FOUND_ROWS | CLIENT_IGNORE_SIGPIPE | CLIENT_INTERACTIVE | CLIENT_IGNORE_SPACE */ if (! mysql_real_connect(m_pDBLink, m_pDBHost, m_pDBUser, m_pDBPassword, NULL, m_nPort, NULL, CLIENT_COMPRESS)) { LOG_ERROR(mysql_error(m_pDBLink)); } else { m_bIsConnected = true; }}
MySQL_Connector::MySQL_Connector(CSTR DBName, CSTR DBHost, CSTR DBUser, CSTR DBPassword, uint16_t Port) : m_mAccessMutex(){ m_pLog = basicLogCollection::getInstance(); m_pDBLink = mysql_init(NULL); m_pDBName = (CSTR) malloc(strlen((const char *) DBName) + 1); strcpy(m_pDBName, DBName); m_pDBHost = (CSTR) malloc(strlen((const char *) DBHost) + 1); strcpy(m_pDBHost, DBHost); m_pDBUser = (CSTR) malloc(strlen((const char *) DBUser) + 1); strcpy(m_pDBUser, DBUser); m_pDBPassword = (CSTR) malloc(strlen((const char *) DBPassword) + 1); strcpy(m_pDBPassword, DBPassword); m_nPort = Port; m_bIsConnected = false; /* CLIENT_COMPRESS | CLIENT_FOUND_ROWS | CLIENT_IGNORE_SIGPIPE | CLIENT_INTERACTIVE | CLIENT_IGNORE_SPACE */ if (! mysql_real_connect(m_pDBLink, m_pDBHost, m_pDBUser, m_pDBPassword, NULL, m_nPort, NULL, CLIENT_COMPRESS)) { LOG_ERROR(mysql_error(m_pDBLink)); } else { if (mysql_select_db(m_pDBLink, m_pDBName) == 0) { m_bIsConnected = true;#ifdef DEBUG
char temp[256]; sprintf(temp, "Connected to %s@%s:%d", m_pDBName, m_pDBHost, m_nPort); LOG(temp);#endif
} else { LOG_ERROR(mysql_error(m_pDBLink)); }; };}
/* default Destructor */MySQL_Connector::~MySQL_Connector(){ if (m_pDBName != NULL) { delete(m_pDBName); } if (m_pDBHost != NULL) { delete(m_pDBHost); } if (m_pDBUser != NULL) { delete(m_pDBUser); } if (m_pDBPassword != NULL) { delete(m_pDBPassword); } if (m_pDBLink != NULL) { mysql_close(m_pDBLink); } mysql_library_end(); m_bIsConnected = false;}
bool MySQL_Connector::Connect(CSTR DBHost, CSTR DBUser, CSTR DBPassword, uint16_t Port){ m_bIsConnected = false; if (m_pDBLink != NULL) { mysql_close(m_pDBLink); }; m_pDBLink = mysql_init(NULL); if (m_pDBName != NULL) { delete(m_pDBName); } if (m_pDBHost != NULL) { delete(m_pDBHost); } if (m_pDBUser != NULL) { delete(m_pDBUser); } if (m_pDBPassword != NULL) { delete(m_pDBPassword); } m_pDBHost = (CSTR) malloc(strlen((const char *) DBHost) + 1); strcpy(m_pDBHost, DBHost); m_pDBUser = (CSTR) malloc(strlen((const char *) DBUser) + 1); strcpy(m_pDBUser, DBUser); m_pDBPassword = (CSTR) malloc(strlen((const char *) DBPassword) + 1); strcpy(m_pDBPassword, DBPassword); m_nPort = Port; /* CLIENT_COMPRESS | CLIENT_FOUND_ROWS | CLIENT_IGNORE_SIGPIPE | CLIENT_INTERACTIVE | CLIENT_IGNORE_SPACE */ if (! mysql_real_connect(m_pDBLink, m_pDBHost, m_pDBUser, m_pDBPassword, NULL, m_nPort, NULL, CLIENT_COMPRESS)) { LOG_ERROR(mysql_error(m_pDBLink)); } else { m_bIsConnected = true; } return m_bIsConnected;}
bool MySQL_Connector::Connect(CSTR DBName, CSTR DBHost, CSTR DBUser, CSTR DBPassword, U16 Port){ m_bIsConnected = false; if (m_pDBLink != NULL) { mysql_close(m_pDBLink); }; m_pDBLink = mysql_init(NULL);
if (m_pDBName != NULL) { delete(m_pDBName); } if (m_pDBHost != NULL) { delete(m_pDBHost); } if (m_pDBUser != NULL) { delete(m_pDBUser); } if (m_pDBPassword != NULL) { delete(m_pDBPassword); } m_pDBName = (CSTR) malloc(strlen((const char *) DBName) + 1); strcpy(m_pDBName, DBName); m_pDBHost = (CSTR) malloc(strlen((const char *) DBHost) + 1); strcpy(m_pDBHost, DBHost); m_pDBUser = (CSTR) malloc(strlen((const char *) DBUser) + 1); strcpy(m_pDBUser, DBUser); m_pDBPassword = (CSTR) malloc(strlen((const char *) DBPassword) + 1); strcpy(m_pDBPassword, DBPassword); m_nPort = Port; /* CLIENT_COMPRESS | CLIENT_FOUND_ROWS | CLIENT_IGNORE_SIGPIPE | CLIENT_INTERACTIVE | CLIENT_IGNORE_SPACE */ if (! mysql_real_connect(m_pDBLink, m_pDBHost, m_pDBUser, m_pDBPassword, NULL, m_nPort, NULL, CLIENT_COMPRESS)) { LOG_ERROR(mysql_error(m_pDBLink)); } else { if (mysql_select_db(m_pDBLink, m_pDBName) == 0) { m_bIsConnected = true;#ifdef DEBUG
char temp[256]; sprintf(temp, "Connected to %s@%s:%d", m_pDBName, m_pDBHost, m_nPort); LOG(temp);#endif
} else { LOG_ERROR(mysql_error(m_pDBLink)); }; }; return m_bIsConnected;}
bool MySQL_Connector::ReConnect(void){ m_bIsConnected = false; if (m_pDBLink != NULL) { mysql_close(m_pDBLink); }; m_pDBLink = mysql_init(NULL); /* CLIENT_COMPRESS | CLIENT_FOUND_ROWS | CLIENT_IGNORE_SIGPIPE | CLIENT_INTERACTIVE | CLIENT_IGNORE_SPACE */ if (! mysql_real_connect(m_pDBLink, m_pDBHost, m_pDBUser, m_pDBPassword, NULL, m_nPort, NULL, CLIENT_COMPRESS)) { LOG_ERROR(mysql_error(m_pDBLink)); } else { if (mysql_select_db(m_pDBLink, m_pDBName) == 0) { m_bIsConnected = true;#ifdef DEBUG
char temp[256]; sprintf(temp, "ReConnected to %s@%s:%d", m_pDBName, m_pDBHost, m_nPort); LOG(temp);#endif
} else { LOG_ERROR(mysql_error(m_pDBLink)); }; }; return m_bIsConnected;}
AAssoc * MySQL_Connector::Query(CSTR QS, bool useCache){ AAssoc * RetVal = NULL; Assoc * tElement; unsigned int num_Fields; MYSQL_RES * Result = NULL; char temp[256]; if (useCache) useCache = true;#ifdef DEBUG_MYSQL_QUERIES
LOG(QS);#endif
m_mAccessMutex.lock(); /*
if( mysql_query( m_pDBLink, QS ) ){ LOG_ERROR( mysql_error( m_pDBLink ));
char temp[256]; sprintf( temp, "Error Code: %d", mysql_errno( m_pDBLink )); LOG_ERROR( temp );
switch( mysql_errno( m_pDBLink ) ){ case 1156: case 2006: case 2013 case 2014:{// Server Gone
if( ReConnect() ){ if ( !mysql_query( m_pDBLink, QS ) ){ Result = mysql_store_result( m_pDBLink ); } else { LOG_ERROR( mysql_error( m_pDBLink )); sprintf( temp, "Reconnect Error Code: %d", mysql_errno( m_pDBLink )); LOG_ERROR( temp ); }; }; break; }; }; } else { Result = mysql_store_result( m_pDBLink ); };*/ int tRetries = 0; while (mysql_query(m_pDBLink, QS)) { LOG_ERROR(mysql_error(m_pDBLink)); sprintf(temp, "Error Code: %d", mysql_errno(m_pDBLink)); LOG_ERROR(temp); switch (mysql_errno(m_pDBLink)) { case 1156: case 2006: case 2013: case 2014: { // Bounded: with the server down this looped forever while holding the access mutex,
// blocking every thread that uses the database
if (tRetries++ < MYSQL_MAX_RECONNECT_ATTEMPTS) { ReConnect(); continue; } break; }; }; break; }; Result = mysql_store_result(m_pDBLink); if (Result != NULL) { if (mysql_num_rows(Result)) { RetVal = new AAssoc(); num_Fields = mysql_num_fields(Result); MYSQL_FIELD * Fields; MYSQL_ROW Row; Fields = mysql_fetch_fields(Result); while ((Row = mysql_fetch_row(Result)) != NULL) { tElement = new Assoc(); string Key; string Val; for (uint32_t i = 0; i < num_Fields; i++) { Key = string(Fields[i].name); if (Row[i] != NULL) { Val = string(Row[i]); } else { Val = string("0"); }; (*tElement)[Key] = Val; }; /*for (map<string, string>::iterator p = (*tElement).begin( ); p != (*tElement).end( ); ++p ) {
cout << "Field: " << p->first<< ", #: " << p->second << endl; } */ RetVal->push_back(tElement); }; } else {#ifdef DEBUG_MYSQL_QUERIES
LOG("No Rows");#endif
RetVal = NULL; }; mysql_free_result(Result); Result = NULL; } else {#ifdef DEBUG_MYSQL_QUERIES
LOG("Empty Result");#endif
RetVal = NULL; }; m_mAccessMutex.unlock(); return RetVal;}
CSTR MySQL_Connector::escapeString(CSTR str){ int len = strlen(str); CSTR temp = (CSTR) malloc(len * 2 + 1); if (temp) { m_mAccessMutex.lock(); mysql_real_escape_string(m_pDBLink, temp, str, len); m_mAccessMutex.unlock(); }; return temp;}
CSTR MySQL_Connector::escapeBinary(uint8_t * Data, uint32_t Size){ CSTR temp = NULL; if (Data && Size) { temp = (CSTR) malloc(Size * 2 + 1); if (temp) { m_mAccessMutex.lock(); mysql_real_escape_string(m_pDBLink, temp, (const char *) Data, Size); m_mAccessMutex.unlock(); }; }; return temp;}
/*
Non-blocking query without logging, for the database log service: it runs inside the log broadcast (log mutex held) and must not wait for the access mutex - a thread that holds the access mutex and logs an error waits for the log mutex (deadlock), and on the same thread the non-recursive access mutex would deadlock by itself. Returns false when the connection is busy.*/bool MySQL_Connector::TrySilentQuery(CSTR QS){ if (! m_mAccessMutex.try_lock()) { return false; } bool RetVal = (mysql_query(m_pDBLink, QS) == 0); if (RetVal) { MYSQL_RES * tRes = mysql_store_result(m_pDBLink); // INSERT: normally none
if (tRes) { mysql_free_result(tRes); } } m_mAccessMutex.unlock(); return RetVal;}
uint64_t MySQL_Connector::QueryID(CSTR QS){ uint64_t RetVal = 0; char temp[256];
m_mAccessMutex.lock();#ifdef DEBUG_MYSQL_QUERIES
LOG(QS);#endif
int tRetries = 0; while (mysql_query(m_pDBLink, QS)) { LOG_ERROR(mysql_error(m_pDBLink)); sprintf(temp, "Error Code: %d", mysql_errno(m_pDBLink)); LOG_ERROR(temp); switch (mysql_errno(m_pDBLink)) { case 1156: case 2006: case 2013: case 2014: { // Bounded: with the server down this looped forever while holding the access mutex,
// blocking every thread that uses the database
if (tRetries++ < MYSQL_MAX_RECONNECT_ATTEMPTS) { ReConnect(); continue; } break; }; }; break; }; RetVal = (uint64_t) mysql_insert_id(m_pDBLink); m_mAccessMutex.unlock(); return RetVal;}
void MySQL_Connector::SilentQuery(CSTR QS){ char temp[256];
m_mAccessMutex.lock();#ifdef DEBUG_MYSQL_QUERIES
LOG(QS);#endif
int tRetries = 0; while (mysql_query(m_pDBLink, QS)) { LOG_ERROR(mysql_error(m_pDBLink)); sprintf(temp, "Error Code: %d", mysql_errno(m_pDBLink)); LOG_ERROR(temp); switch (mysql_errno(m_pDBLink)) { case 1156: case 2006: case 2013: case 2014: { // Bounded: with the server down this looped forever while holding the access mutex,
// blocking every thread that uses the database
if (tRetries++ < MYSQL_MAX_RECONNECT_ATTEMPTS) { ReConnect(); continue; } break; }; }; break; }; m_mAccessMutex.unlock();}
void deleteResult(AAssoc *& R){ if (R) { while (R->size()) { delete((Assoc *) R->at(0)); R->erase(R->begin()); }; R->clear(); delete(R); R = NULL; };}
#undef LOG
#undef LOG_ERROR
|