Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
b75caac
test(locks): pin the named lock behaviour at the six Syslog lock sites
somethingwithproof Dec 4, 2026
d20502d
feat(locks): add a task lock on Cacti's process registry
somethingwithproof Dec 4, 2026
be226a4
fix(locks): serialize the pipeline health check through the process r…
somethingwithproof Dec 4, 2026
36d8fee
fix(locks): serialize partition creation through the process registry
somethingwithproof Dec 4, 2026
bd536e0
fix(locks): serialize partition removal through the process registry
somethingwithproof Dec 4, 2026
42b4a61
fix(locks): retry once per expiry sweep in the task lock
somethingwithproof Dec 4, 2026
102df1f
fix(locks): serialize recovery delivery through the process registry
somethingwithproof Dec 4, 2026
b2d4ea7
fix(locks): serialize rule snapshot publishing through the process re…
somethingwithproof Dec 4, 2026
189b706
fix(locks): serialize default dashboard seeding through the process r…
somethingwithproof Dec 4, 2026
176ff54
test(locks): contend for a task lock from two processes on MariaDB
somethingwithproof Dec 4, 2026
724b497
docs(changelog): note the process registry locks (#502)
somethingwithproof Dec 4, 2026
8946e52
style(locks): format the task lock tests with Cacti's php-cs-fixer rules
somethingwithproof Dec 4, 2026
3bb64c7
test(locks): run task lock waits on an overridable clock
somethingwithproof Dec 4, 2026
97b936d
fix(locks): keep an expired task entry while its process still runs
somethingwithproof Dec 4, 2026
e77a8f6
test(locks): catch a foreign release and a lost insert after a sweep
somethingwithproof Dec 4, 2026
8974e45
fix(partitions): cap the metadata lock wait of partition ALTERs
somethingwithproof Dec 4, 2026
4114cc7
test(locks): pin the legacy named lock names as literal strings
somethingwithproof Dec 4, 2026
8a7f294
test(locks): quote database names through one checked helper
somethingwithproof Dec 4, 2026
23aed5b
refactor(locks): leave the health lock name line as it was
somethingwithproof Dec 4, 2026
2fb0b7e
test(locks): pin the clock, the retry timeout and the TO_DAYS ALTER w…
somethingwithproof Dec 4, 2026
e89b64b
test(locks): let the server derive the legacy lock name
somethingwithproof Dec 4, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
* issue#480: Split the syslog upgrade notice in `includes/installer.php` into separate balanced `<p>` 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=<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
Expand Down
199 changes: 183 additions & 16 deletions includes/functions.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

Expand Down Expand Up @@ -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);
}
}
}

Expand Down Expand Up @@ -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.
*
Expand Down Expand Up @@ -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.
*
Expand All @@ -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 = '';

Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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');

Expand All @@ -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;
Expand All @@ -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');
Expand All @@ -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');
Expand Down Expand Up @@ -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');
Expand All @@ -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;
Expand Down Expand Up @@ -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;
}

Expand Down Expand Up @@ -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);
}
}
}

Expand Down
20 changes: 14 additions & 6 deletions includes/processing.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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)) {
Expand Down Expand Up @@ -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;
}

Expand Down Expand Up @@ -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);
}
}
}
14 changes: 10 additions & 4 deletions setup.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

Expand Down Expand Up @@ -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);
}
}
}

Expand Down
Loading