Skip to content

mactrack: run the database upgrade in a background CLI - #423

Merged
TheWitness merged 4 commits into
developfrom
feature/mactrack-bg-db-upgrade
Nov 12, 2026
Merged

TheWitness merged 4 commits into
developfrom
feature/mactrack-bg-db-upgrade

Conversation

@TheWitness

Copy link
Copy Markdown
Member

Summary

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:

    • CLI bootstrap (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.
    • 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:

    1. rename the live table aside (_upgrade);
    2. create the modified table (bigint row_id, UNIQUE port_number);
    3. read the distinct scan dates;
    4. 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;
    5. 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>
Copilot AI balanced review requested due to automatic review settings November 12, 2026 19:23
Comment thread includes/database.php Fixed
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>

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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.

6 open issues
What changed in this PR

Moves MacTrack’s long-running database upgrades from web requests to a background CLI to avoid request timeouts on large installations.

Changes:

  • Adds a CLI upgrade runner with process registration, signal handling, and diagnostic options.
  • Rebuilds aggregated-port data in resumable scan-date batches, normalizing MAC addresses and merging duplicates.
  • Updates background launch detection, completion bookkeeping, tests, and packaging metadata.
File Description
tests/​Unit/​MactrackUpgradeTest.php Tests the extracted upgrade routine and installation path.
tests/​Unit/​AggregatedPortsRebuildTest.php Adds rebuild, resume, locking, and rollback coverage.
tests/​Unit/​AggregatedPortsKeyTest.php Updates key-repair and background-launch expectations.
tests/​Security/​PreparedStatementConsistencyTest.php Adjusts database-call baselines.
tests/​bootstrap-unit.php Adds process stubs and configurable settings reads.
tests/​bin/​patch-coverage.php Excludes the standalone CLI from isolated coverage measurement.
setup.php Launches upgrades asynchronously and separates upgrade execution.
manifest.json Includes the new cli/ directory.
locales/​po/​cacti.pot Adds the background-upgrade notice for translation.
includes/​database.php Implements schema normalization and batched aggregate rebuilding.
cli/​upgrade_database.php Provides the background upgrade entry point and process lifecycle.

Review effort: Balanced

Comment thread includes/database.php Resolved
Comment thread includes/database.php Resolved
Comment thread includes/database.php Resolved
Comment thread setup.php Resolved
Comment thread includes/database.php Resolved
Comment thread includes/database.php Resolved
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>

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Comment thread cli/upgrade_database.php Resolved
Comment thread includes/database.php Resolved
Comment thread poller_mactrack.php Resolved
Comment thread poller_mactrack.php Resolved
Comment thread setup.php Resolved
- 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>
@sonarqubecloud

Copy link
Copy Markdown

@TheWitness
TheWitness merged commit 95d37e8 into develop Nov 12, 2026
10 checks passed
@TheWitness
TheWitness deleted the feature/mactrack-bg-db-upgrade branch November 12, 2026 20:06

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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.

1 open issue
1 previously missed issue

In code that hasn't changed since last review

Medium severity 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.

5 resolved since last review

Review effort: Balanced

Comment thread includes/database.php Resolved

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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.

1 open issue
1 resolved since last review

Review effort: Balanced

Comment thread includes/database.php
Comment on lines +920 to +922
$insert_columns = 'site_id, device_id, hostname, device_name, vlan_id, vlan_name,
mac_address, vendor_mac, ip_address, dns_hostname, port_number, port_name,
date_last, first_scan_date, count_rec, active_last, authorized';

@somethingwithproof somethingwithproof left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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.

Comment thread includes/database.php

// A registration that has outlived its timeout is stale; let the caller
// replace or ignore a crashed upgrade.
return ((int) $process['now'] - (int) $process['started']) <= (int) $process['timeout'];

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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.

Comment thread poller_mactrack.php
$upgrade_active = mactrack_db_table_exists('mac_track_aggregated_ports_upgrade');
}

if ($upgrade_active) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

With the staleness check above, a crashed upgrade keeps this branch taken for up to 24 h, and no MacTrack data is collected in that time.

Comment thread setup.php
$php_binary = read_config_option('path_php_binary');
$script = $config['base_path'] . '/plugins/mactrack/cli/upgrade_database.php';

if ($php_binary != '' && file_exists($script)) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants