You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
mactrack: run the database upgrade in a background CLI - #423
The MacTrack schema upgrade rebuilds indexes and rewrites the (potentially very large) mac_track_aggregated_ports table. That work runs far longer than a web request is allowed to live, so it was being killed at the request timeout (~300s), the new version was never recorded, and every subsequent page re-ran the upgrade — an endless loop with a repeating error.
This moves the upgrade into a background CLI that the console launches once, so large installs can take the 30–60 minutes they need.
What changed
New cli/upgrade_database.php — the background entry point:
register_process_start('mtupgrade','database',0,86400) prevents a second copy from running; a crashed run past the timeout is taken over on the next launch.
pcntl SIGTERM/SIGINT handlers stop cleanly; because each scan-date batch commits on its own, an interrupted run simply resumes next launch.
Runs mactrack_perform_upgrade(), heartbeats the process registry, clears the operator-notice flag, and unregister_process() on completion. Supports --debug, --force, --help, --version.
includes/database.php — mactrack_rebuild_aggregated_ports() rebuilds mac_track_aggregated_ports without the table-wide rewrite:
rename the live table aside (_upgrade);
create the modified table (bigint row_id, UNIQUE port_number);
read the distinct scan dates;
copy each scan date back with INSERT … SELECT … WHERE date_last = ? ON DUPLICATE KEY UPDATE, which merges the rows that MAC normalization collapses (count_rec += VALUES, first_scan_date = LEAST, date_last = GREATEST, active_last = GREATEST), deleting each processed date in the same transaction so the migration is resumable;
drop the drained source table.
The satellite tables keep their one-pass MAC normalization.
setup.php — mactrack_check_upgrade() no longer upgrades inline. On pending work it launches the CLI once via exec_background() and raises a single operator notice while it runs. mactrack_perform_upgrade() performs the full upgrade and records the new plugin_config version last, so an interrupted run re-runs cleanly and the hook stops relaunching once it finishes.
Testing
Unit suite: 317 passed.
Patch coverage: 100% of changed lines (the CLI entry point is allowlisted as unloadable in the isolated unit process; its orchestration is covered via setup.php/includes/database.php).
PHPStan level 6: clean.
validate-manifest and check-i18n-pot: OK (manifest.json and locales/po/cacti.pot updated).
The schema migration rebuilds indexes and rewrites the large
mac_track_aggregated_ports table, which runs far longer than a web
request is allowed to live, so it was being killed at the request
timeout and never recorded the new version. Every later page then
re-ran it, looping forever.
Move the upgrade into cli/upgrade_database.php, launched with
exec_background() from mactrack_check_upgrade(). The CLI guards against
double runs with register_process_start(), handles SIGTERM/SIGINT to
stop cleanly and resume later, and heartbeats the process registry while
it works.
Rebuild mac_track_aggregated_ports by renaming it aside, recreating the
modified table (bigint row_id, unique port_number key), and copying it
back one scan date at a time with INSERT ... SELECT ... ON DUPLICATE KEY
UPDATE, deleting each processed date so the migration is resumable, then
dropping the old table.
The web hook launches the CLI once, raises a single operator notice while
it runs, and records the new plugin version only after the upgrade
completes.
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
SonarCloud flagged the SHA-1 in the aggregated-ports rebuild lock name as a
weak hash. The name only needs to be stable per database, and the SHA-1 form
also pushed the GET_LOCK name past MySQL's 64-character limit. Use a
truncated SHA-256 instead.
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
The reason will be displayed to describe this comment to others. Learn more.
🟡 Changes recommended
Unresolved critical migration defects can discard history, mark failed rebuilds as complete, and lose or restore stale data during concurrent poller and administrative updates.
Hardens the aggregated-ports rebuild and failure handling per the Copilot
code review:
- Pause the poller while a background upgrade is registered, so its aggregate
writes and scan-buffer truncation do not race with the renamed table.
- Validate that the destination unique key is actually in place after schema
normalization, and abort before copying if it is not.
- Only drop the drained source after a COUNT(*) confirms it is empty, so a
failed scan-date lookup (db_fetch_cell returns false for empty and error
alike) can never discard remaining history.
- Propagate rebuild failure so plugin_perform_upgrade leaves the version
unrecorded and the CLI exits non-zero and is retried.
- Keep repairing a non-unique key even after the rebuild flag is set, so a
later key regression does not loop the web hook forever.
- Preserve the newer survivor's descriptive fields when a merge collapses
rows from different scan dates.
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
The reason will be displayed to describe this comment to others. Learn more.
🟡 Changes recommended
Critical issues can cause migration failures, prevent resumable retries, and allow pollers or concurrent upgrades to run during rebuilds, risking lost scan results or overwritten metadata.
- Register the background-upgrade maintenance entry even for --force runs, so
the poller guard and web launcher still see a forced rebuild and pause.
- Qualify the existing-value column references in the aggregated-ports
ON DUPLICATE KEY UPDATE with the destination table name, since the same
names are exposed by the INSERT ... SELECT source and would be ambiguous.
- Hold off the destructive table rename while a poller is mid-run
(mactrack_poller_running), and keep the poller paused while the rebuild work
table (mac_track_aggregated_ports_upgrade) still exists, closing the
coordination gap in both directions.
- Treat a leftover rebuild work table as pending work in
mactrack_database_upgrade_pending(), so an interrupted rebuild that already
restored the unique key at the current version still keeps relaunching until
the table is drained.
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
The reason will be displayed to describe this comment to others. Learn more.
🟡 Changes recommended
The rebuild can report completion after a failed DROP TABLE, leaving cleanup permanently blocked, and omitted row IDs can cause pending bulk-delete confirmations to delete the wrong records.
Preserve row IDs during rebuild to keep pending bulk deletes valid
includes/database.php:927
The copy omits row_id, so even records whose normalized keys do not collide can receive different IDs. Aggregate bulk-delete confirmations retain those IDs and later execute DELETE ... WHERE row_id IN (...) (mactrack_view_macs.php:275–281); a confirmation opened before the rebuild can therefore delete nothing, or target another record if an ID is reused. Preserve source IDs for non-colliding records by including row_id in both column lists.
The reason will be displayed to describe this comment to others. Learn more.
🟡 Changes recommended
The rebuild assigns new row IDs, causing previously opened bulk-delete confirmations to silently miss selected records unless IDs are preserved or stale selections are rejected.
The reason will be displayed to describe this comment to others. Learn more.
Reviewed at afdb12e. 5b6c813 and afdb12e fixed what I was going to raise: a failed rebuild no longer records the version, the _upgrade table keeps the upgrade pending, and the source is dropped only when it's empty. One blocker is left, plus two smaller points.
Blocker: a CLI that dies without unregistering stops MacTrack polling for up to 24 hours. The poller now exits whenever mactrack_background_upgrade_running() is true, and that check only compares started with the 86400 s timeout. A kill -9, an OOM kill, a PHP fatal error or a host reboot mid-upgrade leaves the processes row behind. Until it ages out, every poller run defers, and the launcher won't start a replacement either. register_process_start() in core also only takes the row over after its timeout. SIGTERM is handled, but nothing else is. Before this PR the same crash only delayed the upgrade. Now it stops data collection. Suggestion: treat the row as stale when its pid no longer exists (posix_kill($pid, 0), since it's always a local CLI), or when last_update from heartbeat_process() is older than a few minutes, and add a register_shutdown_function() that unregisters on a fatal error.
Launch failures are silent. When path_php_binary is empty, or the web user can't exec_background() (disable_functions, SELinux), the CLI never starts. Nothing is logged, and the notice still says the upgrade is running. A cacti_log() there, and the manual command (php plugins/mactrack/cli/upgrade_database.php) in the notice, would cover it.
Batch size depends on the date distribution (unverified). Each batch is one date_last value. On a live install, most rows probably share the last few scan timestamps, so the biggest batch could be close to the whole active set in a single transaction. That's the large undo and lock footprint the PR is trying to avoid. SELECT date_last, COUNT(*) FROM mac_track_aggregated_ports GROUP BY 1 ORDER BY 2 DESC LIMIT 5 on a big install would show whether it matters. If it does, batching by row_id ranges within a date bounds it.
CI is green. I didn't run the rebuild against a real MariaDB; the unit tests mock the database.
The reason will be displayed to describe this comment to others. Learn more.
This only checks started against the 24 h timeout, so a CLI killed without unregistering (SIGKILL, OOM, fatal error, reboot) still counts as running for up to a day. The poller guard then skips every run for that long. Checking that the pid is alive (posix_kill((int) $process['pid'], 0)), or that last_update is recent, would end that early.
The reason will be displayed to describe this comment to others. Learn more.
If path_php_binary is empty or exec_background() can't run, the upgrade never starts and nothing is logged, while the notice still says it's running. A cacti_log() in the else branch would make that visible.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
The MacTrack schema upgrade rebuilds indexes and rewrites the (potentially very large)
mac_track_aggregated_portstable. That work runs far longer than a web request is allowed to live, so it was being killed at the request timeout (~300s), the new version was never recorded, and every subsequent page re-ran the upgrade — an endless loop with a repeating error.This moves the upgrade into a background CLI that the console launches once, so large installs can take the 30–60 minutes they need.
What changed
New
cli/upgrade_database.php— the background entry point:chdir+include/cli_check.php),max_execution_time=0.register_process_start('mtupgrade','database',0,86400)prevents a second copy from running; a crashed run past the timeout is taken over on the next launch.pcntlSIGTERM/SIGINT handlers stop cleanly; because each scan-date batch commits on its own, an interrupted run simply resumes next launch.mactrack_perform_upgrade(), heartbeats the process registry, clears the operator-notice flag, andunregister_process()on completion. Supports--debug,--force,--help,--version.includes/database.php—mactrack_rebuild_aggregated_ports()rebuildsmac_track_aggregated_portswithout the table-wide rewrite:_upgrade);row_id, UNIQUEport_number);INSERT … SELECT … WHERE date_last = ? ON DUPLICATE KEY UPDATE, which merges the rows that MAC normalization collapses (count_rec += VALUES,first_scan_date = LEAST,date_last = GREATEST,active_last = GREATEST), deleting each processed date in the same transaction so the migration is resumable;The satellite tables keep their one-pass MAC normalization.
setup.php—mactrack_check_upgrade()no longer upgrades inline. On pending work it launches the CLI once viaexec_background()and raises a single operator notice while it runs.mactrack_perform_upgrade()performs the full upgrade and records the newplugin_configversion last, so an interrupted run re-runs cleanly and the hook stops relaunching once it finishes.Testing
setup.php/includes/database.php).validate-manifestandcheck-i18n-pot: OK (manifest.jsonandlocales/po/cacti.potupdated).