Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

--- develop ---

* bug: Fix a fatal upgrade regression that crashed Cacti on every page load: the mac_track_aggregated_ports `port_number` key is now a plain (non-unique) index and `row_id` is bigint unsigned, so the upgrade no longer rejects the multiple rows per MAC this table keeps by design; the aggregated-ports poller insert no longer uses ON DUPLICATE KEY UPDATE (row_id is the only key, so there is nothing to collide on)
* 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
Expand Down
2 changes: 1 addition & 1 deletion INFO
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@

[info]
name = mactrack
version = 4.10
version = 4.11
longname = Device Tracking
author = The Cacti Group
email =
Expand Down
59 changes: 27 additions & 32 deletions includes/database.php
Original file line number Diff line number Diff line change
Expand Up @@ -689,39 +689,34 @@ 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');

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, '-', '')");
// 4.9/4.11: normalize the legacy MAC-address formatting and convert the
// aggregated-ports `port_number` key from the old UNIQUE index to a plain
// index. Aggregated ports intentionally keep multiple rows per MAC (the
// MAC view counts them), so the table must not enforce uniqueness on that
// composite -- enforcing it crashed upgrades on installs holding such rows.
// db_update_table() reconciles indexes by column set only, so it never
// drops a UNIQUE key on its own; do it explicitly here. Gated by a
// persistent flag so the table-wide rewrites run only once.
if (read_config_option('mt_mac_separators_stripped') != 'on') {
db_execute("UPDATE mac_track_aggregated_ports SET mac_address = REPLACE(REPLACE(mac_address, ':', ''), '-', '')");
db_execute("UPDATE mac_track_dot1x SET mac_address = REPLACE(REPLACE(mac_address, ':', ''), '-', '')");
db_execute("UPDATE mac_track_ips SET mac_address = REPLACE(REPLACE(mac_address, ':', ''), '-', '')");
db_execute("UPDATE mac_track_macauth SET mac_address = REPLACE(REPLACE(mac_address, ':', ''), '-', '')");
db_execute("UPDATE mac_track_macwatch SET mac_address = REPLACE(REPLACE(mac_address, ':', ''), '-', '')");
db_execute("UPDATE mac_track_ports SET mac_address = REPLACE(REPLACE(mac_address, ':', ''), '-', '')");
db_execute("UPDATE mac_track_temp_ports SET mac_address = REPLACE(REPLACE(mac_address, ':', ''), '-', '')");
db_execute("UPDATE mac_track_arp SET mac_address = REPLACE(REPLACE(mac_address, ':', ''), '-', '')");
db_execute("UPDATE mac_track_oui_database SET vendor_mac = REPLACE(REPLACE(vendor_mac, ':', ''), '-', '')");

// Drop any existing `port_number` index (UNIQUE or not) and re-add it
// as a plain composite index.
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('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, '-', '')");

db_execute("UPDATE mac_track_ips SET mac_address = REPLACE(mac_address, ':', '')");
db_execute("UPDATE mac_track_ips SET mac_address = REPLACE(mac_address, '-', '')");

db_execute("UPDATE mac_track_macauth SET mac_address = REPLACE(mac_address, ':', '')");
db_execute("UPDATE mac_track_macauth SET mac_address = REPLACE(mac_address, '-', '')");

db_execute("UPDATE mac_track_macwatch SET mac_address = REPLACE(mac_address, ':', '')");
db_execute("UPDATE mac_track_macwatch SET mac_address = REPLACE(mac_address, '-', '')");

db_execute("UPDATE mac_track_ports SET mac_address = REPLACE(mac_address, ':', '')");
db_execute("UPDATE mac_track_ports SET mac_address = REPLACE(mac_address, '-', '')");

db_execute("UPDATE mac_track_temp_ports SET mac_address = REPLACE(mac_address, ':', '')");
db_execute("UPDATE mac_track_temp_ports SET mac_address = REPLACE(mac_address, '-', '')");

db_execute("UPDATE mac_track_arp SET mac_address = REPLACE(mac_address, ':', '')");
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_stripped', 'on');
}

mactrack_fix_aruba_oscx_device_type_functions();
Expand Down Expand Up @@ -960,7 +955,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' => ''];
Expand All @@ -979,7 +974,7 @@ function mactrack_setup_database(bool $notify_seed_failure = false): bool {
$data['columns'][] = ['name' => 'active_last', 'unsigned' => true, 'type' => 'tinyint(1)', 'NULL' => false, 'default' => '0'];
$data['columns'][] = ['name' => 'authorized', 'unsigned' => true, 'type' => 'tinyint(3)', 'NULL' => false, 'default' => '0'];
$data['primary'] = 'row_id';
$data['unique_keys'][] = ['name' => 'port_number', 'columns' => 'port_number`,`mac_address`,`ip_address`,`device_id`,`site_id`,`vlan_id`,`authorized'];
$data['keys'][] = ['name' => 'port_number', 'columns' => 'port_number`,`mac_address`,`ip_address`,`device_id`,`site_id`,`vlan_id`,`authorized'];
$data['keys'][] = ['name' => 'site_id', 'columns' => 'site_id'];
$data['keys'][] = ['name' => 'device_name', 'columns' => 'device_name'];
$data['keys'][] = ['name' => 'mac', 'columns' => 'mac_address'];
Expand Down
7 changes: 5 additions & 2 deletions poller_mactrack.php
Original file line number Diff line number Diff line change
Expand Up @@ -1100,6 +1100,10 @@ function collect_mactrack_data($start, $site_id = 0): void {
// process aggregated data
db_execute('UPDATE mac_track_aggregated_ports SET active_last=0');

// Aggregated ports keep one row per observation (the MAC view counts
// them to show how often a MAC has been seen). row_id is the only
// unique/primary key, so there is no composite key to collide on; this
// is a plain append, not an upsert.
db_execute_prepared('INSERT INTO mac_track_aggregated_ports
(site_id, device_id, hostname, device_name,
vlan_id, vlan_name, mac_address, vendor_mac, ip_address, dns_hostname,
Expand All @@ -1112,8 +1116,7 @@ function collect_mactrack_data($start, $site_id = 0): void {
ON (t1.mac_address = t2.mac_address
AND t1.site_id = t2.site_id
AND t1.port_number <> ""
AND t2.scan_date = ?)
ON DUPLICATE KEY UPDATE count_rec=count_rec+1, active_last=1, date_last=t1.scan_date,port_name=t1.port_name',
AND t2.scan_date = ?)',
[$scan_date]);

// purge the ip address and temp port table
Expand Down
172 changes: 172 additions & 0 deletions tests/Integration/AggregatedPortsUpgradeTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,172 @@
<?php
/*
+-------------------------------------------------------------------------+
| Copyright (C) 2004-2026 The Cacti Group |
| |
| This program is free software; you can redistribute it and/or |
| modify it under the terms of the GNU General Public License |
| as published by the Free Software Foundation; either version 2 |
| of the License, or (at your option) any later version. |
+-------------------------------------------------------------------------+
| Cacti: The Complete RRDtool-based Graphing Solution |
+-------------------------------------------------------------------------+
| http://www.cacti.net/ |
+-------------------------------------------------------------------------+
*/

/**
* Regression coverage for the mac_track_aggregated_ports upgrade crash.
*
* The schema used to declare `port_number` as a UNIQUE composite key, but the
* aggregated-ports table keeps multiple rows per MAC by design (the MAC view
* counts them to show how often a MAC has been seen). When a version bump
* re-entered the upgrade path, api_plugin_db_table_create() tried to apply the
* UNIQUE key and aborted with "Duplicate entry ... for key 'port_number'",
* cascading into a fatal "could not update table" plugin error on every Cacti
* page load.
*
* The fix makes `port_number` a plain (non-unique) index and widens `row_id`
* to bigint unsigned. The upgrade drops any legacy UNIQUE index and re-adds it
* non-unique (db_update_table reconciles indexes by column set only and will
* not do it on its own), and the poller inserts aggregated rows as a plain
* append rather than an ON DUPLICATE KEY UPDATE upsert.
*/
final class AggregatedPortsUpgradeTest extends TestCase {
/**
* @return void
*/
public static function setUpBeforeClass(): void {
self::loadPluginSource('includes/database.php');
self::loadPluginSource('setup.php');
}

/**
* @return array<int, string>
*/
private function sqlCalls(): array {
return array_column($GLOBALS['__test_db_calls'], 'sql');
}

/**
* Prime the stubs mactrack_database_upgrade() needs to run cleanly: a
* seeded Default site (so the trailing seed is a no-op) and the port_number
* column type lookup on mac_track_ips.
*
* @return void
*/
private function primeUpgradeStubs(): void {
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',
array(array('Field' => 'port_number', 'Type' => 'varchar(30)')));
}

/**
* @return void
*/
public function testAggregatedPortsSchemaIsNonUniqueWithBigintRowId(): void {
$src = file_get_contents(dirname(__DIR__, 2) . '/includes/database.php');

$this->assertStringContainsString(
"['name' => 'row_id', 'unsigned' => true, 'type' => 'bigint(20)'",
$src,
'row_id should be bigint unsigned'
);
$this->assertStringContainsString(
"\$data['keys'][] = ['name' => 'port_number'",
$src,
'port_number should be a plain (non-unique) index'
);
$this->assertStringNotContainsString(
"\$data['unique_keys'][] = ['name' => 'port_number'",
$src,
'port_number must no longer be a unique key'
);
}

/**
* @return void
*/
public function testUpgradeReaddsPortNumberAsAPlainIndex(): void {
$this->primeUpgradeStubs();

mactrack_database_upgrade();

$adds = array_values(array_filter($this->sqlCalls(), static fn ($sql) =>
strpos($sql, 'ADD INDEX `port_number`') !== false
));
$this->assertCount(1, $adds, 'The port_number index should be re-added');
$this->assertStringNotContainsString('UNIQUE', $adds[0], 'The re-added index must be non-unique');

foreach ($this->sqlCalls() as $sql) {
$this->assertStringNotContainsString('ADD UNIQUE INDEX `port_number`', $sql);
}
}

/**
* @return void
*/
public function testUpgradeDropsAnExistingPortNumberIndexBeforeReadding(): void {
$this->primeUpgradeStubs();

// Make mactrack_db_key_exists() report an existing port_number index.
mactrack_test_queue_return_for('db_fetch_assoc', "SHOW TABLES LIKE 'mac_track_aggregated_ports'",
array(array('name' => 'mac_track_aggregated_ports')));
mactrack_test_queue_return_for('db_fetch_assoc', 'SHOW INDEXES FROM mac_track_aggregated_ports',
array(array('Key_name' => 'port_number')));

mactrack_database_upgrade();

$calls = $this->sqlCalls();

$drops = array_filter($calls, static fn ($sql) =>
strpos($sql, 'DROP INDEX port_number') !== false
);
$this->assertCount(1, $drops, 'An existing port_number index should be dropped first');

$adds = array_filter($calls, static fn ($sql) =>
strpos($sql, 'ADD INDEX `port_number`') !== false
);
$this->assertCount(1, $adds, 'The index should then be re-added as a plain index');
}

/**
* @return void
*/
public function testUpgradeStripsMacSeparatorsOnceThenSkips(): void {
$this->primeUpgradeStubs();

$this->assertNotSame('on', read_config_option('mt_mac_separators_stripped'));

mactrack_database_upgrade();

$this->assertSame('on', read_config_option('mt_mac_separators_stripped'));

$firstPass = array_filter($this->sqlCalls(), static fn ($sql) =>
strpos($sql, 'UPDATE mac_track_dot1x SET mac_address') !== false
);
$this->assertCount(1, $firstPass, 'Legacy MAC normalization should run on the first upgrade');

// A later upgrade with the flag already set must not re-run the heavy
// table-wide normalization UPDATEs or re-index the table.
$GLOBALS['__test_db_calls'] = array();
$this->primeUpgradeStubs();

mactrack_database_upgrade();

foreach ($this->sqlCalls() as $sql) {
$this->assertStringNotContainsString('UPDATE mac_track_dot1x SET mac_address', $sql);
$this->assertStringNotContainsString('ADD INDEX `port_number`', $sql);
}
}

/**
* @return void
*/
public function testPollerAppendsAggregatedPortsWithoutAnUpsert(): void {
$src = file_get_contents(dirname(__DIR__, 2) . '/poller_mactrack.php');

$this->assertStringContainsString('INSERT INTO mac_track_aggregated_ports', $src);
$this->assertStringNotContainsString('ON DUPLICATE KEY UPDATE count_rec', $src,
'The aggregated-ports insert must be a plain append, not an upsert');
}
}
Loading