Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@
* issue#491: Syslog Status no longer fails with "Undefined constant SYSLOG_COLLECTOR_STALE_SECONDS" (and Cacti no longer disables the plugin) when Collector Staleness Threshold or Collector Backlog Threshold is set to Default; both defaults (300 seconds, 10000 messages) are now defined in `includes/functions.php` before the Status tab is drawn
* issue#484: Mark the syslog search help string in `syslog.php` as `no-php-format` and update `locales/po/cacti.pot` so the literal `%` in `LIKE` syntax is not flagged as a PHP format specifier
* issue#480: Split the syslog upgrade notice in `includes/installer.php` into separate balanced `<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; a worker that finds the processing lock no longer held by its master now records the failure and logs the expected lock owner and the holder `IS_USED_LOCK()` reported
* 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
* feature: Add manually importable recommendation catalogues for Arista, Dell, Fortinet, HPE, Huawei, MikroTik, Nokia, NVIDIA and Palo Alto Networks in docs/<vendor>.json.gz, built from each vendor's public message references
* feature: Recommendations are matched only against the sending device's vendor (and vendor-neutral records) when the syslog host is a Cacti device whose vendor is recognised from its SNMP sysDescr or device template and has records; other hosts match every vendor, except that all-digit identifiers then match only vendor-neutral records

Expand Down
23 changes: 15 additions & 8 deletions cli/upgrade_partitioning.php
Original file line number Diff line number Diff line change
Expand Up @@ -166,26 +166,32 @@ function syslog_upart_run(bool $confirm, bool $convert_ms, bool $preserve_data =
}

// Writers would interleave with copied rows and break verification, so
// processing must be disabled, and the processing lock that
// syslog_process.php also takes is held for the duration. Unlike Cacti's
// process registry, the lock never takes over or terminates a live run.
// processing must be disabled, and this rebuild registers as the
// ('syslog', 'master') process for the duration, which syslog_process.php
// also registers, so the two mutually exclude through Cacti's process
// registry rather than a connection-bound GET_LOCK.
if ((string) read_config_option('syslog_enabled', true) !== '') {
fwrite(STDERR, 'ERROR: Syslog processing is enabled. Uncheck Settings > Syslog > Syslog Enabled, stop remote collectors and any other Syslog database writers, then retry. No changes were made.' . PHP_EOL);

return false;
}

$lock = syslog_processing_lock_name();
global $config;

if ((int) syslog_db_fetch_cell_prepared('SELECT GET_LOCK(?, 0)', [$lock]) !== 1) {
// A rebuild can run far longer than the default process timeout; a large
// timeout keeps register_process_start() from treating this run as stale
// and killing it, while the live-worker check below still prevents takeover.
if (!register_process_start('syslog', 'master', (int) $config['poller_id'], 86400)) {
fwrite(STDERR, 'ERROR: A Syslog processing run or another rebuild is still active; wait for it to finish, then retry. No changes were made.' . PHP_EOL);

return false;
}

$GLOBALS['syslog_master_registered'] = true;

try {
// Workers launched before the lock was taken may still be writing;
// later ones see the lock is no longer their master's and exit.
// Workers launched before this rebuild registered may still be writing;
// later ones find their master's pid gone and exit.
$workers = syslog_upart_live_workers();

if ($workers > 0) {
Expand All @@ -196,7 +202,8 @@ function syslog_upart_run(bool $confirm, bool $convert_ms, bool $preserve_data =

return syslog_upart_run_locked($confirm, $convert_ms, $preserve_data, $engines[strtolower($engine)], (int) $days, $ahead, $granularity, $limit, $partition !== null, $source_zone);
} finally {
syslog_db_fetch_cell_prepared('SELECT RELEASE_LOCK(?)', [$lock]);
unregister_process('syslog', 'master', (int) $config['poller_id']);
unset($GLOBALS['syslog_master_registered']);
}
}

Expand Down
258 changes: 117 additions & 141 deletions includes/functions.php
Original file line number Diff line number Diff line change
Expand Up @@ -2345,11 +2345,13 @@ function syslog_worker_stats_get() {
* The settings table lives in the main Cacti database, so the core
* db helper is required here.
*
* @param int $workers The number of workers that may have run
* @param int $workers The number of workers that may have run
* @param string $run_id The run whose reports count, or '' for any run
* @param string $phase The phase whose reports count, or '' for any phase
*
* @return array Aggregated moved and resolved totals
*/
function syslog_aggregate_worker_stats($workers) {
function syslog_aggregate_worker_stats($workers, $run_id = '', $phase = '') {
$moved = 0;
$resolved = 0;
$reported = [];
Expand All @@ -2371,6 +2373,11 @@ function syslog_aggregate_worker_stats($workers) {

$data = json_decode((string) $row['value'], true);

// A report from another run or phase is not this phase's result.
if (is_array($data) && !syslog_worker_report_matches($row['value'], $run_id, $phase)) {
continue;
}

if (!is_array($data)) {
cacti_log('WARNING: Ignoring malformed Syslog worker statistics.', false, 'SYSLOG');
$reported[$child] = false;
Expand Down Expand Up @@ -2838,131 +2845,18 @@ function syslog_partition_ahead_days() {
}

/**
* Name of the database lock shared by syslog_process.php and
* cli/upgrade_partitioning.php, so a rebuild never runs beside processing.
* GET_LOCK waits for nobody and terminates nothing; it is released when its
* connection closes, even after a crash.
*
* @return string A lock name within MySQL's 64-character limit.
*/
function syslog_processing_lock_name(): string {
global $syslogdb_default;

return substr(hash('sha256', $syslogdb_default . '.syslog_processing'), 0, 60);
}

/**
* Take the processing lock for syslog_process.php on a connection of its own.
* MySQL before 5.7.5 holds one named lock per session, so the GET_LOCK calls
* partition maintenance and alert delivery make on the Syslog connection
* would otherwise release it while processing continues. The new connection
* reaches the same server as $syslog_cnn and stays open until the process
* exits.
*
* @return bool|null True when held, false when another session holds it, and
* null when the lock connection could not be opened or its
* idle timeout could not be raised.
*/
function syslog_processing_lock_acquire(): ?bool {
global $syslog_cnn, $database_sessions, $database_details, $database_persist;

$details = null;

foreach ((array) $database_details as $entry) {
if (is_array($entry) && is_object($syslog_cnn) && ($entry['database_conn'] ?? null) === $syslog_cnn) {
$details = $entry;

break;
}
}

if ($details === null) {
return null;
}

// db_connect_real() returns a cached session for the same server and
// database, and a persistent PDO handle would share this session too.
$key = $details['database_hostname'] . ':' . $details['database_port'] . ':' . $details['database_default'];
$cached = $database_sessions[$key] ?? null;
$persist = $database_persist ?? false;

unset($database_sessions[$key]);
$database_persist = false;

$args = [
(string) $details['database_hostname'], (string) $details['database_username'], (string) $details['database_password'],
(string) $details['database_default'], (string) ($details['database_type'] ?? 'mysql'), (int) $details['database_port'],
(int) ($details['database_retries'] ?? 5), (bool) ($details['database_ssl'] ?? false), (string) ($details['database_ssl_key'] ?? ''),
(string) ($details['database_ssl_cert'] ?? ''), (string) ($details['database_ssl_ca'] ?? ''),
];

// Cacti 1.3 also records the CA path and server certificate verification.
if (array_key_exists('database_ssl_capath', $details)) {
$args[] = (string) $details['database_ssl_capath'];
$args[] = (bool) ($details['database_ssl_verify_server_cert'] ?? true);
}

try {
$cnn = db_connect_real(...$args);
} finally {
if ($cached !== null) {
$database_sessions[$key] = $cached;
} else {
unset($database_sessions[$key]);
}

$database_persist = $persist;
}

if (!is_object($cnn)) {
return null;
}

// The lock connection stays idle while processing runs; the server would
// close it, and release the lock, once wait_timeout elapses. Hold it for
// at least a day and stop if the server does not accept that.
db_execute('SET SESSION wait_timeout = GREATEST(@@SESSION.wait_timeout, 86400)', false, $cnn);

if ((int) db_fetch_cell('SELECT @@SESSION.wait_timeout', '', false, $cnn) < 86400) {
return null;
}

if ((int) db_fetch_cell_prepared('SELECT GET_LOCK(?, 0)', [syslog_processing_lock_name()], '', false, $cnn) !== 1) {
return false;
}

$GLOBALS['syslog_processing_lock_cnn'] = $cnn;
$GLOBALS['syslog_processing_lock_id'] = (int) db_fetch_cell('SELECT CONNECTION_ID()', '', false, $cnn);

return true;
}

/**
* Release a processing lock taken with syslog_processing_lock_acquire().
*
* @return void
*/
function syslog_processing_lock_release(): void {
$cnn = $GLOBALS['syslog_processing_lock_cnn'] ?? null;

if (is_object($cnn)) {
db_fetch_cell_prepared('SELECT RELEASE_LOCK(?)', [syslog_processing_lock_name()], '', false, $cnn);
}

unset($GLOBALS['syslog_processing_lock_cnn'], $GLOBALS['syslog_processing_lock_id']);
}

/**
* Whether the processing lock is still held by the given session. Transfer
* workers check the master's session so they never write once the master has
* gone and a partition rebuild may hold the lock.
* Whether the master processing run that launched a transfer worker is still
* alive. Transfer workers check this before writing, so an orphaned child
* never writes after its master has gone (for example while a partition
* rebuild runs). Unlike GET_LOCK()/IS_USED_LOCK(), a local process check does
* not depend on which cluster node a database connection is routed to.
*
* @param int $owner The CONNECTION_ID() of the session expected to hold it.
* @param int $pid The master processing run's process id.
*
* @return bool
*/
function syslog_processing_lock_held_by(int $owner): bool {
return $owner > 0 && (int) syslog_db_fetch_cell_prepared('SELECT IS_USED_LOCK(?)', [syslog_processing_lock_name()], '', false) === $owner;
function syslog_processing_master_alive(int $pid): bool {
return $pid > 0 && cacti_process_still_running($pid);
}

/**
Expand Down Expand Up @@ -3346,22 +3240,33 @@ function syslog_validate_worker_args($child, $run_id, $phase, $seq_start, $seq_e
* @return int The number of live, registered workers
*/
function syslog_workers_running() {
$processes = db_fetch_assoc("SELECT pid
return cacti_sizeof(syslog_workers_running_ids());
}

/**
* syslog_workers_running_ids - list the child numbers of the live worker
* children registered in Cacti's process table, removing stale rows as
* described for syslog_workers_running().
*
* @return array<int> The child number of each live, registered worker
*/
function syslog_workers_running_ids() {
$processes = db_fetch_assoc("SELECT pid, taskid
FROM processes
WHERE tasktype = 'syslog'
AND taskname = 'child'");

if (!is_array($processes) || !cacti_sizeof($processes)) {
return 0;
return [];
}

$running = 0;
$running = [];

foreach ($processes as $process) {
$pid = (int) $process['pid'];

if (cacti_process_still_running($pid)) {
$running++;
$running[] = (int) ($process['taskid'] ?? 0);

continue;
}
Expand All @@ -3377,6 +3282,58 @@ function syslog_workers_running() {
return $running;
}

/**
* syslog_workers_reported - list the child numbers that recorded their
* statistics for the current phase.
*
* The rows are read from the settings table directly because
* read_config_option() caches values per process, so a value read while
* the children were still running would never be seen to change.
*
* @param string $run_id The run whose reports count, or '' for any run
* @param string $phase The phase whose reports count, or '' for any phase
*
* @return array<int> The child number of each worker that reported
*/
function syslog_workers_reported($run_id = '', $phase = '') {
$rows = db_fetch_assoc("SELECT `name`, `value`
FROM settings
WHERE `name` LIKE 'stats_syslog_child_%'");

$reported = [];

foreach ((array) $rows as $row) {
$child = (int) str_replace('stats_syslog_child_', '', (string) $row['name']);

if ($child > 0 && syslog_worker_report_matches($row['value'] ?? '', $run_id, $phase)) {
$reported[] = $child;
}
}

return $reported;
}

/**
* syslog_worker_report_matches - whether a worker's recorded statistics
* belong to the given run and phase.
*
* A child of an earlier run can report after the next run has cleared the
* statistics rows, so a report counts only for the run and phase that
* launched it. An empty run or phase matches any report.
*
* @param mixed $value The recorded statistics, JSON encoded
* @param string $run_id The run whose reports count, or '' for any run
* @param string $phase The phase whose reports count, or '' for any phase
*
* @return bool
*/
function syslog_worker_report_matches($value, $run_id, $phase) {
$data = json_decode((string) $value, true);

return ($run_id === '' || (is_array($data) && ($data['run_id'] ?? '') === $run_id))
&& ($phase === '' || (is_array($data) && ($data['phase'] ?? '') === $phase));
}

/**
* syslog_wait_workers - wait for the launched worker children to finish.
*
Expand All @@ -3391,18 +3348,23 @@ function syslog_workers_running() {
* not spam the process table. Children that disappear without recording
* their statistics are warned about after the wait completes.
*
* @param int $expected The number of children that were launched
* @param int $expected The number of children that were launched
* @param string $run_id The run that launched them, or '' for any run
* @param string $phase The phase they run, or '' for any phase
*
* @return (void)
*/
function syslog_wait_workers($expected) {
function syslog_wait_workers($expected, $run_id = '', $phase = '') {
// STAGE 1: give every launched child time to register, bounded so a
// child that crashed before registering cannot stall the master.
// The grace window stays at ten seconds; the tenth of a second poll
// just notices registration as soon as it happens.
// just notices registration as soon as it happens. A child that has
// already recorded its statistics and unregistered is accounted for
// too, otherwise a phase that finishes quickly always waits out the
// whole window.
$grace_polls = 100;

for ($i = 0; $i < $grace_polls && syslog_workers_running() < $expected; $i++) {
for ($i = 0; $i < $grace_polls && syslog_workers_accounted($expected, $run_id, $phase) < $expected; $i++) {
syslog_debug(sprintf('Waiting for %s Worker(s) to register.', $expected));

usleep(100000);
Expand All @@ -3421,21 +3383,35 @@ function syslog_wait_workers($expected) {
}

// verify that each child recorded its completion
$missing = [];

for ($i = 1; $i <= $expected; $i++) {
$stat = read_config_option('stats_syslog_child_' . $i);
$missing = array_values(array_diff(range(1, max(1, $expected)), syslog_workers_reported($run_id, $phase)));

if ($stat === false || $stat === '' || $stat === null) {
$missing[] = $i;
}
}

if (cacti_sizeof($missing)) {
if ($expected > 0 && cacti_sizeof($missing)) {
cacti_log('WARNING: Syslog worker(s) exited without recording completion: ' . implode(', ', $missing), false, 'SYSLOG');
}
}

/**
* syslog_workers_accounted - count the launched children that are either
* registered and running or have already recorded their statistics.
*
* Child numbers are combined rather than added, because a child is briefly
* both registered and reported between writing its statistics and
* unregistering.
*
* @param int $expected The number of children that were launched
* @param string $run_id The run that launched them, or '' for any run
* @param string $phase The phase they run, or '' for any phase
*
* @return int The number of distinct children accounted for
*/
function syslog_workers_accounted($expected, $run_id = '', $phase = '') {
$children = array_unique(array_merge(syslog_workers_running_ids(), syslog_workers_reported($run_id, $phase)));

return cacti_sizeof(array_filter($children, function ($child) use ($expected) {
return $child >= 1 && $child <= $expected;
}));
}

/**
* Report suspicious partition metadata after a crash or database restart.
*
Expand Down
Loading