diff --git a/CHANGELOG.md b/CHANGELOG.md index 04064c2c..5ac99919 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 `

` 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/.json.gz, built from each vendor's public message references * feature: Recommendations are matched only against the sending device's vendor (and vendor-neutral records) when the syslog host is a Cacti device whose vendor is recognised from its SNMP sysDescr or device template and has records; other hosts match every vendor, except that all-digit identifiers then match only vendor-neutral records diff --git a/cli/upgrade_partitioning.php b/cli/upgrade_partitioning.php index ee295f4c..c0a1c026 100644 --- a/cli/upgrade_partitioning.php +++ b/cli/upgrade_partitioning.php @@ -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) { @@ -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']); } } diff --git a/includes/functions.php b/includes/functions.php index 4f1055ff..69a0f603 100644 --- a/includes/functions.php +++ b/includes/functions.php @@ -2345,11 +2345,13 @@ function syslog_worker_stats_get() { * The settings table lives in the main Cacti database, so the core * db helper is required here. * - * @param int $workers The number of workers that may have run + * @param int $workers The number of workers that may have run + * @param string $run_id The run whose reports count, or '' for any run + * @param string $phase The phase whose reports count, or '' for any phase * * @return array Aggregated moved and resolved totals */ -function syslog_aggregate_worker_stats($workers) { +function syslog_aggregate_worker_stats($workers, $run_id = '', $phase = '') { $moved = 0; $resolved = 0; $reported = []; @@ -2371,6 +2373,11 @@ function syslog_aggregate_worker_stats($workers) { $data = json_decode((string) $row['value'], true); + // A report from another run or phase is not this phase's result. + if (is_array($data) && !syslog_worker_report_matches($row['value'], $run_id, $phase)) { + continue; + } + if (!is_array($data)) { cacti_log('WARNING: Ignoring malformed Syslog worker statistics.', false, 'SYSLOG'); $reported[$child] = false; @@ -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); } /** @@ -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 The child number of each live, registered worker + */ +function syslog_workers_running_ids() { + $processes = db_fetch_assoc("SELECT pid, taskid FROM processes WHERE tasktype = 'syslog' AND taskname = 'child'"); if (!is_array($processes) || !cacti_sizeof($processes)) { - return 0; + return []; } - $running = 0; + $running = []; foreach ($processes as $process) { $pid = (int) $process['pid']; if (cacti_process_still_running($pid)) { - $running++; + $running[] = (int) ($process['taskid'] ?? 0); continue; } @@ -3377,6 +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 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. * @@ -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); @@ -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. * diff --git a/includes/schema.php b/includes/schema.php index 7d6c547e..f921b0cc 100644 --- a/includes/schema.php +++ b/includes/schema.php @@ -1130,21 +1130,28 @@ function syslog_ensure_table_structures(): bool { foreach ($tables as $table) { if (!syslog_db_table_exists($table, false)) { - // A partition rebuild renames the message tables while it holds the - // processing lock; never recreate a table underneath it. - $borrowed = empty($GLOBALS['syslog_processing_lock_cnn']); + // A partition rebuild renames the message tables while it is + // registered as the ('syslog', 'master') process; never recreate a + // table underneath it. If this process is not already that master, + // register as it so a concurrent run or rebuild excludes us. + $borrowed = empty($GLOBALS['syslog_master_registered']); - if ($borrowed && syslog_processing_lock_acquire() !== true) { - cacti_log("NOTE: Missing Syslog table '$table' was not repaired while a processing run or partition rebuild holds the processing lock.", false, 'SYSLOG'); + if ($borrowed && !register_process_start('syslog', 'master', (int) $config['poller_id'], 1200)) { + cacti_log("NOTE: Missing Syslog table '$table' was not repaired while a processing run or partition rebuild is active.", false, 'SYSLOG'); return false; } + if ($borrowed) { + $GLOBALS['syslog_master_registered'] = true; + } + try { syslog_setup_table_new([], true); } finally { if ($borrowed) { - syslog_processing_lock_release(); + unregister_process('syslog', 'master', (int) $config['poller_id']); + unset($GLOBALS['syslog_master_registered']); } } diff --git a/syslog_process.php b/syslog_process.php index d6e260e9..c433f12c 100644 --- a/syslog_process.php +++ b/syslog_process.php @@ -62,7 +62,7 @@ */ global $config; -global $child, $run_id, $phase, $seq_start, $seq_end, $lock_owner; +global $child, $run_id, $phase, $seq_start, $seq_end, $master_pid; $debug = false; $forcer = false; @@ -71,7 +71,7 @@ $phase = ''; $seq_start = 0; $seq_end = 0; -$lock_owner = 0; +$master_pid = 0; // process calling arguments $parms = $_SERVER['argv']; @@ -147,14 +147,14 @@ $seq_end = (int) $value; break; - case '--lock-owner': + case '--master-pid': if (preg_match('/^[1-9][0-9]*$/', $value) !== 1) { - print "ERROR: Lock owner must be a positive integer.\n\n"; + print "ERROR: Master pid must be a positive integer.\n\n"; display_help(); exit(1); } - $lock_owner = (int) $value; + $master_pid = (int) $value; break; case '--version': @@ -244,21 +244,11 @@ exit(0); } -// cli/upgrade_partitioning.php holds this lock while it rebuilds the message -// tables. It is taken on a connection of its own and held until this process -// exits and that connection closes. -$processing_lock = syslog_processing_lock_acquire(); - -if ($processing_lock !== true) { - if ($processing_lock === false) { - cacti_log('NOTE: Syslog processing skipped while cli/upgrade_partitioning.php rebuilds the message tables.', false, 'SYSLOG'); - } else { - cacti_log('ERROR: Syslog processing skipped; the processing lock connection could not be opened or kept open.', false, 'SYSLOG'); - } - - unregister_process('syslog', 'master', $config['poller_id']); - exit($processing_lock === false ? 0 : 1); -} +// The master's registration in Cacti's process table is the single-master +// mutex: cli/upgrade_partitioning.php and on-demand table repair register the +// same ('syslog', 'master') task, so a rebuild never runs beside processing. +// Transfer workers verify this process by pid, not a connection-bound lock. +$GLOBALS['syslog_master_registered'] = true; require_once(__DIR__ . '/includes/schema.php'); @@ -365,7 +355,7 @@ * follow all operate on the same incoming rows the workers are * updating, so the master must not race ahead of its children. */ - syslog_wait_workers($launched); + syslog_wait_workers($launched, $run_id, 'references'); $phase_start = time(); $phase_micro = microtime(true); @@ -449,9 +439,9 @@ * block until every child has recorded its statistics and * unregistered itself. */ - syslog_wait_workers($launched); + syslog_wait_workers($launched, $run_id, 'transfer'); - $worker_stats = syslog_aggregate_worker_stats($launched); + $worker_stats = syslog_aggregate_worker_stats($launched, $run_id, 'transfer'); $moved = $worker_stats['moved']; @@ -581,7 +571,7 @@ function sig_handler($signo) { * @return (void) This function always exits. */ function syslog_worker_main($debug = false) { - global $child, $run_id, $phase, $seq_start, $seq_end, $lock_owner; + global $child, $run_id, $phase, $seq_start, $seq_end, $master_pid; // The command line is the only source of these values, revalidate if (!syslog_validate_worker_args($child, $run_id, $phase, $seq_start, $seq_end)) { @@ -603,12 +593,23 @@ function syslog_worker_main($debug = false) { } /* - * Write only while the master that launched this worker still holds the - * processing lock. Registration comes first, so a partition rebuild that - * takes the lock afterwards sees this worker and refuses to start. + * Write only while the master processing run that launched this worker is + * still alive. Registration comes first, so a partition rebuild that + * registers afterwards sees this worker and refuses to start. */ - if (!syslog_processing_lock_held_by((int) $lock_owner)) { - cacti_log("WARNING: Syslog child $child exited; the processing run that launched it no longer holds the processing lock", false, 'SYSLOG'); + if (!syslog_processing_master_alive((int) $master_pid)) { + cacti_log(sprintf('WARNING: Syslog child %s exited; the processing run that launched it (master pid %d) is no longer running', $child, (int) $master_pid), false, 'SYSLOG'); + + // Report the failure so the master stops waiting for this child + // and counts the phase as failed. + set_config_option('stats_syslog_child_' . $child, json_encode([ + 'child' => $child, + 'run_id' => $run_id, + 'phase' => $phase, + 'moved' => 0, + 'success' => false, + 'reason' => 'master', + ])); unregister_process('syslog', 'child', $child); @@ -738,7 +739,7 @@ function syslog_launch_workers($phase, $slices, $run_id, $debug = false) { ' --phase=' . $phase . ' --seq-start=' . $slice['start'] . ' --seq-end=' . $slice['end'] . - ' --lock-owner=' . (int) ($GLOBALS['syslog_processing_lock_id'] ?? 0) . + ' --master-pid=' . (int) getmypid() . ($debug ? ' --debug' : ''); exec_background($php_binary, $extra_args); @@ -807,7 +808,7 @@ function display_help() { print 'The main Syslog poller process script for Cacti Syslogging.' . PHP_EOL . PHP_EOL; print 'usage: syslog_process.php [--debug] [--force-report]' . PHP_EOL . PHP_EOL; - print ' syslog_process.php --child=N --run-id=<32hex> --phase=references|transfer --seq-start=N --seq-end=N --lock-owner=N' . PHP_EOL . PHP_EOL; + print ' syslog_process.php --child=N --run-id=<32hex> --phase=references|transfer --seq-start=N --seq-end=N --master-pid=N' . PHP_EOL . PHP_EOL; print 'options:' . PHP_EOL; print ' --force-report Send email reports now.' . PHP_EOL; print ' --debug Provide more verbose debug output.' . PHP_EOL . PHP_EOL; @@ -817,5 +818,5 @@ function display_help() { print ' --phase The phase to process, references or transfer.' . PHP_EOL; print ' --seq-start The first seq of the slice to process.' . PHP_EOL; print ' --seq-end The last seq of the slice to process.' . PHP_EOL; - print ' --lock-owner The database session holding the master\'s processing lock.' . PHP_EOL . PHP_EOL; + print ' --master-pid The process id of the master processing run that launched this worker.' . PHP_EOL . PHP_EOL; } diff --git a/tests/Unit/PartitionRebuildTest.php b/tests/Unit/PartitionRebuildTest.php index 79d7de53..3bcc261f 100644 --- a/tests/Unit/PartitionRebuildTest.php +++ b/tests/Unit/PartitionRebuildTest.php @@ -17,6 +17,8 @@ function syslog_upart_rebuild(...$args): bool { return \test_call_override("sysl function syslog_upart_source_zone_error(...$args): string { return \test_call_override("syslog_upart_source_zone_error", $args, ""); } function posix_kill($pid, $signal) { return \test_call_override("posix_kill", [$pid, $signal], false); } function posix_get_last_error() { return \test_call_override("posix_get_last_error", [], 3); } + function register_process_start(...$args) { return \test_call_override("register_process_start", $args, true); } + function unregister_process(...$args) { return \test_call_override("unregister_process", $args, true); } ' . $run[0] . "\n" . $locked[0] . "\n" . $workers[0] . "\n" . $widen[0] . "\n" . $type[0]); try { @@ -39,6 +41,7 @@ function partition_rebuild_setup(): stdClass { 'bytes' => '10737418240', 'lock' => 1, 'queries' => [], + 'registry' => [], 'rebuilds' => [], 'settings' => [], 'executions' => [], @@ -74,6 +77,18 @@ function partition_rebuild_setup(): stdClass { test_override('set_config_option', static function ($key, $value) use ($state) { $state->settings[$key] = $value; }); + // The rebuild coordinates through Cacti's process registry; $state->lock + // doubles as "the registry is free" (1) or "already taken" (0). + test_override('register_process_start', static function (...$args) use ($state) { + $state->registry[] = ['start', $args]; + + return $state->lock === 1; + }); + test_override('unregister_process', static function (...$args) use ($state) { + $state->registry[] = ['stop', $args]; + + return true; + }); test_override('syslog_db_execute_prepared', static function ($sql, $params) use ($state) { $state->executions[] = [$sql, $params]; @@ -124,9 +139,9 @@ function partition_rebuild_setup(): stdClass { ->toContain('receive new sequence numbers') ->not->toContain('Type "yes"') ->and($state->rebuilds)->toBe([['syslog', false, true, 'InnoDB', 30, 3, 'day', 8192, 50000, null]]) - ->and($state->queries[0])->toBe(['SELECT GET_LOCK(?, 0)', [syslog_processing_lock_name()]]); + ->and($state->registry[0])->toBe(['start', ['syslog', 'master', 1, 86400]]); expect($state->settings)->toBe([]); - expect(array_column($state->queries, 0))->toContain('SELECT RELEASE_LOCK(?)'); + expect(array_column($state->registry, 0))->toContain('stop'); }); it('saves --partition=hourly once confirmed and rebuilds with at least two days ahead', function () { @@ -180,7 +195,8 @@ function partition_rebuild_setup(): stdClass { $run = partition_rebuild_runner(); expect($run(true, false))->toBeFalse() - ->and($state->queries)->toBe([['SELECT GET_LOCK(?, 0)', [syslog_processing_lock_name()]]]) + ->and($state->registry)->toBe([['start', ['syslog', 'master', 1, 86400]]]) + ->and($state->queries)->toBe([]) ->and($state->rebuilds)->toBe([]); }); @@ -204,7 +220,7 @@ function partition_rebuild_setup(): stdClass { expect($run(true, false))->toBeFalse() ->and($state->rebuilds)->toBe([]) ->and($state->statements)->toBe([]) - ->and(end($state->queries))->toBe(['SELECT RELEASE_LOCK(?)', [syslog_processing_lock_name()]]); + ->and(end($state->registry))->toBe(['stop', ['syslog', 'master', 1]]); // Only stale rows remain: the rebuild proceeds. test_override('posix_kill', static fn() => false); @@ -224,7 +240,7 @@ function partition_rebuild_setup(): stdClass { expect($run(true, false))->toBeFalse() ->and($state->rebuilds)->toBe([]) ->and($state->statements)->toBe([]) - ->and(end($state->queries))->toBe(['SELECT RELEASE_LOCK(?)', [syslog_processing_lock_name()]]); + ->and(end($state->registry))->toBe(['stop', ['syslog', 'master', 1]]); }); it('refuses a source time zone that fails validation before any change', function () { @@ -237,7 +253,7 @@ function partition_rebuild_setup(): stdClass { ->and($state->rebuilds)->toBe([]) ->and($state->statements)->toBe([]) ->and($state->settings)->toBe([]) - ->and(end($state->queries))->toBe(['SELECT RELEASE_LOCK(?)', [syslog_processing_lock_name()]]); + ->and(end($state->registry))->toBe(['stop', ['syslog', 'master', 1]]); }); it('copies legacy DATETIME history in the validated source zone and clears the retry zone afterwards', function () { @@ -368,7 +384,7 @@ function partition_rebuild_setup(): stdClass { expect($run(true, false))->toBeFalse() ->and($state->rebuilds)->toBe([]); - expect(array_column($state->queries, 0))->toContain('SELECT RELEASE_LOCK(?)'); + expect(array_column($state->registry, 0))->toContain('stop'); }); it('prevents a destructive retry from deleting retained originals', function () { diff --git a/tests/Unit/ProcessingLockTest.php b/tests/Unit/ProcessingLockTest.php deleted file mode 100644 index 6410010b..00000000 --- a/tests/Unit/ProcessingLockTest.php +++ /dev/null @@ -1,172 +0,0 @@ - - */ -function syslog_test_lock_details(object $cnn, bool $cacti13): array { - $details = [ - 'database_conn' => $cnn, - 'database_hostname' => 'syslog-db', - 'database_username' => 'syslog', - 'database_password' => 'secret', - 'database_default' => 'syslog', - 'database_type' => 'mysql', - 'database_port' => 3307, - 'database_retries' => 2, - 'database_ssl' => true, - 'database_ssl_key' => 'key.pem', - 'database_ssl_cert' => 'cert.pem', - 'database_ssl_ca' => 'ca.pem', - 'database_persist' => false, - ]; - - if ($cacti13) { - $details['database_ssl_capath'] = '/etc/ssl/certs'; - $details['database_ssl_verify_server_cert'] = false; - } - - return $details; -} - -beforeEach(function () { - syslog_load_plugin_source('includes/functions.php'); - - $this->saved = []; - - foreach (['syslog_cnn', 'syslogdb_default', 'database_sessions', 'database_details', 'database_persist', 'syslog_processing_lock_cnn', 'syslog_processing_lock_id'] as $name) { - $this->saved[$name] = $GLOBALS[$name] ?? null; - } - - $GLOBALS['syslogdb_default'] = 'syslog'; - $GLOBALS['syslog_cnn'] = new stdClass(); - unset($GLOBALS['syslog_processing_lock_cnn']); -}); - -afterEach(function () { - foreach ($this->saved as $name => $value) { - if ($value === null) { - unset($GLOBALS[$name]); - } else { - $GLOBALS[$name] = $value; - } - } -}); - -it('takes the processing lock on a new connection to the Syslog server', function () { - $lock_cnn = new stdClass(); - $seen = []; - - $GLOBALS['database_details'] = ['other' => ['database_conn' => new stdClass()], 'syslog' => syslog_test_lock_details($GLOBALS['syslog_cnn'], true)]; - $GLOBALS['database_sessions'] = ['syslog-db:3307:syslog' => $GLOBALS['syslog_cnn']]; - $GLOBALS['database_persist'] = true; - - test_override('db_connect_real', function (...$args) use (&$seen, $lock_cnn) { - // The cached session and persistent handles would reuse $syslog_cnn. - $seen = [$args, isset($GLOBALS['database_sessions']['syslog-db:3307:syslog']), $GLOBALS['database_persist']]; - - return $lock_cnn; - }); - test_override('db_fetch_cell_prepared', fn($sql, $params, $col, $log, $cnn) => $sql === 'SELECT GET_LOCK(?, 0)' && $params === [syslog_processing_lock_name()] && $cnn === $lock_cnn ? '1' : '0'); - test_override('db_fetch_cell', fn($sql, $col, $log, $cnn) => $cnn !== $lock_cnn ? '0' : ['SELECT @@SESSION.wait_timeout' => '86400', 'SELECT CONNECTION_ID()' => '42'][$sql] ?? '0'); - $GLOBALS['__test_db_calls'] = []; - - expect(syslog_processing_lock_acquire())->toBeTrue() - ->and(array_column($GLOBALS['__test_db_calls'], 'sql'))->toContain('SET SESSION wait_timeout = GREATEST(@@SESSION.wait_timeout, 86400)') - ->and($seen)->toBe([['syslog-db', 'syslog', 'secret', 'syslog', 'mysql', 3307, 2, true, 'key.pem', 'cert.pem', 'ca.pem', '/etc/ssl/certs', false], false, false]) - ->and($GLOBALS['syslog_processing_lock_cnn'])->toBe($lock_cnn) - ->and($GLOBALS['syslog_processing_lock_id'])->toBe(42) - ->and($GLOBALS['database_sessions']['syslog-db:3307:syslog'])->toBe($GLOBALS['syslog_cnn']) - ->and($GLOBALS['database_persist'])->toBeTrue(); - - $released = []; - test_override('db_fetch_cell_prepared', function ($sql, $params, $col, $log, $cnn) use (&$released) { - $released[] = [$sql, $cnn]; - - return '1'; - }); - syslog_processing_lock_release(); - - expect($released)->toBe([['SELECT RELEASE_LOCK(?)', $lock_cnn]]) - ->and($GLOBALS)->not->toHaveKey('syslog_processing_lock_cnn') - ->and($GLOBALS)->not->toHaveKey('syslog_processing_lock_id'); -}); - -it('lets a worker write only while its master session holds the lock', function () { - test_override('syslog_db_fetch_cell_prepared', fn($sql, $params) => $sql === 'SELECT IS_USED_LOCK(?)' && $params === [syslog_processing_lock_name()] ? '42' : null); - - expect(syslog_processing_lock_held_by(42))->toBeTrue() - ->and(syslog_processing_lock_held_by(43))->toBeFalse() - ->and(syslog_processing_lock_held_by(0))->toBeFalse(); - - // A released lock reports NULL. - test_override('syslog_db_fetch_cell_prepared', fn() => null); - - expect(syslog_processing_lock_held_by(42))->toBeFalse(); -}); - -it('reports a lock held elsewhere and a lock connection that cannot be opened', function () { - $GLOBALS['database_details'] = [syslog_test_lock_details($GLOBALS['syslog_cnn'], false)]; - $GLOBALS['database_sessions'] = []; - $args = []; - - test_override('db_connect_real', function (...$connect) use (&$args) { - $args = $connect; - - return new stdClass(); - }); - test_override('db_fetch_cell_prepared', fn() => '0'); - test_override('db_fetch_cell', fn() => '86400'); - - // Cacti 1.2 records no CA path, so only its eleven connection arguments are passed. - expect(syslog_processing_lock_acquire())->toBeFalse() - ->and($args)->toHaveCount(11) - ->and($GLOBALS)->not->toHaveKey('syslog_processing_lock_cnn') - ->and($GLOBALS['database_sessions'])->toBe([]); - - // A server that keeps a short idle timeout would drop the lock mid-run. - test_override('db_fetch_cell', fn() => '600'); - test_override('db_fetch_cell_prepared', fn() => '1'); - - expect(syslog_processing_lock_acquire())->toBeNull() - ->and($GLOBALS)->not->toHaveKey('syslog_processing_lock_cnn'); - - test_override('db_connect_real', fn() => false); - - expect(syslog_processing_lock_acquire())->toBeNull(); - - // Without recorded details the Syslog server cannot be reached again. - $GLOBALS['database_details'] = []; - - expect(syslog_processing_lock_acquire())->toBeNull(); -}); diff --git a/tests/Unit/ProcessingRegistryTest.php b/tests/Unit/ProcessingRegistryTest.php new file mode 100644 index 00000000..c58357bd --- /dev/null +++ b/tests/Unit/ProcessingRegistryTest.php @@ -0,0 +1,73 @@ + $pid === 4242); + + expect(syslog_processing_master_alive(4242))->toBeTrue() + ->and(syslog_processing_master_alive(9999))->toBeFalse() + ->and(syslog_processing_master_alive(0))->toBeFalse() + ->and(syslog_processing_master_alive(-1))->toBeFalse(); +}); + +it('never consults the operating system for a non-positive pid', function () { + $checked = []; + test_override('cacti_process_still_running', function ($pid) use (&$checked) { + $checked[] = $pid; + + return true; + }); + + syslog_processing_master_alive(0); + syslog_processing_master_alive(-5); + + expect($checked)->toBe([]); +}); + +it('no longer uses a session-bound lock in the processing path', function () { + $process = plugin_test_read_source('syslog_process.php'); + + expect($process)->not->toContain('GET_LOCK') + ->and($process)->not->toContain('IS_USED_LOCK') + ->and($process)->not->toContain('--lock-owner') + ->and($process)->toContain('--master-pid') + ->and($process)->toContain('syslog_processing_master_alive') + ->and($process)->toContain("register_process_start('syslog', 'master'"); +}); + +it('coordinates rebuilds and on-demand table repair through the registry', function () { + $upart = plugin_test_read_source('cli/upgrade_partitioning.php'); + $schema = plugin_test_read_source('includes/schema.php'); + + expect($upart)->toContain("register_process_start('syslog', 'master'") + ->and($upart)->not->toContain('syslog_processing_lock_name') + ->and($schema)->toContain("register_process_start('syslog', 'master'") + ->and($schema)->not->toContain('syslog_processing_lock_acquire'); +}); + +it('removed the GET_LOCK processing-lock helpers from functions.php', function () { + $functions = plugin_test_read_source('includes/functions.php'); + + expect($functions)->not->toContain('function syslog_processing_lock_acquire') + ->and($functions)->not->toContain('function syslog_processing_lock_held_by') + ->and($functions)->not->toContain('function syslog_processing_lock_name') + ->and($functions)->toContain('function syslog_processing_master_alive'); +}); diff --git a/tests/Unit/SyslogWorkerAggregationTest.php b/tests/Unit/SyslogWorkerAggregationTest.php index 1ed6d844..2bb678bb 100644 --- a/tests/Unit/SyslogWorkerAggregationTest.php +++ b/tests/Unit/SyslogWorkerAggregationTest.php @@ -96,6 +96,25 @@ expect($warnings)->toBe(1, 'Exactly one malformed row warning is logged'); }); +it('counts only the reports of the run and phase being aggregated', function () { + $GLOBALS['syslogdb_default'] = 'syslog'; + + test_override('db_fetch_assoc', function () { + return [ + ['name' => 'stats_syslog_child_1', 'value' => json_encode(['run_id' => 'current', 'phase' => 'transfer', 'moved' => 40, 'success' => true])], + ['name' => 'stats_syslog_child_2', 'value' => json_encode(['run_id' => 'earlier', 'phase' => 'transfer', 'moved' => 900, 'success' => true])] + ]; + }); + + test_override('db_execute', function () { + return true; + }); + + // A late report from an earlier run is neither counted nor accepted as + // child 2's result for this run. + expect(syslog_aggregate_worker_stats(2, 'current', 'transfer'))->toBe(['moved' => 40, 'resolved' => 0, 'success' => false]); +}); + it('reports a failed transfer slice through the child result and skips stale cleanup', function () { $process = file_get_contents(dirname(__DIR__, 2) . '/syslog_process.php'); diff --git a/tests/Unit/SyslogWorkerWaitTest.php b/tests/Unit/SyslogWorkerWaitTest.php index 79e539d8..1662b6d8 100644 --- a/tests/Unit/SyslogWorkerWaitTest.php +++ b/tests/Unit/SyslogWorkerWaitTest.php @@ -37,24 +37,39 @@ * Install fakes that replay a fixed snapshot of the process table on * every poll and record every log line and DELETE issued. * - * @param array $snapshots List of pid arrays, one per db_fetch_assoc call + * @param array $snapshots List of pid arrays, one per process table poll * @param array $logs Filled with every cacti_log() message * @param array $deletes Filled with every db_execute() statement * @param array $stats Child numbers that recorded statistics + * @param int $stats_at Process table poll from which the statistics are + * visible; by default once the last snapshot is reached * * @return void */ -function syslog_wait_test_environment(array $snapshots, array &$logs, array &$deletes, array $stats = [1, 2]) { - $logs = []; - $deletes = []; - $poll = 0; +function syslog_wait_test_environment(array $snapshots, array &$logs, array &$deletes, array $stats = [1, 2], ?int $stats_at = null) { + $logs = []; + $deletes = []; + $poll = 0; + $stats_at = $stats_at ?? max(0, cacti_sizeof($snapshots) - 1); + + test_override('db_fetch_assoc', function ($sql) use ($snapshots, $stats, $stats_at, &$poll) { + if (str_contains($sql, 'FROM settings')) { + if ($poll < $stats_at) { + return []; + } + + return array_map(function ($child) { + return ['name' => 'stats_syslog_child_' . $child]; + }, $stats); + } - test_override('db_fetch_assoc', function ($sql) use ($snapshots, &$poll) { // The last snapshot repeats so a runaway loop fails the poll // count assertion below rather than looping the suite forever. - return array_map(function ($pid) { - return ['pid' => $pid]; - }, $snapshots[min($poll++, max(0, cacti_sizeof($snapshots) - 1))]); + $pids = $snapshots[min($poll++, max(0, cacti_sizeof($snapshots) - 1))]; + + return array_map(function ($pid, $index) { + return ['pid' => $pid, 'taskid' => $index + 1]; + }, $pids, array_keys($pids)); }); test_override('cacti_process_still_running', function ($pid) { @@ -71,14 +86,6 @@ function syslog_wait_test_environment(array $snapshots, array &$logs, array &$de $logs[] = $message; }); - test_override('read_config_option', function ($name) use ($stats) { - if (preg_match('/^stats_syslog_child_(\d+)$/', $name, $m) && in_array((int) $m[1], $stats, true)) { - return json_encode(['child' => (int) $m[1], 'moved' => 10, 'resolved' => 0, 'runtime' => 0.1]); - } - - return ''; - }); - return function () use (&$poll) { return $poll; }; @@ -147,6 +154,92 @@ function syslog_wait_test_environment(array $snapshots, array &$logs, array &$de expect($logs)->toContain('WARNING: Syslog worker(s) exited without recording completion: 2'); }); +it('does not wait out the registration window for workers that already finished (issue#479)', function () { + $logs = []; + $deletes = []; + + // Both children registered, recorded statistics and unregistered + // before the master's first poll. Counting only registered workers + // held the master for the whole ten second window on every phase. + $polls = syslog_wait_test_environment([[]], $logs, $deletes, [1, 2], 0); + + syslog_wait_workers(2); + + expect($polls())->toBe(2, 'Finished workers must end the registration wait at once'); + expect($logs)->toBeEmpty(); +}); + +it('counts a worker once while it is both registered and reported', function () { + $logs = []; + $deletes = []; + + // Child 1 has written its statistics but not yet unregistered, and + // child 2 has not registered. Adding the two counts would end the + // registration wait before child 2 appears. + $polls = syslog_wait_test_environment([[501], [501, 502], []], $logs, $deletes, [1], 0); + + syslog_wait_workers(2); + + // Registration ends on the second poll and the drain takes one more. + // Adding the counts would end registration on the first poll and need + // four polls in total. + expect($polls())->toBe(3, 'The master must keep waiting for the unregistered child'); +}); + +it('does not count a late report from an earlier run as a current result', function () { + $logs = []; + $deletes = []; + + $polls = syslog_wait_test_environment([[], [601, 602], []], $logs, $deletes, [1, 2], 0); + + // Both rows belong to another run, so they must neither end the + // registration wait nor satisfy the completion check. + test_override('db_fetch_assoc', (function ($inner) { + return function ($sql) use ($inner) { + $rows = $inner($sql); + + if (str_contains($sql, 'FROM settings')) { + foreach ($rows as &$row) { + $row['value'] = json_encode(['run_id' => 'earlier', 'phase' => 'transfer']); + } + } + + return $rows; + }; + })($GLOBALS['__test_overrides']['db_fetch_assoc'])); + + syslog_wait_workers(2, 'current', 'transfer'); + + expect($polls())->toBe(3, 'Stale reports must not end the registration wait'); + expect($logs)->toContain('WARNING: Syslog worker(s) exited without recording completion: 1, 2'); +}); + +it('accepts the reports of the current run and phase', function () { + $logs = []; + $deletes = []; + + $polls = syslog_wait_test_environment([[]], $logs, $deletes, [1, 2], 0); + + test_override('db_fetch_assoc', (function ($inner) { + return function ($sql) use ($inner) { + $rows = $inner($sql); + + if (str_contains($sql, 'FROM settings')) { + foreach ($rows as &$row) { + $row['value'] = json_encode(['run_id' => 'current', 'phase' => 'references']); + } + } + + return $rows; + }; + })($GLOBALS['__test_overrides']['db_fetch_assoc'])); + + syslog_wait_workers(2, 'current', 'references'); + + expect($polls())->toBe(2); + expect($logs)->toBeEmpty(); +}); + it('waits out the registration window instead of racing ahead at zero', function () { $logs = []; $deletes = []; @@ -173,9 +266,8 @@ function syslog_wait_test_environment(array $snapshots, array &$logs, array &$de $root = dirname(__DIR__, 2); $process = file_get_contents($root . '/syslog_process.php'); - // The master must block after launching each phase. - expect(substr_count($process, 'syslog_wait_workers($launched);'))->toBe(2, 'Both launch sites must be followed by a wait'); - + // The master must block after launching each phase, scoped to the run + // and phase it launched. foreach (['references', 'transfer'] as $phase) { $launch = strpos($process, "syslog_launch_workers('$phase'"); @@ -183,11 +275,13 @@ function syslog_wait_test_environment(array $snapshots, array &$logs, array &$de throw new RuntimeException("The '$phase' phase launch is missing from the master flow"); } - if (strpos($process, 'syslog_wait_workers($launched);', $launch) === false) { + if (strpos($process, "syslog_wait_workers(\$launched, \$run_id, '$phase');", $launch) === false) { throw new RuntimeException("The '$phase' phase launch is not followed by a wait"); } } + expect($process)->toContain("syslog_aggregate_worker_stats(\$launched, \$run_id, 'transfer')"); + // A child that cannot register must leave a breadcrumb and exit // non-zero, never exit silently. $register = strpos($process, "register_process_start('syslog', 'child'"); diff --git a/tests/regression/cli_schema_upgrade_test.php b/tests/regression/cli_schema_upgrade_test.php index a2f692fb..4355ff10 100644 --- a/tests/regression/cli_schema_upgrade_test.php +++ b/tests/regression/cli_schema_upgrade_test.php @@ -64,11 +64,11 @@ function syslog_ensure_message_digest_columns() {} function syslog_db_add_column($table, $column, $log = true) { return true; } function syslog_db_fetch_cell_prepared($sql, $params = [], $col_name = '', $log = true) { return '50'; } function syslog_status_set($name, $value) { return true; } -// Repair of a missing table runs under the processing lock. +// Repair of a missing table runs under the process registry. $lock_calls = []; $lock_free = true; -function syslog_processing_lock_acquire() { $GLOBALS['lock_calls'][] = 'acquire'; return $GLOBALS['lock_free']; } -function syslog_processing_lock_release() { $GLOBALS['lock_calls'][] = 'release'; } +function register_process_start($tasktype, $taskname, $taskid = 0, $timeout = 300) { $GLOBALS['lock_calls'][] = 'acquire'; return $GLOBALS['lock_free']; } +function unregister_process($tasktype, $taskname, $taskid = 0, $pid = -1) { $GLOBALS['lock_calls'][] = 'release'; } function cacti_log(...$args) {} function db_update_table($table, $definition, $create, $upgrade, $connection) { return true; } // syslog_setup_table_new() routes table creation through this wrapper; forward @@ -94,11 +94,11 @@ function syslog_db_table_exists($table, $log = true) { // The stubbed builder never records `syslog` as created, so it stays missing. $lock_free = false; -check(!syslog_ensure_table_structures() && $lock_calls === ['acquire'], 'Repair must not recreate a missing table while another session holds the processing lock'); +check(!syslog_ensure_table_structures() && $lock_calls === ['acquire'], 'Repair must not recreate a missing table while a processing run or rebuild is registered'); $lock_free = true; $lock_calls = []; syslog_ensure_table_structures(); -check($lock_calls === ['acquire', 'release'], 'Repair of a missing table must run under the processing lock'); +check($lock_calls === ['acquire', 'release'], 'Repair of a missing table must run under the process registry'); $config['poller_id'] = 2; $all_tables_exist = true; check(syslog_ensure_table_structures(), 'Remote schema repair failed'); diff --git a/tests/regression/partition_rebuild_database_test.php b/tests/regression/partition_rebuild_database_test.php index bbc9d4e1..54ec87b8 100644 --- a/tests/regression/partition_rebuild_database_test.php +++ b/tests/regression/partition_rebuild_database_test.php @@ -96,6 +96,21 @@ function db_column_exists(...$args) { return false; } function db_fetch_cell_prepared(...$args) { return ''; } // No Cacti process table here, so no transfer workers are registered. function db_fetch_assoc($sql, ...$args) { return []; } +// Cacti's process registry: an in-memory stand-in. register_process_start() +// refuses while a ('syslog', 'master') registration is held, as core does. +$master_registered_by = 0; +function register_process_start($tasktype, $taskname, $taskid = 0, $timeout = 300) { + if ($GLOBALS['master_registered_by'] !== 0) { + return false; + } + $GLOBALS['master_registered_by'] = getmypid(); + return true; +} +function unregister_process($tasktype, $taskname, $taskid = 0, $pid = -1) { + $GLOBALS['master_registered_by'] = 0; + return true; +} +$GLOBALS['config']['poller_id'] = 1; require dirname(__DIR__, 2) . '/includes/schema.php'; @@ -104,8 +119,7 @@ function db_fetch_assoc($sql, ...$args) { return []; } $helper_code = ''; foreach (['syslog_partition_periods', 'syslog_partition_requested_granularity', 'syslog_partition_ahead_days_for', - 'syslog_partition_server_limit', 'syslog_partition_projected_count', 'syslog_partition_settings_error', - 'syslog_processing_lock_name'] as $helper) { + 'syslog_partition_server_limit', 'syslog_partition_projected_count', 'syslog_partition_settings_error'] as $helper) { if (preg_match('/^function ' . $helper . '\(.*?^\}/ms', $helpers, $match) !== 1) { throw new RuntimeException("Cannot find $helper"); } @@ -130,7 +144,7 @@ function db_fetch_assoc($sql, ...$args) { return []; } } function is_free_processing_lock(): bool { - return (int) syslog_db_fetch_cell_prepared('SELECT IS_FREE_LOCK(?)', [syslog_processing_lock_name()]) === 1; + return $GLOBALS['master_registered_by'] === 0; } function rebuild_table(string $table, bool $convert = true, string $engine = 'InnoDB'): bool { @@ -239,14 +253,13 @@ function rebuild_table(string $table, bool $convert = true, string $engine = 'In ob_end_clean(); rebuild_check(is_free_processing_lock(), 'Enabled processing is refused before taking the processing lock'); set_config_option('syslog_enabled', ''); - // A second connection stands in for a running syslog_process.php. - $holder = new PDO($dsn, 'root', getenv('SYSLOG_TEST_MYSQL_PASSWORD') ?: '', [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]); - $holder->prepare('SELECT GET_LOCK(?, 0)')->execute([syslog_processing_lock_name()]); + // Stand in for a running syslog_process.php holding the master registration. + $GLOBALS['master_registered_by'] = 999999; ob_start(); rebuild_check(!syslog_upart_run(true, false), 'The command refuses to run while a processing run holds the processing lock'); ob_end_clean(); rebuild_check(!syslog_db_table_exists('syslog_rebuild') && !syslog_db_table_exists('syslog_removed_rebuild'), 'Refusals leave the message tables untouched'); - $holder = null; + $GLOBALS['master_registered_by'] = 0; $pdo->exec('CREATE TABLE syslog_incoming (seq BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY, logtime TIMESTAMP NOT NULL, status INT, message TEXT) ENGINE=InnoDB'); $pdo->exec("INSERT INTO syslog_incoming VALUES(30,UTC_DATE(),1,'queued'),(40,UTC_DATE(),0,'new')");