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
diff --git a/includes/functions.php b/includes/functions.php
index e0125746..6c419039 100644
--- a/includes/functions.php
+++ b/includes/functions.php
@@ -2193,7 +2193,11 @@ function syslog_pipeline_health_check(): void {
$lock = 'syslog_health_' . sha1($syslogdb_default . ':' . (int) ($config['poller_id'] ?? 1));
- if ((int) syslog_db_fetch_cell_prepared('SELECT GET_LOCK(?, 0)', [$lock], '', false) !== 1) {
+ $poller = (int) ($config['poller_id'] ?? 1);
+ // 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;
}
@@ -2267,7 +2271,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);
+ }
}
}
@@ -2859,6 +2867,111 @@ 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. 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 $pid_is_local = false): ?bool {
+ if (!function_exists('cacti_process_registry_ensure_table') || !cacti_process_registry_ensure_table()) {
+ return null;
+ }
+
+ $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)) {
+ return true;
+ }
+
+ 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 ($swept && db_affected_rows() > 0 && register_process('syslog', $task, $taskid, (int) getmypid(), $timeout)) {
+ return true;
+ }
+
+ if ($clock(0) >= $deadline) {
+ return false;
+ }
+
+ $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.
+ *
+ * @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.
*
@@ -3504,6 +3617,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.
*
@@ -3515,7 +3657,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 = '';
@@ -3546,13 +3688,18 @@ 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.
+ * 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.
*/
- $locked = syslog_db_fetch_cell_prepared('SELECT GET_LOCK(?, 10)', [$lock_name]);
+ $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) {
// NULL means the GET_LOCK call itself failed, not just contention.
@@ -3702,13 +3849,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');
@@ -3729,7 +3876,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;
@@ -3745,7 +3896,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');
@@ -3759,9 +3910,12 @@ 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);
+ // 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 = 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');
@@ -3835,7 +3989,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');
@@ -3847,7 +4001,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;
@@ -6015,8 +6173,13 @@ 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. 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 ((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;
}
@@ -6053,7 +6216,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/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/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/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/PartitionLockWaitTest.php b/tests/Unit/PartitionLockWaitTest.php
new file mode 100644
index 00000000..4f970262
--- /dev/null
+++ b/tests/Unit/PartitionLockWaitTest.php
@@ -0,0 +1,142 @@
+ [], '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');
+});
+
+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
new file mode 100644
index 00000000..c2d6e742
--- /dev/null
+++ b/tests/Unit/TaskLockTest.php
@@ -0,0 +1,524 @@
+ $lock, 'locks' => [], 'logs' => [], 'work' => 0];
+ unset($GLOBALS['syslog_task_lock_clock']);
+ 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, 7);
+}
+
+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]
+ *
+ * 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_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: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_bd6709e523caf8a3db8a588bf83012b7', 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'"],
+ ]);
+});
+
+/**
+ * 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' => [], '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);
+ 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]);
+ // 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()
+ ->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($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 () {
+ 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('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]);
+ 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();
+
+ syslog_task_unlock('health', 3);
+
+ 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],
+ '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],
+ ];
+}
+
+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('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);
+ task_lock_registry([false]);
+ $start = microtime(true);
+
+ expect(task_lock_call($site, 'success'))->toBe([$result, null])
+ ->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()
+ ->and($GLOBALS['task_lock']['unregistered'])->toBe([]);
+
+ if ($log !== null) {
+ expect($GLOBALS['task_lock']['logs'])->toContain($log);
+ }
+ })->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 a1f2ab00..8244df19 100644
--- a/tests/bootstrap-unit.php
+++ b/tests/bootstrap-unit.php
@@ -469,6 +469,31 @@ 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() {
+ 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);
diff --git a/tests/regression/task_lock_database_test.php b/tests/regression/task_lock_database_test.php
new file mode 100644
index 00000000..9f827199
--- /dev/null
+++ b/tests/regression/task_lock_database_test.php
@@ -0,0 +1,324 @@
+ PDO::ERRMODE_EXCEPTION,
+ PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
+]);
+$config = ['poller_id' => 1];
+$syslogdb_default = $database;
+$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']++;
+
+ 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();
+
+ // 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;
+
+ 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') {
+ lock_database('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 {
+ 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,
+ 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');
+
+ // 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);
+
+ $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'];
+ $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);
+
+ // 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');
+ 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)];
+ $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');
+ // 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();
+ 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 {
+ lock_database('DROP DATABASE IF EXISTS', $database);
+}