Commit Graph
109 Commits
Author SHA1 Message Date
Jash Ambaliya d3a156b029 fix: zmDbDo returns 0 on every failed query, including one that fails during shutdown refs #7982 (#7984) 2026-11-24 20:44:10 -05:00
Jash 6dcef45fb6 fix: stop a hung database from blocking Fatal and Panic from exiting fixes #5643 2026-11-15 10:47:45 +05:30
Jash a049f8fd66 fix: cap queued database log rows so a log flood can't grow memory without bound fixes #5674 2026-11-13 13:06:26 +05:30
Jash 351f096974 fix: keep the DB queue writing until stop() so rows queued at shutdown are saved refs #5603 2026-11-12 09:41:22 +05:30
Isaac ConnorandClaude Opus 5.5 4bc4c6e4e0 fix: pause database logging only around the queue's inserts into Logs
Holding a DatabaseLogPause on the dbQueue thread for its whole life kept the
errors of every queued write out of Logs too: Monitor_Status updates, Events,
Frames and Stats rows. Under lock contention most "Giving up on query" errors
were only in the log files.

Mark each queued row with whether the logger queued it, and pause database
logging only around those inserts into Logs and the backlog warning. The loop
stays closed: a line about a queued write queues one Logs insert, which logs
nothing to the database.

Test: an error from a queued write reaches Logs.

From review by @nabbi on #5208.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 22:12:11 -04:00
Isaac ConnorandClaude Opus 5.5 26acd8db0f fix: keep only the database queue thread out of database logging
zmDbDo() kept its calling thread out of the database for the whole query,
which stopped its own "Success running sql query" line from queueing another
Logs insert. But the loop only starts where the Logs rows are inserted, on
the dbQueue thread, and pausing every zmDbDo() also kept the calling thread's
errors about its query out of Logs: "Can't run query" and the lock contention
retries were only in the log files.

Hold one Logger::DatabaseLogPause on the dbQueue thread for its whole life,
in zmDbQueue::process(), and none in zmDbDo(). Lines the queue thread logs,
the backlog warning included, still stay out of the database; every other
thread's query lines reach it, errors and, at a debug database level, the
success lines too.

Tests: the queue thread's inserts into Logs log nothing and the row count
settles, a query on another thread logs its success line at debug, and an
error from a failed query reaches Logs. The last two fail with the pause in
zmDbDo().

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 22:10:14 -04:00
nicandClaude Opus 5.5 378b774c12 fix: stop dropping other threads' database log lines during queries (#5197)
* test: cover lines logged to the database while a query runs

Live-database tests ([notCI][dblive]) for how the logger and zmDbDo
interact:

- a line logged on one thread while another thread is inside zmDbDo
  reaches the Logs table
- zmDbDo's own debug lines stay out of Logs when the database level is
  debug, so inserting a Logs row cannot log another one without end
- a dbQueue backlog over 40 rows does not deadlock threads that log

The first fails on master: zmDbDo sets the process-wide database log
level to NOLOG for the whole query, so the line is dropped.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: stop dropping other threads' database log lines during queries

zmDbDo lowered the logger's database level to NOLOG for as long as its
query ran, so that its own lines (and, at a debug database level, the line
about every insert into Logs) could not queue more inserts into Logs. The
level is shared by the whole process, so every line any other thread
logged in that window never reached the Logs table or the web log view,
while the log file and syslog still had it. The save and restore of that
shared level from several threads is also a data race: a thread can
restore a stale NOLOG and leave database logging off.

Replace the toggle with Logger::DatabaseLogPause, a thread_local count
that keeps only the current thread's lines out of the database. zmDbDo
and the queue's backlog warning use it; mDatabaseLevel is no longer
written outside of initialise().

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: warn about the database queue backlog outside the queue's lock

zmDbQueue::process logged its "db queue size has grown larger" warning
while holding the queue mutex. logPrint holds the logger's mutex while it
pushes a Logs row, which takes the queue mutex. With more than 40 rows
waiting, a thread logging to the database and the queue thread could each
hold one of the two locks and wait for the other, stopping every thread
that logs.

Take the backlog size under the lock and warn after releasing it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 10:52:18 -04:00
Isaac ConnorandClaude Opus 5 1f70965a98 fix: retry deadlocked queries with bounded backoff instead of failing them
zmDbDo, zmDbDoInsert and zmDbDoUpdate all decided what to do with a failed
query by testing for ER_LOCK_WAIT_TIMEOUT alone, which got both halves of
lock contention wrong:

- ER_LOCK_DEADLOCK was not retried at all. InnoDB resolves a deadlock by
  rolling one side back and expects that side to re-run; instead the query
  was logged and abandoned. Event creation goes through zmDbDoInsert, which
  is where this actually bites.

- ER_LOCK_WAIT_TIMEOUT re-ran immediately and forever, with no delay and no
  attempt limit, so two writers deadlocking against each other kept
  colliding on the same schedule.

Both now go through one retry decision: five attempts with a jittered
50ms-doubling backoff, then give up and report. The jitter is what stops
two contending sessions waking together and repeating the deadlock.

The wait happens under db_mutex, which every other database user in the
process is blocked on, so the budget is deliberately small -- about 3.1s
across all five attempts. That is still far less than the unbounded
ER_LOCK_WAIT_TIMEOUT loop it replaces, where each round costs a full
innodb_lock_wait_timeout. The change in behaviour is that a query which
would eventually have won after many minutes is now abandoned; it is
reported at Error with the attempt count.

The error is now logged once, when giving up, rather than on every round.
mysql_errno is read next to mysql_error rather than after the logging
call, so it cannot be clobbered in between.

Two other things, both small and both in the same area:

zmDbEscapeString called mysql_real_escape_string unconditionally, and that
reads the character set off the connection, so a closed handle sends it
into freed state. It now falls back to escaping the injection-relevant
characters itself. That fallback is only correct because the connection is
utf8mb4, where no byte of a multi-byte sequence is ASCII and so no sequence
can absorb a trailing backslash; the comment says so, since it would be
wrong for a character set like GBK. It deliberately does not take
db_mutex to read the flag: the logger calls this from Error(), and
zmDbFetch reaches Error() while holding db_mutex, so locking here would
self-deadlock the process on any failed query.

zm_rtsp_server was the one daemon closing the database without stopping
the queue that writes through it. Fixed at the call site rather than
inside zmDbClose, which holds db_mutex while the queue thread needs that
same mutex to drain -- joining it from in there would deadlock.

Tests: tests/zm_db_contention.cpp covers the retry budget only, 2011
assertions. Verified it fails when the budget is removed. The retry loop
itself needs a database and two contending sessions and is NOT covered;
it wants verifying against a real server under contention before this is
relied on. Full suite 12171 assertions in 133 test cases. Builds clean.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015Y6FieTwEXuLhhR4e2yiax
2026-09-04 07:15:30 -04:00
Isaac ConnorandClaude Opus 4.8 eb83ca1e78 fix: return the insert id as uint64_t so event ids past 2^31 survive
mysql_insert_id() returns my_ulonglong, but zmDbDoInsert() returned int.
Once Events.Id passed INT32_MAX the id was truncated, then sign-extended
when stored in Event::id (uint64_t), so 3502167073 became
18446744072916751373. The Events_Hour/Day/Week/Month inserts were given
the negative value and rejected, and every later UPDATE of the event
matched no row.

Also widen the callers that re-truncated the result: the re-analysis
event id in zma, Tag::Id() when building an Event_Tag, and
Event_Tag::save(). The Events_* insert format specifiers become PRIu64
to match the unsigned id.

fixes #4974

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BV1gDc9T6D6H8gtTcxwLvk
2026-07-21 18:01:05 -04:00
Isaac ConnorandClaude Opus 4.8 a04cd7a432 fix: use utf8mb4 for C++ DB connection so Unicode monitor names log intact refs #4785
The connection charset was "utf8", MySQL's alias for 3-byte utf8mb3, while
Monitors.Name and the DB default are utf8mb4. On a utf8mb3 connection any
4-byte UTF-8 character is read back as '?' and, when embedded in a log message
written to the Logs table, raises ERROR 1366 and truncates the value. Names
with such characters lost their multibyte portion in logs, keeping only the
ASCII tail.

Connect with utf8mb4, falling back to utf8 with a warning if the server
rejects it.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-14 10:06:37 -04:00
SteveGilvarry 8801c42064 fix: address review feedback on DB SSL verify option
- API (database.php.default): only set the PDO verify flag when SSL is
  actually configured (ZM_DB_SSL_CA_CERT set), matching the web/Perl/C++
  layers. Previously a fresh install's default (1) would set the flag on a
  non-SSL connection, since the CakePHP datasource merges 'flags' uncondi-
  tionally.
- Both PHP layers: cast to string and trim before parsing the value, and use
  strict in_array, to avoid type-juggling and stray-whitespace edge cases.
- zm_db.cpp: use my_bool (not char) for the MYSQL_OPT_SSL_VERIFY_SERVER_CERT
  fallback argument, the type libmysqlclient expects. That branch only
  compiles on older clients without MYSQL_OPT_SSL_MODE, where my_bool exists.

refs #3816
2026-06-14 15:57:09 +10:00
SteveGilvarry e60bdc67b2 feat: add ZM_DB_SSL_VERIFY_SERVER_CERT option (portable across MySQL/MariaDB)
Add a ZM_DB_SSL_VERIFY_SERVER_CERT setting so a database connection that uses
ZM_DB_SSL_CA_CERT can talk to a server with a self-signed or otherwise
non-matching certificate. When enabled, verification is by identity (the cert
must chain to the CA and its CN/SAN must match ZM_DB_HOST), consistent across
the C++ daemons, the PHP web interface, the CakePHP API and the Perl scripts.

This re-does the reverted #3817. That PR broke the build because it called
mysql_options(MYSQL_OPT_SSL_VERIFY_SERVER_CERT, ...), and that enum was removed
from the MySQL 8.0 C client in favour of MYSQL_OPT_SSL_MODE; it also passed a
c_str() where a my_bool* was expected, and referenced the PHP constant
unconditionally (fatal on PHP 8 for an upgraded install whose zm.conf predates
the option).

The option that controls server-cert verification differs by client library and
the symbols are enum values, not macros, so CMake feature-detects them by
compiling:
  - HAVE_MYSQL_OPT_SSL_MODE  (MySQL 5.7.11+/8.0, MariaDB Connector/C 3.1+)
  - HAVE_MYSQL_OPT_SSL_VERIFY_SERVER_CERT  (older MariaDB/MySQL)
zm_db.cpp uses SSL_MODE_VERIFY_IDENTITY / SSL_MODE_REQUIRED when the former is
available, else falls back to the latter with a proper my_bool.

Value handling is three-way in every layer: a truthy value verifies, a false-y
value (0/false/no/off) skips verification, and an empty/unset value leaves the
client default in place so existing installs are unchanged on upgrade. PHP, the
API datasource (via PDO flags) and the Perl DSN are all guarded with defined()
checks. Fresh installs default to 1.

Documents the full ZM_DB_* connection and SSL settings, including the hostname
verification gotcha when connecting by IP, in docs/userguide/configfiles.rst.

refs #3816
2026-06-14 13:20:00 +10:00
Isaac ConnorandClaude Opus 4.5 df6c4a4a13 fix: address multiple bugs across core source files
- zm_analysis_thread.cpp, zm_decoder_thread.cpp: Fix potential deadlock
  in Start() by calling Stop() before joining thread
- zm_camera.cpp: Add null check after avformat_alloc_context()
- zm_comms.cpp: Fix memory leak in InetSocket::bind(), fix error message
  typo in deleteReader(), fix clearReaders/clearWriters to recalculate
  mMaxFd properly
- zm_config.cpp: Fix potential buffer underrun when parsing config files,
  fix misplaced SERVER_ID check logic
- zm_db.cpp: Fix logger level not restored on early return in zmDbDo(),
  fix empty string access in DB_HOST parsing
- zm_event.cpp: Fix typo "foudn" -> "found", fix memory leak with Tag
  allocation, fix variable shadowing with video_file
- zm_event_tag.cpp: Fix null dereference when AssignedBy is NULL
- zm_eventstream.cpp: Fix dangling pointer bugs with emplace_back
  (use auto& instead of auto), fix memory leak in loadInitialEventData

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-03 10:18:49 -05:00
Isaac Connor 49e11855d6 Store error reason so it doesn't get clobbered by second attempt. 2025-07-23 13:25:43 -04:00
Isaac Connor a95f37ff83 Fix blank reason for mysql failure 2025-06-13 09:34:24 -04:00
Isaac Connor c56d23a5a7 Always turn off db logging in zmDbDo. If db logging is set to debug, we will infinitely recurse. 2024-06-20 09:08:51 -04:00
Aaron Kling c4683d90a9 Format code using astyle google format
Commands used:
astyle --style=google --indent=spaces=2 --keep-one-line-blocks src/*.cpp
astyle --style=google --indent=spaces=2 --keep-one-line-blocks src/*.h
2024-03-26 13:43:58 -05:00
Isaac Connor f5cdab131f Include rc in debug 2024-03-04 14:13:41 -05:00
Isaac Connor 067ca68549 Add debugging of db failures 2024-03-04 13:20:21 -05:00
Isaac Connor b9da90522b Wait forever until reconnect, the fallthrough case had us retrying the sql on a closed connection which may have led to a crash. 2024-03-04 09:32:15 -05:00
Isaac Connor 72cbf4a393 Include unistd because we use sleep 2024-02-20 20:29:49 -05:00
Isaac Connor e03afd678a Add a return value to zmDbReconnect which seems to fix the crashing 2024-02-20 19:31:11 -05:00
Isaac Connor 93ee735086 Fix nitpick 2024-02-20 18:56:54 -05:00
Isaac Connor 87156149a0 Only do mysql_close if we think we are connected 2024-02-20 18:56:02 -05:00
Isaac Connor e9e429083e Add zmDbReconnect, which closes the connection before trying to reconnect, in an attempt to prevent mem leak. This adds a 1 sec sleep if we fail to connect. This also removes the disabling of db logging before doing logging... because we are going to assume (possibly incorrectly) that the logging code is correct and generating well-formed sql, and hence the error is external. This might be a bad idea. 2024-02-20 18:36:10 -05:00
Isaac Connor aaa55b9776 Improve debug logging when failed to connect to db, and provide reason when fail to run query 2024-01-23 16:11:44 -05:00
Isaac Connor e132181f6a Make reconnection logging a debug 2023-12-08 17:42:50 -05:00
Isaac Connor 70c5dc6fa9 Replace deprecated mysql_ssl_set with mysql_options() 2023-10-30 16:07:34 -04:00
Isaac Connor 3346a67b94 set zmDbConnected to false before calling zmDbConnect 2023-09-25 17:17:38 -04:00
Isaac Connor df8f725afa Auto reconnect when mysql is lost 2023-09-22 13:35:30 -04:00
Isaac Connor 22d911940f Remove deprecated reconnect setting for mysql 2023-09-12 15:10:34 -04:00
Isaac Connor e49876de53 Bump number of db queue entries before warning to 40. 40 is still a reasonable number and rarely hit in testing. 2022-10-13 17:36:41 -04:00
Isaac Connor 619cf1975f Add getting the connection id from mysql and log it in zmDbDo. This is so that when mysql reports a dropped connection, we can figure out which process it was. 2022-10-06 10:28:49 -04:00
Ratchanan Srirattanamet d0a7b51283 db: start the processing thread after all fields are initialized
Initializing `zmDbQueue::mThread` with initializer list makes the thread
start in the middle of object initialization. This means `zmDbQueue::
process()` could start and reach mCondition.wait(lock); before `std::
wait_condition`'s constructor, which causes deadlock.

To make sure thread won't start before object initialize, move
`mThread`'s initialization to constructor's body.

This _at last_ solves the random zmu deadlock issue that has plagued my
setup for almost a year.
2022-08-08 03:13:08 +07:00
Isaac Connor 1531ced590 Remove unneeded debug 2022-06-08 16:44:47 -04:00
Isaac Connor 6aeb163cba Fix lock around terminate 2022-03-13 08:37:33 -04:00
Isaac Connor fc21fb643e Release lock before notify 2022-02-20 10:33:13 -05:00
Isaac Connor 02ccf13c7b Merge branch 'master' of github.com:ZoneMinder/zoneminder 2022-02-20 10:32:43 -05:00
Isaac Connor b896974a29 Should get lock before testing for connected 2022-02-20 10:32:40 -05:00
Ratchanan Srirattanamet ebe502a747 db: fix dead lock in zmDbQueue::stop()
Notifying `mCondition` without taking the lock causes a race condition
in ::process() between checking `mTerminate` and waiting for the
`mCondition`, which causes a dead lock. This commit moves writing to
`mTerminate` and notifying `mCondition` under the lock to eliminate race
condition and dead lock.

This is not theoretical. It has caused zmu to hang at exit on a
Raspberry Pi 4, exhuasting PHP-FPM process pool. The stacks below are
captured when running ZoneMinder 1.36.12-focal1 on Ubuntu 20.04:

(gdb) thread apply all bt

Thread 2 (Thread 0xffff80c1c880 (LWP 259988)):
#0  futex_wait_cancelable (private=0, expected=0, futex_word=0xaaaae0584e80 <dbQueue+176>) at ../sysdeps/nptl/futex-internal.h:183
#1  __pthread_cond_wait_common (abstime=0x0, clockid=0, mutex=0xaaaae0584e28 <dbQueue+88>, cond=0xaaaae0584e58 <dbQueue+136>) at pthread_cond_wait.c:508
#2  __pthread_cond_wait (cond=0xaaaae0584e58 <dbQueue+136>, mutex=0xaaaae0584e28 <dbQueue+88>) at pthread_cond_wait.c:638
#3  0x0000ffff8700d670 in std::condition_variable::wait(std::unique_lock<std::mutex>&) () from /lib/aarch64-linux-gnu/libstdc++.so.6
#4  0x0000aaaae0438f08 in zmDbQueue::process (this=0xaaaae0584dd0 <dbQueue>) at ./src/zm_db.cpp:250
#5  0x0000ffff87013fac in ?? () from /lib/aarch64-linux-gnu/libstdc++.so.6
#6  0x0000ffff891264fc in start_thread (arg=0xffffe60d84bf) at pthread_create.c:477
#7  0x0000ffff86dd767c in thread_start () at ../sysdeps/unix/sysv/linux/aarch64/clone.S:78

Thread 1 (Thread 0xffff80c23010 (LWP 259987)):
#0  __pthread_clockjoin_ex (threadid=281472841926784, thread_return=0x0, clockid=0, abstime=<optimized out>, block=<optimized out>) at pthread_join_common.c:145
#1  0x0000ffff87014240 in std::thread::join() () from /lib/aarch64-linux-gnu/libstdc++.so.6
#2  0x0000aaaae04314d0 in exit_zmu (exit_code=0) at ./src/zmu.cpp:200
#3  0x0000aaaae042f4c8 in main (argc=<optimized out>, argv=<optimized out>) at ./src/zmu.cpp:797
2022-02-20 09:58:03 +00:00
Isaac Connor 146ea4822d Bump the db queue limit to 30 before we warn. I only have 1 server that gets over 20 and it is still ok. 2022-01-24 09:24:16 -05:00
Isaac Connor 77d3109152 Increase to 20 before warning about db queue size. Put lock in it's own scope so that we unlock before notifying 2021-11-24 13:44:45 -05:00
Isaac Connor 61f7989bec Actually report the # of dbQueue entries 2021-11-02 17:24:05 -04:00
Isaac Connor c2bd2dc129 Add a warning if db queue is larger than 10 2021-10-28 10:46:50 -04:00
ColorfullyZhang 6009bba339 Set mysql character set to utf8 explicitly to support chinese characters (or other special characters). 2021-09-16 14:41:24 +08:00
Peter Keresztes Schmidt 65656de6ce db: Adjust the query methods to accept std::strings 2021-07-06 10:20:46 +02:00
Peter Keresztes Schmidt cf9c47149f db: Add helper for escaping strings and use it 2021-07-06 10:20:45 +02:00
Isaac Connor b8e3cc33f0 make it so that the queue will more likely be empty on termination. Do not queue more sql if terminate flag is set. 2021-05-10 12:54:35 -04:00
Isaac Connor 76080cb857 add a stop function to dbQueue to clear out the queue before we kill log. 2021-04-23 09:25:07 -04:00
Isaac Connor cbec5b2800 Implement zmDbDoUpdate which returns -mysql_errer or # of rows modified 2021-03-11 13:48:16 -05:00