From b75caac80cbbad8e5994163781f4bd14ec40bde8 Mon Sep 17 00:00:00 2001 From: Thomas Vincent Date: Thu, 3 Dec 2026 20:13:53 -0800 Subject: [PATCH 01/21] test(locks): pin the named lock behaviour at the six Syslog lock sites Each site is run while another process holds its lock, and to success, an early failure return and an exception, so a change of lock mechanism for #502 can be checked against the current behaviour: the wait each lock uses, what the caller returns and logs when it is busy, and that the lock is released on every exit path. Signed-off-by: Thomas Vincent --- tests/Unit/TaskLockTest.php | 221 ++++++++++++++++++++++++++++++++++++ 1 file changed, 221 insertions(+) create mode 100644 tests/Unit/TaskLockTest.php diff --git a/tests/Unit/TaskLockTest.php b/tests/Unit/TaskLockTest.php new file mode 100644 index 00000000..854ee838 --- /dev/null +++ b/tests/Unit/TaskLockTest.php @@ -0,0 +1,221 @@ + $lock, 'locks' => [], 'logs' => [], 'work' => 0]; + test_override('cacti_log', function ($text) { + $GLOBALS['task_lock']['logs'][] = $text; + }); +} + +/** Answer and record a named lock statement; anything else returns $other. */ +function task_lock_named(string $sql, array $params, $other = 1) { + if (str_contains($sql, 'GET_LOCK') || str_contains($sql, 'RELEASE_LOCK')) { + $GLOBALS['task_lock']['locks'][] = [$sql, $params[0] ?? null]; + + return str_contains($sql, 'GET_LOCK') ? $GLOBALS['task_lock']['lock'] : 1; + } + + return $other; +} + +function task_lock_work(string $outcome, string $message): void { + $GLOBALS['task_lock']['work']++; + + if ($outcome === 'exception') { + throw new RuntimeException($message); + } +} + +function task_lock_run_health(string $outcome) { + syslog_load_plugin_source('includes/functions.php'); + $GLOBALS['syslog_incoming_config'] = ['timeField' => 'received_at']; + $settings = ['syslog_enabled' => 'on', 'syslog_remote_enabled' => 'on', 'poller_interval' => '300','syslog_pipeline_health_email' => 'ops@example.test']; + test_override('read_config_option', fn ($name) => $settings[$name] ?? ''); + test_override('syslog_db_table_exists', fn () => true); + test_override('syslog_db_fetch_assoc', fn () => [['name' => 'last_end_time', 'value' => (string) time(), 'updated' => time()]]); + test_override('syslog_db_fetch_row', function ($sql) use ($outcome) { + task_lock_work($outcome, 'health query failed'); + + return str_contains($sql, 'syslog_incoming') ? ['pending' => 20000, 'oldest' => time()] : ['pending' => 0, 'oldest_pending' => '']; + }); + test_override('syslog_db_fetch_cell_prepared', fn ($sql, $params) => task_lock_named($sql, $params)); + // A failed status write is the function's early return before mailing. + test_override('syslog_db_execute_prepared', fn () => $outcome !== 'failure'); + test_override('mailer', fn () => ''); + + return syslog_pipeline_health_check(); +} + +function task_lock_run_partition_create(string $outcome) { + syslog_load_plugin_source('includes/functions.php'); + test_override('syslog_db_fetch_cell_prepared', fn ($sql, $params) => task_lock_named($sql, $params)); + test_override('syslog_db_fetch_row_prepared', function () use ($outcome) { + task_lock_work($outcome, 'partition lookup failed'); + + // An existing partition is success; no row leaves an unknown overflow, which defers. + return $outcome === 'success' ? ['PARTITION_NAME' => 'd20260103'] : []; + }); + $reason = ''; + + return syslog_partition_create('syslog', 1767398400, $reason, 'day'); +} + +function task_lock_run_partition_remove(string $outcome) { + syslog_load_plugin_source('includes/functions.php'); + test_override('syslog_db_fetch_cell_prepared', fn ($sql, $params) => task_lock_named($sql, $params)); + test_override('read_config_option', fn ($name) => $name === 'syslog_retention' && $outcome !== 'failure' ? '30' : ''); + test_override('syslog_db_fetch_assoc_prepared', function () use ($outcome) { + task_lock_work($outcome, 'partition list failed'); + + return [['PARTITION_NAME' => 'd20000101', 'PARTITION_DESCRIPTION' => '946771200', 'PARTITION_EXPRESSION' => 'UNIX_TIMESTAMP(`logtime`)']]; + }); + test_override('syslog_db_execute_prepared', fn () => true); + + return syslog_partition_remove('syslog'); +} + +function task_lock_run_recoveries(string $outcome) { + syslog_load_plugin_source('includes/functions.php'); + test_override('syslog_db_fetch_cell_prepared', fn ($sql, $params) => task_lock_named($sql, $params)); + test_override('syslog_db_execute_prepared', function () use ($outcome) { + task_lock_work($outcome, 'recovery cleanup failed'); + + return $outcome !== 'failure'; + }); + test_override('syslog_db_fetch_assoc_prepared', fn () => []); + + return syslog_threshold_deliver_recoveries(1000); +} + +function task_lock_run_replace_data(string $outcome) { + syslog_load_plugin_source('includes/processing.php'); + $target = new stdClass(); + $source = new stdClass(); + $GLOBALS['task_lock']['target'] = $target; + test_override('db_fetch_row', fn () => ['Create Table' => 'CREATE TABLE `syslog_alert` (`id` INT PRIMARY KEY) ENGINE=InnoDB']); + test_override('db_fetch_cell_prepared', function ($sql, $params, $column, $log, $connection) use ($target) { + if (str_contains($sql, '_LOCK(')) { + expect($connection)->toBe($target); + } + + return task_lock_named($sql, $params); + }); + test_override('db_execute', function ($sql) use ($outcome) { + if (!str_starts_with($sql, 'CREATE TABLE')) { + return true; + } + task_lock_work($outcome, 'snapshot create failed'); + + return $outcome !== 'failure'; + }); + $rows = []; + + return syslog_replace_data('syslog_alert', $rows, $target, $source); +} + +function task_lock_run_dashboard(string $outcome) { + syslog_load_plugin_source('setup.php'); + test_override('syslog_db_fetch_cell_prepared', fn ($sql, $params) => task_lock_named($sql, $params, 0)); + test_override('syslog_db_execute', function ($sql) use ($outcome) { + if ($sql !== 'START TRANSACTION') { + return true; + } + $GLOBALS['task_lock']['work']++; + + return $outcome !== 'failure'; + }); + test_override('syslog_db_execute_prepared', function () use ($outcome) { + if ($outcome === 'exception') { + throw new RuntimeException('dashboard insert failed'); + } + + return true; + }); + test_override('syslog_db_fetch_insert_id', fn () => 42); + + return syslog_dashboard_seed_default(); +} + +/* + * site => [runner, named lock wait seconds, named lock name, result when the + * lock is held elsewhere, log line when the lock is held elsewhere, results + * after success and after the early failure return] + */ +function task_lock_sites(): array { + return [ + 'pipeline health' => ['task_lock_run_health', 0, 'syslog_health_' . sha1('lock_test:3'), null, null, [null, null]], + 'partition create' => ['task_lock_run_partition_create', 10, substr(hash('sha256', 'lock_test.syslog_partition_create.syslog'), 0, 60), false, "SYSLOG: Unable to acquire partition create lock for 'syslog'", [true, false]], + 'partition remove' => ['task_lock_run_partition_remove', 10, substr(hash('sha256', 'lock_test.syslog_partition_remove.syslog'), 0, 60), 0, "SYSLOG: Unable to acquire partition remove lock for 'syslog'", [1, 0]], + 'recovery delivery' => ['task_lock_run_recoveries', 0, 'syslog-clear:' . sha1('lock_test:3'), null, null, [null, null]], + 'rule snapshot' => ['task_lock_run_replace_data', 5, 'syslog_rule_snapshot_syslog_alert', false, null, [true, false]], + 'dashboard seed' => ['task_lock_run_dashboard', 5, 'syslog_dashboard_' . md5('lock_test'), null, null, [null, null]], + ]; +} + +function task_lock_site_names(): array { + return array_keys(task_lock_sites()); +} + +/** Run a site, returning [result, exception message]. */ +function task_lock_call(string $site, string $outcome): array { + try { + return [task_lock_sites()[$site][0]($outcome), null]; + } catch (RuntimeException $error) { + return [null, $error->getMessage()]; + } +} + +describe('named lock path', function () { + it('skips the work while another process holds the lock', function (string $site) { + [, $wait, $name, $result, $log] = task_lock_sites()[$site]; + task_lock_fixture(0); + + expect(task_lock_call($site, 'success'))->toBe([$result, null]) + ->and($GLOBALS['task_lock']['work'])->toBe(0) + ->and($GLOBALS['task_lock']['locks'])->toBe([["SELECT GET_LOCK(?, $wait)", $name]]); + + if ($log !== null) { + expect($GLOBALS['task_lock']['logs'])->toContain($log); + } + })->with(task_lock_site_names()); + + it('releases the lock after success, an early failure return and an exception', function (string $site, string $outcome) { + [, $wait, $name, , , $results] = task_lock_sites()[$site]; + task_lock_fixture(1); + + [$result, $error] = task_lock_call($site, $outcome); + + expect($error === null)->toBe($outcome !== 'exception') + ->and($result)->toBe(['success' => $results[0], 'failure' => $results[1], 'exception' => null][$outcome]) + ->and($GLOBALS['task_lock']['work'])->toBeGreaterThan(0) + ->and($GLOBALS['task_lock']['locks'])->toBe([["SELECT GET_LOCK(?, $wait)", $name], ['SELECT RELEASE_LOCK(?)', $name]]); + })->with(task_lock_site_names())->with(['success', 'failure', 'exception']); + + it('reports a failed lock query separately from contention at the partition sites', function (string $site, $result, string $log) { + task_lock_fixture(null); + + expect(task_lock_call($site, 'success'))->toBe([$result, null]) + ->and($GLOBALS['task_lock']['work'])->toBe(0) + ->and($GLOBALS['task_lock']['logs'])->toContain($log) + ->and(array_column($GLOBALS['task_lock']['locks'], 0))->not->toContain('SELECT RELEASE_LOCK(?)'); + })->with([ + ['partition create', false, "SYSLOG: GET_LOCK call failed for partition create on 'syslog'"], + ['partition remove', 0, "SYSLOG: GET_LOCK call failed for partition remove on 'syslog'"], + ]); +}); From d20502d82bad254816482153a3fc37776d65c7f4 Mon Sep 17 00:00:00 2001 From: Thomas Vincent Date: Thu, 3 Dec 2026 20:15:02 -0800 Subject: [PATCH 02/21] feat(locks): add a task lock on Cacti's process registry Refs #502. GET_LOCK() is granted per database server, so two Galera nodes can both hand out the same lock. syslog_task_lock() registers the task through register_process(), whose insert admits one holder once Cacti 1.2.32 keeps the registry in InnoDB with a unique task key. It waits up to a given number of seconds, retires an entry older than its timeout, and never signals a holder. On a Cacti without that registry it returns null so the caller keeps its named lock. The unit bootstrap stubs the three core registry functions; the registry reports itself unavailable unless a test opts in. Signed-off-by: Thomas Vincent --- includes/functions.php | 66 +++++++++++++++++++++++++ tests/Unit/TaskLockTest.php | 97 +++++++++++++++++++++++++++++++++++++ tests/bootstrap-unit.php | 19 ++++++++ 3 files changed, 182 insertions(+) diff --git a/includes/functions.php b/includes/functions.php index e0125746..e73ad3cb 100644 --- a/includes/functions.php +++ b/includes/functions.php @@ -2859,6 +2859,72 @@ function syslog_processing_master_alive(int $pid): bool { return $pid > 0 && cacti_process_still_running($pid); } +/** + * Hold a Syslog task in Cacti's process registry instead of a named lock. + * + * GET_LOCK() belongs to one database server, so two Galera nodes can grant + * the same lock (#502). From Cacti 1.2.32 the registry is an InnoDB table with + * a unique task key, and register_process() reports whether its insert won, + * so one holder is admitted across the cluster. Older Cacti has neither, and + * the caller keeps its named lock. + * + * register_process_start() is not used: it treats a holder running another + * script as dead and takes over, and signals a holder that outlives its + * timeout. Here a holder is never signalled. Cacti's poller maintenance + * removes the entry of a holder that died on this host; otherwise the entry + * is retired once $timeout seconds have passed, so $timeout must exceed the + * longest legitimate run. + * + * @param string $task Task name, unique among Syslog tasks. + * @param int $taskid The collector whose data the task protects. + * @param int $wait Seconds to wait for another holder; 0 tries once. + * @param int $timeout Seconds after which the entry counts as abandoned. + * + * @return bool|null Whether the task was acquired, or null when the caller + * must use its named lock. + */ +function syslog_task_lock(string $task, int $taskid, int $wait, int $timeout): ?bool { + if (!function_exists('cacti_process_registry_ensure_table') || !cacti_process_registry_ensure_table()) { + return null; + } + + $deadline = microtime(true) + $wait; + + while (true) { + if (register_process('syslog', $task, $taskid, (int) getmypid(), $timeout)) { + return true; + } + + db_execute_prepared('DELETE FROM processes + WHERE tasktype = ? AND taskname = ? AND taskid = ? + AND UNIX_TIMESTAMP(started) + timeout < UNIX_TIMESTAMP()', + ['syslog', $task, $taskid]); + + if (db_affected_rows() > 0) { + continue; + } + + if (microtime(true) >= $deadline) { + return false; + } + + usleep(250000); + } +} + +/** + * Release a task taken by syslog_task_lock(). Only this process's entry is + * removed, so a holder whose entry was retired cannot release its successor. + * + * @param string $task Task name passed to syslog_task_lock(). + * @param int $taskid Task id passed to syslog_task_lock(). + * + * @return void + */ +function syslog_task_unlock(string $task, int $taskid): void { + unregister_process('syslog', $task, $taskid, (int) getmypid()); +} + /** * Supported partition sizes, in seconds. * diff --git a/tests/Unit/TaskLockTest.php b/tests/Unit/TaskLockTest.php index 854ee838..61524b67 100644 --- a/tests/Unit/TaskLockTest.php +++ b/tests/Unit/TaskLockTest.php @@ -219,3 +219,100 @@ function task_lock_call(string $site, string $outcome): array { ['partition remove', 0, "SYSLOG: GET_LOCK call failed for partition remove on 'syslog'"], ]); }); + +/** + * Report Cacti's process registry as cluster-safe and record its use. Each + * registration attempt takes the next answer from $free; the last repeats. + * $expired is how many timed-out holders the first expiry sweep removes. + */ +function task_lock_registry(array $free = [true], int $expired = 0): void { + syslog_load_plugin_source('includes/functions.php'); + $GLOBALS['task_lock'] += ['registered' => [], 'unregistered' => []]; + $GLOBALS['task_lock']['free'] = $free; + $GLOBALS['task_lock']['expired'] = $expired; + test_override('cacti_process_registry_ensure_table', fn () => true); + test_override('register_process', function (...$args) { + $GLOBALS['task_lock']['registered'][] = $args; + + return count($GLOBALS['task_lock']['free']) > 1 ? array_shift($GLOBALS['task_lock']['free']) : $GLOBALS['task_lock']['free'][0]; + }); + test_override('unregister_process', function (...$args) { + $GLOBALS['task_lock']['unregistered'][] = $args; + + return true; + }); + test_override('db_affected_rows', function () { + $removed = $GLOBALS['task_lock']['expired']; + $GLOBALS['task_lock']['expired'] = 0; + + return $removed; + }); +} + +describe('process registry helper', function () { + it('leaves a Cacti without a cluster-safe registry on its named lock', function () { + task_lock_fixture(1); + syslog_load_plugin_source('includes/functions.php'); + test_override('register_process', fn () => throw new LogicException('registry used')); + + expect(syslog_task_lock('health', 3, 0, 300))->toBeNull(); + }); + + it('registers the task for this process with its timeout', function () { + task_lock_fixture(1); + task_lock_registry(); + + expect(syslog_task_lock('health', 3, 0, 300))->toBeTrue() + ->and($GLOBALS['task_lock']['registered'])->toBe([['syslog', 'health', 3, getmypid(), 300]]); + }); + + it('tries once when it may not wait', function () { + task_lock_fixture(1); + task_lock_registry([false]); + $start = microtime(true); + + expect(syslog_task_lock('health', 3, 0, 300))->toBeFalse() + ->and($GLOBALS['task_lock']['registered'])->toHaveCount(1) + ->and(microtime(true) - $start)->toBeLessThan(0.2); + }); + + it('waits for the holder until the deadline', function () { + task_lock_fixture(1); + task_lock_registry([false]); + $start = microtime(true); + + expect(syslog_task_lock('partition_create_syslog', 3, 1, 1200))->toBeFalse() + ->and(microtime(true) - $start)->toBeGreaterThanOrEqual(1.0)->toBeLessThan(2.0) + ->and(count($GLOBALS['task_lock']['registered']))->toBeGreaterThan(1); + }); + + it('takes the task when the holder finishes during the wait', function () { + task_lock_fixture(1); + task_lock_registry([false, false, true]); + + expect(syslog_task_lock('partition_create_syslog', 3, 5, 1200))->toBeTrue() + ->and($GLOBALS['task_lock']['registered'])->toHaveCount(3); + }); + + it('retires a holder that outlived its timeout without waiting', function () { + task_lock_fixture(1); + task_lock_registry([false, true], 1); + + expect(syslog_task_lock('health', 3, 0, 300))->toBeTrue() + ->and($GLOBALS['task_lock']['registered'])->toHaveCount(2); + + $sweep = array_values(array_filter($GLOBALS['__test_db_calls'], fn ($call) => str_starts_with($call['sql'], 'DELETE FROM processes'))); + expect($sweep)->toHaveCount(1) + ->and($sweep[0]['sql'])->toContain('UNIX_TIMESTAMP(started) + timeout < UNIX_TIMESTAMP()') + ->and($sweep[0]['params'])->toBe(['syslog', 'health', 3]); + }); + + it('removes only this process\'s entry on release', function () { + task_lock_fixture(1); + task_lock_registry(); + + syslog_task_unlock('health', 3); + + expect($GLOBALS['task_lock']['unregistered'])->toBe([['syslog', 'health', 3, getmypid()]]); + }); +}); diff --git a/tests/bootstrap-unit.php b/tests/bootstrap-unit.php index a1f2ab00..c35e5837 100644 --- a/tests/bootstrap-unit.php +++ b/tests/bootstrap-unit.php @@ -469,6 +469,25 @@ function cacti_process_still_running($pid) { } } +// Absent before Cacti 1.2.32; false keeps every test on the named lock path unless it opts in. +if (!function_exists('cacti_process_registry_ensure_table')) { + function cacti_process_registry_ensure_table() { + return test_call_override('cacti_process_registry_ensure_table', [], false); + } +} + +if (!function_exists('register_process')) { + function register_process($tasktype, $taskname, $taskid, $pid, $timeout) { + return test_call_override('register_process', [$tasktype, $taskname, $taskid, $pid, $timeout], true); + } +} + +if (!function_exists('unregister_process')) { + function unregister_process($tasktype, $taskname, $taskid = 0, $pid = -1) { + return test_call_override('unregister_process', [$tasktype, $taskname, $taskid, $pid], true); + } +} + if (!function_exists('is_realm_allowed')) { function is_realm_allowed($realm) { return test_call_override('is_realm_allowed', [$realm], true); From be226a4a58f094c498339198eb7dcdf7e451c10a Mon Sep 17 00:00:00 2001 From: Thomas Vincent Date: Thu, 3 Dec 2026 20:15:42 -0800 Subject: [PATCH 03/21] fix(locks): serialize the pipeline health check through the process registry Refs #502. The per-collector health check tries once for task ('syslog', 'health', ) and skips the run when another process holds it, as it did with GET_LOCK(..., 0). An entry left by a holder that died expires after 300 seconds; the check itself makes a few queries and sends at most one mail. Cacti before 1.2.32 keeps the named lock. Signed-off-by: Thomas Vincent --- includes/functions.php | 12 +++++++--- tests/Unit/TaskLockTest.php | 45 ++++++++++++++++++++++++++++++++++++- 2 files changed, 53 insertions(+), 4 deletions(-) diff --git a/includes/functions.php b/includes/functions.php index e73ad3cb..f1d20b9d 100644 --- a/includes/functions.php +++ b/includes/functions.php @@ -2191,9 +2191,11 @@ function syslog_pipeline_health(): array { function syslog_pipeline_health_check(): void { global $config, $syslogdb_default; - $lock = 'syslog_health_' . sha1($syslogdb_default . ':' . (int) ($config['poller_id'] ?? 1)); + $poller = (int) ($config['poller_id'] ?? 1); + $lock = 'syslog_health_' . sha1($syslogdb_default . ':' . $poller); + $registered = syslog_task_lock('health', $poller, 0, 300); - if ((int) syslog_db_fetch_cell_prepared('SELECT GET_LOCK(?, 0)', [$lock], '', false) !== 1) { + if (!($registered ?? (int) syslog_db_fetch_cell_prepared('SELECT GET_LOCK(?, 0)', [$lock], '', false) === 1)) { return; } @@ -2267,7 +2269,11 @@ function syslog_pipeline_health_check(): void { } syslog_status_set('pipeline_health_monitor', (string) json_encode($monitor)); } finally { - syslog_db_fetch_cell_prepared('SELECT RELEASE_LOCK(?)', [$lock], '', false); + if ($registered === null) { + syslog_db_fetch_cell_prepared('SELECT RELEASE_LOCK(?)', [$lock], '', false); + } else { + syslog_task_unlock('health', $poller); + } } } diff --git a/tests/Unit/TaskLockTest.php b/tests/Unit/TaskLockTest.php index 61524b67..477d2227 100644 --- a/tests/Unit/TaskLockTest.php +++ b/tests/Unit/TaskLockTest.php @@ -126,7 +126,7 @@ function task_lock_run_replace_data(string $outcome) { }); $rows = []; - return syslog_replace_data('syslog_alert', $rows, $target, $source); + return syslog_replace_data('syslog_alert', $rows, $target, $source, 7); } function task_lock_run_dashboard(string $outcome) { @@ -316,3 +316,46 @@ function task_lock_registry(array $free = [true], int $expired = 0): void { expect($GLOBALS['task_lock']['unregistered'])->toBe([['syslog', 'health', 3, getmypid()]]); }); }); + +/* site => [registry task name, task id, entry timeout seconds] */ +function task_lock_registry_sites(): array { + return [ + 'pipeline health' => ['health', 3, 300], + ]; +} + +describe('process registry path', function () { + it('holds the task in the registry instead of a named lock', function (string $site, string $outcome) { + [$task, $taskid, $timeout] = task_lock_registry_sites()[$site]; + [, , , , , $results] = task_lock_sites()[$site]; + task_lock_fixture(1); + task_lock_registry(); + + [$result, $error] = task_lock_call($site, $outcome); + + expect($error === null)->toBe($outcome !== 'exception') + ->and($result)->toBe(['success' => $results[0], 'failure' => $results[1], 'exception' => null][$outcome]) + ->and($GLOBALS['task_lock']['work'])->toBeGreaterThan(0) + ->and($GLOBALS['task_lock']['locks'])->toBe([]) + ->and($GLOBALS['task_lock']['registered'])->toBe([['syslog', $task, $taskid, getmypid(), $timeout]]) + ->and($GLOBALS['task_lock']['unregistered'])->toBe([['syslog', $task, $taskid, getmypid()]]); + })->with(array_keys(task_lock_registry_sites()))->with(['success', 'failure', 'exception']); + + it('skips the work after the same wait while another process holds the task', function (string $site) { + [, $wait, , $result, $log] = task_lock_sites()[$site]; + task_lock_fixture(1); + task_lock_registry([false]); + $start = microtime(true); + + expect(task_lock_call($site, 'success'))->toBe([$result, null]) + ->and(microtime(true) - $start)->toBeGreaterThanOrEqual((float) $wait)->toBeLessThan($wait + 1.0) + ->and($GLOBALS['task_lock']['work'])->toBe(0) + ->and($GLOBALS['task_lock']['locks'])->toBe([]) + ->and($GLOBALS['task_lock']['registered'])->not->toBeEmpty() + ->and($GLOBALS['task_lock']['unregistered'])->toBe([]); + + if ($log !== null) { + expect($GLOBALS['task_lock']['logs'])->toContain($log); + } + })->with(array_keys(task_lock_registry_sites())); +}); From 36d8fee3e28f59a90fb3b31aaceb8c9f70f50da5 Mon Sep 17 00:00:00 2001 From: Thomas Vincent Date: Thu, 3 Dec 2026 20:16:21 -0800 Subject: [PATCH 04/21] fix(locks): serialize partition creation through the process registry Refs #502. syslog_partition_create() now holds task ('syslog', 'partition_create_', ). It waits up to 10 seconds for another holder, as GET_LOCK(..., 10) did, and logs the same 'Unable to acquire' line when it gives up. Partition maintenance runs inside the processing master, whose own registration expires after 1200 seconds, so an abandoned entry expires after 1200 seconds too; until then writes stay in dMaxValue. Cacti before 1.2.32 keeps the named lock. Signed-off-by: Thomas Vincent --- includes/functions.php | 14 +++++++++++--- tests/Unit/TaskLockTest.php | 1 + 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/includes/functions.php b/includes/functions.php index f1d20b9d..f279916d 100644 --- a/includes/functions.php +++ b/includes/functions.php @@ -3587,7 +3587,7 @@ function syslog_partition_report_state($table) { * @return bool true on success, false on lock failure or disallowed table. */ function syslog_partition_create($table, $time = null, &$reason = null, $granularity = null) { - global $syslogdb_default; + global $config, $syslogdb_default; $reason = ''; @@ -3618,13 +3618,17 @@ function syslog_partition_create($table, $time = null, &$reason = null, $granula // Hash to guarantee the lock name stays within MySQL's 64-byte limit. $lock_name = substr(hash('sha256', $syslogdb_default . '.syslog_partition_create.' . $table), 0, 60); + $poller = (int) ($config['poller_id'] ?? 1); /* * 10-second timeout is sufficient: partition maintenance runs once per * poller cycle (typically 5 minutes), so sustained contention is not * expected. A failure is logged so monitoring can detect repeated misses. + * An abandoned registry entry expires after 1200 seconds, the timeout of + * the processing master that runs partition maintenance. */ - $locked = syslog_db_fetch_cell_prepared('SELECT GET_LOCK(?, 10)', [$lock_name]); + $registered = syslog_task_lock('partition_create_' . $table, $poller, 10, 1200); + $locked = $registered ?? syslog_db_fetch_cell_prepared('SELECT GET_LOCK(?, 10)', [$lock_name]); if ($locked === null) { // NULL means the GET_LOCK call itself failed, not just contention. @@ -3801,7 +3805,11 @@ function syslog_partition_create($table, $time = null, &$reason = null, $granula $success = true; } finally { - syslog_db_fetch_cell_prepared('SELECT RELEASE_LOCK(?)', [$lock_name]); + if ($registered === null) { + syslog_db_fetch_cell_prepared('SELECT RELEASE_LOCK(?)', [$lock_name]); + } else { + syslog_task_unlock('partition_create_' . $table, $poller); + } } return $success; diff --git a/tests/Unit/TaskLockTest.php b/tests/Unit/TaskLockTest.php index 477d2227..2707e6a3 100644 --- a/tests/Unit/TaskLockTest.php +++ b/tests/Unit/TaskLockTest.php @@ -321,6 +321,7 @@ function task_lock_registry(array $free = [true], int $expired = 0): void { function task_lock_registry_sites(): array { return [ 'pipeline health' => ['health', 3, 300], + 'partition create' => ['partition_create_syslog', 3, 1200], ]; } From bd536e05d8da2840f19d9a2ab106defa5c8da4e1 Mon Sep 17 00:00:00 2001 From: Thomas Vincent Date: Thu, 3 Dec 2026 20:17:17 -0800 Subject: [PATCH 05/21] fix(locks): serialize partition removal through the process registry Refs #502. syslog_partition_remove() now holds task ('syslog', 'partition_remove_
', ), waits up to 10 seconds as before, and returns 0 with the same log line when another process holds it. An abandoned entry expires after 1200 seconds, which delays retention pruning by at most that long. Cacti before 1.2.32 keeps the named lock. Signed-off-by: Thomas Vincent --- includes/functions.php | 14 ++++++++++---- tests/Unit/TaskLockTest.php | 1 + 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/includes/functions.php b/includes/functions.php index f279916d..63bc9c00 100644 --- a/includes/functions.php +++ b/includes/functions.php @@ -3825,7 +3825,7 @@ function syslog_partition_create($table, $time = null, &$reason = null, $granula * @return int Number of partitions removed. */ function syslog_partition_remove($table) { - global $syslogdb_default; + global $config, $syslogdb_default; if (!syslog_partition_table_allowed($table)) { cacti_log("SYSLOG: partition_remove called with disallowed table '$table'", false, 'SYSTEM'); @@ -3839,9 +3839,11 @@ function syslog_partition_remove($table) { return 0; } - $lock_name = substr(hash('sha256', $syslogdb_default . '.syslog_partition_remove.' . $table), 0, 60); + $lock_name = substr(hash('sha256', $syslogdb_default . '.syslog_partition_remove.' . $table), 0, 60); + $poller = (int) ($config['poller_id'] ?? 1); + $registered = syslog_task_lock('partition_remove_' . $table, $poller, 10, 1200); - $locked = syslog_db_fetch_cell_prepared('SELECT GET_LOCK(?, 10)', [$lock_name]); + $locked = $registered ?? syslog_db_fetch_cell_prepared('SELECT GET_LOCK(?, 10)', [$lock_name]); if ($locked === null) { cacti_log("SYSLOG: GET_LOCK call failed for partition remove on '$table'", false, 'SYSTEM'); @@ -3927,7 +3929,11 @@ function syslog_partition_remove($table) { } } finally { - syslog_db_fetch_cell_prepared('SELECT RELEASE_LOCK(?)', [$lock_name]); + if ($registered === null) { + syslog_db_fetch_cell_prepared('SELECT RELEASE_LOCK(?)', [$lock_name]); + } else { + syslog_task_unlock('partition_remove_' . $table, $poller); + } } return $syslog_deleted; diff --git a/tests/Unit/TaskLockTest.php b/tests/Unit/TaskLockTest.php index 2707e6a3..ac6de07f 100644 --- a/tests/Unit/TaskLockTest.php +++ b/tests/Unit/TaskLockTest.php @@ -322,6 +322,7 @@ function task_lock_registry_sites(): array { return [ 'pipeline health' => ['health', 3, 300], 'partition create' => ['partition_create_syslog', 3, 1200], + 'partition remove' => ['partition_remove_syslog', 3, 1200], ]; } From 42b4a616d6f08dd9804676b8a8864f252cd8cdd4 Mon Sep 17 00:00:00 2001 From: Thomas Vincent Date: Thu, 3 Dec 2026 20:25:29 -0800 Subject: [PATCH 06/21] fix(locks): retry once per expiry sweep in the task lock Refs #502. After retiring an expired entry the task lock retried at once, without a bound, for as long as the sweep reported a removed row. It now makes one immediate retry per sweep and otherwise waits for the deadline. The lock tests also reset their overrides afterwards, so the registry they enable no longer reaches tests in later files. Signed-off-by: Thomas Vincent --- includes/functions.php | 4 ++-- tests/Unit/TaskLockTest.php | 22 ++++++++++++++++++++++ 2 files changed, 24 insertions(+), 2 deletions(-) diff --git a/includes/functions.php b/includes/functions.php index 63bc9c00..00e8954d 100644 --- a/includes/functions.php +++ b/includes/functions.php @@ -2906,8 +2906,8 @@ function syslog_task_lock(string $task, int $taskid, int $wait, int $timeout): ? AND UNIX_TIMESTAMP(started) + timeout < UNIX_TIMESTAMP()', ['syslog', $task, $taskid]); - if (db_affected_rows() > 0) { - continue; + if (db_affected_rows() > 0 && register_process('syslog', $task, $taskid, (int) getmypid(), $timeout)) { + return true; } if (microtime(true) >= $deadline) { diff --git a/tests/Unit/TaskLockTest.php b/tests/Unit/TaskLockTest.php index ac6de07f..eb06969e 100644 --- a/tests/Unit/TaskLockTest.php +++ b/tests/Unit/TaskLockTest.php @@ -13,6 +13,10 @@ * exception, and is also run while another process holds its lock. */ +afterEach(function () { + syslog_test_reset_globals(); +}); + function task_lock_fixture(?int $lock): void { syslog_test_reset_globals(); $GLOBALS['config']['poller_id'] = 3; @@ -307,6 +311,24 @@ function task_lock_registry(array $free = [true], int $expired = 0): void { ->and($sweep[0]['params'])->toBe(['syslog', 'health', 3]); }); + it('makes one immediate retry per expiry sweep', function () { + task_lock_fixture(1); + task_lock_registry([false]); + test_override('db_affected_rows', fn () => 1); + test_override('register_process', function (...$args) { + $GLOBALS['task_lock']['registered'][] = $args; + + if (count($GLOBALS['task_lock']['registered']) > 10) { + throw new LogicException('registration retried without a bound'); + } + + return false; + }); + + expect(syslog_task_lock('health', 3, 0, 300))->toBeFalse() + ->and($GLOBALS['task_lock']['registered'])->toHaveCount(2); + }); + it('removes only this process\'s entry on release', function () { task_lock_fixture(1); task_lock_registry(); From 102df1f36935552e26dac466250aca9b817eafaf Mon Sep 17 00:00:00 2001 From: Thomas Vincent Date: Thu, 3 Dec 2026 20:26:05 -0800 Subject: [PATCH 07/21] fix(locks): serialize recovery delivery through the process registry Refs #502. syslog_threshold_deliver_recoveries() tries once for task ('syslog', 'recovery', ) and skips delivery when another process holds it, as with GET_LOCK(..., 0). Recovery commands run through exec() with no time limit inside the processing master, which the next master replaces after 1200 seconds, so an abandoned entry expires after 1200 seconds. Cacti before 1.2.32 keeps the named lock. Signed-off-by: Thomas Vincent --- includes/functions.php | 10 ++++++++-- tests/Unit/TaskLockTest.php | 1 + 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/includes/functions.php b/includes/functions.php index 00e8954d..b5a84fcc 100644 --- a/includes/functions.php +++ b/includes/functions.php @@ -6101,8 +6101,10 @@ function syslog_threshold_deliver_recoveries(?int $now = null): void { $now = $now ?? time(); $source = max(1, (int) ($config['poller_id'] ?? 1)); $lock = 'syslog-clear:' . sha1($syslogdb_default . ':' . $source); + // Commands have no time limit; the processing master that runs them is replaced after 1200 seconds. + $registered = syslog_task_lock('recovery', $source, 0, 1200); - if ((int) syslog_db_fetch_cell_prepared('SELECT GET_LOCK(?, 0)', [$lock]) !== 1) { + if (!($registered ?? (int) syslog_db_fetch_cell_prepared('SELECT GET_LOCK(?, 0)', [$lock]) === 1)) { return; } @@ -6139,7 +6141,11 @@ function syslog_threshold_deliver_recoveries(?int $now = null): void { syslog_db_execute_prepared('UPDATE syslog_threshold_recovery_queue SET attempts = attempts + 1, available_at = ? WHERE source_poller_id = ? AND breach_key = ?', [$now + $delay, $source, $row['breach_key']]); } } finally { - syslog_db_fetch_cell_prepared('SELECT RELEASE_LOCK(?)', [$lock]); + if ($registered === null) { + syslog_db_fetch_cell_prepared('SELECT RELEASE_LOCK(?)', [$lock]); + } else { + syslog_task_unlock('recovery', $source); + } } } diff --git a/tests/Unit/TaskLockTest.php b/tests/Unit/TaskLockTest.php index eb06969e..57b5835a 100644 --- a/tests/Unit/TaskLockTest.php +++ b/tests/Unit/TaskLockTest.php @@ -345,6 +345,7 @@ function task_lock_registry_sites(): array { 'pipeline health' => ['health', 3, 300], 'partition create' => ['partition_create_syslog', 3, 1200], 'partition remove' => ['partition_remove_syslog', 3, 1200], + 'recovery delivery' => ['recovery', 3, 1200], ]; } From b2d4ea747fcdefbf809aa7a6c1461837baca819d Mon Sep 17 00:00:00 2001 From: Thomas Vincent Date: Thu, 3 Dec 2026 20:27:33 -0800 Subject: [PATCH 08/21] fix(locks): serialize rule snapshot publishing through the process registry Refs #502. syslog_replace_data() holds task ('syslog', 'rules_
', ) where the collector owns the target database: the remote collector for syslog_replicate_out(), this collector for syslog_replicate_in(). Publishing to two collectors at once stays independent, as it was with a lock on each target server. It waits up to 5 seconds as before and returns false when another process holds the task. Copying a rule table takes seconds, so an abandoned entry expires after 300 seconds. Cacti before 1.2.32 keeps the named lock on the target connection. Signed-off-by: Thomas Vincent --- includes/processing.php | 20 ++++++++++++++------ tests/Unit/DeviceRulePolicyTest.php | 2 +- tests/Unit/TaskLockTest.php | 14 ++++++++++++++ 3 files changed, 29 insertions(+), 7 deletions(-) diff --git a/includes/processing.php b/includes/processing.php index f2547e71..3e0c1bc5 100644 --- a/includes/processing.php +++ b/includes/processing.php @@ -28,7 +28,7 @@ function syslog_replicate_out($data) { foreach (['syslog_alert', 'syslog_device_rule', 'syslog_remove', 'syslog_reports'] as $table) { $rows = syslog_db_fetch_assoc("SELECT * FROM `$table`"); - if (!syslog_replace_data($table, $rows, $data['rcnn_id'], $syslog_cnn)) { + if (!syslog_replace_data($table, $rows, $data['rcnn_id'], $syslog_cnn, (int) $data['remote_poller_id'])) { cacti_log("ERROR: Unable to replicate Syslog rule table $table", false, 'REPLICATE'); break; @@ -104,11 +104,12 @@ function syslog_poller_bottom(): void { * @param array|false $data Source rows; false must never clear a table. * @param object|null $target Destination, defaulting to the local Syslog DB. * @param object|null $source Schema source, defaulting to Cacti's local DB. + * @param int|null $poller Collector that owns $target, defaulting to this one. * * @return bool Whether the full snapshot was published. */ -function syslog_replace_data($table, &$data, $target = null, $source = null): bool { - global $syslog_cnn, $local_db_cnn_id; +function syslog_replace_data($table, &$data, $target = null, $source = null, $poller = null): bool { + global $config, $syslog_cnn, $local_db_cnn_id; if (!in_array($table, ['syslog_alert', 'syslog_device_rule', 'syslog_remove', 'syslog_reports'], true) || !is_array($data)) { @@ -160,9 +161,11 @@ function syslog_replace_data($table, &$data, $target = null, $source = null): bo } } - $lock = 'syslog_rule_snapshot_' . $table; + $lock = 'syslog_rule_snapshot_' . $table; + $poller = (int) ($poller ?? $config['poller_id'] ?? 1); + $registered = syslog_task_lock('rules_' . $table, $poller, 5, 300); - if (!db_fetch_cell_prepared('SELECT GET_LOCK(?, 5)', [$lock], '', true, $target)) { + if (!($registered ?? db_fetch_cell_prepared('SELECT GET_LOCK(?, 5)', [$lock], '', true, $target))) { return false; } @@ -207,6 +210,11 @@ function syslog_replace_data($table, &$data, $target = null, $source = null): bo return db_execute("RENAME TABLE $rename`$stage` TO `$table`", true, $target); } finally { db_execute("DROP TABLE IF EXISTS `$stage`, `$backup`", true, $target); - db_fetch_cell_prepared('SELECT RELEASE_LOCK(?)', [$lock], '', true, $target); + + if ($registered === null) { + db_fetch_cell_prepared('SELECT RELEASE_LOCK(?)', [$lock], '', true, $target); + } else { + syslog_task_unlock('rules_' . $table, $poller); + } } } diff --git a/tests/Unit/DeviceRulePolicyTest.php b/tests/Unit/DeviceRulePolicyTest.php index 4e10eeb5..6b9724ea 100644 --- a/tests/Unit/DeviceRulePolicyTest.php +++ b/tests/Unit/DeviceRulePolicyTest.php @@ -53,7 +53,7 @@ ->toContain('syslog_create_device_rule_table();'); expect($setup)->not->toContain('syslog_create_device_rule_table();'); expect($processing)->toContain("['syslog_alert', 'syslog_device_rule', 'syslog_remove', 'syslog_reports']") - ->toContain("syslog_replace_data(\$table, \$rows, \$data['rcnn_id'], \$syslog_cnn)"); + ->toContain("syslog_replace_data(\$table, \$rows, \$data['rcnn_id'], \$syslog_cnn, (int) \$data['remote_poller_id'])"); }); it('maps the legacy host_id hostField to the incoming host column', function () { diff --git a/tests/Unit/TaskLockTest.php b/tests/Unit/TaskLockTest.php index 57b5835a..80b3d3de 100644 --- a/tests/Unit/TaskLockTest.php +++ b/tests/Unit/TaskLockTest.php @@ -346,6 +346,7 @@ function task_lock_registry_sites(): array { 'partition create' => ['partition_create_syslog', 3, 1200], 'partition remove' => ['partition_remove_syslog', 3, 1200], 'recovery delivery' => ['recovery', 3, 1200], + 'rule snapshot' => ['rules_syslog_alert', 7, 300], ]; } @@ -366,6 +367,19 @@ function task_lock_registry_sites(): array { ->and($GLOBALS['task_lock']['unregistered'])->toBe([['syslog', $task, $taskid, getmypid()]]); })->with(array_keys(task_lock_registry_sites()))->with(['success', 'failure', 'exception']); + it('keys a rule snapshot by this collector when no target collector is given', function () { + task_lock_fixture(1); + task_lock_registry(); + syslog_load_plugin_source('includes/processing.php'); + $GLOBALS['syslog_cnn'] = new stdClass(); + $GLOBALS['local_db_cnn_id'] = new stdClass(); + test_override('db_fetch_row', fn () => ['Create Table' => 'CREATE TABLE `syslog_alert` (`id` INT PRIMARY KEY) ENGINE=InnoDB']); + $rows = []; + + expect(syslog_replace_data('syslog_alert', $rows))->toBeTrue() + ->and($GLOBALS['task_lock']['registered'])->toBe([['syslog', 'rules_syslog_alert', 3, getmypid(), 300]]); + }); + it('skips the work after the same wait while another process holds the task', function (string $site) { [, $wait, , $result, $log] = task_lock_sites()[$site]; task_lock_fixture(1); From 189b70690af001ff890289fad7029dfc1b2da735 Mon Sep 17 00:00:00 2001 From: Thomas Vincent Date: Thu, 3 Dec 2026 20:28:57 -0800 Subject: [PATCH 09/21] fix(locks): serialize default dashboard seeding through the process registry Refs #502. syslog_dashboard_seed_default() holds task ('syslog', 'dashboard', ), waits up to 5 seconds as before, and leaves seeding to the holder when it cannot get the task. Seeding inserts six rows; an entry left by a web request that ended without releasing it stays until it expires after 300 seconds, because the web server process keeps running. Cacti before 1.2.32 keeps the named lock. Signed-off-by: Thomas Vincent --- setup.php | 14 ++++++++++---- tests/Unit/TaskLockTest.php | 1 + 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/setup.php b/setup.php index 85eb624c..180fa987 100644 --- a/setup.php +++ b/setup.php @@ -1243,13 +1243,15 @@ function syslog_check_upgrade(bool $force = false): bool { /** Seed the shared starter after the install/upgrade caller creates its tables. */ function syslog_dashboard_seed_default(): void { - global $syslogdb_default; + global $config, $syslogdb_default; // Both callers already ensured the schema. Repeating that work can reuse // Cacti's cached missing-table result and try to create the tables twice. - $lock = 'syslog_dashboard_' . md5($syslogdb_default); + $lock = 'syslog_dashboard_' . md5($syslogdb_default); + $poller = (int) ($config['poller_id'] ?? 1); + $registered = syslog_task_lock('dashboard', $poller, 5, 300); - if (!syslog_db_fetch_cell_prepared('SELECT GET_LOCK(?, 5)', [$lock])) { + if (!($registered ?? syslog_db_fetch_cell_prepared('SELECT GET_LOCK(?, 5)', [$lock]))) { return; } @@ -1307,7 +1309,11 @@ function syslog_dashboard_seed_default(): void { throw $error; } finally { - syslog_db_fetch_cell_prepared('SELECT RELEASE_LOCK(?)', [$lock]); + if ($registered === null) { + syslog_db_fetch_cell_prepared('SELECT RELEASE_LOCK(?)', [$lock]); + } else { + syslog_task_unlock('dashboard', $poller); + } } } diff --git a/tests/Unit/TaskLockTest.php b/tests/Unit/TaskLockTest.php index 80b3d3de..87d0975d 100644 --- a/tests/Unit/TaskLockTest.php +++ b/tests/Unit/TaskLockTest.php @@ -347,6 +347,7 @@ function task_lock_registry_sites(): array { 'partition remove' => ['partition_remove_syslog', 3, 1200], 'recovery delivery' => ['recovery', 3, 1200], 'rule snapshot' => ['rules_syslog_alert', 7, 300], + 'dashboard seed' => ['dashboard', 3, 300], ]; } From 176ff5453fcfe0517986718a863b60770eb9139d Mon Sep 17 00:00:00 2001 From: Thomas Vincent Date: Thu, 3 Dec 2026 20:32:05 -0800 Subject: [PATCH 10/21] test(locks): contend for a task lock from two processes on MariaDB Refs #502. With Cacti's lib/poller.php the script starts from the MEMORY processes table older Cacti created and checks that the first lock has Cacti convert it, that a second process on another connection is refused or waits, that recovery delivery is skipped while another process holds its task and runs after release, that a live holder is not signalled, that only an entry past its timeout is retired, and that one of two callers starting together wins in each of 20 rounds. Run with the argument 'main named', it checks that without that core the named lock still decides. Signed-off-by: Thomas Vincent --- tests/regression/task_lock_database_test.php | 220 +++++++++++++++++++ 1 file changed, 220 insertions(+) create mode 100644 tests/regression/task_lock_database_test.php diff --git a/tests/regression/task_lock_database_test.php b/tests/regression/task_lock_database_test.php new file mode 100644 index 00000000..f6e5ae92 --- /dev/null +++ b/tests/regression/task_lock_database_test.php @@ -0,0 +1,220 @@ + PDO::ERRMODE_EXCEPTION, + PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC +]); +$config = ['poller_id' => 1]; +$syslogdb_default = $database; +$affected = 0; +$checks = 0; + +function lock_check(bool $ok, string $message): void { + $GLOBALS['checks']++; + + if (!$ok) { + throw new RuntimeException($message); + } +} + +function db_run(string $sql, array $params) { + try { + $query = $GLOBALS['pdo']->prepare($sql); + $query->execute($params); + $GLOBALS['affected'] = $query->rowCount(); + + return $query; + } catch (PDOException $error) { + $GLOBALS['affected'] = 0; + + return false; + } +} + +function db_execute($sql, $log = true, $connection = false) { return db_run($sql, []) !== false; } +function db_execute_prepared($sql, $params = [], $log = true, $connection = false) { return db_run($sql, $params) !== false; } +function db_affected_rows($connection = false) { return $GLOBALS['affected']; } +function db_fetch_row($sql, $log = true, $connection = false) { $query = db_run($sql, []); return $query ? ($query->fetch() ?: []) : false; } +function db_fetch_row_prepared($sql, $params = [], $log = true, $connection = false) { $query = db_run($sql, $params); return $query ? ($query->fetch() ?: []) : false; } +function db_fetch_cell_prepared($sql, $params = [], $col = '', $log = true, $connection = false) { $query = db_run($sql, $params); return $query ? $query->fetchColumn() : false; } +function db_table_exists($table, $log = true) { return (bool) db_fetch_cell_prepared('SELECT COUNT(*) FROM information_schema.TABLES WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ?', [$table]); } +function db_column_exists($table, $column, $log = true) { return (bool) db_fetch_cell_prepared('SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ? AND COLUMN_NAME = ?', [$table, $column]); } +function syslog_db_execute($sql, $log = true) { return db_execute($sql); } +function syslog_db_execute_prepared($sql, $params = [], $log = true) { return db_execute_prepared($sql, $params); } +function syslog_db_fetch_cell_prepared($sql, $params = [], $col = '', $log = true) { $query = db_run($sql, $params); return $query ? $query->fetchColumn() : null; } +function syslog_db_fetch_assoc_prepared($sql, $params = [], $log = true) { $query = db_run($sql, $params); return $query ? $query->fetchAll() : false; } +function read_config_option($name, $force = false) { return ''; } +function cacti_log(...$args) {} +function cacti_sizeof($items) { return is_array($items) ? count($items) : 0; } +function cacti_escapeshellarg($value) { return escapeshellarg((string) $value); } +function clean_up_name($value) { return $value; } + +if ($mode === 'registry') { + require $cacti_root . '/lib/poller.php'; +} + +require dirname(__DIR__, 2) . '/includes/functions.php'; + +/** A second process on its own connection that takes $task, reports, and releases on request. */ +function lock_child(string $mode, string $task, float $start = 0.0) { + global $database; + + $pipes = []; + $process = proc_open([PHP_BINARY, __FILE__, 'child', $mode, $database, $task, (string) $start], [0 => ['pipe', 'r'], 1 => ['pipe', 'w']], $pipes); + + return [$process, $pipes]; +} + +function lock_child_state(array $child): string { + return trim((string) fgets($child[1][1])); +} + +function lock_child_finish(array $child): void { + fwrite($child[1][0], "release\n"); + fclose($child[1][0]); + stream_get_contents($child[1][1]); + proc_close($child[0]); +} + +if ($role === 'child') { + $pdo->exec("USE `$database`"); + + if ((float) $child_start > 0) { + time_sleep_until((float) $child_start); + } + + if ($mode === 'registry') { + $held = syslog_task_lock($child_task, 1, 0, 1200); + } else { + $held = (int) syslog_db_fetch_cell_prepared('SELECT GET_LOCK(?, 0)', [$child_task]) === 1; + } + + print ($held ? 'held' : 'busy') . "\n"; + + if (trim((string) fgets(STDIN)) === 'later') { + sleep(1); + } + + if ($held && $mode === 'registry') { + syslog_task_unlock($child_task, 1); + } + + exit(0); +} + +try { + $pdo->exec("CREATE DATABASE `$database`"); + $pdo->exec("USE `$database`"); + $pdo->exec('CREATE TABLE syslog_alert (id INT PRIMARY KEY, enabled CHAR(2), method INT, date BIGINT, + recovery_command VARCHAR(255), alarm_destination VARCHAR(16) NOT NULL DEFAULT \'syslog\')'); + $pdo->exec('CREATE TABLE syslog_threshold_recovery_queue (source_poller_id INT, breach_key CHAR(32), alert_id INT, + rule_date BIGINT, context TEXT, attempts INT DEFAULT 0, available_at BIGINT, PRIMARY KEY (source_poller_id, breach_key))'); + $queue = static function () use ($pdo): int { + $pdo->exec("INSERT IGNORE INTO syslog_threshold_recovery_queue VALUES (1, 'orphan', 99, 1, '{}', 0, 0)"); + + return (int) $pdo->query('SELECT COUNT(*) FROM syslog_threshold_recovery_queue')->fetchColumn(); + }; + $queued = static fn (): int => (int) $pdo->query('SELECT COUNT(*) FROM syslog_threshold_recovery_queue')->fetchColumn(); + + if ($mode === 'registry') { + // The table as Cacti before 1.2.32 created it; the first lock converts it. + $pdo->exec('CREATE TABLE processes (id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, pid INT UNSIGNED NOT NULL DEFAULT 0, + tasktype VARCHAR(20) NOT NULL DEFAULT \'\', taskname VARCHAR(40) NOT NULL DEFAULT \'\', taskid INT UNSIGNED NOT NULL DEFAULT 0, + timeout INT UNSIGNED DEFAULT 300, connection_id BIGINT UNSIGNED NOT NULL DEFAULT 0, + started TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, last_update TIMESTAMP NOT NULL DEFAULT \'0000-00-00 00:00:00\', + PRIMARY KEY (pid, tasktype, taskname, taskid), KEY tasktype (tasktype), KEY id (id)) ENGINE=MEMORY'); + + lock_check(syslog_task_lock('probe', 1, 0, 60) === true, 'The first task lock is taken'); + $state = cacti_process_registry_table_state(); + lock_check(strcasecmp($state['engine'], 'InnoDB') === 0 && (int) $state['task_key'] > 0, 'Cacti converts the registry before the plugin relies on it'); + syslog_task_unlock('probe', 1); + + $holder = lock_child('registry', 'recovery'); + lock_check(lock_child_state($holder) === 'held', 'The first process takes the task'); + lock_check(syslog_task_lock('recovery', 1, 0, 1200) === false, 'A second process on another connection is refused at once'); + $start = microtime(true); + lock_check(syslog_task_lock('recovery', 1, 2, 1200) === false && microtime(true) - $start >= 2, 'A waiting caller gives up after its wait'); + $queue(); + syslog_threshold_deliver_recoveries(1000); + lock_check($queued() === 1, 'Recovery delivery is skipped while another process holds it'); + lock_check(proc_get_status($holder[0])['running'], 'A live holder is never signalled'); + lock_child_finish($holder); + syslog_threshold_deliver_recoveries(1000); + lock_check($queued() === 0, 'Recovery delivery runs once the holder released the task'); + lock_check((int) $pdo->query('SELECT COUNT(*) FROM processes')->fetchColumn() === 0, 'Delivery releases its registry entry'); + + $holder = lock_child('registry', 'recovery'); + lock_check(lock_child_state($holder) === 'held', 'The holder retakes the task'); + fwrite($holder[1][0], "later\n"); + $start = microtime(true); + lock_check(syslog_task_lock('recovery', 1, 5, 1200) === true, 'A waiting caller takes the task when the holder releases it'); + lock_check(microtime(true) - $start >= 1 && microtime(true) - $start < 5, 'The caller waited for the holder'); + syslog_task_unlock('recovery', 1); + fclose($holder[1][0]); + proc_close($holder[0]); + + $pdo->exec("INSERT INTO processes (pid, tasktype, taskname, taskid, timeout, started) VALUES (999999, 'syslog', 'recovery', 1, 1200, NOW() - INTERVAL 1201 SECOND)"); + lock_check(syslog_task_lock('recovery', 1, 0, 1200) === true, 'An entry older than its timeout is retired'); + syslog_task_unlock('recovery', 1); + $pdo->exec("INSERT INTO processes (pid, tasktype, taskname, taskid, timeout, started) VALUES (999999, 'syslog', 'recovery', 1, 1200, NOW() - INTERVAL 1100 SECOND)"); + lock_check(syslog_task_lock('recovery', 1, 0, 1200) === false, 'An entry within its timeout is kept even if its process is gone'); + $pdo->exec('DELETE FROM processes'); + + for ($round = 0; $round < 20; $round++) { + $start = microtime(true) + 0.5; + $children = [lock_child('registry', 'race', $start), lock_child('registry', 'race', $start)]; + $states = array_map('lock_child_state', $children); + sort($states); + lock_check($states === ['busy', 'held'], "Exactly one of two simultaneous callers takes the task (round $round)"); + array_map('lock_child_finish', $children); + } + } else { + lock_check(!function_exists('cacti_process_registry_ensure_table'), 'Cacti before 1.2.32 has no cluster-safe registry'); + lock_check(syslog_task_lock('recovery', 1, 0, 1200) === null, 'The task lock defers to the named lock'); + $name = 'syslog-clear:' . sha1($database . ':1'); + $holder = lock_child('named', $name); + lock_check(lock_child_state($holder) === 'held', 'The first process takes the named lock'); + $queue(); + syslog_threshold_deliver_recoveries(1000); + lock_check($queued() === 1, 'Recovery delivery is skipped while another connection holds the named lock'); + lock_child_finish($holder); + syslog_threshold_deliver_recoveries(1000); + lock_check($queued() === 0, 'Recovery delivery runs once the named lock is free'); + lock_check(!db_table_exists('processes'), 'The registry is not touched'); + } + + print "Task lock $mode checks passed: $checks\n"; +} finally { + $pdo->exec("DROP DATABASE IF EXISTS `$database`"); +} From 724b497132c562665bb4d00859e9819d86862826 Mon Sep 17 00:00:00 2001 From: Thomas Vincent Date: Thu, 3 Dec 2026 20:32:12 -0800 Subject: [PATCH 11/21] docs(changelog): note the process registry locks (#502) Signed-off-by: Thomas Vincent --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index cdd0305c..88d30fc2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -21,6 +21,7 @@ * 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 * issue#479: Replace the GET_LOCK()-based Syslog processing lock with Cacti's process registry so transfer workers no longer stop writing when their database connection is routed to a different cluster node; the master, partition rebuilds and on-demand table repair now coordinate through register_process_start('syslog','master',...) and workers verify the master by process id +* issue#502: On Cacti 1.2.32 and later, the pipeline health check, partition creation and removal, threshold recovery delivery, rule synchronization and default dashboard seeding coordinate through Cacti's process registry instead of GET_LOCK(), so each stays exclusive on a database cluster where named locks are granted per node; earlier Cacti versions keep the named locks * 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 * feature: Preserve legacy DATETIME logtime history (including TO_DAYS partitioned tables) in cli/upgrade_partitioning.php with --source-time-zone=. Before any change the zone must be known to PHP/Cacti and the Syslog database, both must agree on its offsets across the stored history, and every value must exist in it. Stored and removed messages are then renamed and copied in verified batches in that zone, and a retry must reuse the same zone From 8946e520b5136f2349179512f174254064baa63c Mon Sep 17 00:00:00 2001 From: Thomas Vincent Date: Thu, 3 Dec 2026 20:36:58 -0800 Subject: [PATCH 12/21] style(locks): format the task lock tests with Cacti's php-cs-fixer rules Signed-off-by: Thomas Vincent --- tests/Unit/TaskLockTest.php | 30 +++---- tests/regression/task_lock_database_test.php | 87 +++++++++++++++----- 2 files changed, 80 insertions(+), 37 deletions(-) diff --git a/tests/Unit/TaskLockTest.php b/tests/Unit/TaskLockTest.php index 87d0975d..53c629b4 100644 --- a/tests/Unit/TaskLockTest.php +++ b/tests/Unit/TaskLockTest.php @@ -20,8 +20,8 @@ function task_lock_fixture(?int $lock): void { syslog_test_reset_globals(); $GLOBALS['config']['poller_id'] = 3; - $GLOBALS['syslogdb_default'] = 'lock_test'; - $GLOBALS['task_lock'] = ['lock' => $lock, 'locks' => [], 'logs' => [], 'work' => 0]; + $GLOBALS['syslogdb_default'] = 'lock_test'; + $GLOBALS['task_lock'] = ['lock' => $lock, 'locks' => [], 'logs' => [], 'work' => 0]; test_override('cacti_log', function ($text) { $GLOBALS['task_lock']['logs'][] = $text; }); @@ -49,7 +49,7 @@ function task_lock_work(string $outcome, string $message): void { function task_lock_run_health(string $outcome) { syslog_load_plugin_source('includes/functions.php'); $GLOBALS['syslog_incoming_config'] = ['timeField' => 'received_at']; - $settings = ['syslog_enabled' => 'on', 'syslog_remote_enabled' => 'on', 'poller_interval' => '300','syslog_pipeline_health_email' => 'ops@example.test']; + $settings = ['syslog_enabled' => 'on', 'syslog_remote_enabled' => 'on', 'poller_interval' => '300', 'syslog_pipeline_health_email' => 'ops@example.test']; test_override('read_config_option', fn ($name) => $settings[$name] ?? ''); test_override('syslog_db_table_exists', fn () => true); test_override('syslog_db_fetch_assoc', fn () => [['name' => 'last_end_time', 'value' => (string) time(), 'updated' => time()]]); @@ -109,8 +109,8 @@ function task_lock_run_recoveries(string $outcome) { function task_lock_run_replace_data(string $outcome) { syslog_load_plugin_source('includes/processing.php'); - $target = new stdClass(); - $source = new stdClass(); + $target = new stdClass(); + $source = new stdClass(); $GLOBALS['task_lock']['target'] = $target; test_override('db_fetch_row', fn () => ['Create Table' => 'CREATE TABLE `syslog_alert` (`id` INT PRIMARY KEY) ENGINE=InnoDB']); test_override('db_fetch_cell_prepared', function ($sql, $params, $column, $log, $connection) use ($target) { @@ -232,7 +232,7 @@ function task_lock_call(string $site, string $outcome): array { function task_lock_registry(array $free = [true], int $expired = 0): void { syslog_load_plugin_source('includes/functions.php'); $GLOBALS['task_lock'] += ['registered' => [], 'unregistered' => []]; - $GLOBALS['task_lock']['free'] = $free; + $GLOBALS['task_lock']['free'] = $free; $GLOBALS['task_lock']['expired'] = $expired; test_override('cacti_process_registry_ensure_table', fn () => true); test_override('register_process', function (...$args) { @@ -246,7 +246,7 @@ function task_lock_registry(array $free = [true], int $expired = 0): void { return true; }); test_override('db_affected_rows', function () { - $removed = $GLOBALS['task_lock']['expired']; + $removed = $GLOBALS['task_lock']['expired']; $GLOBALS['task_lock']['expired'] = 0; return $removed; @@ -339,22 +339,22 @@ function task_lock_registry(array $free = [true], int $expired = 0): void { }); }); -/* site => [registry task name, task id, entry timeout seconds] */ +// site => [registry task name, task id, entry timeout seconds] function task_lock_registry_sites(): array { return [ - 'pipeline health' => ['health', 3, 300], - 'partition create' => ['partition_create_syslog', 3, 1200], - 'partition remove' => ['partition_remove_syslog', 3, 1200], + 'pipeline health' => ['health', 3, 300], + 'partition create' => ['partition_create_syslog', 3, 1200], + 'partition remove' => ['partition_remove_syslog', 3, 1200], 'recovery delivery' => ['recovery', 3, 1200], - 'rule snapshot' => ['rules_syslog_alert', 7, 300], - 'dashboard seed' => ['dashboard', 3, 300], + 'rule snapshot' => ['rules_syslog_alert', 7, 300], + 'dashboard seed' => ['dashboard', 3, 300], ]; } describe('process registry path', function () { it('holds the task in the registry instead of a named lock', function (string $site, string $outcome) { [$task, $taskid, $timeout] = task_lock_registry_sites()[$site]; - [, , , , , $results] = task_lock_sites()[$site]; + [, , , , , $results] = task_lock_sites()[$site]; task_lock_fixture(1); task_lock_registry(); @@ -372,7 +372,7 @@ function task_lock_registry_sites(): array { task_lock_fixture(1); task_lock_registry(); syslog_load_plugin_source('includes/processing.php'); - $GLOBALS['syslog_cnn'] = new stdClass(); + $GLOBALS['syslog_cnn'] = new stdClass(); $GLOBALS['local_db_cnn_id'] = new stdClass(); test_override('db_fetch_row', fn () => ['Create Table' => 'CREATE TABLE `syslog_alert` (`id` INT PRIMARY KEY) ENGINE=InnoDB']); $rows = []; diff --git a/tests/regression/task_lock_database_test.php b/tests/regression/task_lock_database_test.php index f6e5ae92..1ff7ea15 100644 --- a/tests/regression/task_lock_database_test.php +++ b/tests/regression/task_lock_database_test.php @@ -27,12 +27,12 @@ exit(2); } -$cacti_root = getenv('SYSLOG_TEST_CACTI_ROOT') ?: dirname(__DIR__, 4); +$cacti_root = getenv('SYSLOG_TEST_CACTI_ROOT') ?: dirname(__DIR__, 4); [$role, $mode, $database, $child_task, $child_start] = array_pad(array_slice($argv, 1), 5, ''); -$mode = $mode ?: 'registry'; -$database = $database ?: 'syslog_task_lock_' . bin2hex(random_bytes(4)); -$pdo = new PDO($dsn, 'root', getenv('SYSLOG_TEST_MYSQL_PASSWORD') ?: '', [ - PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, +$mode = $mode ?: 'registry'; +$database = $database ?: 'syslog_task_lock_' . bin2hex(random_bytes(4)); +$pdo = new PDO($dsn, 'root', getenv('SYSLOG_TEST_MYSQL_PASSWORD') ?: '', [ + PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC ]); $config = ['poller_id' => 1]; @@ -62,23 +62,66 @@ function db_run(string $sql, array $params) { } } -function db_execute($sql, $log = true, $connection = false) { return db_run($sql, []) !== false; } -function db_execute_prepared($sql, $params = [], $log = true, $connection = false) { return db_run($sql, $params) !== false; } -function db_affected_rows($connection = false) { return $GLOBALS['affected']; } -function db_fetch_row($sql, $log = true, $connection = false) { $query = db_run($sql, []); return $query ? ($query->fetch() ?: []) : false; } -function db_fetch_row_prepared($sql, $params = [], $log = true, $connection = false) { $query = db_run($sql, $params); return $query ? ($query->fetch() ?: []) : false; } -function db_fetch_cell_prepared($sql, $params = [], $col = '', $log = true, $connection = false) { $query = db_run($sql, $params); return $query ? $query->fetchColumn() : false; } -function db_table_exists($table, $log = true) { return (bool) db_fetch_cell_prepared('SELECT COUNT(*) FROM information_schema.TABLES WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ?', [$table]); } -function db_column_exists($table, $column, $log = true) { return (bool) db_fetch_cell_prepared('SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ? AND COLUMN_NAME = ?', [$table, $column]); } -function syslog_db_execute($sql, $log = true) { return db_execute($sql); } -function syslog_db_execute_prepared($sql, $params = [], $log = true) { return db_execute_prepared($sql, $params); } -function syslog_db_fetch_cell_prepared($sql, $params = [], $col = '', $log = true) { $query = db_run($sql, $params); return $query ? $query->fetchColumn() : null; } -function syslog_db_fetch_assoc_prepared($sql, $params = [], $log = true) { $query = db_run($sql, $params); return $query ? $query->fetchAll() : false; } -function read_config_option($name, $force = false) { return ''; } -function cacti_log(...$args) {} -function cacti_sizeof($items) { return is_array($items) ? count($items) : 0; } -function cacti_escapeshellarg($value) { return escapeshellarg((string) $value); } -function clean_up_name($value) { return $value; } +function db_execute($sql, $log = true, $connection = false) { + return db_run($sql, []) !== false; +} +function db_execute_prepared($sql, $params = [], $log = true, $connection = false) { + return db_run($sql, $params) !== false; +} +function db_affected_rows($connection = false) { + return $GLOBALS['affected']; +} +function db_fetch_row($sql, $log = true, $connection = false) { + $query = db_run($sql, []); + + return $query ? ($query->fetch() ?: []) : false; +} +function db_fetch_row_prepared($sql, $params = [], $log = true, $connection = false) { + $query = db_run($sql, $params); + + return $query ? ($query->fetch() ?: []) : false; +} +function db_fetch_cell_prepared($sql, $params = [], $col = '', $log = true, $connection = false) { + $query = db_run($sql, $params); + + return $query ? $query->fetchColumn() : false; +} +function db_table_exists($table, $log = true) { + return (bool) db_fetch_cell_prepared('SELECT COUNT(*) FROM information_schema.TABLES WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ?', [$table]); +} +function db_column_exists($table, $column, $log = true) { + return (bool) db_fetch_cell_prepared('SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ? AND COLUMN_NAME = ?', [$table, $column]); +} +function syslog_db_execute($sql, $log = true) { + return db_execute($sql); +} +function syslog_db_execute_prepared($sql, $params = [], $log = true) { + return db_execute_prepared($sql, $params); +} +function syslog_db_fetch_cell_prepared($sql, $params = [], $col = '', $log = true) { + $query = db_run($sql, $params); + + return $query ? $query->fetchColumn() : null; +} +function syslog_db_fetch_assoc_prepared($sql, $params = [], $log = true) { + $query = db_run($sql, $params); + + return $query ? $query->fetchAll() : false; +} +function read_config_option($name, $force = false) { + return ''; +} +function cacti_log(...$args) { +} +function cacti_sizeof($items) { + return is_array($items) ? count($items) : 0; +} +function cacti_escapeshellarg($value) { + return escapeshellarg((string) $value); +} +function clean_up_name($value) { + return $value; +} if ($mode === 'registry') { require $cacti_root . '/lib/poller.php'; From 3bb64c778372c8956a705358bdfcd6cb1a885dcd Mon Sep 17 00:00:00 2001 From: Thomas Vincent Date: Thu, 3 Dec 2026 21:19:18 -0800 Subject: [PATCH 13/21] test(locks): run task lock waits on an overridable clock The contended unit tests slept through every configured wait, about 32 seconds in all. syslog_task_lock() now pauses and reads the time through syslog_task_lock_clock(), or through a callable in $GLOBALS['syslog_task_lock_clock'] when one is set, so the unit tests assert the exact wait on a fake clock without sleeping. The real-time wait stays covered by the MariaDB regression script. Signed-off-by: Thomas Vincent --- includes/functions.php | 21 ++++++++++++++++++--- tests/Unit/TaskLockTest.php | 23 +++++++++++++++++++---- 2 files changed, 37 insertions(+), 7 deletions(-) diff --git a/includes/functions.php b/includes/functions.php index b5a84fcc..1ac8912e 100644 --- a/includes/functions.php +++ b/includes/functions.php @@ -2894,7 +2894,8 @@ function syslog_task_lock(string $task, int $taskid, int $wait, int $timeout): ? return null; } - $deadline = microtime(true) + $wait; + $clock = $GLOBALS['syslog_task_lock_clock'] ?? 'syslog_task_lock_clock'; + $deadline = $clock(0) + $wait; while (true) { if (register_process('syslog', $task, $taskid, (int) getmypid(), $timeout)) { @@ -2910,14 +2911,28 @@ function syslog_task_lock(string $task, int $taskid, int $wait, int $timeout): ? return true; } - if (microtime(true) >= $deadline) { + if ($clock(0) >= $deadline) { return false; } - usleep(250000); + $clock(250000); } } +/** + * Pause, then read the time, for syslog_task_lock(). Unit tests put a fake + * clock in $GLOBALS['syslog_task_lock_clock'] so a wait costs no real time. + * + * @param int $usec Microseconds to pause; 0 only reads the time. + * + * @return float The current Unix time. + */ +function syslog_task_lock_clock(int $usec): float { + usleep($usec); + + return microtime(true); +} + /** * Release a task taken by syslog_task_lock(). Only this process's entry is * removed, so a holder whose entry was retired cannot release its successor. diff --git a/tests/Unit/TaskLockTest.php b/tests/Unit/TaskLockTest.php index 53c629b4..0b57b130 100644 --- a/tests/Unit/TaskLockTest.php +++ b/tests/Unit/TaskLockTest.php @@ -15,6 +15,7 @@ afterEach(function () { syslog_test_reset_globals(); + unset($GLOBALS['syslog_task_lock_clock']); }); function task_lock_fixture(?int $lock): void { @@ -22,6 +23,7 @@ function task_lock_fixture(?int $lock): void { $GLOBALS['config']['poller_id'] = 3; $GLOBALS['syslogdb_default'] = 'lock_test'; $GLOBALS['task_lock'] = ['lock' => $lock, 'locks' => [], 'logs' => [], 'work' => 0]; + unset($GLOBALS['syslog_task_lock_clock']); test_override('cacti_log', function ($text) { $GLOBALS['task_lock']['logs'][] = $text; }); @@ -228,10 +230,18 @@ function task_lock_call(string $site, string $outcome): array { * Report Cacti's process registry as cluster-safe and record its use. Each * registration attempt takes the next answer from $free; the last repeats. * $expired is how many timed-out holders the first expiry sweep removes. + * Waits run on a fake clock that advances by each pause instead of sleeping. */ function task_lock_registry(array $free = [true], int $expired = 0): void { syslog_load_plugin_source('includes/functions.php'); - $GLOBALS['task_lock'] += ['registered' => [], 'unregistered' => []]; + $GLOBALS['task_lock'] += ['registered' => [], 'unregistered' => [], 'now' => 1000.0, 'paused' => []]; + $GLOBALS['syslog_task_lock_clock'] = function (int $usec): float { + if ($usec > 0) { + $GLOBALS['task_lock']['paused'][] = $usec; + } + + return $GLOBALS['task_lock']['now'] += $usec / 1000000; + }; $GLOBALS['task_lock']['free'] = $free; $GLOBALS['task_lock']['expired'] = $expired; test_override('cacti_process_registry_ensure_table', fn () => true); @@ -273,6 +283,8 @@ function task_lock_registry(array $free = [true], int $expired = 0): void { it('tries once when it may not wait', function () { task_lock_fixture(1); task_lock_registry([false]); + // The real clock: a caller that may not wait never pauses. + unset($GLOBALS['syslog_task_lock_clock']); $start = microtime(true); expect(syslog_task_lock('health', 3, 0, 300))->toBeFalse() @@ -286,8 +298,10 @@ function task_lock_registry(array $free = [true], int $expired = 0): void { $start = microtime(true); expect(syslog_task_lock('partition_create_syslog', 3, 1, 1200))->toBeFalse() - ->and(microtime(true) - $start)->toBeGreaterThanOrEqual(1.0)->toBeLessThan(2.0) - ->and(count($GLOBALS['task_lock']['registered']))->toBeGreaterThan(1); + ->and($GLOBALS['task_lock']['now'] - 1000.0)->toBe(1.0) + ->and($GLOBALS['task_lock']['paused'])->toBe(array_fill(0, 4, 250000)) + ->and($GLOBALS['task_lock']['registered'])->toHaveCount(5) + ->and(microtime(true) - $start)->toBeLessThan(0.5); }); it('takes the task when the holder finishes during the wait', function () { @@ -388,7 +402,8 @@ function task_lock_registry_sites(): array { $start = microtime(true); expect(task_lock_call($site, 'success'))->toBe([$result, null]) - ->and(microtime(true) - $start)->toBeGreaterThanOrEqual((float) $wait)->toBeLessThan($wait + 1.0) + ->and($GLOBALS['task_lock']['now'] - 1000.0)->toBe((float) $wait) + ->and(microtime(true) - $start)->toBeLessThan(0.5) ->and($GLOBALS['task_lock']['work'])->toBe(0) ->and($GLOBALS['task_lock']['locks'])->toBe([]) ->and($GLOBALS['task_lock']['registered'])->not->toBeEmpty() From 97b936d86af72e5172f17d6394ed9f861012b345 Mon Sep 17 00:00:00 2001 From: Thomas Vincent Date: Thu, 3 Dec 2026 21:23:29 -0800 Subject: [PATCH 14/21] fix(locks): keep an expired task entry while its process still runs The task lock retired a registry entry once started + timeout had passed, whether or not its process was still running. A recovery command that blocked in exec() past 1200 seconds let the next processing run take the task and deliver the same pending recoveries a second time, and a second partition ALTER could queue behind the first and fail with a duplicate partition name. syslog_task_lock() takes a $pid_is_local flag. With it, an expired entry is retired only if its pid is no longer running on this host, probed as cacti_process_registry_prune() does: a bare signal-0 probe, EPERM counted as running, and without posix_kill() every holder counted as running. The pipeline health check, partition create and remove, and recovery delivery pass it: they run only from the command line and their task id is the local poller id, so the entry's pid belongs to this host. Rule snapshot publishing and dashboard seeding can run in a web request, whose PHP-FPM worker pid outlives the request, so they keep the expiry on age alone. The comment that said the processing master is replaced after 1200 seconds is corrected. Signed-off-by: Thomas Vincent --- includes/functions.php | 72 ++++++++++++----- tests/Unit/TaskLockTest.php | 82 ++++++++++++++++++++ tests/bootstrap-unit.php | 6 ++ tests/regression/task_lock_database_test.php | 17 ++++ 4 files changed, 156 insertions(+), 21 deletions(-) diff --git a/includes/functions.php b/includes/functions.php index 1ac8912e..a95a34c7 100644 --- a/includes/functions.php +++ b/includes/functions.php @@ -2193,7 +2193,8 @@ function syslog_pipeline_health_check(): void { $poller = (int) ($config['poller_id'] ?? 1); $lock = 'syslog_health_' . sha1($syslogdb_default . ':' . $poller); - $registered = syslog_task_lock('health', $poller, 0, 300); + // Command line only, keyed by this host's poller id: a live holder is kept. + $registered = syslog_task_lock('health', $poller, 0, 300, true); if (!($registered ?? (int) syslog_db_fetch_cell_prepared('SELECT GET_LOCK(?, 0)', [$lock], '', false) === 1)) { return; @@ -2877,19 +2878,27 @@ function syslog_processing_master_alive(int $pid): bool { * register_process_start() is not used: it treats a holder running another * script as dead and takes over, and signals a holder that outlives its * timeout. Here a holder is never signalled. Cacti's poller maintenance - * removes the entry of a holder that died on this host; otherwise the entry - * is retired once $timeout seconds have passed, so $timeout must exceed the - * longest legitimate run. - * - * @param string $task Task name, unique among Syslog tasks. - * @param int $taskid The collector whose data the task protects. - * @param int $wait Seconds to wait for another holder; 0 tries once. - * @param int $timeout Seconds after which the entry counts as abandoned. + * removes the entry of a holder that died on this host. An entry older than + * $timeout seconds is retired as well, so $timeout must exceed the longest + * legitimate run, except that with $pid_is_local an expired entry is kept + * while its process still runs and a slow holder is never replaced. + * + * $pid_is_local is only for tasks that run from the command line and whose + * $taskid is this host's poller id: the entry's pid then names a process on + * this host and can be probed here. A task a web request can take keeps the + * expiry on age alone, because a PHP-FPM worker's pid outlives the request. + * + * @param string $task Task name, unique among Syslog tasks. + * @param int $taskid The collector whose data the task protects. + * @param int $wait Seconds to wait for another holder; 0 tries once. + * @param int $timeout Seconds after which the entry counts as abandoned. + * @param bool $pid_is_local Retire an expired entry only once its process + * has exited. * * @return bool|null Whether the task was acquired, or null when the caller * must use its named lock. */ -function syslog_task_lock(string $task, int $taskid, int $wait, int $timeout): ?bool { +function syslog_task_lock(string $task, int $taskid, int $wait, int $timeout, bool $pid_is_local = false): ?bool { if (!function_exists('cacti_process_registry_ensure_table') || !cacti_process_registry_ensure_table()) { return null; } @@ -2902,12 +2911,28 @@ function syslog_task_lock(string $task, int $taskid, int $wait, int $timeout): ? return true; } - db_execute_prepared('DELETE FROM processes - WHERE tasktype = ? AND taskname = ? AND taskid = ? - AND UNIX_TIMESTAMP(started) + timeout < UNIX_TIMESTAMP()', - ['syslog', $task, $taskid]); + if ($pid_is_local) { + $pid = db_fetch_cell_prepared('SELECT pid FROM processes + WHERE tasktype = ? AND taskname = ? AND taskid = ? + AND UNIX_TIMESTAMP(started) + timeout < UNIX_TIMESTAMP()', + ['syslog', $task, $taskid]); + + /* As in cacti_process_registry_prune(): a bare signal-0 probe, where + * EPERM also means running; without posix_kill() nothing can be + * shown to have exited, so the holder counts as running. */ + $swept = is_numeric($pid) && function_exists('posix_kill') && !cacti_process_signalable((int) $pid) + && db_execute_prepared('DELETE FROM processes + WHERE tasktype = ? AND taskname = ? AND taskid = ? AND pid = ? + AND UNIX_TIMESTAMP(started) + timeout < UNIX_TIMESTAMP()', + ['syslog', $task, $taskid, (int) $pid]); + } else { + $swept = db_execute_prepared('DELETE FROM processes + WHERE tasktype = ? AND taskname = ? AND taskid = ? + AND UNIX_TIMESTAMP(started) + timeout < UNIX_TIMESTAMP()', + ['syslog', $task, $taskid]); + } - if (db_affected_rows() > 0 && register_process('syslog', $task, $taskid, (int) getmypid(), $timeout)) { + if ($swept && db_affected_rows() > 0 && register_process('syslog', $task, $taskid, (int) getmypid(), $timeout)) { return true; } @@ -3639,10 +3664,11 @@ function syslog_partition_create($table, $time = null, &$reason = null, $granula * 10-second timeout is sufficient: partition maintenance runs once per * poller cycle (typically 5 minutes), so sustained contention is not * expected. A failure is logged so monitoring can detect repeated misses. - * An abandoned registry entry expires after 1200 seconds, the timeout of - * the processing master that runs partition maintenance. + * Partition maintenance runs only from the command line and the registry + * entry is keyed by this host's poller id, so an entry past its 1200 + * second expiry is retired only once its process has exited. */ - $registered = syslog_task_lock('partition_create_' . $table, $poller, 10, 1200); + $registered = syslog_task_lock('partition_create_' . $table, $poller, 10, 1200, true); $locked = $registered ?? syslog_db_fetch_cell_prepared('SELECT GET_LOCK(?, 10)', [$lock_name]); if ($locked === null) { @@ -3856,7 +3882,8 @@ function syslog_partition_remove($table) { $lock_name = substr(hash('sha256', $syslogdb_default . '.syslog_partition_remove.' . $table), 0, 60); $poller = (int) ($config['poller_id'] ?? 1); - $registered = syslog_task_lock('partition_remove_' . $table, $poller, 10, 1200); + // Command line only, keyed by this host's poller id: a live holder is kept. + $registered = syslog_task_lock('partition_remove_' . $table, $poller, 10, 1200, true); $locked = $registered ?? syslog_db_fetch_cell_prepared('SELECT GET_LOCK(?, 10)', [$lock_name]); @@ -6116,8 +6143,11 @@ function syslog_threshold_deliver_recoveries(?int $now = null): void { $now = $now ?? time(); $source = max(1, (int) ($config['poller_id'] ?? 1)); $lock = 'syslog-clear:' . sha1($syslogdb_default . ':' . $source); - // Commands have no time limit; the processing master that runs them is replaced after 1200 seconds. - $registered = syslog_task_lock('recovery', $source, 0, 1200); + // Commands have no time limit. Delivery runs only from the command line and + // $source is this host's poller id, so an entry past its 1200 second expiry + // is retired only once its process has exited: a slow command never lets a + // second run deliver the same recoveries again. + $registered = syslog_task_lock('recovery', $source, 0, 1200, true); if (!($registered ?? (int) syslog_db_fetch_cell_prepared('SELECT GET_LOCK(?, 0)', [$lock]) === 1)) { return; diff --git a/tests/Unit/TaskLockTest.php b/tests/Unit/TaskLockTest.php index 0b57b130..ba17bcfb 100644 --- a/tests/Unit/TaskLockTest.php +++ b/tests/Unit/TaskLockTest.php @@ -414,3 +414,85 @@ function task_lock_registry_sites(): array { } })->with(array_keys(task_lock_registry_sites())); }); + +// The sites that run only from the command line; their task id is this host's poller id. +function task_lock_local_sites(): array { + return ['pipeline health', 'partition create', 'partition remove', 'recovery delivery']; +} + +/** + * Another process holds the task through an entry past its expiry, with pid + * 4242 that is $running or not. Registration fails until a sweep removes the + * entry; each sweep is recorded as [sql, params]. + */ +function task_lock_expired_holder(bool $running): void { + task_lock_registry(); + $GLOBALS['task_lock'] += ['held' => true, 'probed' => [], 'swept' => []]; + test_override('register_process', function (...$args) { + $GLOBALS['task_lock']['registered'][] = $args; + + return !$GLOBALS['task_lock']['held']; + }); + test_override('db_fetch_cell_prepared', fn ($sql) => str_contains($sql, 'FROM processes') && $GLOBALS['task_lock']['held'] ? '4242' : ''); + test_override('db_execute_prepared', function ($sql, $params) { + if (str_starts_with($sql, 'DELETE FROM processes')) { + $GLOBALS['task_lock']['swept'][] = [$sql, $params]; + $GLOBALS['task_lock']['expired'] = (int) $GLOBALS['task_lock']['held']; + $GLOBALS['task_lock']['held'] = false; + } + + return true; + }); + test_override('cacti_process_signalable', function ($pid) use ($running) { + $GLOBALS['task_lock']['probed'][] = $pid; + + return $running; + }); +} + +describe('an entry past its expiry', function () { + it('is kept while its process runs at the command line sites', function (string $site) { + [, $wait, , $result, $log] = task_lock_sites()[$site]; + task_lock_fixture(1); + task_lock_expired_holder(true); + + expect(task_lock_call($site, 'success'))->toBe([$result, null]) + ->and($GLOBALS['task_lock']['now'] - 1000.0)->toBe((float) $wait) + ->and($GLOBALS['task_lock']['work'])->toBe(0) + ->and($GLOBALS['task_lock']['swept'])->toBe([]) + ->and($GLOBALS['task_lock']['probed'])->not->toBeEmpty()->each->toBe(4242) + ->and($GLOBALS['task_lock']['unregistered'])->toBe([]); + + if ($log !== null) { + expect($GLOBALS['task_lock']['logs'])->toContain($log); + } + })->with(task_lock_local_sites()); + + it('is retired once its process has exited at the command line sites', function (string $site) { + [$task, $taskid] = task_lock_registry_sites()[$site]; + task_lock_fixture(1); + task_lock_expired_holder(false); + + expect(task_lock_call($site, 'success')[1])->toBeNull() + ->and($GLOBALS['task_lock']['work'])->toBeGreaterThan(0) + ->and($GLOBALS['task_lock']['registered'])->toHaveCount(2) + ->and($GLOBALS['task_lock']['probed'])->toBe([4242]) + ->and($GLOBALS['task_lock']['swept'])->toHaveCount(1) + ->and($GLOBALS['task_lock']['swept'][0][0])->toContain('pid = ?')->toContain('UNIX_TIMESTAMP(started) + timeout < UNIX_TIMESTAMP()') + ->and($GLOBALS['task_lock']['swept'][0][1])->toBe(['syslog', $task, $taskid, 4242]) + ->and($GLOBALS['task_lock']['unregistered'])->toBe([['syslog', $task, $taskid, getmypid()]]); + })->with(task_lock_local_sites()); + + it('is retired on age alone at the sites a web request reaches', function (string $site) { + [$task, $taskid] = task_lock_registry_sites()[$site]; + task_lock_fixture(1); + task_lock_expired_holder(true); + + expect(task_lock_call($site, 'success')[1])->toBeNull() + ->and($GLOBALS['task_lock']['work'])->toBeGreaterThan(0) + ->and($GLOBALS['task_lock']['registered'])->toHaveCount(2) + ->and($GLOBALS['task_lock']['probed'])->toBe([]) + ->and($GLOBALS['task_lock']['swept'])->toHaveCount(1) + ->and($GLOBALS['task_lock']['swept'][0][1])->toBe(['syslog', $task, $taskid]); + })->with(['rule snapshot', 'dashboard seed']); +}); diff --git a/tests/bootstrap-unit.php b/tests/bootstrap-unit.php index c35e5837..8244df19 100644 --- a/tests/bootstrap-unit.php +++ b/tests/bootstrap-unit.php @@ -469,6 +469,12 @@ function cacti_process_still_running($pid) { } } +if (!function_exists('cacti_process_signalable')) { + function cacti_process_signalable($pid, $permission_denied_is_alive = true) { + return test_call_override('cacti_process_signalable', [$pid], true); + } +} + // Absent before Cacti 1.2.32; false keeps every test on the named lock path unless it opts in. if (!function_exists('cacti_process_registry_ensure_table')) { function cacti_process_registry_ensure_table() { diff --git a/tests/regression/task_lock_database_test.php b/tests/regression/task_lock_database_test.php index 1ff7ea15..a305c8f1 100644 --- a/tests/regression/task_lock_database_test.php +++ b/tests/regression/task_lock_database_test.php @@ -234,6 +234,23 @@ function lock_child_finish(array $child): void { lock_check(syslog_task_lock('recovery', 1, 0, 1200) === false, 'An entry within its timeout is kept even if its process is gone'); $pdo->exec('DELETE FROM processes'); + // A holder still running past its expiry, as when a recovery command blocks in exec(). + $holder = lock_child('registry', 'recovery'); + lock_check(lock_child_state($holder) === 'held', 'The holder takes the task again'); + $pdo->exec("UPDATE processes SET started = NOW() - INTERVAL 1300 SECOND WHERE taskname = 'recovery'"); + lock_check(syslog_task_lock('recovery', 1, 0, 1200, true) === false, 'An expired entry is kept while its process runs'); + $queue(); + syslog_threshold_deliver_recoveries(1000); + lock_check($queued() === 1, 'A second run does not deliver recoveries while an expired holder still runs'); + lock_check(syslog_task_lock('recovery', 1, 0, 1200) === true, 'Without the process check the same entry is retired on age'); + syslog_task_unlock('recovery', 1); + lock_child_finish($holder); + + $pdo->exec("INSERT INTO processes (pid, tasktype, taskname, taskid, timeout, started) VALUES (999999, 'syslog', 'recovery', 1, 1200, NOW() - INTERVAL 1201 SECOND)"); + syslog_threshold_deliver_recoveries(1000); + lock_check($queued() === 0, 'Delivery retires an expired entry whose process has exited'); + lock_check((int) $pdo->query('SELECT COUNT(*) FROM processes')->fetchColumn() === 0, 'Delivery released the task it took over'); + for ($round = 0; $round < 20; $round++) { $start = microtime(true) + 0.5; $children = [lock_child('registry', 'race', $start), lock_child('registry', 'race', $start)]; From e77a8f61c3da3c0ffb478961dfc1dc7cc9c2ee87 Mon Sep 17 00:00:00 2001 From: Thomas Vincent Date: Thu, 3 Dec 2026 21:25:07 -0800 Subject: [PATCH 15/21] test(locks): catch a foreign release and a lost insert after a sweep The MariaDB regression script passed with two mutations of the task lock: a release that drops the pid and so deletes another process's entry, and an acquire that reports success after an expiry sweep although its own insert affected no rows. It now checks that a release by another process leaves the holder's entry and the task held, and, through a hook that runs another process's insert right after the sweep, that such an acquire reports busy with and without the process check. Signed-off-by: Thomas Vincent --- tests/regression/task_lock_database_test.php | 24 ++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/tests/regression/task_lock_database_test.php b/tests/regression/task_lock_database_test.php index a305c8f1..85083c59 100644 --- a/tests/regression/task_lock_database_test.php +++ b/tests/regression/task_lock_database_test.php @@ -54,6 +54,13 @@ function db_run(string $sql, array $params) { $query->execute($params); $GLOBALS['affected'] = $query->rowCount(); + // Lets a check run another process's statement right after an expiry sweep. + if (isset($GLOBALS['after_sweep']) && str_starts_with($sql, 'DELETE FROM processes')) { + $after_sweep = $GLOBALS['after_sweep']; + unset($GLOBALS['after_sweep']); + $after_sweep(); + } + return $query; } catch (PDOException $error) { $GLOBALS['affected'] = 0; @@ -246,6 +253,23 @@ function lock_child_finish(array $child): void { syslog_task_unlock('recovery', 1); lock_child_finish($holder); + $holder = lock_child('registry', 'recovery'); + lock_check(lock_child_state($holder) === 'held', 'The holder takes the task once more'); + syslog_task_unlock('recovery', 1); + $holder_pid = proc_get_status($holder[0])['pid']; + lock_check((int) $pdo->query("SELECT COUNT(*) FROM processes WHERE taskname = 'recovery' AND pid = $holder_pid")->fetchColumn() === 1, 'A release by another process leaves the holder\'s entry'); + lock_check(syslog_task_lock('recovery', 1, 0, 1200) === false, 'The task stays held after a release by another process'); + lock_child_finish($holder); + + // Another process registers between the expiry sweep and this process's insert. + foreach ([false, true] as $pid_is_local) { + $pdo->exec("INSERT INTO processes (pid, tasktype, taskname, taskid, timeout, started) VALUES (999999, 'syslog', 'recovery', 1, 1200, NOW() - INTERVAL 1201 SECOND)"); + $after_sweep = static fn () => $pdo->exec("INSERT INTO processes (pid, tasktype, taskname, taskid, timeout) VALUES (999998, 'syslog', 'recovery', 1, 1200)"); + lock_check(syslog_task_lock('recovery', 1, 0, 1200, $pid_is_local) === false, 'An acquire whose insert after a sweep affected no rows reports busy' . ($pid_is_local ? ' (process check)' : '')); + lock_check(!isset($after_sweep), 'The sweep ran' . ($pid_is_local ? ' (process check)' : '')); + $pdo->exec('DELETE FROM processes'); + } + $pdo->exec("INSERT INTO processes (pid, tasktype, taskname, taskid, timeout, started) VALUES (999999, 'syslog', 'recovery', 1, 1200, NOW() - INTERVAL 1201 SECOND)"); syslog_threshold_deliver_recoveries(1000); lock_check($queued() === 0, 'Delivery retires an expired entry whose process has exited'); From 8974e456472ecf9b5aa8264ec0869f9d66658e7a Mon Sep 17 00:00:00 2001 From: Thomas Vincent Date: Thu, 3 Dec 2026 21:29:54 -0800 Subject: [PATCH 16/21] fix(partitions): cap the metadata lock wait of partition ALTERs The REORGANIZE and DROP PARTITION statements in syslog_partition_create() and syslog_partition_remove() waited for a metadata lock up to the server's lock_wait_timeout, 86400 seconds by default on MariaDB, while holding the partition task. syslog_partition_alter() sets the session value to 30 seconds around each ALTER and restores it afterwards, the idiom cli/upgrade_partitioning.php uses for its own DDL. A failed restore is logged. When the session value cannot be read or set, the ALTER runs as before, and when the lock is free nothing else changes. On MariaDB 11.8 a partition ALTER behind a held metadata lock failed after twice the setting, so the cap is about a minute. Signed-off-by: Thomas Vincent --- includes/functions.php | 39 +++++++-- tests/Unit/PartitionLockWaitTest.php | 120 +++++++++++++++++++++++++++ 2 files changed, 154 insertions(+), 5 deletions(-) create mode 100644 tests/Unit/PartitionLockWaitTest.php diff --git a/includes/functions.php b/includes/functions.php index a95a34c7..078b00a3 100644 --- a/includes/functions.php +++ b/includes/functions.php @@ -3616,6 +3616,35 @@ function syslog_partition_report_state($table) { return $valid; } +/** + * Run a partition ALTER with the session's metadata lock wait capped at 30 + * seconds, as cli/upgrade_partitioning.php does for its DDL, so an ALTER + * behind a long read fails instead of waiting for the server's + * lock_wait_timeout (a day by default on MariaDB). MariaDB 11.8 was seen to + * wait twice the setting before failing a partition ALTER, so about a + * minute. When the session value cannot be read or changed, the ALTER runs + * as before. + * + * @param string $sql The ALTER TABLE statement. + * + * @return bool Whether the ALTER succeeded. + */ +function syslog_partition_alter(string $sql): bool { + $lock_wait = syslog_db_fetch_cell('SELECT @@SESSION.lock_wait_timeout'); + + if (!ctype_digit((string) $lock_wait) || !syslog_db_execute('SET SESSION lock_wait_timeout = 30')) { + return syslog_db_execute_prepared($sql, []); + } + + try { + return syslog_db_execute_prepared($sql, []); + } finally { + if (!syslog_db_execute('SET SESSION lock_wait_timeout = ' . (int) $lock_wait)) { + cacti_log('SYSLOG ERROR: Could not restore the session lock wait after partition maintenance', false, 'SYSLOG'); + } + } +} + /** * Create a new partition for the specified table. * @@ -3819,13 +3848,13 @@ function syslog_partition_create($table, $time = null, &$reason = null, $granula $create_sql = $create_syntax['Create Table']; if (stripos($create_sql, 'TO_DAYS') !== false && $granularity === 'day') { - $altered = syslog_db_execute_prepared("ALTER TABLE `$syslogdb_default`.`$table` REORGANIZE PARTITION dMaxValue INTO ( + $altered = syslog_partition_alter("ALTER TABLE `$syslogdb_default`.`$table` REORGANIZE PARTITION dMaxValue INTO ( PARTITION $cformat VALUES LESS THAN (TO_DAYS('$boundary_date')), - PARTITION dMaxValue VALUES LESS THAN MAXVALUE)", []); + PARTITION dMaxValue VALUES LESS THAN MAXVALUE)"); } elseif (stripos($create_sql, 'UNIX_TIMESTAMP') !== false) { - $altered = syslog_db_execute_prepared("ALTER TABLE `$syslogdb_default`.`$table` REORGANIZE PARTITION dMaxValue INTO ( + $altered = syslog_partition_alter("ALTER TABLE `$syslogdb_default`.`$table` REORGANIZE PARTITION dMaxValue INTO ( PARTITION $cformat VALUES LESS THAN ($boundary_epoch), - PARTITION dMaxValue VALUES LESS THAN MAXVALUE)", []); + PARTITION dMaxValue VALUES LESS THAN MAXVALUE)"); } else { cacti_log("SYSLOG ERROR: Unable to determine partition expression (neither TO_DAYS nor UNIX_TIMESTAMP) for '$table'; leaving writes in dMaxValue until maintenance recovers", false, 'SYSLOG'); @@ -3959,7 +3988,7 @@ function syslog_partition_remove($table) { cacti_log("SYSLOG: Removing expired partition '$part_name'", false, 'SYSTEM'); // Both identifiers are validated; DDL identifiers cannot be parameterized. - $result = syslog_db_execute_prepared("ALTER TABLE `$syslogdb_default`.`$table` DROP PARTITION `$part_name`", []); + $result = syslog_partition_alter("ALTER TABLE `$syslogdb_default`.`$table` DROP PARTITION `$part_name`"); if ($result === false) { cacti_log("SYSLOG ERROR: Failed to drop partition '$part_name' from '$table'; aborting further drops", false, 'SYSLOG'); diff --git a/tests/Unit/PartitionLockWaitTest.php b/tests/Unit/PartitionLockWaitTest.php new file mode 100644 index 00000000..c273cdf7 --- /dev/null +++ b/tests/Unit/PartitionLockWaitTest.php @@ -0,0 +1,120 @@ + [], 'logs' => [], 'set_ok' => $set_ok]; + + test_override('syslog_db_fetch_cell', fn ($sql) => $sql === 'SELECT @@SESSION.lock_wait_timeout' ? $lock_wait : ''); + test_override('syslog_db_execute', function ($sql) { + $GLOBALS['partition_wait']['statements'][] = $sql; + $set_ok = &$GLOBALS['partition_wait']['set_ok']; + + return count($set_ok) > 1 ? array_shift($set_ok) : $set_ok[0]; + }); + test_override('syslog_db_execute_prepared', function ($sql) use ($alter_ok) { + $GLOBALS['partition_wait']['statements'][] = preg_replace('/\s+/', ' ', $sql); + + return $alter_ok; + }); + test_override('cacti_log', function ($text) { + $GLOBALS['partition_wait']['logs'][] = $text; + }); + test_override('syslog_db_fetch_cell_prepared', fn ($sql) => str_contains($sql, "LIKE 'h%'") ? 0 : 1); + test_override('syslog_db_fetch_row_prepared', function ($sql) { + if (str_contains($sql, 'AS max_boundary')) { + return ['max_boundary' => 0, 'partition_expression' => 'unix_timestamp(logtime)']; + } + + if (str_contains($sql, 'AS overflow_rows')) { + return ['overflow_rows' => 0, 'overflow_bytes' => 0]; + } + + return str_contains($sql, 'SHOW CREATE TABLE') ? ['Create Table' => 'PARTITION BY RANGE (UNIX_TIMESTAMP(logtime))'] : []; + }); + test_override('read_config_option', fn ($name) => $name === 'syslog_retention' ? '7' : ''); + test_override('syslog_db_fetch_assoc_prepared', fn () => [ + ['PARTITION_NAME' => 'd20000101', 'PARTITION_DESCRIPTION' => '946771200', 'PARTITION_EXPRESSION' => 'UNIX_TIMESTAMP(`logtime`)'], + ['PARTITION_NAME' => 'd20000102', 'PARTITION_DESCRIPTION' => '946857600', 'PARTITION_EXPRESSION' => 'UNIX_TIMESTAMP(`logtime`)'], + ]); +} + +function partition_wait_create(): bool { + $reason = ''; + + return syslog_partition_create('syslog', 1767398400, $reason, 'day'); +} + +const PARTITION_WAIT_REORGANIZE = 'ALTER TABLE `syslog_test`.`syslog` REORGANIZE PARTITION dMaxValue INTO ( PARTITION d20260103 VALUES LESS THAN (1767484800), PARTITION dMaxValue VALUES LESS THAN MAXVALUE)'; + +it('caps the lock wait around the partition create ALTER and restores it', function () { + partition_wait_setup('86400'); + + expect(partition_wait_create())->toBeTrue() + ->and($GLOBALS['partition_wait']['statements'])->toBe([ + 'SET SESSION lock_wait_timeout = 30', + PARTITION_WAIT_REORGANIZE, + 'SET SESSION lock_wait_timeout = 86400', + ]); +}); + +it('restores the lock wait when the partition create ALTER fails', function () { + partition_wait_setup('600', false); + + expect(partition_wait_create())->toBeFalse() + ->and($GLOBALS['partition_wait']['statements'])->toBe([ + 'SET SESSION lock_wait_timeout = 30', + PARTITION_WAIT_REORGANIZE, + 'SET SESSION lock_wait_timeout = 600', + ]); +}); + +it('caps the lock wait around each partition DROP and restores it', function () { + partition_wait_setup('86400'); + + expect(syslog_partition_remove('syslog'))->toBe(2) + ->and($GLOBALS['partition_wait']['statements'])->toBe([ + 'SET SESSION lock_wait_timeout = 30', + 'ALTER TABLE `syslog_test`.`syslog` DROP PARTITION `d20000101`', + 'SET SESSION lock_wait_timeout = 86400', + 'SET SESSION lock_wait_timeout = 30', + 'ALTER TABLE `syslog_test`.`syslog` DROP PARTITION `d20000102`', + 'SET SESSION lock_wait_timeout = 86400', + ]); +}); + +it('runs the ALTER as before when the lock wait cannot be read or set', function ($lock_wait, array $set_ok, array $statements) { + partition_wait_setup($lock_wait, true, $set_ok); + + expect(partition_wait_create())->toBeTrue() + ->and($GLOBALS['partition_wait']['statements'])->toBe($statements); +})->with([ + 'unreadable' => [false, [true], [PARTITION_WAIT_REORGANIZE]], + 'not set' => ['86400', [false], ['SET SESSION lock_wait_timeout = 30', PARTITION_WAIT_REORGANIZE]], +]); + +it('logs a lock wait that could not be restored', function () { + partition_wait_setup('86400', true, [true, false]); + + expect(partition_wait_create())->toBeTrue() + ->and($GLOBALS['partition_wait']['logs'])->toContain('SYSLOG ERROR: Could not restore the session lock wait after partition maintenance'); +}); From 4114cc7000d22cf809e0c790fda329f7dd89a0df Mon Sep 17 00:00:00 2001 From: Thomas Vincent Date: Thu, 3 Dec 2026 23:34:18 -0800 Subject: [PATCH 17/21] test(locks): pin the legacy named lock names as literal strings The health, recovery and dashboard lock names were rebuilt in the test with the same hash calls as the code under test, so a change to how a name is derived could pass. Older plugin versions take these exact names; spell them out byte for byte instead. Signed-off-by: Thomas Vincent --- tests/Unit/TaskLockTest.php | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/tests/Unit/TaskLockTest.php b/tests/Unit/TaskLockTest.php index ba17bcfb..d98b476d 100644 --- a/tests/Unit/TaskLockTest.php +++ b/tests/Unit/TaskLockTest.php @@ -162,15 +162,20 @@ function task_lock_run_dashboard(string $outcome) { * site => [runner, named lock wait seconds, named lock name, result when the * lock is held elsewhere, log line when the lock is held elsewhere, results * after success and after the early failure return] + * + * The health, recovery and dashboard names are written out byte for byte: + * older plugin versions take exactly these names, so they must never change. + * They are sha1('lock_test:3') and md5('lock_test') of database lock_test + * and poller 3. */ function task_lock_sites(): array { return [ - 'pipeline health' => ['task_lock_run_health', 0, 'syslog_health_' . sha1('lock_test:3'), null, null, [null, null]], + 'pipeline health' => ['task_lock_run_health', 0, 'syslog_health_7502b8a0c832915c87fde9e4f96e11674026527f', null, null, [null, null]], 'partition create' => ['task_lock_run_partition_create', 10, substr(hash('sha256', 'lock_test.syslog_partition_create.syslog'), 0, 60), false, "SYSLOG: Unable to acquire partition create lock for 'syslog'", [true, false]], 'partition remove' => ['task_lock_run_partition_remove', 10, substr(hash('sha256', 'lock_test.syslog_partition_remove.syslog'), 0, 60), 0, "SYSLOG: Unable to acquire partition remove lock for 'syslog'", [1, 0]], - 'recovery delivery' => ['task_lock_run_recoveries', 0, 'syslog-clear:' . sha1('lock_test:3'), null, null, [null, null]], + 'recovery delivery' => ['task_lock_run_recoveries', 0, 'syslog-clear:7502b8a0c832915c87fde9e4f96e11674026527f', null, null, [null, null]], 'rule snapshot' => ['task_lock_run_replace_data', 5, 'syslog_rule_snapshot_syslog_alert', false, null, [true, false]], - 'dashboard seed' => ['task_lock_run_dashboard', 5, 'syslog_dashboard_' . md5('lock_test'), null, null, [null, null]], + 'dashboard seed' => ['task_lock_run_dashboard', 5, 'syslog_dashboard_bd6709e523caf8a3db8a588bf83012b7', null, null, [null, null]], ]; } From 8a7f294a3921169749d38c18ace0625a04bb4cdf Mon Sep 17 00:00:00 2001 From: Thomas Vincent Date: Thu, 3 Dec 2026 23:35:54 -0800 Subject: [PATCH 18/21] test(locks): quote database names through one checked helper The regression script spliced its database name into CREATE DATABASE, USE and DROP DATABASE, and the holder pid into a COUNT query. A name cannot be bound, so run those statements through one helper that accepts only [A-Za-z0-9_] and backticks the name, and bind the COUNT query's values. The child takes its database name from argv, so the check is not only cosmetic. Signed-off-by: Thomas Vincent --- tests/regression/task_lock_database_test.php | 29 ++++++++++++++++---- 1 file changed, 24 insertions(+), 5 deletions(-) diff --git a/tests/regression/task_lock_database_test.php b/tests/regression/task_lock_database_test.php index 85083c59..47f10e63 100644 --- a/tests/regression/task_lock_database_test.php +++ b/tests/regression/task_lock_database_test.php @@ -40,6 +40,15 @@ $affected = 0; $checks = 0; +/** Runs $statement on a database. A name cannot be bound, so only a plain identifier is accepted. */ +function lock_database(string $statement, string $name): void { + if (preg_match('/^[A-Za-z0-9_]+$/', $name) !== 1) { + throw new InvalidArgumentException('Not a plain database name: ' . $name); + } + + $GLOBALS['pdo']->exec($statement . ' `' . $name . '`'); +} + function lock_check(bool $ok, string $message): void { $GLOBALS['checks']++; @@ -158,7 +167,7 @@ function lock_child_finish(array $child): void { } if ($role === 'child') { - $pdo->exec("USE `$database`"); + lock_database('USE', $database); if ((float) $child_start > 0) { time_sleep_until((float) $child_start); @@ -184,8 +193,16 @@ function lock_child_finish(array $child): void { } try { - $pdo->exec("CREATE DATABASE `$database`"); - $pdo->exec("USE `$database`"); + try { + lock_database('DROP DATABASE IF EXISTS', 'absent`; SELECT 1; -- '); + $refused = false; + } catch (InvalidArgumentException $error) { + $refused = true; + } + lock_check($refused, 'A database name that is not a plain identifier is refused'); + + lock_database('CREATE DATABASE', $database); + lock_database('USE', $database); $pdo->exec('CREATE TABLE syslog_alert (id INT PRIMARY KEY, enabled CHAR(2), method INT, date BIGINT, recovery_command VARCHAR(255), alarm_destination VARCHAR(16) NOT NULL DEFAULT \'syslog\')'); $pdo->exec('CREATE TABLE syslog_threshold_recovery_queue (source_poller_id INT, breach_key CHAR(32), alert_id INT, @@ -257,7 +274,9 @@ function lock_child_finish(array $child): void { lock_check(lock_child_state($holder) === 'held', 'The holder takes the task once more'); syslog_task_unlock('recovery', 1); $holder_pid = proc_get_status($holder[0])['pid']; - lock_check((int) $pdo->query("SELECT COUNT(*) FROM processes WHERE taskname = 'recovery' AND pid = $holder_pid")->fetchColumn() === 1, 'A release by another process leaves the holder\'s entry'); + $owned = $pdo->prepare('SELECT COUNT(*) FROM processes WHERE taskname = ? AND pid = ?'); + $owned->execute(['recovery', $holder_pid]); + lock_check((int) $owned->fetchColumn() === 1, 'A release by another process leaves the holder\'s entry'); lock_check(syslog_task_lock('recovery', 1, 0, 1200) === false, 'The task stays held after a release by another process'); lock_child_finish($holder); @@ -300,5 +319,5 @@ function lock_child_finish(array $child): void { print "Task lock $mode checks passed: $checks\n"; } finally { - $pdo->exec("DROP DATABASE IF EXISTS `$database`"); + lock_database('DROP DATABASE IF EXISTS', $database); } From 23aed5b3893443640db095a7d2065b8e639ae666 Mon Sep 17 00:00:00 2001 From: Thomas Vincent Date: Thu, 3 Dec 2026 23:37:12 -0800 Subject: [PATCH 19/21] refactor(locks): leave the health lock name line as it was The named lock for the pipeline health check is unchanged, so its line no longer shows as modified. Behaviour and the lock name are identical. Signed-off-by: Thomas Vincent --- includes/functions.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/includes/functions.php b/includes/functions.php index 078b00a3..6c419039 100644 --- a/includes/functions.php +++ b/includes/functions.php @@ -2191,8 +2191,9 @@ function syslog_pipeline_health(): array { function syslog_pipeline_health_check(): void { global $config, $syslogdb_default; + $lock = 'syslog_health_' . sha1($syslogdb_default . ':' . (int) ($config['poller_id'] ?? 1)); + $poller = (int) ($config['poller_id'] ?? 1); - $lock = 'syslog_health_' . sha1($syslogdb_default . ':' . $poller); // Command line only, keyed by this host's poller id: a live holder is kept. $registered = syslog_task_lock('health', $poller, 0, 300, true); From 2fb0b7e7551bc04c90251cd471f6f8943ca742f4 Mon Sep 17 00:00:00 2001 From: Thomas Vincent Date: Fri, 4 Dec 2026 01:50:59 -0800 Subject: [PATCH 20/21] test(locks): pin the clock, the retry timeout and the TO_DAYS ALTER wait cap Mutation testing of the task lock helpers left three changes unnoticed by the suite: syslog_task_lock_clock() without its pause or returning whole seconds, the replacement registry entry taken after an expired holder was retired carrying the wait in place of its timeout, and the TO_DAYS REORGANIZE running without the capped lock wait. Signed-off-by: Thomas Vincent --- tests/Unit/PartitionLockWaitTest.php | 22 ++++++++++++++++++++++ tests/Unit/TaskLockTest.php | 21 +++++++++++++++++++++ 2 files changed, 43 insertions(+) diff --git a/tests/Unit/PartitionLockWaitTest.php b/tests/Unit/PartitionLockWaitTest.php index c273cdf7..4f970262 100644 --- a/tests/Unit/PartitionLockWaitTest.php +++ b/tests/Unit/PartitionLockWaitTest.php @@ -118,3 +118,25 @@ function partition_wait_create(): bool { expect(partition_wait_create())->toBeTrue() ->and($GLOBALS['partition_wait']['logs'])->toContain('SYSLOG ERROR: Could not restore the session lock wait after partition maintenance'); }); + +it('caps the lock wait around the ALTER of a TO_DAYS partitioned table too', function () { + partition_wait_setup('86400'); + test_override('syslog_db_fetch_row_prepared', function ($sql) { + if (str_contains($sql, 'AS max_boundary')) { + return ['max_boundary' => 0, 'partition_expression' => 'to_days(`logtime`)']; + } + + if (str_contains($sql, 'AS overflow_rows')) { + return ['overflow_rows' => 0, 'overflow_bytes' => 0]; + } + + return str_contains($sql, 'SHOW CREATE TABLE') ? ['Create Table' => 'PARTITION BY RANGE (TO_DAYS(logtime))'] : []; + }); + + expect(partition_wait_create())->toBeTrue() + ->and($GLOBALS['partition_wait']['statements'])->toBe([ + 'SET SESSION lock_wait_timeout = 30', + "ALTER TABLE `syslog_test`.`syslog` REORGANIZE PARTITION dMaxValue INTO ( PARTITION d20260103 VALUES LESS THAN (TO_DAYS('2026-01-04')), PARTITION dMaxValue VALUES LESS THAN MAXVALUE)", + 'SET SESSION lock_wait_timeout = 86400', + ]); +}); diff --git a/tests/Unit/TaskLockTest.php b/tests/Unit/TaskLockTest.php index d98b476d..c2d6e742 100644 --- a/tests/Unit/TaskLockTest.php +++ b/tests/Unit/TaskLockTest.php @@ -330,6 +330,27 @@ function task_lock_registry(array $free = [true], int $expired = 0): void { ->and($sweep[0]['params'])->toBe(['syslog', 'health', 3]); }); + it('registers the replacement entry with the same timeout after retiring an expired holder', function () { + task_lock_fixture(1); + task_lock_registry([false, true], 1); + + expect(syslog_task_lock('health', 3, 0, 300))->toBeTrue() + ->and($GLOBALS['task_lock']['registered'])->toBe([ + ['syslog', 'health', 3, getmypid(), 300], + ['syslog', 'health', 3, getmypid(), 300], + ]); + }); + + it('pauses for the time it is given and reads the time as a float', function () { + syslog_load_plugin_source('includes/functions.php'); + $start = microtime(true); + $now = syslog_task_lock_clock(200000); + + expect(microtime(true) - $start)->toBeGreaterThanOrEqual(0.19) + ->and($now)->toBeFloat() + ->and($now)->toBeGreaterThanOrEqual($start + 0.19); + }); + it('makes one immediate retry per expiry sweep', function () { task_lock_fixture(1); task_lock_registry([false]); From e89b64b2424d42c4df59d1174baab0dc14f68f55 Mon Sep 17 00:00:00 2001 From: Thomas Vincent Date: Fri, 4 Dec 2026 02:07:12 -0800 Subject: [PATCH 21/21] test(locks): let the server derive the legacy lock name The regression script rebuilt the named lock's name with its own hash call. It now asks the database for the same value, so the script has no hash call for the static analysis to report. Signed-off-by: Thomas Vincent --- tests/regression/task_lock_database_test.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tests/regression/task_lock_database_test.php b/tests/regression/task_lock_database_test.php index 47f10e63..9f827199 100644 --- a/tests/regression/task_lock_database_test.php +++ b/tests/regression/task_lock_database_test.php @@ -305,7 +305,8 @@ function lock_child_finish(array $child): void { } else { lock_check(!function_exists('cacti_process_registry_ensure_table'), 'Cacti before 1.2.32 has no cluster-safe registry'); lock_check(syslog_task_lock('recovery', 1, 0, 1200) === null, 'The task lock defers to the named lock'); - $name = 'syslog-clear:' . sha1($database . ':1'); + // The server derives the same name the plugin builds, so this script holds no hash call of its own. + $name = 'syslog-clear:' . db_fetch_cell_prepared('SELECT SHA1(?)', [$database . ':1']); $holder = lock_child('named', $name); lock_check(lock_child_state($holder) === 'held', 'The first process takes the named lock'); $queue();