Skip to content
Merged
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 ---

* 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
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
157 changes: 149 additions & 8 deletions includes/database.php
Original file line number Diff line number Diff line change
Expand Up @@ -689,17 +689,17 @@
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, '-', '')");

Expand All @@ -722,12 +722,153 @@
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();

// 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();
}

/**
* 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<int, string>
*/
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);

Check failure on line 805 in includes/database.php

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Make sure this weak hash algorithm is not used in a sensitive context here.

See more on https://sonarcloud.io/project/issues?id=Cacti_plugin_mactrack&issues=AaHNcUTyNQH-V9sr2-np&open=AaHNcUTyNQH-V9sr2-np&pullRequest=418
Comment thread
TheWitness marked this conversation as resolved.
Dismissed

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.
*
Expand Down Expand Up @@ -960,7 +1101,7 @@
*/
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 Down
34 changes: 33 additions & 1 deletion setup.php
Original file line number Diff line number Diff line change
Expand Up @@ -212,7 +212,7 @@
* locate library files to include.
*/
function mactrack_check_upgrade(): void {
global $config;
global $config, $database_default;

$files = ['index.php', 'plugins.php', 'mactrack_devices.php'];

Expand All @@ -230,13 +230,41 @@

$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);

Check failure on line 237 in setup.php

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Make sure this weak hash algorithm is not used in a sensitive context here.

See more on https://sonarcloud.io/project/issues?id=Cacti_plugin_mactrack&issues=AaHNcUPQNQH-V9sr2-no&open=AaHNcUPQNQH-V9sr2-no&pullRequest=418
Comment thread
TheWitness marked this conversation as resolved.
Dismissed
$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.
if (!$version_changed && in_array((int) $old['status'], [1, 4], true) && mactrack_realms_are_stale()) {
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) {
Expand Down Expand Up @@ -294,6 +322,10 @@
[$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();
}

Expand Down
Loading
Loading