Review follow-ups to the async-signal-safe die handler:
- The log file descriptor the handler wrote to could be closed by a log
rotation after the handler loaded it, and its number reused by an
unrelated file or socket. zmSetCrashLogFile() now keeps one descriptor
that is never closed and dup2()s each new log file onto it, so it only
ever refers to a log file.
- Lines were formatted with snprintf(), which is not async-signal-safe. A
small fixed-buffer CrashLine appends strings, decimals and hex instead.
- glibc backtrace() loads libgcc_s on first use, which allocates. It is now
called once when the handler is installed, and the comment that called it
safe is corrected.
- zmdc points daemons' stderr at /dev/null, so with file logging off the
report went nowhere. The handler now also sends each line to syslog over
its own datagram socket, connected by zmSetCrashSyslog() when the Logger
opens syslog, without calling syslog(3).
- A second signal arriving during the report was blocked when re-raised, so
the process exited 255 instead of dying of it. Both paths now go through
die_of(), which unblocks the signal.
- The shared volatile flag did not stop two threads that fault together from
both reporting. A lock-free atomic_flag picks the reporting thread; a fault
on another thread waits for it to end the process, and a fault inside the
handler on the same thread dies at once.
- sigaltstack() only covers the calling thread. zmSetThreadAltStack() gives
a thread its own stack, freed when it exits; main, the decoder and the
analysis threads call it.
Tests fork a child per case: report formatting, the rotated log file, the
syslog datagram, a second signal mid-report, a fault on another thread
mid-report, and a stack overflow on a worker thread.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
zm_die_handler logged through Error()/Fatal() and, on the second signal,
called Fatal() -> logPrint(), which from inside the handler stopped the
database queue, closed the MySQL handle, deleted the Logger and called
exit(): it joined and freed objects the decoder, analysis and stream
threads were still using, ran atexit handlers and static destructors (the
libcrypto/MariaDB signal-unsafe-call floods seen under ThreadSanitizer),
and could deadlock on the log mutex. The crash report it wrote to the Logs
table was sometimes cut short or lost, and the process could hang instead
of exiting.
Emit the crash report (signal, fault reason, fault and instruction
address, backtrace) with async-signal-safe write(2) only, to stderr and,
when open, the per-process log file, then restore the default disposition
and re-raise the signal so the process dies of the actual fault and can
leave a core dump. Nothing touches the database, the log queue or the
Logger from the handler.
- The Logger publishes its log-file descriptor in zm_crash_log_fd when it
opens the file and clears it on close, so the handler can write to the
log file without going through the Logger.
- The glibc path uses backtrace_symbols_fd(), which does not allocate,
instead of backtrace_symbols(); the libunwind path writes fixed buffers.
- Install the handler on a dedicated sigaltstack so a stack-overflow fault
can still be reported, and guard against faulting again while handling.
The crash detail now lands in the log file and syslog rather than the Logs
table; zmdc restarts the daemon and records the abnormal exit.
tests/zm_signal.cpp forks a child, installs the handler, raises SIGSEGV
and checks the process dies of the signal rather than exiting from the
handler, and that the report reached stderr and the published log fd.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The comment still said zmDbDo() holds the Logger pointer across its
query, which #5197 removed; the test comment was updated in 6d3e86994.
Comment only, no behaviour change.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Logger::usrHandler changed the level and called Info() from the handler.
Info() takes log_mutex, glibc's syslog and tzset locks (syslog,
localtime_r) and the database queue's mutex, and allocates. A SIGUSR1 or
SIGUSR2 delivered to a thread already inside one of those waits on
itself, and the process hangs until zmwatch/zmdc kill it.
The handler now only adds +1/-1 to a lock-free atomic, as the SIGWINCH
branch already sets a flag. Logger::fetch(), which every log macro calls
before its level check, applies a pending change under log_mutex and logs
"Level changed" from normal context, so the new level is in effect at the
next log call on any thread. Several signals before that add up to one
change, clamped to NOLOG..DEBUG9. logInit() drops a change still pending
for the logger it replaces.
fixes#5216
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
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>
* 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>
zmc's SIGHUP reload ran logTerm(); logInit(), which deletes the Logger
and creates a new one. The dbQueue thread and the stream socket threads
keep running through the reload, and zmDbDo() holds the Logger pointer
across its query to restore the database log level afterwards, so the
reload freed the object under them (heap use-after-free under ASan).
Add logReload(), which re-initialises the existing instance under
log_mutex: syslog is closed and reopened and the log file closed, as with
a new instance, but the pointer stays valid. Only the reload calls it;
logInit() and logTerm() are unchanged.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
With ZM_LOG_DEBUG off, Logger::initialise() clamped every target level
(file, database, syslog, terminal) to INFO as well as the overall level.
SIGUSR1 raises the overall level, but the effective level is the lower of
that and the highest target level, so it stayed at INFO and the signal
did nothing.
Only cap the overall level. Targets keep their configured levels, so
SIGUSR1 behaves as if ZM_LOG_DEBUG_LEVEL had been incremented: targets
configured for debug start receiving it, targets at INFO stay at INFO.
Startup behaviour is unchanged since the effective level is still INFO.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
(cherry picked from commit af970628c3fe5fe76d163a30747cf534babbb8a6)
SIGHUP means reload. zmc responds by closing its events, disconnecting the
camera and reconnecting; the perl daemons respond by exiting so zmdc restarts
them. zmdc.pl logrot hupped every managed process, so the nightly logrotate
run cost about 8 seconds of capture on a default install.
Rotating a log file only needs the daemon to drop its file handle, so use a
separate signal for it. SIGWINCH is otherwise unused, is ignored by default and
exists on every supported platform.
- Logger (C++) installs a SIGWINCH handler beside its USR1/USR2 handler. The
handler only sets a flag; the next logPrint closes the file and the write
reopens it at the original path. This covers every C++ binary without
touching any daemon's main loop.
- Logger.pm registers WINCH alongside HUP in logSetSignal, which logInit
already calls, so the scripts that install their own HUP handler still
rotate.
- zmdc.pl logrot sends WINCH. The logrotate config is unchanged - it still
calls zmpkg.pl logrot.
Filter.pm and FilterTerm.php justified MAX_EVENT_DAYS by events not outliving
the nightly HUP, which is no longer what bounds them; cite SectionLength.
Tests: tests/zm_logger_rotate.cpp and tests/perl/test_log_rotate_signal.pl both
log, rename the file out from under the process, confirm writes still land in
the renamed file, signal WINCH and confirm the original path is written again.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NDhTBPj9xEaT52pRmAufaP
Add a new AUDIT logging level (-5) between PANIC (-4) and NOLOG (shifted
to -6) across C++, PHP, and Perl loggers. AUDIT entries use code 'AUD'
and syslog priority LOG_NOTICE. They record who changed what, from where,
for monitors, filters, users, config, roles, groups, zones, states,
servers, storage, events, snapshots, control caps, and login/logout.
AUDIT entries have their own retention period (ZM_LOG_AUDIT_DATABASE_LIMIT,
default 1 year) separate from regular log pruning. The log pruning in
zmstats.pl and zmaudit.pl now excludes AUDIT rows from regular pruning
and prunes them independently.
Critical safety: the C++ termination logic is changed from
'if (level <= FATAL)' to 'if (level == FATAL || level == PANIC)' to
prevent AUDIT-level log calls from killing the process.
Includes db migration zm_update-1.39.1.sql to shift any stored NOLOG
config values from -5 to -6.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
GCC 12 incorrectly detects a format truncation.
src/zm_logger.cpp:86:39: warning: ‘%d’ directive output may be truncated writing between 1 and 11 bytes into a region of size 2 [-Wformat-truncation=]
86 | snprintf(code, sizeof(code), "DB%d", i);
| ^~
src/zm_logger.cpp:86:36: note: directive argument in the range [-2147483647, 9]
86 | snprintf(code, sizeof(code), "DB%d", i);
| ^~~~~~
Unfortunately the compilers can't emit Wformat warnings for variadic templates
and those can't be annotated with the format attribute.
Use a variadic function which can be annotated and thus warns on format string-args mismatches.
Ref 0796a2262e