From 3b1ccb9480f79ce73163bf6e1248770fedc79024 Mon Sep 17 00:00:00 2001 From: Thomas Vincent Date: Wed, 11 Nov 2026 17:30:19 -0800 Subject: [PATCH 1/3] fix(mactrack): restore the unique aggregated ports key on upgrade The 4.9 upgrade dropped the mac_track_aggregated_ports port_number key and recreated it as a plain index. Its guard compared the SHOW INDEXES result array with 7, which is always unequal, so this ran on every upgrade. With a plain index the poller's ON DUPLICATE KEY UPDATE never matches and each pass inserts a new row. Since Cacti refreshes existing plugin tables during install, the refresh now tries to restore the UNIQUE key and fails with "Duplicate entry ... for key 'port_number'". Merge each duplicate group into its newest row (summed count_rec, earliest first_scan_date, latest date_last) in one transaction, then rebuild the key as UNIQUE. mactrack_check_upgrade() runs this before plugin_mactrack_install() refreshes the table, and also without a version change, because installs whose failed refresh already recorded the new version never re-enter the upgrade. Gate the separator migration on a one-time setting instead of the index comparison. Fixes #359 Signed-off-by: Thomas Vincent --- CHANGELOG.md | 1 + includes/database.php | 145 +++++++++++- setup.php | 8 + tests/Unit/AggregatedPortsKeyTest.php | 327 ++++++++++++++++++++++++++ tests/bootstrap-unit.php | 26 +- 5 files changed, 499 insertions(+), 8 deletions(-) create mode 100644 tests/Unit/AggregatedPortsKeyTest.php diff --git a/CHANGELOG.md b/CHANGELOG.md index 61674742..b14b8203 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,7 @@ --- develop --- +* issue#359: Restore the unique mac_track_aggregated_ports `port_number` key on upgraded installs, merging the duplicate rows the 4.9 upgrade let accumulate, so the table refresh no longer fails with "Duplicate entry ... for key 'port_number'" and the MAC separator migration runs only once * issue#399: Use the registered Aruba AOS-CX callback names in the built-in 6200/6300 device types and repair existing defaults during upgrade * dev: Adopt the shared, byte-identical dashboarding card chrome used across the Cacti plugins: the MacTrack dashboard now drives its card grid through the shared `js/cards.js` (`CactiCards`) controller plus a thin `js/mactrack_dashboard.js` adapter, and the card markup/CSS use the shared `.cc*` contract (`css/cards.css`), with MacTrack's `--cc-*` theme bindings and card-body widgets kept in `css/mactrack-dashboard.css`. No functional change to the dashboard; this aligns MacTrack with the other plugins so the chrome can be promoted to Cacti core unchanged * dev: Load the shared card chrome from Cacti core on 1.2.32+ (`include/js/cards.js` + `include/css/cards.css`) and only bundle the plugin's own copy on older cores diff --git a/includes/database.php b/includes/database.php index 0cb84e61..32638fd6 100644 --- a/includes/database.php +++ b/includes/database.php @@ -689,17 +689,17 @@ function mactrack_database_upgrade(): void { db_fetch_cell("UPDATE plugin_realms set display='Mactrack Administrator' WHERE plugin = 'mactrack' and display='Device Tracking Administrator'"); } - // 4.9 - $keys = db_fetch_assoc('SHOW INDEXES FROM mac_track_aggregated_ports WHERE KEY_NAME="port_number"'); - - if ($keys != 7) { - db_execute('ALTER TABLE mac_track_aggregated_ports DROP INDEX port_number'); + // 4.9: MAC addresses are stored without separators. Stripping them can + // turn two aggregated rows into one key, so the unique key is dropped + // first and rebuilt, duplicates merged, by the repair call below. Run once. + if (read_config_option('mt_mac_separators_removed', true) != 'on') { + if (mactrack_db_key_exists('mac_track_aggregated_ports', 'port_number')) { + db_execute('ALTER TABLE mac_track_aggregated_ports DROP INDEX port_number'); + } db_execute("UPDATE mac_track_aggregated_ports SET mac_address = REPLACE(mac_address, ':', '')"); db_execute("UPDATE mac_track_aggregated_ports SET mac_address = REPLACE(mac_address, '-', '')"); - db_execute('ALTER TABLE mac_track_aggregated_ports ADD INDEX `port_number` (`port_number`, `mac_address`, `ip_address`, `device_id`, `site_id`, `vlan_id`, `authorized`)'); - db_execute("UPDATE mac_track_dot1x SET mac_address = REPLACE(mac_address, ':', '')"); db_execute("UPDATE mac_track_dot1x SET mac_address = REPLACE(mac_address, '-', '')"); @@ -722,12 +722,143 @@ function mactrack_database_upgrade(): void { db_execute("UPDATE mac_track_arp SET mac_address = REPLACE(mac_address, '-', '')"); db_execute("UPDATE mac_track_oui_database SET vendor_mac = REPLACE(vendor_mac, ':', '')"); + + set_config_option('mt_mac_separators_removed', 'on'); } + mactrack_repair_aggregated_ports_key(); + mactrack_fix_aruba_oscx_device_type_functions(); mactrack_ensure_default_site(); } +/** + * Returns the ordered columns of the mac_track_aggregated_ports + * `port_number` unique key. The poller's ON DUPLICATE KEY UPDATE + * aggregation only merges scans while this key is unique. + * + * @return array + */ +function mactrack_aggregated_ports_key_columns(): array { + return ['port_number', 'mac_address', 'ip_address', 'device_id', 'site_id', 'vlan_id', 'authorized']; +} + +/** + * Checks whether mac_track_aggregated_ports has its `port_number` key as a + * unique index over exactly the expected columns. + * + * @return bool + */ +function mactrack_aggregated_ports_key_is_unique(): bool { + $rows = db_fetch_assoc_prepared('SHOW INDEX FROM mac_track_aggregated_ports WHERE Key_name = ?', ['port_number']); + + if (!cacti_sizeof($rows)) { + return false; + } + + $columns = []; + + foreach ($rows as $row) { + if ((int) $row['Non_unique'] !== 0) { + return false; + } + + $columns[(int) $row['Seq_in_index']] = $row['Column_name']; + } + + ksort($columns); + + return array_values($columns) === mactrack_aggregated_ports_key_columns(); +} + +/** + * Restores the mac_track_aggregated_ports `port_number` unique key. + * + * The 4.9 upgrade recreated it as a plain index, so each poller pass + * inserted a new row instead of updating the existing one, and the + * Cacti table refresh then fails with a duplicate-entry error. This + * merges each duplicate group into its newest row (summed count_rec, + * earliest first_scan_date, latest date_last), deletes the rest, and + * rebuilds the key as UNIQUE. An advisory lock keeps concurrent page + * loads from running it twice. + * + * @return bool True if the key is unique afterwards or the table does + * not exist yet, false if the repair did not complete. + */ +function mactrack_repair_aggregated_ports_key(): bool { + global $database_default; + + if (!mactrack_db_table_exists('mac_track_aggregated_ports') || mactrack_aggregated_ports_key_is_unique()) { + return true; + } + + $lock_name = 'mactrack.aggregated.' . sha1((string) $database_default); + + if ((string) db_fetch_cell_prepared('SELECT GET_LOCK(?, ?)', [$lock_name, 0]) !== '1') { + return false; + } + + try { + // Another request may have finished the repair before the lock was free. + if (mactrack_aggregated_ports_key_is_unique()) { + return true; + } + + $key_columns = mactrack_aggregated_ports_key_columns(); + $group_by = implode(', ', $key_columns); + $join = implode(' AND ', array_map(static fn ($c) => "a.$c = d.$c", $key_columns)); + + $merge = db_begin_transaction() + && db_execute_prepared("UPDATE mac_track_aggregated_ports AS a + INNER JOIN ( + SELECT MAX(row_id) AS row_id, SUM(count_rec) AS count_rec, + MIN(first_scan_date) AS first_scan_date, MAX(date_last) AS date_last, + MAX(active_last) AS active_last + FROM mac_track_aggregated_ports + GROUP BY $group_by + HAVING COUNT(*) > 1 + ) AS d + ON a.row_id = d.row_id + SET a.count_rec = d.count_rec, a.first_scan_date = d.first_scan_date, + a.date_last = d.date_last, a.active_last = d.active_last") + && db_execute_prepared("DELETE a FROM mac_track_aggregated_ports AS a + INNER JOIN ( + SELECT MAX(row_id) AS keep_id, $group_by + FROM mac_track_aggregated_ports + GROUP BY $group_by + HAVING COUNT(*) > 1 + ) AS d + ON $join + AND a.row_id < d.keep_id") + && db_commit_transaction(); + + if (!$merge) { + db_rollback_transaction(); + cacti_log('MACTRACK: Could not merge duplicate mac_track_aggregated_ports rows; the unique key was not restored', false, 'SYSTEM'); + + return false; + } + + $add = 'ADD UNIQUE INDEX `port_number` (`' . implode('`, `', $key_columns) . '`)'; + + if (mactrack_db_key_exists('mac_track_aggregated_ports', 'port_number')) { + $add = 'DROP INDEX `port_number`, ' . $add; + } + + if (!db_execute_prepared('ALTER TABLE mac_track_aggregated_ports ' . $add)) { + cacti_log('MACTRACK: Could not restore the mac_track_aggregated_ports unique key', false, 'SYSTEM'); + + return false; + } + + cacti_log('MACTRACK: Restored the mac_track_aggregated_ports unique key', false, 'SYSTEM'); + + return true; + } finally { + db_fetch_cell_prepared('SELECT RELEASE_LOCK(?)', [$lock_name]); + } +} + /** * Replaces the obsolete callback names on the built-in Aruba AOS-CX types. * diff --git a/setup.php b/setup.php index caa7c430..8b8f1896 100644 --- a/setup.php +++ b/setup.php @@ -237,6 +237,14 @@ function mactrack_check_upgrade(): void { mactrack_install_realms(false); } + // Merge duplicate aggregated rows before plugin_mactrack_install() + // refreshes the table: Cacti cannot restore the unique key while they + // exist. Also runs without a version change, for installs that recorded + // the new version after a failed refresh. + if (cacti_sizeof($old) && in_array((int) $old['status'], [1, 4], true)) { + mactrack_repair_aggregated_ports_key(); + } + if ($version_changed) { // if the plugin is installed and/or active if (!cacti_sizeof($old) || $old['status'] == 1 || $old['status'] == 4) { diff --git a/tests/Unit/AggregatedPortsKeyTest.php b/tests/Unit/AggregatedPortsKeyTest.php new file mode 100644 index 00000000..07a1cdf1 --- /dev/null +++ b/tests/Unit/AggregatedPortsKeyTest.php @@ -0,0 +1,327 @@ + $columns Key columns in index order. + * + * @return array> + */ + private static function keyRows(int $non_unique, array $columns = self::KEY_COLUMNS): array { + $rows = []; + + foreach ($columns as $i => $column) { + $rows[] = ['Key_name' => 'port_number', 'Non_unique' => $non_unique, 'Seq_in_index' => $i + 1, 'Column_name' => $column]; + } + + return $rows; + } + + /** + * Stub the table, its `port_number` key, and the lock. + * + * @param array> $rows SHOW INDEX result. + * + * @return void + */ + private static function givenKey(array $rows): void { + mactrack_test_queue_return_for('db_fetch_assoc', "SHOW TABLES LIKE 'mac_track_aggregated_ports'", [['Tables_in_cacti' => 'mac_track_aggregated_ports']]); + mactrack_test_queue_return_for('db_fetch_assoc_prepared', 'SHOW INDEX FROM mac_track_aggregated_ports WHERE Key_name = ?', $rows); + mactrack_test_queue_return_for('db_fetch_assoc', 'SHOW INDEXES FROM mac_track_aggregated_ports', $rows); + mactrack_test_queue_return_for('db_fetch_cell_prepared', 'GET_LOCK', '1'); + mactrack_test_queue_return_for('db_fetch_cell_prepared', 'RELEASE_LOCK', '1'); + } + + /** + * Position of the first recorded call whose SQL contains $fragment. + * + * @param string $fragment SQL substring. + * + * @return int|null + */ + private static function callIndex(string $fragment): ?int { + foreach ($GLOBALS['__test_db_calls'] as $i => $call) { + if (strpos(preg_replace('/\s+/', ' ', $call['sql']), $fragment) !== false) { + return $i; + } + } + + return null; + } + + /** + * SQL of every recorded call whose SQL contains $fragment. + * + * @param string $fragment SQL substring. + * + * @return array + */ + private static function callsMatching(string $fragment): array { + return array_values(array_filter( + array_column($GLOBALS['__test_db_calls'], 'sql'), + static fn ($sql) => strpos($sql, $fragment) !== false + )); + } + + /** + * @return void + */ + public function testIntactUniqueKeyIsLeftAlone(): void { + self::givenKey(self::keyRows(0)); + + $this->assertTrue(mactrack_repair_aggregated_ports_key()); + $this->assertNull(self::callIndex('GET_LOCK')); + $this->assertSame([], self::callsMatching('ALTER TABLE')); + $this->assertSame([], self::callsMatching('DELETE')); + } + + /** + * @return void + */ + public function testNonUniqueKeyIsDedupedBeforeTheUniqueKeyIsRebuilt(): void { + self::givenKey(self::keyRows(1)); + + $this->assertTrue(mactrack_repair_aggregated_ports_key()); + + $order = [ + self::callIndex('GET_LOCK'), + self::callIndex('BEGIN'), + self::callIndex('SUM(count_rec) AS count_rec'), + self::callIndex('DELETE a FROM mac_track_aggregated_ports'), + self::callIndex('COMMIT'), + self::callIndex('ALTER TABLE mac_track_aggregated_ports'), + self::callIndex('RELEASE_LOCK'), + ]; + + $this->assertNotContains(null, $order); + $sorted = $order; + sort($sorted); + $this->assertSame($sorted, $order, 'Merge must commit before the unique key is rebuilt, inside the lock'); + + $merge = self::callsMatching('SUM(count_rec)')[0]; + $this->assertStringContainsString('GROUP BY ' . implode(', ', self::KEY_COLUMNS), $merge); + $this->assertStringContainsString('MIN(first_scan_date)', $merge); + $this->assertStringContainsString('MAX(date_last)', $merge); + + $delete = self::callsMatching('DELETE a FROM')[0]; + $this->assertStringContainsString('a.authorized = d.authorized', $delete); + $this->assertStringContainsString('a.row_id < d.keep_id', $delete); + + $this->assertSame( + ['ALTER TABLE mac_track_aggregated_ports DROP INDEX `port_number`, ADD UNIQUE INDEX `port_number` (`' . implode('`, `', self::KEY_COLUMNS) . '`)'], + self::callsMatching('ALTER TABLE') + ); + $this->assertContains('MACTRACK: Restored the mac_track_aggregated_ports unique key', $GLOBALS['__test_cacti_log']); + } + + /** + * @return void + */ + public function testUniqueKeyOverTheWrongColumnsIsRebuilt(): void { + self::givenKey(self::keyRows(0, ['port_number', 'mac_address', 'device_id'])); + + $this->assertTrue(mactrack_repair_aggregated_ports_key()); + $this->assertCount(1, self::callsMatching('ADD UNIQUE INDEX `port_number`')); + } + + /** + * @return void + */ + public function testMissingKeyIsAddedWithoutADrop(): void { + self::givenKey([]); + + $this->assertTrue(mactrack_repair_aggregated_ports_key()); + $this->assertSame( + ['ALTER TABLE mac_track_aggregated_ports ADD UNIQUE INDEX `port_number` (`' . implode('`, `', self::KEY_COLUMNS) . '`)'], + self::callsMatching('ALTER TABLE') + ); + } + + /** + * @return void + */ + public function testMissingTableIsLeftToTheInstaller(): void { + $this->assertTrue(mactrack_repair_aggregated_ports_key()); + $this->assertNull(self::callIndex('SHOW INDEX FROM')); + $this->assertNull(self::callIndex('GET_LOCK')); + } + + /** + * @return void + */ + public function testConcurrentRepairIsSkippedWhileAnotherRequestHoldsTheLock(): void { + mactrack_test_queue_return_for('db_fetch_cell_prepared', 'GET_LOCK', '0'); + self::givenKey(self::keyRows(1)); + + $this->assertFalse(mactrack_repair_aggregated_ports_key()); + $this->assertNull(self::callIndex('BEGIN')); + $this->assertNull(self::callIndex('RELEASE_LOCK')); + } + + /** + * @return void + */ + public function testRepairFinishedByAnotherRequestWhileWaitingIsNotRepeated(): void { + mactrack_test_queue_return_for('db_fetch_assoc', "SHOW TABLES LIKE 'mac_track_aggregated_ports'", [['Tables_in_cacti' => 'mac_track_aggregated_ports']]); + mactrack_test_queue_return_for('db_fetch_cell_prepared', 'GET_LOCK', '1'); + mactrack_test_queue_return('db_fetch_assoc_prepared', self::keyRows(1)); // before the lock + mactrack_test_queue_return('db_fetch_assoc_prepared', self::keyRows(0)); // after the lock + + $this->assertTrue(mactrack_repair_aggregated_ports_key()); + $this->assertNull(self::callIndex('BEGIN')); + $this->assertSame([], self::callsMatching('ALTER TABLE')); + $this->assertNotNull(self::callIndex('RELEASE_LOCK')); + } + + /** + * @return void + */ + public function testFailedMergeRollsBackAndKeepsTheKey(): void { + self::givenKey(self::keyRows(1)); + mactrack_test_queue_return('db_execute_prepared', false); // merge UPDATE + + $this->assertFalse(mactrack_repair_aggregated_ports_key()); + $this->assertNotNull(self::callIndex('ROLLBACK')); + $this->assertNull(self::callIndex('DELETE a FROM')); + $this->assertSame([], self::callsMatching('ALTER TABLE')); + $this->assertNotNull(self::callIndex('RELEASE_LOCK')); + } + + /** + * @return void + */ + public function testFailedKeyRebuildIsReported(): void { + self::givenKey(self::keyRows(1)); + + foreach ([true, true, false] as $result) { // UPDATE, DELETE, ALTER + mactrack_test_queue_return('db_execute_prepared', $result); + } + + $this->assertFalse(mactrack_repair_aggregated_ports_key()); + $this->assertContains('MACTRACK: Could not restore the mac_track_aggregated_ports unique key', $GLOBALS['__test_cacti_log']); + $this->assertNotNull(self::callIndex('RELEASE_LOCK')); + } + + /** + * Stub the lookups mactrack_database_upgrade() makes outside this change. + * + * @return void + */ + private static function givenUpgradeFixtures(): void { + mactrack_test_queue_return('db_fetch_cell', '0'); + mactrack_test_queue_return_for('db_fetch_cell_prepared', 'COUNT(*) FROM mac_track_sites', '1'); + mactrack_test_queue_return_for('db_fetch_assoc', 'SHOW COLUMNS FROM mac_track_ips', [ + ['Field' => 'port_number', 'Type' => 'varchar(30)'], + ]); + } + + /** + * @return void + */ + public function testSeparatorMigrationRunsOnceAndRestoresTheUniqueKey(): void { + self::givenUpgradeFixtures(); + self::givenKey(self::keyRows(0)); + + mactrack_database_upgrade(); + + $this->assertSame('on', read_config_option('mt_mac_separators_removed')); + $this->assertCount(1, self::callsMatching('ALTER TABLE mac_track_aggregated_ports DROP INDEX port_number')); + $this->assertCount(2, self::callsMatching('UPDATE mac_track_ports SET mac_address = REPLACE')); + $this->assertLessThan( + self::callIndex('UPDATE mac_track_aggregated_ports SET mac_address'), + self::callIndex('ALTER TABLE mac_track_aggregated_ports DROP INDEX port_number'), + 'The unique key must be gone before separators are stripped' + ); + } + + /** + * Before this fix the 4.9 block compared an array to 7, so it dropped + * the key and rewrote every MAC table on each upgrade. + * + * @return void + */ + public function testLaterUpgradesSkipTheSeparatorMigration(): void { + set_config_option('mt_mac_separators_removed', 'on'); + self::givenUpgradeFixtures(); + self::givenKey(self::keyRows(0)); + + mactrack_database_upgrade(); + + $this->assertSame([], self::callsMatching('REPLACE(mac_address')); + $this->assertSame([], self::callsMatching('INDEX port_number')); + $this->assertSame([], self::callsMatching('INDEX `port_number`')); + } + + /** + * An install that recorded the new version after a failed refresh never + * re-enters the upgrade, so the repair must also run without a drift. + * + * @return void + */ + public function testCheckUpgradeRepairsTheKeyWithoutAVersionChange(): void { + $info = plugin_mactrack_version(); + mactrack_test_queue_return('get_current_page', 'index.php'); + mactrack_test_queue_return('db_fetch_row', ['version' => $info['version'], 'status' => 1]); + self::givenKey(self::keyRows(1)); + + mactrack_check_upgrade(); + + $this->assertCount(1, self::callsMatching('ADD UNIQUE INDEX `port_number`')); + $this->assertNull(self::callIndex('UPDATE plugin_config')); + } + + /** + * @return void + */ + public function testCheckUpgradeLeavesADisabledPluginAlone(): void { + $info = plugin_mactrack_version(); + mactrack_test_queue_return('get_current_page', 'index.php'); + mactrack_test_queue_return('db_fetch_row', ['version' => $info['version'], 'status' => 0]); + self::givenKey(self::keyRows(1)); + + mactrack_check_upgrade(); + + $this->assertNull(self::callIndex('SHOW INDEX FROM mac_track_aggregated_ports WHERE Key_name = ?')); + } + + /** + * plugin_mactrack_install() refreshes the table through Cacti, which + * fails while duplicates exist, so the repair has to come first. + * + * @return void + */ + public function testCheckUpgradeRepairsBeforeReinstalling(): void { + $source = (string) file_get_contents(dirname(__DIR__, 2) . '/setup.php'); + $body = substr($source, (int) strpos($source, 'function mactrack_check_upgrade(')); + + $repair = strpos($body, 'mactrack_repair_aggregated_ports_key();'); + $install = strpos($body, 'plugin_mactrack_install(false);'); + + $this->assertNotFalse($repair); + $this->assertNotFalse($install); + $this->assertLessThan($install, $repair); + } +} diff --git a/tests/bootstrap-unit.php b/tests/bootstrap-unit.php index 591468ed..e0b2c6c5 100644 --- a/tests/bootstrap-unit.php +++ b/tests/bootstrap-unit.php @@ -177,7 +177,31 @@ function db_fetch_assoc($sql) { function db_fetch_assoc_prepared($sql, $params = array()) { $GLOBALS['__test_db_calls'][] = array('fn' => 'db_fetch_assoc_prepared', 'sql' => $sql, 'params' => $params); - return mactrack_test_next_return('db_fetch_assoc_prepared', array()); + return mactrack_test_next_return('db_fetch_assoc_prepared', array(), $sql); + } +} + +if (!function_exists('db_begin_transaction')) { + function db_begin_transaction($db_conn = false) { + $GLOBALS['__test_db_calls'][] = array('fn' => 'db_begin_transaction', 'sql' => 'BEGIN', 'params' => array()); + + return mactrack_test_next_return('db_begin_transaction', true); + } +} + +if (!function_exists('db_commit_transaction')) { + function db_commit_transaction($db_conn = false) { + $GLOBALS['__test_db_calls'][] = array('fn' => 'db_commit_transaction', 'sql' => 'COMMIT', 'params' => array()); + + return mactrack_test_next_return('db_commit_transaction', true); + } +} + +if (!function_exists('db_rollback_transaction')) { + function db_rollback_transaction($db_conn = false) { + $GLOBALS['__test_db_calls'][] = array('fn' => 'db_rollback_transaction', 'sql' => 'ROLLBACK', 'params' => array()); + + return mactrack_test_next_return('db_rollback_transaction', true); } } From 7434748d776b4e1e6eaa889c7a2c75e1cd6f470d Mon Sep 17 00:00:00 2001 From: Thomas Vincent Date: Wed, 11 Nov 2026 17:33:31 -0800 Subject: [PATCH 2/3] fix(mactrack): run a version upgrade in one request at a time mactrack_check_upgrade() runs on every index.php, plugins.php and mactrack_devices.php load until the new version is recorded at the end, so concurrent page loads run the whole upgrade in parallel. They race on the same DDL and log errors such as "Can't DROP INDEX `port_number`", "Duplicate key name 'site_id_device_id'" and "Table ... already exists". Take a session-scoped advisory lock before upgrading. A request that cannot get it skips the hook; one that gets it rechecks the recorded version so it does not repeat an upgrade that just finished. Ref #359 Signed-off-by: Thomas Vincent --- setup.php | 26 +++++++++++++++- tests/Unit/AggregatedPortsKeyTest.php | 44 +++++++++++++++++++++++++++ tests/Unit/MactrackUpgradeTest.php | 2 ++ 3 files changed, 71 insertions(+), 1 deletion(-) diff --git a/setup.php b/setup.php index 8b8f1896..89eac6c3 100644 --- a/setup.php +++ b/setup.php @@ -212,7 +212,7 @@ function mactrack_realms_are_stale(): bool { * locate library files to include. */ function mactrack_check_upgrade(): void { - global $config; + global $config, $database_default; $files = ['index.php', 'plugins.php', 'mactrack_devices.php']; @@ -230,6 +230,26 @@ function mactrack_check_upgrade(): void { $version_changed = !cacti_sizeof($old) || $current != $old['version']; + // Every page load that sees the old version would otherwise run the + // upgrade at once and race on the same ALTERs. One request takes the + // lock and upgrades; the others skip this hook until it is recorded. + // The lock is session-scoped, so it is freed if the request dies. + $upgrade_lock = 'mactrack.upgrade.' . sha1((string) $database_default); + $upgrade_locked = false; + + if ($version_changed) { + if ((string) db_fetch_cell_prepared('SELECT GET_LOCK(?, ?)', [$upgrade_lock, 0]) !== '1') { + return; + } + + $upgrade_locked = true; + + // Another request may have finished the upgrade before the lock was free. + if (cacti_sizeof($old) && (string) db_fetch_cell_prepared('SELECT version FROM plugin_config WHERE directory = ?', ['mactrack']) === (string) $current) { + $version_changed = false; + } + } + // A realm file list can drift from the code without a version bump (the // Dashboard was added that way). Repair only the realms in that case; the // full upgrade below rebuilds indexes and rewrites large tables. @@ -302,6 +322,10 @@ function mactrack_check_upgrade(): void { [$info['longname'], $info['author'], $info['homepage'], $info['version'], $id]); } + if ($upgrade_locked) { + db_fetch_cell_prepared('SELECT RELEASE_LOCK(?)', [$upgrade_lock]); + } + mactrack_retry_default_site(); } diff --git a/tests/Unit/AggregatedPortsKeyTest.php b/tests/Unit/AggregatedPortsKeyTest.php index 07a1cdf1..dfd962a8 100644 --- a/tests/Unit/AggregatedPortsKeyTest.php +++ b/tests/Unit/AggregatedPortsKeyTest.php @@ -307,6 +307,50 @@ public function testCheckUpgradeLeavesADisabledPluginAlone(): void { $this->assertNull(self::callIndex('SHOW INDEX FROM mac_track_aggregated_ports WHERE Key_name = ?')); } + /** + * A second page load that sees the old version while another request + * holds the upgrade lock must not run any part of the upgrade. + * + * @return void + */ + public function testCheckUpgradeSkipsWhileAnotherRequestIsUpgrading(): void { + mactrack_test_queue_return('get_current_page', 'index.php'); + mactrack_test_queue_return('db_fetch_row', ['version' => '4.8', 'status' => 1]); + mactrack_test_queue_return_for('db_fetch_cell_prepared', 'GET_LOCK', '0'); + self::givenKey(self::keyRows(1)); + + mactrack_check_upgrade(); + + $this->assertSame(1, count(self::callsMatching('GET_LOCK'))); + $this->assertNull(self::callIndex('SHOW INDEX FROM')); + $this->assertNull(self::callIndex('ALTER TABLE')); + $this->assertNull(self::callIndex('UPDATE plugin_config')); + $this->assertNull(self::callIndex('RELEASE_LOCK')); + } + + /** + * A request that waited out another's upgrade sees the recorded version + * once it holds the lock and does not run the upgrade again. + * + * @return void + */ + public function testCheckUpgradeDoesNotRepeatAnUpgradeThatJustFinished(): void { + $info = plugin_mactrack_version(); + mactrack_test_queue_return('get_current_page', 'index.php'); + mactrack_test_queue_return('db_fetch_row', ['version' => '4.8', 'status' => 1]); + mactrack_test_queue_return_for('db_fetch_cell_prepared', 'SELECT version FROM plugin_config', $info['version']); + self::givenKey(self::keyRows(0)); + + mactrack_check_upgrade(); + + $this->assertNull(self::callIndex('UPDATE plugin_config')); + $this->assertSame(['SELECT RELEASE_LOCK(?)'], self::callsMatching('RELEASE_LOCK')); + $this->assertLessThan( + self::callIndex('RELEASE_LOCK'), + self::callIndex('SELECT GET_LOCK') + ); + } + /** * plugin_mactrack_install() refreshes the table through Cacti, which * fails while duplicates exist, so the repair has to come first. diff --git a/tests/Unit/MactrackUpgradeTest.php b/tests/Unit/MactrackUpgradeTest.php index 98bfe41e..a4597d03 100644 --- a/tests/Unit/MactrackUpgradeTest.php +++ b/tests/Unit/MactrackUpgradeTest.php @@ -35,6 +35,8 @@ mactrack_test_queue_return('db_fetch_row', array('version' => '1.0.0', 'status' => 0)); // Permission realms already present -> the realm-insert branch is skipped. mactrack_test_queue_return('db_fetch_cell', '1'); + // This request wins the upgrade lock. + mactrack_test_queue_return_for('db_fetch_cell_prepared', 'GET_LOCK', '1'); // Sandbox base_path (with empty include stubs + a minimal INFO) so the // upgrade-time prune runs against a throwaway tree, never the real checkout. From 0d4a0d6a9b00fd696961a2f728389032b218fa25 Mon Sep 17 00:00:00 2001 From: Thomas Vincent Date: Wed, 11 Nov 2026 17:43:47 -0800 Subject: [PATCH 3/3] fix(mactrack): widen the aggregated ports row_id and bump to 4.11 INSERT ... ON DUPLICATE KEY UPDATE consumes an auto-increment value for every row it offers, including rows it merges, so a long-lived mac_track_aggregated_ports table can exhaust an int(10) row_id. Declare it bigint(20) unsigned and widen existing tables during the upgrade, since cores before 1.2.32 do not refresh existing plugin tables. Bump the version to 4.11 so installs that already recorded 4.10 after the failed refresh run the upgrade again. Ref #359 Signed-off-by: Thomas Vincent --- CHANGELOG.md | 2 +- INFO | 2 +- includes/database.php | 12 ++++++++- tests/Unit/AggregatedPortsKeyTest.php | 39 +++++++++++++++++++++++++++ tests/bootstrap-unit.php | 2 +- 5 files changed, 53 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b14b8203..9bd91ccd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,7 +2,7 @@ --- develop --- -* issue#359: Restore the unique mac_track_aggregated_ports `port_number` key on upgraded installs, merging the duplicate rows the 4.9 upgrade let accumulate, so the table refresh no longer fails with "Duplicate entry ... for key 'port_number'" and the MAC separator migration runs only once +* issue#359: Restore the unique mac_track_aggregated_ports `port_number` key on upgraded installs, merging the duplicate rows the 4.9 upgrade let accumulate, so the table refresh no longer fails with "Duplicate entry ... for key 'port_number'" and the MAC separator migration runs only once; widen its `row_id` to bigint unsigned and run a version upgrade in only one page load at a time * issue#399: Use the registered Aruba AOS-CX callback names in the built-in 6200/6300 device types and repair existing defaults during upgrade * dev: Adopt the shared, byte-identical dashboarding card chrome used across the Cacti plugins: the MacTrack dashboard now drives its card grid through the shared `js/cards.js` (`CactiCards`) controller plus a thin `js/mactrack_dashboard.js` adapter, and the card markup/CSS use the shared `.cc*` contract (`css/cards.css`), with MacTrack's `--cc-*` theme bindings and card-body widgets kept in `css/mactrack-dashboard.css`. No functional change to the dashboard; this aligns MacTrack with the other plugins so the chrome can be promoted to Cacti core unchanged * dev: Load the shared card chrome from Cacti core on 1.2.32+ (`include/js/cards.js` + `include/css/cards.css`) and only bundle the plugin's own copy on older cores diff --git a/INFO b/INFO index f7537e34..37644e9c 100644 --- a/INFO +++ b/INFO @@ -21,7 +21,7 @@ [info] name = mactrack -version = 4.10 +version = 4.11 longname = Device Tracking author = The Cacti Group email = diff --git a/includes/database.php b/includes/database.php index 32638fd6..2458f12f 100644 --- a/includes/database.php +++ b/includes/database.php @@ -728,6 +728,16 @@ function mactrack_database_upgrade(): void { mactrack_repair_aggregated_ports_key(); + // 4.11: the poller's INSERT ... ON DUPLICATE KEY UPDATE consumes an + // auto-increment value for every row it offers, even ones it merges, so + // an int(10) row_id can run out on large installs. Cacti cores before + // 1.2.32 do not refresh existing tables, so widen it here. + $row_id = db_fetch_row_prepared('SHOW COLUMNS FROM mac_track_aggregated_ports LIKE ?', ['row_id']); + + if (cacti_sizeof($row_id) && stripos($row_id['Type'], 'bigint') === false) { + db_execute_prepared('ALTER TABLE mac_track_aggregated_ports MODIFY COLUMN row_id bigint(20) unsigned NOT NULL auto_increment'); + } + mactrack_fix_aruba_oscx_device_type_functions(); mactrack_ensure_default_site(); } @@ -1091,7 +1101,7 @@ function mactrack_retry_default_site(): bool { */ function mactrack_setup_database(bool $notify_seed_failure = false): bool { $data = []; - $data['columns'][] = ['name' => 'row_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'auto_increment' => true]; + $data['columns'][] = ['name' => 'row_id', 'unsigned' => true, 'type' => 'bigint(20)', 'NULL' => false, 'auto_increment' => true]; $data['columns'][] = ['name' => 'site_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; $data['columns'][] = ['name' => 'device_id', 'unsigned' => true, 'type' => 'int(10)', 'NULL' => false, 'default' => '0']; $data['columns'][] = ['name' => 'hostname', 'type' => 'varchar(40)', 'NULL' => false, 'default' => '']; diff --git a/tests/Unit/AggregatedPortsKeyTest.php b/tests/Unit/AggregatedPortsKeyTest.php index dfd962a8..f0de8aff 100644 --- a/tests/Unit/AggregatedPortsKeyTest.php +++ b/tests/Unit/AggregatedPortsKeyTest.php @@ -275,6 +275,45 @@ public function testLaterUpgradesSkipTheSeparatorMigration(): void { $this->assertSame([], self::callsMatching('INDEX `port_number`')); } + /** + * @return void + */ + public function testUpgradeWidensAnIntRowIdToBigint(): void { + self::givenUpgradeFixtures(); + self::givenKey(self::keyRows(0)); + mactrack_test_queue_return_for('db_fetch_row_prepared', 'SHOW COLUMNS FROM mac_track_aggregated_ports LIKE ?', ['Field' => 'row_id', 'Type' => 'int(10) unsigned']); + + mactrack_database_upgrade(); + + $this->assertSame( + ['ALTER TABLE mac_track_aggregated_ports MODIFY COLUMN row_id bigint(20) unsigned NOT NULL auto_increment'], + self::callsMatching('MODIFY COLUMN row_id') + ); + } + + /** + * @return void + */ + public function testUpgradeLeavesABigintRowIdAlone(): void { + self::givenUpgradeFixtures(); + self::givenKey(self::keyRows(0)); + mactrack_test_queue_return_for('db_fetch_row_prepared', 'SHOW COLUMNS FROM mac_track_aggregated_ports LIKE ?', ['Field' => 'row_id', 'Type' => 'bigint(20) unsigned']); + + mactrack_database_upgrade(); + + $this->assertSame([], self::callsMatching('MODIFY COLUMN row_id')); + } + + /** + * @return void + */ + public function testFreshSchemaUsesABigintRowId(): void { + $source = (string) file_get_contents(dirname(__DIR__, 2) . '/includes/database.php'); + + $this->assertStringContainsString("['name' => 'row_id', 'unsigned' => true, 'type' => 'bigint(20)'", $source); + $this->assertStringNotContainsString("['name' => 'row_id', 'unsigned' => true, 'type' => 'int(10)'", $source); + } + /** * An install that recorded the new version after a failed refresh never * re-enters the upgrade, so the repair must also run without a drift. diff --git a/tests/bootstrap-unit.php b/tests/bootstrap-unit.php index e0b2c6c5..4c18a6bd 100644 --- a/tests/bootstrap-unit.php +++ b/tests/bootstrap-unit.php @@ -217,7 +217,7 @@ function db_fetch_row($sql) { function db_fetch_row_prepared($sql, $params = array()) { $GLOBALS['__test_db_calls'][] = array('fn' => 'db_fetch_row_prepared', 'sql' => $sql, 'params' => $params); - return mactrack_test_next_return('db_fetch_row_prepared', array()); + return mactrack_test_next_return('db_fetch_row_prepared', array(), $sql); } }