From 4b745f995ecae221a96b255f580fc4a69d25c6b4 Mon Sep 17 00:00:00 2001 From: TheWitness Date: Thu, 3 Dec 2026 00:19:13 -0500 Subject: [PATCH 1/3] fix(process): stop waiting out the worker registration window (#479) syslog_wait_workers() held the master in its registration stage until every launched worker was registered and running. Workers that had already finished, or exited because the processing lock check failed, were never counted, so each parallel phase waited the full ten seconds. A worker now counts once it is registered or has recorded statistics, read from the settings table rather than the read_config_option() cache, and the completion check uses the same fresh read. A worker that finds the processing lock no longer held by its master records a failed statistics row so the master stops waiting, and logs the expected owner and the holder IS_USED_LOCK() reported. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- CHANGELOG.md | 1 + includes/functions.php | 104 +++++++++++++++++++++++----- syslog_process.php | 15 +++- tests/Unit/ProcessingLockTest.php | 8 ++- tests/Unit/SyslogWorkerWaitTest.php | 70 ++++++++++++++----- 5 files changed, 162 insertions(+), 36 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 04064c2c..a1b1ff04 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,7 @@ * issue#491: Syslog Status no longer fails with "Undefined constant SYSLOG_COLLECTOR_STALE_SECONDS" (and Cacti no longer disables the plugin) when Collector Staleness Threshold or Collector Backlog Threshold is set to Default; both defaults (300 seconds, 10000 messages) are now defined in `includes/functions.php` before the Status tab is drawn * issue#484: Mark the syslog search help string in `syslog.php` as `no-php-format` and update `locales/po/cacti.pot` so the literal `%` in `LIKE` syntax is not flagged as a PHP format specifier * issue#480: Split the syslog upgrade notice in `includes/installer.php` into separate balanced `

` translation strings, regenerate `locales/po/cacti.pot`, and remove orphan `locales/LC_MESSAGES/ka.mo` +* issue#479: With more than one Syslog Processing Process, the master no longer waits out the full ten second registration window on each phase when its workers have already finished or exited; a worker that finds the processing lock no longer held by its master now records the failure and logs the expected lock owner and the holder `IS_USED_LOCK()` reported * feature: Add manually importable recommendation catalogues for Arista, Dell, Fortinet, HPE, Huawei, MikroTik, Nokia, NVIDIA and Palo Alto Networks in docs/.json.gz, built from each vendor's public message references * feature: Recommendations are matched only against the sending device's vendor (and vendor-neutral records) when the syslog host is a Cacti device whose vendor is recognised from its SNMP sysDescr or device template and has records; other hosts match every vendor, except that all-digit identifiers then match only vendor-neutral records diff --git a/includes/functions.php b/includes/functions.php index 4f1055ff..f1b989c1 100644 --- a/includes/functions.php +++ b/includes/functions.php @@ -2962,7 +2962,19 @@ function syslog_processing_lock_release(): void { * @return bool */ function syslog_processing_lock_held_by(int $owner): bool { - return $owner > 0 && (int) syslog_db_fetch_cell_prepared('SELECT IS_USED_LOCK(?)', [syslog_processing_lock_name()], '', false) === $owner; + return $owner > 0 && syslog_processing_lock_holder() === $owner; +} + +/** + * The session currently holding the processing lock, as IS_USED_LOCK() + * reports it on the Syslog connection. + * + * @return int|null The holder's CONNECTION_ID(), or null when the lock is free. + */ +function syslog_processing_lock_holder(): ?int { + $holder = syslog_db_fetch_cell_prepared('SELECT IS_USED_LOCK(?)', [syslog_processing_lock_name()], '', false); + + return $holder === null || $holder === '' || $holder === false ? null : (int) $holder; } /** @@ -3346,22 +3358,33 @@ function syslog_validate_worker_args($child, $run_id, $phase, $seq_start, $seq_e * @return int The number of live, registered workers */ function syslog_workers_running() { - $processes = db_fetch_assoc("SELECT pid + return cacti_sizeof(syslog_workers_running_ids()); +} + +/** + * syslog_workers_running_ids - list the child numbers of the live worker + * children registered in Cacti's process table, removing stale rows as + * described for syslog_workers_running(). + * + * @return array The child number of each live, registered worker + */ +function syslog_workers_running_ids() { + $processes = db_fetch_assoc("SELECT pid, taskid FROM processes WHERE tasktype = 'syslog' AND taskname = 'child'"); if (!is_array($processes) || !cacti_sizeof($processes)) { - return 0; + return []; } - $running = 0; + $running = []; foreach ($processes as $process) { $pid = (int) $process['pid']; if (cacti_process_still_running($pid)) { - $running++; + $running[] = (int) ($process['taskid'] ?? 0); continue; } @@ -3377,6 +3400,38 @@ function syslog_workers_running() { return $running; } +/** + * syslog_workers_reported - list the child numbers that recorded their + * statistics for the current phase. + * + * The rows are read from the settings table directly because + * read_config_option() caches values per process, so a value read while + * the children were still running would never be seen to change. + * + * @return array The child number of each worker that reported + */ +function syslog_workers_reported() { + $rows = db_fetch_assoc("SELECT `name` + FROM settings + WHERE `name` LIKE 'stats_syslog_child_%'"); + + if (!is_array($rows)) { + return []; + } + + $reported = []; + + foreach ($rows as $row) { + $child = (int) str_replace('stats_syslog_child_', '', (string) $row['name']); + + if ($child > 0) { + $reported[] = $child; + } + } + + return $reported; +} + /** * syslog_wait_workers - wait for the launched worker children to finish. * @@ -3399,10 +3454,13 @@ function syslog_wait_workers($expected) { // STAGE 1: give every launched child time to register, bounded so a // child that crashed before registering cannot stall the master. // The grace window stays at ten seconds; the tenth of a second poll - // just notices registration as soon as it happens. + // just notices registration as soon as it happens. A child that has + // already recorded its statistics and unregistered is accounted for + // too, otherwise a phase that finishes quickly always waits out the + // whole window. $grace_polls = 100; - for ($i = 0; $i < $grace_polls && syslog_workers_running() < $expected; $i++) { + for ($i = 0; $i < $grace_polls && syslog_workers_accounted($expected) < $expected; $i++) { syslog_debug(sprintf('Waiting for %s Worker(s) to register.', $expected)); usleep(100000); @@ -3421,21 +3479,33 @@ function syslog_wait_workers($expected) { } // verify that each child recorded its completion - $missing = []; - - for ($i = 1; $i <= $expected; $i++) { - $stat = read_config_option('stats_syslog_child_' . $i); + $missing = array_values(array_diff(range(1, max(1, $expected)), syslog_workers_reported())); - if ($stat === false || $stat === '' || $stat === null) { - $missing[] = $i; - } - } - - if (cacti_sizeof($missing)) { + if ($expected > 0 && cacti_sizeof($missing)) { cacti_log('WARNING: Syslog worker(s) exited without recording completion: ' . implode(', ', $missing), false, 'SYSLOG'); } } +/** + * syslog_workers_accounted - count the launched children that are either + * registered and running or have already recorded their statistics. + * + * Child numbers are combined rather than added, because a child is briefly + * both registered and reported between writing its statistics and + * unregistering. + * + * @param int $expected The number of children that were launched + * + * @return int The number of distinct children accounted for + */ +function syslog_workers_accounted($expected) { + $children = array_unique(array_merge(syslog_workers_running_ids(), syslog_workers_reported())); + + return cacti_sizeof(array_filter($children, function ($child) use ($expected) { + return $child >= 1 && $child <= $expected; + })); +} + /** * Report suspicious partition metadata after a crash or database restart. * diff --git a/syslog_process.php b/syslog_process.php index d6e260e9..6a9d7b97 100644 --- a/syslog_process.php +++ b/syslog_process.php @@ -608,7 +608,20 @@ function syslog_worker_main($debug = false) { * takes the lock afterwards sees this worker and refuses to start. */ if (!syslog_processing_lock_held_by((int) $lock_owner)) { - cacti_log("WARNING: Syslog child $child exited; the processing run that launched it no longer holds the processing lock", false, 'SYSLOG'); + $holder = syslog_processing_lock_holder(); + + cacti_log(sprintf('WARNING: Syslog child %s exited; the processing run that launched it no longer holds the processing lock (expected connection %d, IS_USED_LOCK returned %s)', $child, (int) $lock_owner, $holder === null ? 'NULL' : $holder), false, 'SYSLOG'); + + // Report the failure so the master stops waiting for this child + // and counts the phase as failed. + set_config_option('stats_syslog_child_' . $child, json_encode([ + 'child' => $child, + 'run_id' => $run_id, + 'phase' => $phase, + 'moved' => 0, + 'success' => false, + 'reason' => 'lock', + ])); unregister_process('syslog', 'child', $child); diff --git a/tests/Unit/ProcessingLockTest.php b/tests/Unit/ProcessingLockTest.php index 6410010b..56443ffb 100644 --- a/tests/Unit/ProcessingLockTest.php +++ b/tests/Unit/ProcessingLockTest.php @@ -132,7 +132,13 @@ function syslog_test_lock_details(object $cnn, bool $cacti13): array { // A released lock reports NULL. test_override('syslog_db_fetch_cell_prepared', fn() => null); - expect(syslog_processing_lock_held_by(42))->toBeFalse(); + expect(syslog_processing_lock_held_by(42))->toBeFalse() + ->and(syslog_processing_lock_holder())->toBeNull(); + + // The holder is reported so a worker can log what it saw. + test_override('syslog_db_fetch_cell_prepared', fn () => '77'); + + expect(syslog_processing_lock_holder())->toBe(77); }); it('reports a lock held elsewhere and a lock connection that cannot be opened', function () { diff --git a/tests/Unit/SyslogWorkerWaitTest.php b/tests/Unit/SyslogWorkerWaitTest.php index 79e539d8..847693fe 100644 --- a/tests/Unit/SyslogWorkerWaitTest.php +++ b/tests/Unit/SyslogWorkerWaitTest.php @@ -37,24 +37,39 @@ * Install fakes that replay a fixed snapshot of the process table on * every poll and record every log line and DELETE issued. * - * @param array $snapshots List of pid arrays, one per db_fetch_assoc call + * @param array $snapshots List of pid arrays, one per process table poll * @param array $logs Filled with every cacti_log() message * @param array $deletes Filled with every db_execute() statement * @param array $stats Child numbers that recorded statistics + * @param int $stats_at Process table poll from which the statistics are + * visible; by default once the last snapshot is reached * * @return void */ -function syslog_wait_test_environment(array $snapshots, array &$logs, array &$deletes, array $stats = [1, 2]) { - $logs = []; - $deletes = []; - $poll = 0; +function syslog_wait_test_environment(array $snapshots, array &$logs, array &$deletes, array $stats = [1, 2], ?int $stats_at = null) { + $logs = []; + $deletes = []; + $poll = 0; + $stats_at = $stats_at ?? max(0, cacti_sizeof($snapshots) - 1); + + test_override('db_fetch_assoc', function ($sql) use ($snapshots, $stats, $stats_at, &$poll) { + if (str_contains($sql, 'FROM settings')) { + if ($poll < $stats_at) { + return []; + } + + return array_map(function ($child) { + return ['name' => 'stats_syslog_child_' . $child]; + }, $stats); + } - test_override('db_fetch_assoc', function ($sql) use ($snapshots, &$poll) { // The last snapshot repeats so a runaway loop fails the poll // count assertion below rather than looping the suite forever. - return array_map(function ($pid) { - return ['pid' => $pid]; - }, $snapshots[min($poll++, max(0, cacti_sizeof($snapshots) - 1))]); + $pids = $snapshots[min($poll++, max(0, cacti_sizeof($snapshots) - 1))]; + + return array_map(function ($pid, $index) { + return ['pid' => $pid, 'taskid' => $index + 1]; + }, $pids, array_keys($pids)); }); test_override('cacti_process_still_running', function ($pid) { @@ -71,14 +86,6 @@ function syslog_wait_test_environment(array $snapshots, array &$logs, array &$de $logs[] = $message; }); - test_override('read_config_option', function ($name) use ($stats) { - if (preg_match('/^stats_syslog_child_(\d+)$/', $name, $m) && in_array((int) $m[1], $stats, true)) { - return json_encode(['child' => (int) $m[1], 'moved' => 10, 'resolved' => 0, 'runtime' => 0.1]); - } - - return ''; - }); - return function () use (&$poll) { return $poll; }; @@ -147,6 +154,35 @@ function syslog_wait_test_environment(array $snapshots, array &$logs, array &$de expect($logs)->toContain('WARNING: Syslog worker(s) exited without recording completion: 2'); }); +it('does not wait out the registration window for workers that already finished (issue#479)', function () { + $logs = []; + $deletes = []; + + // Both children registered, recorded statistics and unregistered + // before the master's first poll. Counting only registered workers + // held the master for the whole ten second window on every phase. + $polls = syslog_wait_test_environment([[]], $logs, $deletes, [1, 2], 0); + + syslog_wait_workers(2); + + expect($polls())->toBe(2, 'Finished workers must end the registration wait at once'); + expect($logs)->toBeEmpty(); +}); + +it('counts a worker once while it is both registered and reported', function () { + $logs = []; + $deletes = []; + + // Child 1 has written its statistics but not yet unregistered, and + // child 2 has not registered. Adding the two counts would end the + // registration wait before child 2 appears. + $polls = syslog_wait_test_environment([[501], [501, 502], []], $logs, $deletes, [1], 0); + + syslog_wait_workers(2); + + expect($polls())->toBeGreaterThanOrEqual(3, 'The master must keep waiting for the unregistered child'); +}); + it('waits out the registration window instead of racing ahead at zero', function () { $logs = []; $deletes = []; From 4c6b57e5ba8f2fddf4ddd8e7072afa0bf716c0d4 Mon Sep 17 00:00:00 2001 From: TheWitness Date: Thu, 3 Dec 2026 00:29:41 -0500 Subject: [PATCH 2/3] fix(process): scope worker reports to their run and phase Address review on #494. A child of an earlier run could report after the next run cleared the statistics rows and end its registration wait or be counted as its result. The wait, the completion check and the transfer aggregation now count only reports whose run_id and phase match, and a child that fails the lock check records its failure only while the lock is free, so it never overwrites a newer run's rows. The double-count regression test now asserts the exact poll count. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- includes/functions.php | 65 +++++++++++++++------ syslog_process.php | 27 +++++---- tests/Unit/SyslogWorkerAggregationTest.php | 19 ++++++ tests/Unit/SyslogWorkerWaitTest.php | 68 ++++++++++++++++++++-- 4 files changed, 145 insertions(+), 34 deletions(-) diff --git a/includes/functions.php b/includes/functions.php index f1b989c1..3f94824e 100644 --- a/includes/functions.php +++ b/includes/functions.php @@ -2345,11 +2345,13 @@ function syslog_worker_stats_get() { * The settings table lives in the main Cacti database, so the core * db helper is required here. * - * @param int $workers The number of workers that may have run + * @param int $workers The number of workers that may have run + * @param string $run_id The run whose reports count, or '' for any run + * @param string $phase The phase whose reports count, or '' for any phase * * @return array Aggregated moved and resolved totals */ -function syslog_aggregate_worker_stats($workers) { +function syslog_aggregate_worker_stats($workers, $run_id = '', $phase = '') { $moved = 0; $resolved = 0; $reported = []; @@ -2371,6 +2373,11 @@ function syslog_aggregate_worker_stats($workers) { $data = json_decode((string) $row['value'], true); + // A report from another run or phase is not this phase's result. + if (is_array($data) && !syslog_worker_report_matches($row['value'], $run_id, $phase)) { + continue; + } + if (!is_array($data)) { cacti_log('WARNING: Ignoring malformed Syslog worker statistics.', false, 'SYSLOG'); $reported[$child] = false; @@ -3408,23 +3415,22 @@ function syslog_workers_running_ids() { * read_config_option() caches values per process, so a value read while * the children were still running would never be seen to change. * + * @param string $run_id The run whose reports count, or '' for any run + * @param string $phase The phase whose reports count, or '' for any phase + * * @return array The child number of each worker that reported */ -function syslog_workers_reported() { - $rows = db_fetch_assoc("SELECT `name` +function syslog_workers_reported($run_id = '', $phase = '') { + $rows = db_fetch_assoc("SELECT `name`, `value` FROM settings WHERE `name` LIKE 'stats_syslog_child_%'"); - if (!is_array($rows)) { - return []; - } - $reported = []; - foreach ($rows as $row) { + foreach ((array) $rows as $row) { $child = (int) str_replace('stats_syslog_child_', '', (string) $row['name']); - if ($child > 0) { + if ($child > 0 && syslog_worker_report_matches($row['value'] ?? '', $run_id, $phase)) { $reported[] = $child; } } @@ -3432,6 +3438,27 @@ function syslog_workers_reported() { return $reported; } +/** + * syslog_worker_report_matches - whether a worker's recorded statistics + * belong to the given run and phase. + * + * A child of an earlier run can report after the next run has cleared the + * statistics rows, so a report counts only for the run and phase that + * launched it. An empty run or phase matches any report. + * + * @param mixed $value The recorded statistics, JSON encoded + * @param string $run_id The run whose reports count, or '' for any run + * @param string $phase The phase whose reports count, or '' for any phase + * + * @return bool + */ +function syslog_worker_report_matches($value, $run_id, $phase) { + $data = json_decode((string) $value, true); + + return ($run_id === '' || (is_array($data) && ($data['run_id'] ?? '') === $run_id)) + && ($phase === '' || (is_array($data) && ($data['phase'] ?? '') === $phase)); +} + /** * syslog_wait_workers - wait for the launched worker children to finish. * @@ -3446,11 +3473,13 @@ function syslog_workers_reported() { * not spam the process table. Children that disappear without recording * their statistics are warned about after the wait completes. * - * @param int $expected The number of children that were launched + * @param int $expected The number of children that were launched + * @param string $run_id The run that launched them, or '' for any run + * @param string $phase The phase they run, or '' for any phase * * @return (void) */ -function syslog_wait_workers($expected) { +function syslog_wait_workers($expected, $run_id = '', $phase = '') { // STAGE 1: give every launched child time to register, bounded so a // child that crashed before registering cannot stall the master. // The grace window stays at ten seconds; the tenth of a second poll @@ -3460,7 +3489,7 @@ function syslog_wait_workers($expected) { // whole window. $grace_polls = 100; - for ($i = 0; $i < $grace_polls && syslog_workers_accounted($expected) < $expected; $i++) { + for ($i = 0; $i < $grace_polls && syslog_workers_accounted($expected, $run_id, $phase) < $expected; $i++) { syslog_debug(sprintf('Waiting for %s Worker(s) to register.', $expected)); usleep(100000); @@ -3479,7 +3508,7 @@ function syslog_wait_workers($expected) { } // verify that each child recorded its completion - $missing = array_values(array_diff(range(1, max(1, $expected)), syslog_workers_reported())); + $missing = array_values(array_diff(range(1, max(1, $expected)), syslog_workers_reported($run_id, $phase))); if ($expected > 0 && cacti_sizeof($missing)) { cacti_log('WARNING: Syslog worker(s) exited without recording completion: ' . implode(', ', $missing), false, 'SYSLOG'); @@ -3494,12 +3523,14 @@ function syslog_wait_workers($expected) { * both registered and reported between writing its statistics and * unregistering. * - * @param int $expected The number of children that were launched + * @param int $expected The number of children that were launched + * @param string $run_id The run that launched them, or '' for any run + * @param string $phase The phase they run, or '' for any phase * * @return int The number of distinct children accounted for */ -function syslog_workers_accounted($expected) { - $children = array_unique(array_merge(syslog_workers_running_ids(), syslog_workers_reported())); +function syslog_workers_accounted($expected, $run_id = '', $phase = '') { + $children = array_unique(array_merge(syslog_workers_running_ids(), syslog_workers_reported($run_id, $phase))); return cacti_sizeof(array_filter($children, function ($child) use ($expected) { return $child >= 1 && $child <= $expected; diff --git a/syslog_process.php b/syslog_process.php index 6a9d7b97..2479f81d 100644 --- a/syslog_process.php +++ b/syslog_process.php @@ -365,7 +365,7 @@ * follow all operate on the same incoming rows the workers are * updating, so the master must not race ahead of its children. */ - syslog_wait_workers($launched); + syslog_wait_workers($launched, $run_id, 'references'); $phase_start = time(); $phase_micro = microtime(true); @@ -449,9 +449,9 @@ * block until every child has recorded its statistics and * unregistered itself. */ - syslog_wait_workers($launched); + syslog_wait_workers($launched, $run_id, 'transfer'); - $worker_stats = syslog_aggregate_worker_stats($launched); + $worker_stats = syslog_aggregate_worker_stats($launched, $run_id, 'transfer'); $moved = $worker_stats['moved']; @@ -613,15 +613,18 @@ function syslog_worker_main($debug = false) { cacti_log(sprintf('WARNING: Syslog child %s exited; the processing run that launched it no longer holds the processing lock (expected connection %d, IS_USED_LOCK returned %s)', $child, (int) $lock_owner, $holder === null ? 'NULL' : $holder), false, 'SYSLOG'); // Report the failure so the master stops waiting for this child - // and counts the phase as failed. - set_config_option('stats_syslog_child_' . $child, json_encode([ - 'child' => $child, - 'run_id' => $run_id, - 'phase' => $phase, - 'moved' => 0, - 'success' => false, - 'reason' => 'lock', - ])); + // and counts the phase as failed. When another session holds the + // lock, a newer run owns the statistics rows, so leave them alone. + if ($holder === null) { + set_config_option('stats_syslog_child_' . $child, json_encode([ + 'child' => $child, + 'run_id' => $run_id, + 'phase' => $phase, + 'moved' => 0, + 'success' => false, + 'reason' => 'lock', + ])); + } unregister_process('syslog', 'child', $child); diff --git a/tests/Unit/SyslogWorkerAggregationTest.php b/tests/Unit/SyslogWorkerAggregationTest.php index 1ed6d844..2bb678bb 100644 --- a/tests/Unit/SyslogWorkerAggregationTest.php +++ b/tests/Unit/SyslogWorkerAggregationTest.php @@ -96,6 +96,25 @@ expect($warnings)->toBe(1, 'Exactly one malformed row warning is logged'); }); +it('counts only the reports of the run and phase being aggregated', function () { + $GLOBALS['syslogdb_default'] = 'syslog'; + + test_override('db_fetch_assoc', function () { + return [ + ['name' => 'stats_syslog_child_1', 'value' => json_encode(['run_id' => 'current', 'phase' => 'transfer', 'moved' => 40, 'success' => true])], + ['name' => 'stats_syslog_child_2', 'value' => json_encode(['run_id' => 'earlier', 'phase' => 'transfer', 'moved' => 900, 'success' => true])] + ]; + }); + + test_override('db_execute', function () { + return true; + }); + + // A late report from an earlier run is neither counted nor accepted as + // child 2's result for this run. + expect(syslog_aggregate_worker_stats(2, 'current', 'transfer'))->toBe(['moved' => 40, 'resolved' => 0, 'success' => false]); +}); + it('reports a failed transfer slice through the child result and skips stale cleanup', function () { $process = file_get_contents(dirname(__DIR__, 2) . '/syslog_process.php'); diff --git a/tests/Unit/SyslogWorkerWaitTest.php b/tests/Unit/SyslogWorkerWaitTest.php index 847693fe..1662b6d8 100644 --- a/tests/Unit/SyslogWorkerWaitTest.php +++ b/tests/Unit/SyslogWorkerWaitTest.php @@ -180,7 +180,64 @@ function syslog_wait_test_environment(array $snapshots, array &$logs, array &$de syslog_wait_workers(2); - expect($polls())->toBeGreaterThanOrEqual(3, 'The master must keep waiting for the unregistered child'); + // Registration ends on the second poll and the drain takes one more. + // Adding the counts would end registration on the first poll and need + // four polls in total. + expect($polls())->toBe(3, 'The master must keep waiting for the unregistered child'); +}); + +it('does not count a late report from an earlier run as a current result', function () { + $logs = []; + $deletes = []; + + $polls = syslog_wait_test_environment([[], [601, 602], []], $logs, $deletes, [1, 2], 0); + + // Both rows belong to another run, so they must neither end the + // registration wait nor satisfy the completion check. + test_override('db_fetch_assoc', (function ($inner) { + return function ($sql) use ($inner) { + $rows = $inner($sql); + + if (str_contains($sql, 'FROM settings')) { + foreach ($rows as &$row) { + $row['value'] = json_encode(['run_id' => 'earlier', 'phase' => 'transfer']); + } + } + + return $rows; + }; + })($GLOBALS['__test_overrides']['db_fetch_assoc'])); + + syslog_wait_workers(2, 'current', 'transfer'); + + expect($polls())->toBe(3, 'Stale reports must not end the registration wait'); + expect($logs)->toContain('WARNING: Syslog worker(s) exited without recording completion: 1, 2'); +}); + +it('accepts the reports of the current run and phase', function () { + $logs = []; + $deletes = []; + + $polls = syslog_wait_test_environment([[]], $logs, $deletes, [1, 2], 0); + + test_override('db_fetch_assoc', (function ($inner) { + return function ($sql) use ($inner) { + $rows = $inner($sql); + + if (str_contains($sql, 'FROM settings')) { + foreach ($rows as &$row) { + $row['value'] = json_encode(['run_id' => 'current', 'phase' => 'references']); + } + } + + return $rows; + }; + })($GLOBALS['__test_overrides']['db_fetch_assoc'])); + + syslog_wait_workers(2, 'current', 'references'); + + expect($polls())->toBe(2); + expect($logs)->toBeEmpty(); }); it('waits out the registration window instead of racing ahead at zero', function () { @@ -209,9 +266,8 @@ function syslog_wait_test_environment(array $snapshots, array &$logs, array &$de $root = dirname(__DIR__, 2); $process = file_get_contents($root . '/syslog_process.php'); - // The master must block after launching each phase. - expect(substr_count($process, 'syslog_wait_workers($launched);'))->toBe(2, 'Both launch sites must be followed by a wait'); - + // The master must block after launching each phase, scoped to the run + // and phase it launched. foreach (['references', 'transfer'] as $phase) { $launch = strpos($process, "syslog_launch_workers('$phase'"); @@ -219,11 +275,13 @@ function syslog_wait_test_environment(array $snapshots, array &$logs, array &$de throw new RuntimeException("The '$phase' phase launch is missing from the master flow"); } - if (strpos($process, 'syslog_wait_workers($launched);', $launch) === false) { + if (strpos($process, "syslog_wait_workers(\$launched, \$run_id, '$phase');", $launch) === false) { throw new RuntimeException("The '$phase' phase launch is not followed by a wait"); } } + expect($process)->toContain("syslog_aggregate_worker_stats(\$launched, \$run_id, 'transfer')"); + // A child that cannot register must leave a breadcrumb and exit // non-zero, never exit silently. $register = strpos($process, "register_process_start('syslog', 'child'"); From 7889575037a7504557b2a7662c75bbc40a5e79d4 Mon Sep 17 00:00:00 2001 From: Thomas Vincent Date: Thu, 3 Dec 2026 02:39:15 -0800 Subject: [PATCH 3/3] test(syslog): verify orphan workers preserve replacement statistics Signed-off-by: Thomas Vincent --- tests/E2E/run-orb-docker-e2e.sh | 3 ++ tests/E2E/worker-master-stats.php | 75 +++++++++++++++++++++++++++++++ 2 files changed, 78 insertions(+) create mode 100644 tests/E2E/worker-master-stats.php diff --git a/tests/E2E/run-orb-docker-e2e.sh b/tests/E2E/run-orb-docker-e2e.sh index c6b491fb..49c1c2ec 100755 --- a/tests/E2E/run-orb-docker-e2e.sh +++ b/tests/E2E/run-orb-docker-e2e.sh @@ -96,6 +96,9 @@ docker exec cacti_web sh -lc 'touch /var/www/html/cacti/log/cacti.log && chown w docker exec cacti_web php cli/install_cacti.php --accept-eula --install --force docker exec cacti_web php cli/plugin_manage.php --plugin=syslog --install --enable --allperms +docker cp "${ROOT_DIR}/tests/E2E/worker-master-stats.php" cacti_web:/tmp/worker-master-stats.php +docker exec -e SYSLOG_WORKER_E2E=1 cacti_web php /tmp/worker-master-stats.php + docker run --rm \ --network cacti-syslog-e2e_default \ --ipc=host \ diff --git a/tests/E2E/worker-master-stats.php b/tests/E2E/worker-master-stats.php new file mode 100644 index 00000000..c92b03fd --- /dev/null +++ b/tests/E2E/worker-master-stats.php @@ -0,0 +1,75 @@ +getMessage() . PHP_EOL); + exit(1); +}); + +$worker = $config['base_path'] . '/plugins/syslog/syslog_process.php'; +$poller = (int) $config['poller_id']; +$child = random_int(10000, 1000000); +$key = 'stats_syslog_child_' . $child; +$run = bin2hex(random_bytes(16)); +$master = 99999999; +$where = "tasktype = 'syslog' AND taskname = 'master' AND taskid = ?"; + +if (db_fetch_cell_prepared("SELECT COUNT(*) FROM processes WHERE $where", [$poller]) || + db_fetch_cell_prepared('SELECT COUNT(*) FROM settings WHERE name = ?', [$key]) || + posix_kill($master, 0)) { + throw new RuntimeException('Worker test requires an idle fixture and an unused statistics slot'); +} + +$run_worker = static function () use ($worker, $child, $run, $master) { + $process = proc_open([PHP_BINARY, $worker, "--child=$child", "--run-id=$run", + '--phase=references', '--seq-start=1', '--seq-end=1', "--master-pid=$master"], + [0 => ['file', '/dev/null', 'r'], 1 => STDOUT, 2 => STDERR], $pipes, dirname($worker)); + + if (!is_resource($process) || proc_close($process) !== 1) { + throw new RuntimeException('A worker whose master exited must report failure'); + } +}; + +$read_stats = static function () use ($key) { + return json_decode((string) db_fetch_cell_prepared('SELECT value FROM settings WHERE name = ?', [$key]), true); +}; + +if (!db_execute_prepared("INSERT INTO processes (tasktype, taskname, taskid, pid) + VALUES ('syslog', 'master', ?, ?)", [$poller, $master])) { + throw new RuntimeException('Could not register the test master'); +} + +try { + $run_worker(); + $expected = ['child' => $child, 'run_id' => $run, 'phase' => 'references', 'moved' => 0, 'success' => false, 'reason' => 'master']; + if ($read_stats() !== $expected) { + throw new RuntimeException('The worker did not record the failed run'); + } + + db_execute_prepared("UPDATE processes SET pid = ? WHERE $where AND pid = ?", [getmypid(), $poller, $master]); + $replacement = ['run_id' => bin2hex(random_bytes(16)), 'child' => $child, 'success' => true, 'moved' => 1]; + set_config_option($key, json_encode($replacement, JSON_THROW_ON_ERROR)); + $run_worker(); + + if ($read_stats() !== $replacement || db_fetch_cell_prepared("SELECT COUNT(*) FROM processes + WHERE tasktype = 'syslog' AND taskname = 'child' AND taskid = ?", [$child])) { + throw new RuntimeException('The orphan overwrote replacement statistics or stayed registered'); + } + print "Orphan worker and replacement master statistics passed\n"; +} finally { + db_execute_prepared("DELETE FROM processes WHERE $where AND pid IN (?, ?)", [$poller, $master, getmypid()]); + db_execute_prepared('DELETE FROM settings WHERE name = ?', [$key]); +}